From 147d5e6c261bd6b6ee228fd741c0f14c6f920912 Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 16 Nov 2026 09:25:57 -0600 Subject: [PATCH 01/13] [generator] Bind Kotlin suspend functions as Task-returning *Async methods MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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> --- .../Adapters/JavaXmlApiImporter.cs | 2 +- .../Android.Runtime/KotlinCoroutines.cs | 187 ++++++++++++++++++ src/Mono.Android/Mono.Android.csproj | 1 + .../PublicAPI/API-35/PublicAPI.Unshipped.txt | 3 + .../API-36.1/PublicAPI.Unshipped.txt | 3 + .../PublicAPI/API-36/PublicAPI.Unshipped.txt | 3 + .../API-37.1/PublicAPI.Unshipped.txt | 3 + .../API-37.2/PublicAPI.Unshipped.txt | 3 + .../PublicAPI/API-37/PublicAPI.Unshipped.txt | 3 + .../Kotlin/KotlinFixups.cs | 13 ++ src/Xamarin.Android.Tools.Bytecode/Methods.cs | 5 + .../XmlClassDeclarationBuilder.cs | 1 + .../XmlApiImporter.cs | 1 + .../Method.cs | 3 + src/generator/SourceWriters/BoundClass.cs | 8 +- src/generator/SourceWriters/BoundInterface.cs | 5 +- .../SourceWriters/InterfaceExtensionsClass.cs | 3 + .../KotlinSuspendMethodWrapper.cs | 114 +++++++++++ .../KotlinSuspendTests.cs | 38 ++++ ...amarin.Android.Tools.Bytecode-Tests.csproj | 1 + .../kotlin-gradle.targets | 1 + .../src/main/kotlin/SuspendFunctions.kt | 13 ++ .../KotlinInlineClassEndToEndTests.cs | 2 +- .../Unit-Tests/KotlinSuspendTests.cs | 66 +++++++ tests/generator-Tests/generator-Tests.csproj | 1 + 25 files changed, 479 insertions(+), 4 deletions(-) create mode 100644 src/Mono.Android/Android.Runtime/KotlinCoroutines.cs create mode 100644 src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs create mode 100644 tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinSuspendTests.cs create mode 100644 tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/SuspendFunctions.kt create mode 100644 tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs diff --git a/src/Java.Interop.Tools.JavaTypeSystem/Adapters/JavaXmlApiImporter.cs b/src/Java.Interop.Tools.JavaTypeSystem/Adapters/JavaXmlApiImporter.cs index c7aaa5bb432..8839c3151a4 100644 --- a/src/Java.Interop.Tools.JavaTypeSystem/Adapters/JavaXmlApiImporter.cs +++ b/src/Java.Interop.Tools.JavaTypeSystem/Adapters/JavaXmlApiImporter.cs @@ -319,7 +319,7 @@ public static JavaParameterModel ParseParameter (JavaMethodModel method, XElemen // class-parse attributes for Kotlin value classes and default arguments that the generator reads. internal static readonly string [] KotlinClassAttributes = { "kotlin-inline-class", "kotlin-inline-class-underlying-jni-type", "kotlin-inline-class-has-init" }; - internal static readonly string [] KotlinMethodAttributes = { "managedName", "kotlin-inline-class-return-jni-type", "kotlin-default-jni-signature", "kotlin-default-parameters" }; + internal static readonly string [] KotlinMethodAttributes = { "managedName", "kotlin-inline-class-return-jni-type", "kotlin-default-jni-signature", "kotlin-default-parameters", "kotlin-suspend-return-type" }; internal static readonly string [] KotlinParameterAttributes = { "kotlin-inline-class-jni-type" }; static void CopyAttributes (XElement element, Dictionary bag, string [] names) diff --git a/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs b/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs new file mode 100644 index 00000000000..49804f43fa6 --- /dev/null +++ b/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs @@ -0,0 +1,187 @@ +#nullable enable +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using Java.Interop; +using Java.Lang; +using Java.Lang.Reflect; + +using Exception = System.Exception; + +namespace Android.Runtime { + + /// + /// Runs Kotlin suspend functions as objects. + /// Generated bindings call these methods from their *Async methods. + /// + /// + /// The kotlin.coroutines.Continuation is a java.lang.reflect.Proxy, so this type has no + /// build-time dependency on Kotlin. When kotlinx.coroutines is in the app, the continuation context + /// is a kotlinx.coroutines.Job, and cancellation of the token cancels that job. Without + /// kotlinx.coroutines, cancellation of the token cancels only the returned task. + /// + public static class KotlinCoroutines { + const DynamicallyAccessedMemberTypes Constructors = DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors; + + /// Runs a Kotlin suspend function that returns Unit. + /// Calls the bound method with the supplied kotlin.coroutines.Continuation. + /// Cancels the operation. + public static Task InvokeAsync (Func invoke, CancellationToken cancellationToken = default) + { + return InvokeCoreAsync (invoke, cancellationToken); + } + + /// Runs a Kotlin suspend function and converts its result to . + /// Calls the bound method with the supplied kotlin.coroutines.Continuation. + /// Cancels the operation. + public static async Task InvokeAsync< + [DynamicallyAccessedMembers (Constructors)] + T + > (Func invoke, CancellationToken cancellationToken = default) + { + var value = await InvokeCoreAsync (invoke, cancellationToken).ConfigureAwait (false); + // Kotlin metadata makes T nullable when the result can be null. +#pragma warning disable CS8603 + return JavaConvert.FromJavaObject (value); +#pragma warning restore CS8603 + } + + static Task InvokeCoreAsync (Func invoke, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull (invoke); + if (cancellationToken.IsCancellationRequested) + return Task.FromCanceled (cancellationToken); + + var handler = new ContinuationHandler (cancellationToken); + try { + var result = invoke (handler.Continuation); + if (!ContinuationHandler.IsSuspended (result)) + handler.SetResult (result); + } catch (Exception e) { + handler.SetException (e); + } + return handler.Task; + } + + sealed class ContinuationHandler : Java.Lang.Object, IInvocationHandler { + + static readonly KotlinTypes types = new KotlinTypes (); + + readonly TaskCompletionSource completion = new (TaskCreationOptions.RunContinuationsAsynchronously); + readonly CancellationToken cancellationToken; + readonly CancellationTokenRegistration registration; + readonly Java.Lang.Object? job; + + public ContinuationHandler (CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + // Job(parent: Job?) with no parent. + job = types.CreateJob?.Invoke (null, new Java.Lang.Object [1]); + Continuation = Proxy.NewProxyInstance (types.Loader, new [] { types.Continuation }, this); + registration = cancellationToken.Register (Cancel); + } + + public Java.Lang.Object Continuation { get; } + + public Task Task => completion.Task; + + public static bool IsSuspended (Java.Lang.Object? value) => + value != null && JNIEnv.IsSameObject (value.Handle, types.Suspended.Handle); + + public void SetResult (Java.Lang.Object? value) + { + completion.TrySetResult (value); + registration.Dispose (); + } + + public void SetException (Exception e) + { + if (e is Java.Util.Concurrent.CancellationException) + completion.TrySetCanceled (cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken (true)); + else + completion.TrySetException (e); + registration.Dispose (); + } + + void Cancel () + { + if (job == null || types.CancelJob == null) { + completion.TrySetCanceled (cancellationToken); + return; + } + // Kotlin resumes the continuation with a CancellationException. + types.CancelJob.Invoke (job, new Java.Util.Concurrent.CancellationException ("The .NET CancellationToken was canceled.")); + } + + public Java.Lang.Object? Invoke (Java.Lang.Object? proxy, Method? method, Java.Lang.Object []? args) + { + switch (method?.Name) { + case "getContext": + return job ?? types.EmptyContext; + case "resumeWith": + Resume (args?.Length > 0 ? args [0] : null); + return null; + case "hashCode": + return Integer.ValueOf (JavaSystem.IdentityHashCode (proxy)); + case "equals": + return Java.Lang.Boolean.ValueOf (proxy != null && args?.Length > 0 && args [0] != null && JNIEnv.IsSameObject (proxy.Handle, args [0].Handle)); + case "toString": + return new Java.Lang.String ("Android.Runtime.KotlinCoroutines continuation"); + default: + throw new UnsupportedOperationException (method?.Name); + } + } + + void Resume (Java.Lang.Object? value) + { + // `kotlin.Result` is an inline class: a failure is a `kotlin.Result$Failure`, and a success is the value. + if (!types.Failure.IsInstance (value)) { + SetResult (value); + return; + } + if (types.FailureException.Get (value) is not Throwable throwable) { + SetException (new InvalidOperationException ("Kotlin returned a failure without an exception.")); + return; + } + var reference = throwable.PeerReference; + SetException (JniEnvironment.Runtime.GetExceptionForThrowable (ref reference, JniObjectReferenceOptions.Copy) ?? throwable); + } + } + + sealed class KotlinTypes { + public readonly ClassLoader? Loader; + public readonly Class Continuation; + public readonly Java.Lang.Object EmptyContext; + public readonly Java.Lang.Object Suspended; + public readonly Class Failure; + public readonly Field FailureException; + public readonly Method? CreateJob; + public readonly Method? CancelJob; + + public KotlinTypes () + { + // The app class loader, which also loads the Kotlin standard library. + Loader = Class.FromType (typeof (ContinuationHandler)).ClassLoader; + Continuation = Class.ForName ("kotlin.coroutines.Continuation", false, Loader); + EmptyContext = GetStaticField ("kotlin.coroutines.EmptyCoroutineContext", "INSTANCE"); + Suspended = GetStaticField ("kotlin.coroutines.intrinsics.CoroutineSingletons", "COROUTINE_SUSPENDED"); + Failure = Class.ForName ("kotlin.Result$Failure", false, Loader); + FailureException = Failure.GetField ("exception"); + + Class job; + try { + job = Class.ForName ("kotlinx.coroutines.Job", false, Loader); + } catch (ClassNotFoundException) { + return; + } + CreateJob = Class.ForName ("kotlinx.coroutines.JobKt", false, Loader).GetMethod ("Job", job); + CancelJob = job.GetMethod ("cancel", Class.FromType (typeof (Java.Util.Concurrent.CancellationException))); + } + + Java.Lang.Object GetStaticField (string className, string fieldName) => + Class.ForName (className, false, Loader).GetField (fieldName).Get (null) ?? + throw new InvalidOperationException ($"Could not read {className}.{fieldName}."); + } + } +} diff --git a/src/Mono.Android/Mono.Android.csproj b/src/Mono.Android/Mono.Android.csproj index 30d17e3521d..55a77152b07 100644 --- a/src/Mono.Android/Mono.Android.csproj +++ b/src/Mono.Android/Mono.Android.csproj @@ -234,6 +234,7 @@ + diff --git a/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt index afcc72d9abc..68f7697fee1 100644 --- a/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt @@ -6048,3 +6048,6 @@ static Java.Interop.JniMarshalTyped.Invoke_X(nint jnienv, nint self, dele *REMOVED*override Android.Graphics.ColorValueMarshaler.CreateReturnValueFromManagedExpression(Java.Interop.Expressions.JniValueMarshalerContext! context, System.Linq.Expressions.ParameterExpression! sourceValue) -> System.Linq.Expressions.Expression! *REMOVED*override Android.Graphics.ColorValueMarshaler.DestroyGenericArgumentState(Android.Graphics.Color value, ref Java.Interop.JniValueMarshalerState state, System.Reflection.ParameterAttributes synchronize) -> void *REMOVED*override Android.Graphics.ColorValueMarshaler.MarshalType.get -> System.Type! +Android.Runtime.KotlinCoroutines +static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt index 69bf7a889e2..0cc8891ecc7 100644 --- a/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt @@ -6116,3 +6116,6 @@ static Java.Interop.JniMarshalTyped.Invoke_X(nint jnienv, nint self, dele *REMOVED*override Android.Graphics.ColorValueMarshaler.CreateReturnValueFromManagedExpression(Java.Interop.Expressions.JniValueMarshalerContext! context, System.Linq.Expressions.ParameterExpression! sourceValue) -> System.Linq.Expressions.Expression! *REMOVED*override Android.Graphics.ColorValueMarshaler.DestroyGenericArgumentState(Android.Graphics.Color value, ref Java.Interop.JniValueMarshalerState state, System.Reflection.ParameterAttributes synchronize) -> void *REMOVED*override Android.Graphics.ColorValueMarshaler.MarshalType.get -> System.Type! +Android.Runtime.KotlinCoroutines +static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt index c499b1bf19c..d24480b0fc6 100644 --- a/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt @@ -10389,3 +10389,6 @@ virtual Java.Util.IdentityHashMap.Replace(Java.Lang.Object? key, Java.Lang.Objec *REMOVED*override Android.Graphics.ColorValueMarshaler.CreateReturnValueFromManagedExpression(Java.Interop.Expressions.JniValueMarshalerContext! context, System.Linq.Expressions.ParameterExpression! sourceValue) -> System.Linq.Expressions.Expression! *REMOVED*override Android.Graphics.ColorValueMarshaler.DestroyGenericArgumentState(Android.Graphics.Color value, ref Java.Interop.JniValueMarshalerState state, System.Reflection.ParameterAttributes synchronize) -> void *REMOVED*override Android.Graphics.ColorValueMarshaler.MarshalType.get -> System.Type! +Android.Runtime.KotlinCoroutines +static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt index 000c8b28a5c..62491a0b2dc 100644 --- a/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt @@ -11703,3 +11703,6 @@ static Android.Runtime.JNIEnv.NewArray(uint[]? array) -> nint static Android.Runtime.JNIEnv.NewArray(ulong[]? array) -> nint *REMOVED*static Android.Runtime.JNIEnv.NewArray(ushort[]! array) -> nint static Android.Runtime.JNIEnv.NewArray(ushort[]? array) -> nint +Android.Runtime.KotlinCoroutines +static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt index ede15278eb2..0fc56bce831 100644 --- a/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt @@ -12855,3 +12855,6 @@ static Android.Runtime.JNIEnv.NewArray(uint[]? array) -> nint static Android.Runtime.JNIEnv.NewArray(ulong[]? array) -> nint *REMOVED*static Android.Runtime.JNIEnv.NewArray(ushort[]! array) -> nint static Android.Runtime.JNIEnv.NewArray(ushort[]? array) -> nint +Android.Runtime.KotlinCoroutines +static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt index c555f2c72c9..e4bd8e5687b 100644 --- a/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt @@ -11341,3 +11341,6 @@ static Android.Runtime.JNIEnv.NewArray(uint[]? array) -> nint static Android.Runtime.JNIEnv.NewArray(ulong[]? array) -> nint *REMOVED*static Android.Runtime.JNIEnv.NewArray(ushort[]! array) -> nint static Android.Runtime.JNIEnv.NewArray(ushort[]? array) -> nint +Android.Runtime.KotlinCoroutines +static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Xamarin.Android.Tools.Bytecode/Kotlin/KotlinFixups.cs b/src/Xamarin.Android.Tools.Bytecode/Kotlin/KotlinFixups.cs index 0e02105c5c8..5ff37e6cbee 100644 --- a/src/Xamarin.Android.Tools.Bytecode/Kotlin/KotlinFixups.cs +++ b/src/Xamarin.Android.Tools.Bytecode/Kotlin/KotlinFixups.cs @@ -376,6 +376,10 @@ static void FixupFunction (MethodInfo? method, KotlinFunction metadata, KotlinCl // Same projection as above, but for the return type. method.KotlinInlineClassReturnJniType = GetInlineClassJniType (metadata.ReturnType?.ClassName, method.ReturnType.TypeSignature, inlineClasses); + if (metadata.Flags.HasFlag (KotlinFunctionFlags.IsSuspend) && + method.Descriptor.EndsWith ("Lkotlin/coroutines/Continuation;)Ljava/lang/Object;", StringComparison.Ordinal)) + method.KotlinSuspendReturnType = GetSuspendReturnType (metadata.ReturnType); + // Recover the unmangled Kotlin source-level name when the Kotlin // compiler mangled the JVM name for inline-class binary compat // (e.g. JVM name `tint-Rn_QMJI`, Kotlin name `tint`). The generator @@ -429,6 +433,15 @@ static void FixupDefaultArguments (MethodInfo? method, List m.CanHaveStringOverload) || nestedIface.Type.Methods.Any (m => m.Asyncify)) + if (nestedIface.Type.Methods.Any (m => m.CanHaveStringOverload) || nestedIface.Type.Methods.Any (m => m.Asyncify || m.KotlinSuspendReturnType != null)) sibling_types.Add (new InterfaceExtensionsClass (nestedIface.Type, nestedIface.DeclaringType, opt)); } @@ -308,6 +308,9 @@ void AddAbstractMethodDeclaration (GenBase klass, Method method, InterfaceGen if if (method.Asyncify) Methods.Add (new MethodAsyncWrapper (method, opt, klass)); + + if (KotlinSuspendMethodWrapper.ShouldGenerate (method, klass)) + Methods.Add (new KotlinSuspendMethodWrapper (method, opt)); } void AddMethod (GenBase klass, Method method, CodeGenerationOptions opt) @@ -322,6 +325,9 @@ void AddMethod (GenBase klass, Method method, CodeGenerationOptions opt) if (method.Asyncify) Methods.Add (new MethodAsyncWrapper (method, opt, klass)); + + if (KotlinSuspendMethodWrapper.ShouldGenerate (method, klass)) + Methods.Add (new KotlinSuspendMethodWrapper (method, opt)); } void AddProperties (ClassGen klass, CodeGenerationOptions opt) diff --git a/src/generator/SourceWriters/BoundInterface.cs b/src/generator/SourceWriters/BoundInterface.cs index 325e77a683d..9c5558a0d3f 100644 --- a/src/generator/SourceWriters/BoundInterface.cs +++ b/src/generator/SourceWriters/BoundInterface.cs @@ -79,7 +79,7 @@ public BoundInterface (InterfaceGen iface, CodeGenerationOptions opt, CodeGenera return; if (!iface.AssemblyQualifiedName.Contains ('/')) { - if (iface.Methods.Any (m => m.CanHaveStringOverload) || iface.Methods.Any (m => m.Asyncify)) + if (iface.Methods.Any (m => m.CanHaveStringOverload) || iface.Methods.Any (m => m.Asyncify || m.KotlinSuspendReturnType != null)) post_sibling_types.Add (new InterfaceExtensionsClass (iface, null, opt)); } @@ -243,6 +243,9 @@ void AddMethods (InterfaceGen iface, CodeGenerationOptions opt) if (method.Asyncify) Methods.Add (new MethodAsyncWrapper (method, opt, iface)); + + if (method.IsStatic && KotlinSuspendMethodWrapper.ShouldGenerate (method, iface)) + Methods.Add (new KotlinSuspendMethodWrapper (method, opt)); } } diff --git a/src/generator/SourceWriters/InterfaceExtensionsClass.cs b/src/generator/SourceWriters/InterfaceExtensionsClass.cs index 378c7323ad4..2480734ce27 100644 --- a/src/generator/SourceWriters/InterfaceExtensionsClass.cs +++ b/src/generator/SourceWriters/InterfaceExtensionsClass.cs @@ -32,6 +32,9 @@ public InterfaceExtensionsClass (InterfaceGen iface, string declaringTypeName, C if (method.Asyncify) Methods.Add (new MethodExtensionAsyncWrapper (method, opt, iface.FullName)); + + if (KotlinSuspendMethodWrapper.ShouldGenerate (method, iface)) + Methods.Add (new KotlinSuspendMethodWrapper (method, opt, iface.FullName)); } } diff --git a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs new file mode 100644 index 00000000000..05aa7448479 --- /dev/null +++ b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs @@ -0,0 +1,114 @@ +using System; +using System.Linq; +using MonoDroid.Generation; +using Xamarin.SourceWriter; + +namespace generator.SourceWriters +{ + // Exposes a Kotlin `suspend` function as a `Task`-returning `*Async` method. + // The bound method keeps its trailing `Continuation` parameter; + // `Android.Runtime.KotlinCoroutines` supplies that parameter at run time. + public class KotlinSuspendMethodWrapper : MethodWriter + { + const string Runtime = "global::Android.Runtime.KotlinCoroutines"; + + public static bool ShouldGenerate (Method method, GenBase type) => + method.KotlinSuspendReturnType != null && + method.IsValid && + !method.IsOverride && + !method.Asyncify && + method.Parameters.Count > 0 && + !type.ContainsName (method.AdjustedName + "Async"); + + public KotlinSuspendMethodWrapper (Method method, CodeGenerationOptions opt, string selfType = null) + { + Name = method.AdjustedName + "Async"; + IsStatic = method.IsStatic || selfType != null; + + SetVisibility (method.Visibility); + + SourceWriterExtensions.AddSupportedOSPlatform (Attributes, method, opt); + SourceWriterExtensions.AddObsolete (Attributes, method.Deprecated, opt, deprecatedSince: method.DeprecatedSince); + + if (selfType != null) + Parameters.Add (new MethodParameterWriter ("self", new TypeReferenceWriter (selfType)) { IsExtension = true }); + + var parameters = new ParameterList (); + foreach (var p in method.Parameters.Take (method.Parameters.Count - 1)) + parameters.Add (p); + this.AddMethodParameters (parameters, opt); + + var token = parameters.Any (p => opt.GetSafeIdentifier (p.Name) == "cancellationToken") ? "__cancellationToken" : "cancellationToken"; + Parameters.Add (new OptionalParameterWriter (token, "global::System.Threading.CancellationToken", "default")); + + var continuation_type = opt.GetOutputName (method.Parameters [method.Parameters.Count - 1].Type); + var args = parameters.GetCall (opt); + if (args.Length > 0) + args += ", "; + args += $"global::Android.Runtime.Extensions.JavaCast<{continuation_type}> (__continuation)"; + var target = selfType != null ? "self." + method.AdjustedName : method.AdjustedName; + var invoke = $"__continuation => {target} ({args})"; + + var result = GetResultType (method.KotlinSuspendReturnType, opt); + if (result == null) { + ReturnType = new TypeReferenceWriter ("global::System.Threading.Tasks.Task"); + Body.Add ($"return {Runtime}.InvokeAsync ({invoke}, {token});"); + } else { + ReturnType = new TypeReferenceWriter ($"global::System.Threading.Tasks.Task<{result}>"); + Body.Add ($"return {Runtime}.InvokeAsync<{result}> ({invoke}, {token});"); + } + } + + // Maps the Kotlin result type (e.g. `kotlin/Int?`) to a C# type. + // Returns null for `kotlin/Unit`, which becomes a non-generic `Task`. + internal static string GetResultType (string kotlinType, CodeGenerationOptions opt) + { + var nullable = kotlinType.EndsWith ("?", StringComparison.Ordinal); + var name = nullable ? kotlinType.Substring (0, kotlinType.Length - 1) : kotlinType; + + var value_type = name switch { + "kotlin/Boolean" => "bool", + "kotlin/Byte" => "sbyte", + "kotlin/Char" => "char", + "kotlin/Short" => "short", + "kotlin/Int" => "int", + "kotlin/Long" => "long", + "kotlin/Float" => "float", + "kotlin/Double" => "double", + _ => null, + }; + if (value_type != null) + return nullable ? value_type + "?" : value_type; + + if (name == "kotlin/Unit" && !nullable) + return null; + + string reference; + if (name == "kotlin/String") + reference = "string"; + else if (opt.SymbolTable.Lookup (name.Replace ('/', '.')) is GenBase gen) + reference = opt.GetOutputName (gen.FullName); + else + reference = "global::Java.Lang.Object"; + + return nullable ? reference + opt.NullableOperator : reference; + } + + sealed class OptionalParameterWriter : MethodParameterWriter + { + readonly string default_value; + + public OptionalParameterWriter (string name, string type, string defaultValue) + : base (name, new TypeReferenceWriter (type)) + { + default_value = defaultValue; + } + + public override void WriteParameter (CodeWriter writer) + { + base.WriteParameter (writer); + writer.Write (" = " + default_value); + } + } + } +} diff --git a/tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinSuspendTests.cs b/tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinSuspendTests.cs new file mode 100644 index 00000000000..0da76891813 --- /dev/null +++ b/tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinSuspendTests.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using Xamarin.Android.Tools.Bytecode; + +namespace Xamarin.Android.Tools.BytecodeTests +{ + [TestFixture] + public class KotlinSuspendTests : ClassFileFixture + { + [Test] + public void Fixup_SetsKotlinSuspendReturnType () + { + var klass = LoadClassFile ("SuspendFunctions.class"); + KotlinFixups.Fixup (new List { klass }); + + string GetReturnType (string name) => klass.Methods.Single (m => m.Name == name).KotlinSuspendReturnType; + + Assert.AreEqual ("kotlin/Int", GetReturnType ("getInt")); + Assert.AreEqual ("kotlin/String?", GetReturnType ("getNullableString")); + Assert.AreEqual ("kotlin/Unit", GetReturnType ("doWork")); + Assert.AreEqual ("kotlin/Any?", GetReturnType ("echo")); + Assert.IsNull (GetReturnType ("notSuspend")); + } + + [Test] + public void XmlOutput_ContainsKotlinSuspendReturnType () + { + var klass = LoadClassFile ("SuspendFunctions.class"); + KotlinFixups.Fixup (new List { klass }); + + var xml = new XmlClassDeclarationBuilder (klass).ToXElement (); + var method = xml.Elements ("method").Single (m => (string) m.Attribute ("name") == "getInt"); + + Assert.AreEqual ("kotlin/Int", (string) method.Attribute ("kotlin-suspend-return-type")); + } + } +} diff --git a/tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj b/tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj index 3c6a20e2bd5..64a40d675de 100644 --- a/tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj +++ b/tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj @@ -30,6 +30,7 @@ + diff --git a/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle.targets b/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle.targets index f499df8fbc6..7cd0df2bb6b 100644 --- a/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle.targets +++ b/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle.targets @@ -21,6 +21,7 @@ + diff --git a/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/SuspendFunctions.kt b/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/SuspendFunctions.kt new file mode 100644 index 00000000000..df2dc483f56 --- /dev/null +++ b/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/SuspendFunctions.kt @@ -0,0 +1,13 @@ +package xat.bytecode.tests + +import kotlin.coroutines.Continuation + +class SuspendFunctions { + suspend fun getInt(value: Int): Int = value + suspend fun getNullableString(): String? = null + suspend fun doWork() { } + suspend fun echo(value: T): T = value + + // Not `suspend`: it only looks like the suspend ABI. + fun notSuspend(continuation: Continuation): Any? = null +} diff --git a/tests/generator-Tests/Unit-Tests/KotlinInlineClassEndToEndTests.cs b/tests/generator-Tests/Unit-Tests/KotlinInlineClassEndToEndTests.cs index 47571b4e94e..0d2fb3f1b9e 100644 --- a/tests/generator-Tests/Unit-Tests/KotlinInlineClassEndToEndTests.cs +++ b/tests/generator-Tests/Unit-Tests/KotlinInlineClassEndToEndTests.cs @@ -257,7 +257,7 @@ internal static string BuildApiXmlFromKotlinFixture (params string [] resources) return adjusted.ToString (); } - static ClassFile LoadClassFile (string resource) + internal static ClassFile LoadClassFile (string resource) { var assembly = typeof (KotlinInlineClassEndToEndTests).Assembly; var name = assembly.GetManifestResourceNames () diff --git a/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs b/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs new file mode 100644 index 00000000000..187cb57a532 --- /dev/null +++ b/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; +using System.IO; +using System.Xml.Linq; +using NUnit.Framework; +using Xamarin.Android.Tools.Bytecode; + +namespace generatortests +{ + // Drives the real Kotlin `SuspendFunctions` class (compiled by + // tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/) through + // class-parse and the generator, and checks the `Task` wrappers. + [TestFixture] + public class KotlinSuspendTests + { + const string Invoke = "global::Android.Runtime.KotlinCoroutines.InvokeAsync"; + const string Continuation = "global::Android.Runtime.Extensions.JavaCast (__continuation)"; + const string Token = "global::System.Threading.CancellationToken cancellationToken = default"; + + [Test] + public void GeneratesTaskWrappersForSuspendFunctions () + { + var output = KotlinInlineClassEndToEndTests.GenerateCSharp (BuildApiXml (), out _); + + // The bound method that takes the Continuation is unchanged. + StringAssert.Contains ("public Java.Lang.Object GetInt (int value, Kotlin.Coroutines.IContinuation _completion)", output); + + StringAssert.Contains ($"public global::System.Threading.Tasks.Task GetIntAsync (int value, {Token})", output); + StringAssert.Contains ($"return {Invoke} (__continuation => GetInt (value, {Continuation}), cancellationToken);", output); + + StringAssert.Contains ($"public global::System.Threading.Tasks.Task GetNullableStringAsync ({Token})", output); + StringAssert.Contains ($"return {Invoke} (__continuation => GetNullableString ({Continuation}), cancellationToken);", output); + + StringAssert.Contains ($"public global::System.Threading.Tasks.Task DoWorkAsync ({Token})", output); + StringAssert.Contains ($"return {Invoke} (__continuation => DoWork ({Continuation}), cancellationToken);", output); + + // A type parameter result is not inferred. + StringAssert.Contains ("public global::System.Threading.Tasks.Task EchoAsync (Java.Lang.Object value, ", output); + + StringAssert.DoesNotContain ("NotSuspendAsync", output); + } + + static string BuildApiXml () + { + var classes = new List { KotlinInlineClassEndToEndTests.LoadClassFile ("SuspendFunctions.class") }; + KotlinFixups.Fixup (classes); + + var classPath = new ClassPath { ApiSource = "class-parse" }; + foreach (var c in classes) + classPath.Add (c); + + var sw = new StringWriter (); + classPath.SaveXmlDescription (sw); + + var doc = XDocument.Parse (sw.ToString ()); + doc.Root.AddFirst (XElement.Parse ( + "" + + "" + + "")); + doc.Root.AddFirst (XElement.Parse ( + "" + + "" + + "")); + return doc.ToString (); + } + } +} diff --git a/tests/generator-Tests/generator-Tests.csproj b/tests/generator-Tests/generator-Tests.csproj index 5132b5511de..1ef10f586b7 100644 --- a/tests/generator-Tests/generator-Tests.csproj +++ b/tests/generator-Tests/generator-Tests.csproj @@ -46,6 +46,7 @@ + From 3d7eacedf44ba55426f247f946791bf41e1fe59f Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 16 Nov 2026 09:57:10 -0600 Subject: [PATCH 02/13] [Mono.Android] Fix KotlinCoroutines build; keep Kotlin members for R8; 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> --- .../Android.Runtime/KotlinCoroutines.cs | 8 +- .../Resources/proguard_typemap.cfg | 7 + .../Resources/proguard_typemap_coreclr.cfg | 7 + .../Resources/proguard_xamarin.cfg | 8 ++ .../Tests/KotlinSuspendTests.cs | 126 ++++++++++++++++++ 5 files changed, 153 insertions(+), 3 deletions(-) create mode 100644 tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs diff --git a/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs b/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs index 49804f43fa6..b31c2493c6a 100644 --- a/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs +++ b/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs @@ -111,7 +111,8 @@ void Cancel () return; } // Kotlin resumes the continuation with a CancellationException. - types.CancelJob.Invoke (job, new Java.Util.Concurrent.CancellationException ("The .NET CancellationToken was canceled.")); + // Job.cancel(cause: CancellationException?) with no cause. + types.CancelJob.Invoke (job, new Java.Lang.Object [1]); } public Java.Lang.Object? Invoke (Java.Lang.Object? proxy, Method? method, Java.Lang.Object []? args) @@ -140,12 +141,13 @@ void Resume (Java.Lang.Object? value) SetResult (value); return; } - if (types.FailureException.Get (value) is not Throwable throwable) { + if (types.FailureException.Get (value) is not Java.Lang.Object throwable) { SetException (new InvalidOperationException ("Kotlin returned a failure without an exception.")); return; } var reference = throwable.PeerReference; - SetException (JniEnvironment.Runtime.GetExceptionForThrowable (ref reference, JniObjectReferenceOptions.Copy) ?? throwable); + SetException (JniEnvironment.Runtime.GetExceptionForThrowable (ref reference, JniObjectReferenceOptions.Copy) ?? + new InvalidOperationException ("Kotlin returned an invalid exception.")); } } diff --git a/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap.cfg b/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap.cfg index 725f8454f46..b6be648e511 100644 --- a/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap.cfg +++ b/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap.cfg @@ -21,6 +21,13 @@ # Loaded by name from managed code. -keep class net.dot.android.ApplicationRegistration { *; } -keep class net.dot.android.crypto.** { *; (...); } +# Android.Runtime.KotlinCoroutines finds these Kotlin members by name. +-keep interface kotlin.coroutines.Continuation { *; } +-keep class kotlin.coroutines.EmptyCoroutineContext { public static ** INSTANCE; } +-keep enum kotlin.coroutines.intrinsics.CoroutineSingletons { public static ** COROUTINE_SUSPENDED; } +-keep class kotlin.Result$Failure { java.lang.Throwable exception; } +-keep class kotlinx.coroutines.JobKt { public static ** Job(kotlinx.coroutines.Job); } +-keep interface kotlinx.coroutines.Job { void cancel(java.util.concurrent.CancellationException); } # Native hosts resolve these package-private fields by name during startup. -keepclassmembers class mono.android.Runtime { static java.lang.Class *; diff --git a/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap_coreclr.cfg b/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap_coreclr.cfg index aeaafda0687..2bd8ff0c1b5 100644 --- a/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap_coreclr.cfg +++ b/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap_coreclr.cfg @@ -11,6 +11,13 @@ -keep class mono.android.GCUserPeer { *; } -keep class net.dot.android.ApplicationRegistration { *; } -keep class net.dot.android.crypto.** { *; (...); } +# Android.Runtime.KotlinCoroutines finds these Kotlin members by name. +-keep interface kotlin.coroutines.Continuation { *; } +-keep class kotlin.coroutines.EmptyCoroutineContext { public static ** INSTANCE; } +-keep enum kotlin.coroutines.intrinsics.CoroutineSingletons { public static ** COROUTINE_SUSPENDED; } +-keep class kotlin.Result$Failure { java.lang.Throwable exception; } +-keep class kotlinx.coroutines.JobKt { public static ** Job(kotlinx.coroutines.Job); } +-keep interface kotlinx.coroutines.Job { void cancel(java.util.concurrent.CancellationException); } # Managed interface proxy selection observes Class.getInterfaces(). -keep,allowshrinking class * implements ** diff --git a/src/Xamarin.Android.Build.Tasks/Resources/proguard_xamarin.cfg b/src/Xamarin.Android.Build.Tasks/Resources/proguard_xamarin.cfg index 4f9bf7748e6..6051f1fba1c 100644 --- a/src/Xamarin.Android.Build.Tasks/Resources/proguard_xamarin.cfg +++ b/src/Xamarin.Android.Build.Tasks/Resources/proguard_xamarin.cfg @@ -24,6 +24,14 @@ -keep class net.dot.android.ApplicationRegistration { *; } -keep class net.dot.android.crypto.** { *; (...); } +# Android.Runtime.KotlinCoroutines finds these Kotlin members by name. +-keep interface kotlin.coroutines.Continuation { *; } +-keep class kotlin.coroutines.EmptyCoroutineContext { public static ** INSTANCE; } +-keep enum kotlin.coroutines.intrinsics.CoroutineSingletons { public static ** COROUTINE_SUSPENDED; } +-keep class kotlin.Result$Failure { java.lang.Throwable exception; } +-keep class kotlinx.coroutines.JobKt { public static ** Job(kotlinx.coroutines.Job); } +-keep interface kotlinx.coroutines.Job { void cancel(java.util.concurrent.CancellationException); } + # Android's template misses fluent setters... -keepclassmembers class * extends android.view.View { *** set*(...); diff --git a/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs b/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs new file mode 100644 index 00000000000..757c2da2535 --- /dev/null +++ b/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs @@ -0,0 +1,126 @@ +using System.IO; +using NUnit.Framework; +using Xamarin.Android.Tasks; +using Xamarin.ProjectTools; + +namespace Xamarin.Android.Build.Tests +{ + [TestFixture] + [Category ("UsesDevice")] + public class KotlinSuspendTests : DeviceTest + { + // Binds a Gradle module with Kotlin `suspend` functions and awaits the generated `*Async` methods. + [Test] + public void SuspendFunctionsAsTasks ([Values (false, true)] bool isRelease) + { + const string Expected = "KotlinSuspend: sum=5 greeting=Hello, Kotlin nothing=True failure=boom canceled=True"; + + var gradleDir = Path.Combine (Root, "temp", "gradle", TestName); + if (Directory.Exists (gradleDir)) + Directory.Delete (gradleDir, recursive: true); + + var module = new AndroidGradleModule (Path.Combine (gradleDir, "SuspendModule")) { + PackageName = "com.example.suspendtest", + JavaSources = { + new AndroidItem.AndroidJavaSource ("SuspendFunctions.kt") { + TextContent = () => """ +package com.example.suspendtest + +import kotlin.coroutines.resume +import kotlin.coroutines.suspendCoroutine +import kotlinx.coroutines.delay + +class SuspendFunctions { + suspend fun add(a: Int, b: Int): Int = suspendCoroutine { c -> Thread { c.resume(a + b) }.start() } + suspend fun greet(name: String): String = "Hello, $name" + suspend fun nothing(): String? = null + suspend fun fail(message: String): Int = suspendCoroutine { c -> + Thread { c.resumeWith(Result.failure(IllegalStateException(message))) }.start() + } + suspend fun waitForCancel() = delay(Long.MAX_VALUE) +} +""", + }, + }, + }; + module.BuildGradleFileContent = $$""" +plugins { + id("com.android.library") +} +android { + namespace = "com.example.suspendtest" + compileSdk = {{module.CompileSdk}} + defaultConfig { + minSdk = {{module.MinSdk}} + } +} +dependencies { + compileOnly("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2") +} +"""; + var gradleProject = new AndroidGradleProject (gradleDir) { + Modules = { module }, + }; + gradleProject.Create (); + + var proj = new XamarinAndroidApplicationProject { + IsRelease = isRelease, + PackageReferences = { + new Package { Id = "Xamarin.KotlinX.Coroutines.Core", Version = "1.11.0.1" }, + }, + OtherBuildItems = { + new BuildItem (KnownProperties.AndroidGradleProject, gradleProject.BuildFilePath) { + Metadata = { + { "ModuleName", module.Name }, + { "Configuration", "Release" }, + { "Bind", "true" }, + }, + }, + }, + }; + proj.SetRuntime (AndroidRuntime.CoreCLR); + proj.SetRuntimeIdentifiers (new [] { DeviceAbi }); + proj.MainActivity = proj.DefaultMainActivity.Replace ("//${AFTER_ONCREATE}", """ + RunKotlin (); + } + + async void RunKotlin () + { + try { + var kotlin = new Com.Example.Suspendtest.SuspendFunctions (); + int sum = await kotlin.AddAsync (2, 3); + string greeting = await kotlin.GreetAsync ("Kotlin"); + string nothing = await kotlin.NothingAsync (); + string failure = ""; + try { + await kotlin.FailAsync ("boom"); + } catch (Java.Lang.IllegalStateException e) { + failure = e.Message; + } + bool canceled = false; + using var cts = new System.Threading.CancellationTokenSource (100); + try { + await kotlin.WaitForCancelAsync (cts.Token); + } catch (System.OperationCanceledException) { + canceled = true; + } + Android.Util.Log.Info ("KotlinSuspend", $"KotlinSuspend: sum={sum} greeting={greeting} nothing={nothing == null} failure={failure} canceled={canceled}"); + } catch (System.Exception e) { + Android.Util.Log.Error ("KotlinSuspend", $"KotlinSuspend: FAILED {e}"); + } +"""); + + using var builder = CreateApkBuilder (); + Assert.IsTrue (builder.Install (proj), "Install should have succeeded."); + ClearAdbLogcat (); + RunProjectAndAssert (proj, builder); + string failed = null; + Assert.IsTrue (MonitorAdbLogcat (line => { + if (line.Contains ("KotlinSuspend: FAILED")) + failed = line; + return line.Contains (Expected) || failed != null; + }, Path.Combine (Root, builder.ProjectDirectory, "logcat.log"), 60), $"Output did not contain '{Expected}'."); + Assert.IsNull (failed); + } + } +} From d02511e254815794cf140bd3396e39b20d328c66 Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 16 Nov 2026 10:33:15 -0600 Subject: [PATCH 03/13] Simplify Kotlin suspend wrappers; address review findings * 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> --- .../Android.Runtime/KotlinCoroutines.cs | 43 +++++++------------ .../Models/MethodParameterWriter.cs | 4 ++ src/generator/SourceWriters/BoundClass.cs | 2 +- src/generator/SourceWriters/BoundInterface.cs | 2 +- .../KotlinSuspendMethodWrapper.cs | 37 ++++------------ .../Tests/KotlinSuspendTests.cs | 6 ++- .../KotlinSuspendTests.cs | 12 ------ 7 files changed, 35 insertions(+), 71 deletions(-) diff --git a/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs b/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs index b31c2493c6a..22154f36c79 100644 --- a/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs +++ b/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs @@ -18,8 +18,7 @@ namespace Android.Runtime { /// /// The kotlin.coroutines.Continuation is a java.lang.reflect.Proxy, so this type has no /// build-time dependency on Kotlin. When kotlinx.coroutines is in the app, the continuation context - /// is a kotlinx.coroutines.Job, and cancellation of the token cancels that job. Without - /// kotlinx.coroutines, cancellation of the token cancels only the returned task. + /// is a kotlinx.coroutines.Job, and cancellation of the token also cancels that job. /// public static class KotlinCoroutines { const DynamicallyAccessedMemberTypes Constructors = DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors; @@ -27,10 +26,8 @@ public static class KotlinCoroutines { /// Runs a Kotlin suspend function that returns Unit. /// Calls the bound method with the supplied kotlin.coroutines.Continuation. /// Cancels the operation. - public static Task InvokeAsync (Func invoke, CancellationToken cancellationToken = default) - { - return InvokeCoreAsync (invoke, cancellationToken); - } + public static Task InvokeAsync (Func invoke, CancellationToken cancellationToken = default) => + InvokeCoreAsync (invoke, cancellationToken); /// Runs a Kotlin suspend function and converts its result to . /// Calls the bound method with the supplied kotlin.coroutines.Continuation. @@ -92,7 +89,7 @@ public static bool IsSuspended (Java.Lang.Object? value) => public void SetResult (Java.Lang.Object? value) { completion.TrySetResult (value); - registration.Dispose (); + registration.Unregister (); } public void SetException (Exception e) @@ -101,18 +98,15 @@ public void SetException (Exception e) completion.TrySetCanceled (cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken (true)); else completion.TrySetException (e); - registration.Dispose (); + registration.Unregister (); } void Cancel () { - if (job == null || types.CancelJob == null) { - completion.TrySetCanceled (cancellationToken); - return; - } - // Kotlin resumes the continuation with a CancellationException. - // Job.cancel(cause: CancellationException?) with no cause. - types.CancelJob.Invoke (job, new Java.Lang.Object [1]); + // With kotlinx.coroutines, also cancel the Kotlin work. Not all suspend functions observe the Job. + if (job != null) + types.CancelJob?.Invoke (job, new Java.Lang.Object [1]); + completion.TrySetCanceled (cancellationToken); } public Java.Lang.Object? Invoke (Java.Lang.Object? proxy, Method? method, Java.Lang.Object []? args) @@ -141,13 +135,9 @@ void Resume (Java.Lang.Object? value) SetResult (value); return; } - if (types.FailureException.Get (value) is not Java.Lang.Object throwable) { - SetException (new InvalidOperationException ("Kotlin returned a failure without an exception.")); - return; - } - var reference = throwable.PeerReference; + var reference = types.FailureException.Get (value)?.PeerReference ?? default; SetException (JniEnvironment.Runtime.GetExceptionForThrowable (ref reference, JniObjectReferenceOptions.Copy) ?? - new InvalidOperationException ("Kotlin returned an invalid exception.")); + new InvalidOperationException ("Kotlin returned an invalid failure.")); } } @@ -171,14 +161,13 @@ public KotlinTypes () Failure = Class.ForName ("kotlin.Result$Failure", false, Loader); FailureException = Failure.GetField ("exception"); - Class job; try { - job = Class.ForName ("kotlinx.coroutines.Job", false, Loader); - } catch (ClassNotFoundException) { - return; + var job = Class.ForName ("kotlinx.coroutines.Job", false, Loader); + CreateJob = Class.ForName ("kotlinx.coroutines.JobKt", false, Loader).GetMethod ("Job", job); + CancelJob = job.GetMethod ("cancel", Class.FromType (typeof (Java.Util.Concurrent.CancellationException))); + } catch (ReflectiveOperationException) { + CreateJob = CancelJob = null; } - CreateJob = Class.ForName ("kotlinx.coroutines.JobKt", false, Loader).GetMethod ("Job", job); - CancelJob = job.GetMethod ("cancel", Class.FromType (typeof (Java.Util.Concurrent.CancellationException))); } Java.Lang.Object GetStaticField (string className, string fieldName) => diff --git a/src/Xamarin.SourceWriter/Models/MethodParameterWriter.cs b/src/Xamarin.SourceWriter/Models/MethodParameterWriter.cs index e8f2571ef9c..dfa1517e168 100644 --- a/src/Xamarin.SourceWriter/Models/MethodParameterWriter.cs +++ b/src/Xamarin.SourceWriter/Models/MethodParameterWriter.cs @@ -10,6 +10,7 @@ public class MethodParameterWriter public List Attributes { get; } = new List (); public string Name { get; set; } public bool IsExtension { get; set; } + public string DefaultValue { get; set; } public MethodParameterWriter (string name, TypeReferenceWriter type) { @@ -26,6 +27,9 @@ public virtual void WriteParameter (CodeWriter writer) Type.WriteTypeReference (writer); writer.Write (Name); + + if (DefaultValue != null) + writer.Write (" = " + DefaultValue); } public virtual void WriteAttributes (CodeWriter writer) diff --git a/src/generator/SourceWriters/BoundClass.cs b/src/generator/SourceWriters/BoundClass.cs index eda7036c061..dc498781ea8 100644 --- a/src/generator/SourceWriters/BoundClass.cs +++ b/src/generator/SourceWriters/BoundClass.cs @@ -90,7 +90,7 @@ public BoundClass (ClassGen klass, CodeGenerationOptions opt, CodeGeneratorConte // Sibling classes if (!klass.AssemblyQualifiedName.Contains ('/')) { foreach (InterfaceExtensionInfo nestedIface in klass.GetNestedInterfaceTypes ()) - if (nestedIface.Type.Methods.Any (m => m.CanHaveStringOverload) || nestedIface.Type.Methods.Any (m => m.Asyncify || m.KotlinSuspendReturnType != null)) + if (nestedIface.Type.Methods.Any (m => m.CanHaveStringOverload) || nestedIface.Type.Methods.Any (m => m.Asyncify || (!m.IsStatic && m.KotlinSuspendReturnType != null))) sibling_types.Add (new InterfaceExtensionsClass (nestedIface.Type, nestedIface.DeclaringType, opt)); } diff --git a/src/generator/SourceWriters/BoundInterface.cs b/src/generator/SourceWriters/BoundInterface.cs index 9c5558a0d3f..395d6ca9a30 100644 --- a/src/generator/SourceWriters/BoundInterface.cs +++ b/src/generator/SourceWriters/BoundInterface.cs @@ -79,7 +79,7 @@ public BoundInterface (InterfaceGen iface, CodeGenerationOptions opt, CodeGenera return; if (!iface.AssemblyQualifiedName.Contains ('/')) { - if (iface.Methods.Any (m => m.CanHaveStringOverload) || iface.Methods.Any (m => m.Asyncify || m.KotlinSuspendReturnType != null)) + if (iface.Methods.Any (m => m.CanHaveStringOverload) || iface.Methods.Any (m => m.Asyncify || (!m.IsStatic && m.KotlinSuspendReturnType != null))) post_sibling_types.Add (new InterfaceExtensionsClass (iface, null, opt)); } diff --git a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs index 05aa7448479..da4e05c2ddc 100644 --- a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs +++ b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs @@ -16,8 +16,9 @@ public static bool ShouldGenerate (Method method, GenBase type) => method.KotlinSuspendReturnType != null && method.IsValid && !method.IsOverride && - !method.Asyncify && + string.IsNullOrEmpty (method.ExplicitInterface) && method.Parameters.Count > 0 && + !method.Asyncify && !type.ContainsName (method.AdjustedName + "Async"); public KotlinSuspendMethodWrapper (Method method, CodeGenerationOptions opt, string selfType = null) @@ -39,7 +40,7 @@ public KotlinSuspendMethodWrapper (Method method, CodeGenerationOptions opt, str this.AddMethodParameters (parameters, opt); var token = parameters.Any (p => opt.GetSafeIdentifier (p.Name) == "cancellationToken") ? "__cancellationToken" : "cancellationToken"; - Parameters.Add (new OptionalParameterWriter (token, "global::System.Threading.CancellationToken", "default")); + Parameters.Add (new MethodParameterWriter (token, new TypeReferenceWriter ("global::System.Threading.CancellationToken")) { DefaultValue = "default" }); var continuation_type = opt.GetOutputName (method.Parameters [method.Parameters.Count - 1].Type); var args = parameters.GetCall (opt); @@ -50,18 +51,14 @@ public KotlinSuspendMethodWrapper (Method method, CodeGenerationOptions opt, str var invoke = $"__continuation => {target} ({args})"; var result = GetResultType (method.KotlinSuspendReturnType, opt); - if (result == null) { - ReturnType = new TypeReferenceWriter ("global::System.Threading.Tasks.Task"); - Body.Add ($"return {Runtime}.InvokeAsync ({invoke}, {token});"); - } else { - ReturnType = new TypeReferenceWriter ($"global::System.Threading.Tasks.Task<{result}>"); - Body.Add ($"return {Runtime}.InvokeAsync<{result}> ({invoke}, {token});"); - } + var generic = result == null ? "" : $"<{result}>"; + ReturnType = new TypeReferenceWriter ("global::System.Threading.Tasks.Task" + generic); + Body.Add ($"return {Runtime}.InvokeAsync{generic} ({invoke}, {token});"); } // Maps the Kotlin result type (e.g. `kotlin/Int?`) to a C# type. // Returns null for `kotlin/Unit`, which becomes a non-generic `Task`. - internal static string GetResultType (string kotlinType, CodeGenerationOptions opt) + static string GetResultType (string kotlinType, CodeGenerationOptions opt) { var nullable = kotlinType.EndsWith ("?", StringComparison.Ordinal); var name = nullable ? kotlinType.Substring (0, kotlinType.Length - 1) : kotlinType; @@ -86,29 +83,13 @@ internal static string GetResultType (string kotlinType, CodeGenerationOptions o string reference; if (name == "kotlin/String") reference = "string"; - else if (opt.SymbolTable.Lookup (name.Replace ('/', '.')) is GenBase gen) + // Inline classes are boxed in this position; invalid or non-public types are not generated. + else if (opt.SymbolTable.Lookup (name.Replace ('/', '.')) is GenBase { IsValid: true, RawVisibility: "public" } gen && gen is not ClassGen { IsKotlinInlineClass: true }) reference = opt.GetOutputName (gen.FullName); else reference = "global::Java.Lang.Object"; return nullable ? reference + opt.NullableOperator : reference; } - - sealed class OptionalParameterWriter : MethodParameterWriter - { - readonly string default_value; - - public OptionalParameterWriter (string name, string type, string defaultValue) - : base (name, new TypeReferenceWriter (type)) - { - default_value = defaultValue; - } - - public override void WriteParameter (CodeWriter writer) - { - base.WriteParameter (writer); - writer.Write (" = " + default_value); - } - } } } diff --git a/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs b/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs index 757c2da2535..70edd8ea8f5 100644 --- a/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs +++ b/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs @@ -10,8 +10,9 @@ namespace Xamarin.Android.Build.Tests public class KotlinSuspendTests : DeviceTest { // Binds a Gradle module with Kotlin `suspend` functions and awaits the generated `*Async` methods. + // R8 checks the keep rules for the Kotlin members that KotlinCoroutines finds by name. [Test] - public void SuspendFunctionsAsTasks ([Values (false, true)] bool isRelease) + public void SuspendFunctionsAsTasks () { const string Expected = "KotlinSuspend: sum=5 greeting=Hello, Kotlin nothing=True failure=boom canceled=True"; @@ -64,7 +65,7 @@ namespace = "com.example.suspendtest" gradleProject.Create (); var proj = new XamarinAndroidApplicationProject { - IsRelease = isRelease, + IsRelease = true, PackageReferences = { new Package { Id = "Xamarin.KotlinX.Coroutines.Core", Version = "1.11.0.1" }, }, @@ -78,6 +79,7 @@ namespace = "com.example.suspendtest" }, }, }; + proj.SetProperty ("AndroidLinkTool", "r8"); proj.SetRuntime (AndroidRuntime.CoreCLR); proj.SetRuntimeIdentifiers (new [] { DeviceAbi }); proj.MainActivity = proj.DefaultMainActivity.Replace ("//${AFTER_ONCREATE}", """ diff --git a/tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinSuspendTests.cs b/tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinSuspendTests.cs index 0da76891813..bc26c0dfabe 100644 --- a/tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinSuspendTests.cs +++ b/tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinSuspendTests.cs @@ -22,17 +22,5 @@ public void Fixup_SetsKotlinSuspendReturnType () Assert.AreEqual ("kotlin/Any?", GetReturnType ("echo")); Assert.IsNull (GetReturnType ("notSuspend")); } - - [Test] - public void XmlOutput_ContainsKotlinSuspendReturnType () - { - var klass = LoadClassFile ("SuspendFunctions.class"); - KotlinFixups.Fixup (new List { klass }); - - var xml = new XmlClassDeclarationBuilder (klass).ToXElement (); - var method = xml.Elements ("method").Single (m => (string) m.Attribute ("name") == "getInt"); - - Assert.AreEqual ("kotlin/Int", (string) method.Attribute ("kotlin-suspend-return-type")); - } } } From 4a92bd80d1de6696b4881b2ffa8ff88f904c1229 Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 16 Nov 2026 11:21:36 -0600 Subject: [PATCH 04/13] [tests] Bind androidx.datastore and check its suspend functions as Task methods datastore-preferences-core-jvm has real Kotlin suspend APIs. The test binds it with 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> --- .../BindingBuildTest.cs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs index 5cd02cbcbe1..67c1bb721f2 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs @@ -1272,6 +1272,44 @@ static BuildItem CreateMavenLibrary (string artifact) } } + [TestMethod] + [DoNotParallelize] // Shares the Maven cache with the other AndroidMavenLibrary tests + public void KotlinSuspendFunctionsAsTasks () + { + // androidx.datastore has real Kotlin `suspend` APIs, such as `PreferencesKt.edit`. + // The NuGet packages for its dependencies are at 1.2.1. + var datastore = new BuildItem ("AndroidMavenLibrary", "androidx.datastore:datastore-preferences-core-jvm"); + datastore.Metadata.Add ("Version", "1.2.1"); + datastore.Metadata.Add ("Repository", TestEnvironment.DotNetPublicMaven); + + var proj = new XamarinAndroidBindingProject { + Jars = { datastore }, + PackageReferences = { + new Package { Id = "Xamarin.AndroidX.DataStore.Core.Jvm", Version = "1.2.1.1" }, + new Package { Id = "Xamarin.AndroidX.DataStore.Core.OkIO.Jvm", Version = "1.2.1.1" }, + new Package { Id = "Xamarin.AndroidX.DataStore.Preferences.Proto", Version = "1.2.1.1" }, + new Package { Id = "Square.OkIO.JVM", Version = "3.17.0.1" }, + new Package { Id = "Xamarin.Kotlin.StdLib", Version = "2.4.0.1" }, + }, + // The serializers need the generic-interface fixes from dotnet/android-libraries; this test does not use them. + MetadataXml = """ + + + + + """, + }; + + using var b = CreateDllBuilder (); + Assert.IsTrue (b.Build (proj), "Build should have succeeded."); + + var cs_file = b.Output.GetIntermediaryPath (Path.Combine ("generated", "src", "Androidx.Datastore.Preferences.Core.PreferencesKt.cs")); + Assert.IsTrue (File.Exists (cs_file)); + var code = File.ReadAllText (cs_file); + Assert.Contains ("public static global::System.Threading.Tasks.Task EditAsync (global::AndroidX.DataStore.Core.IDataStore obj, global::Kotlin.Jvm.Functions.IFunction2 transform, global::System.Threading.CancellationToken cancellationToken = default)", code); + Assert.Contains ("global::Android.Runtime.KotlinCoroutines.InvokeAsync (__continuation => Edit (", code); + } + [TestMethod] [DoNotParallelize] // All tests download androidx.core:core into the same Maven cache public void AndroidMavenLibrary_FailsDueToUnverifiedDependency () From 2e65ebdb71f3ca61a79fb707242abe80e79f27fc Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 23 Nov 2026 11:00:57 -0600 Subject: [PATCH 05/13] [Mono.Android] Type Kotlin suspend results correctly; address review findings KotlinCoroutines.InvokeAsync hid a nullability mismatch with #pragma warning disable CS8603: JavaConvert.FromJavaObject returns T?, and C# cannot tell string from string? at run time. Split the API: * InvokeAsync where T : notnull returns Task, and throws when Kotlin breaks its non-null contract. * InvokeNullableAsync returns Task. The generator calls InvokeNullableAsync when the Kotlin result type is nullable, so NRT bindings now get Task 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> --- .../Android.Runtime/KotlinCoroutines.cs | 39 +++++++++++----- .../PublicAPI/API-35/PublicAPI.Unshipped.txt | 1 + .../API-36.1/PublicAPI.Unshipped.txt | 1 + .../PublicAPI/API-36/PublicAPI.Unshipped.txt | 1 + .../API-37.1/PublicAPI.Unshipped.txt | 1 + .../API-37.2/PublicAPI.Unshipped.txt | 1 + .../PublicAPI/API-37/PublicAPI.Unshipped.txt | 1 + .../Kotlin/KotlinFixups.cs | 4 +- src/Xamarin.Android.Tools.Bytecode/Methods.cs | 4 +- src/generator/SourceWriters/BoundClass.cs | 2 +- src/generator/SourceWriters/BoundInterface.cs | 2 +- .../KotlinSuspendMethodWrapper.cs | 8 ++-- .../src/main/kotlin/SuspendFunctions.kt | 1 + .../KotlinInlineClassEndToEndTests.cs | 10 ++++- .../Unit-Tests/KotlinSuspendTests.cs | 45 ++++++------------- 15 files changed, 67 insertions(+), 54 deletions(-) diff --git a/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs b/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs index 22154f36c79..b30a84ad8e0 100644 --- a/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs +++ b/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs @@ -29,19 +29,31 @@ public static class KotlinCoroutines { public static Task InvokeAsync (Func invoke, CancellationToken cancellationToken = default) => InvokeCoreAsync (invoke, cancellationToken); - /// Runs a Kotlin suspend function and converts its result to . + /// Runs a Kotlin suspend function with a non-null result and converts the result to . /// Calls the bound method with the supplied kotlin.coroutines.Continuation. /// Cancels the operation. public static async Task InvokeAsync< [DynamicallyAccessedMembers (Constructors)] T + > (Func invoke, CancellationToken cancellationToken = default) + where T : notnull + { + var value = await InvokeCoreAsync (invoke, cancellationToken).ConfigureAwait (false); + return JavaConvert.FromJavaObject (value) ?? + throw new InvalidOperationException ("Kotlin returned null for a non-null result."); + } + + /// Runs a Kotlin suspend function with a nullable result and converts the result to . + /// For a nullable value type, use a type argument, for example int?. + /// Calls the bound method with the supplied kotlin.coroutines.Continuation. + /// Cancels the operation. + public static async Task InvokeNullableAsync< + [DynamicallyAccessedMembers (Constructors)] + T > (Func invoke, CancellationToken cancellationToken = default) { var value = await InvokeCoreAsync (invoke, cancellationToken).ConfigureAwait (false); - // Kotlin metadata makes T nullable when the result can be null. -#pragma warning disable CS8603 return JavaConvert.FromJavaObject (value); -#pragma warning restore CS8603 } static Task InvokeCoreAsync (Func invoke, CancellationToken cancellationToken) @@ -104,9 +116,12 @@ public void SetException (Exception e) void Cancel () { // With kotlinx.coroutines, also cancel the Kotlin work. Not all suspend functions observe the Job. - if (job != null) - types.CancelJob?.Invoke (job, new Java.Lang.Object [1]); - completion.TrySetCanceled (cancellationToken); + try { + if (job != null) + types.CancelJob?.Invoke (job, new Java.Lang.Object [1]); + } finally { + completion.TrySetCanceled (cancellationToken); + } } public Java.Lang.Object? Invoke (Java.Lang.Object? proxy, Method? method, Java.Lang.Object []? args) @@ -135,9 +150,11 @@ void Resume (Java.Lang.Object? value) SetResult (value); return; } - var reference = types.FailureException.Get (value)?.PeerReference ?? default; - SetException (JniEnvironment.Runtime.GetExceptionForThrowable (ref reference, JniObjectReferenceOptions.Copy) ?? - new InvalidOperationException ("Kotlin returned an invalid failure.")); + var throwable = types.FailureException.Get (value); + var reference = throwable?.PeerReference ?? default; + var exception = JniEnvironment.Runtime.GetExceptionForThrowable (ref reference, JniObjectReferenceOptions.Copy); + GC.KeepAlive (throwable); + SetException (exception ?? new InvalidOperationException ("Kotlin returned an invalid failure.")); } } @@ -165,7 +182,7 @@ public KotlinTypes () var job = Class.ForName ("kotlinx.coroutines.Job", false, Loader); CreateJob = Class.ForName ("kotlinx.coroutines.JobKt", false, Loader).GetMethod ("Job", job); CancelJob = job.GetMethod ("cancel", Class.FromType (typeof (Java.Util.Concurrent.CancellationException))); - } catch (ReflectiveOperationException) { + } catch (Throwable) { CreateJob = CancelJob = null; } } diff --git a/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt index 68f7697fee1..8587014d5e2 100644 --- a/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt @@ -6051,3 +6051,4 @@ static Java.Interop.JniMarshalTyped.Invoke_X(nint jnienv, nint self, dele Android.Runtime.KotlinCoroutines static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.InvokeNullableAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt index 0cc8891ecc7..12984f2331a 100644 --- a/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt @@ -6119,3 +6119,4 @@ static Java.Interop.JniMarshalTyped.Invoke_X(nint jnienv, nint self, dele Android.Runtime.KotlinCoroutines static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.InvokeNullableAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt index d24480b0fc6..0306625aad6 100644 --- a/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt @@ -10392,3 +10392,4 @@ virtual Java.Util.IdentityHashMap.Replace(Java.Lang.Object? key, Java.Lang.Objec Android.Runtime.KotlinCoroutines static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.InvokeNullableAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt index 62491a0b2dc..a5fa46297a3 100644 --- a/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt @@ -11706,3 +11706,4 @@ static Android.Runtime.JNIEnv.NewArray(ushort[]? array) -> nint Android.Runtime.KotlinCoroutines static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.InvokeNullableAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt index 0fc56bce831..f17325e9419 100644 --- a/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt @@ -12858,3 +12858,4 @@ static Android.Runtime.JNIEnv.NewArray(ushort[]? array) -> nint Android.Runtime.KotlinCoroutines static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.InvokeNullableAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt index e4bd8e5687b..5ade9e4d9f7 100644 --- a/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt @@ -11344,3 +11344,4 @@ static Android.Runtime.JNIEnv.NewArray(ushort[]? array) -> nint Android.Runtime.KotlinCoroutines static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.InvokeNullableAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Xamarin.Android.Tools.Bytecode/Kotlin/KotlinFixups.cs b/src/Xamarin.Android.Tools.Bytecode/Kotlin/KotlinFixups.cs index 5ff37e6cbee..1af1ea2ce7d 100644 --- a/src/Xamarin.Android.Tools.Bytecode/Kotlin/KotlinFixups.cs +++ b/src/Xamarin.Android.Tools.Bytecode/Kotlin/KotlinFixups.cs @@ -434,12 +434,14 @@ static void FixupDefaultArguments (MethodInfo? method, List m.CanHaveStringOverload) || nestedIface.Type.Methods.Any (m => m.Asyncify || (!m.IsStatic && m.KotlinSuspendReturnType != null))) + if (nestedIface.Type.Methods.Any (m => m.CanHaveStringOverload) || nestedIface.Type.Methods.Any (m => m.Asyncify || (!m.IsStatic && KotlinSuspendMethodWrapper.ShouldGenerate (m, nestedIface.Type)))) sibling_types.Add (new InterfaceExtensionsClass (nestedIface.Type, nestedIface.DeclaringType, opt)); } diff --git a/src/generator/SourceWriters/BoundInterface.cs b/src/generator/SourceWriters/BoundInterface.cs index 395d6ca9a30..e5e4562cb33 100644 --- a/src/generator/SourceWriters/BoundInterface.cs +++ b/src/generator/SourceWriters/BoundInterface.cs @@ -79,7 +79,7 @@ public BoundInterface (InterfaceGen iface, CodeGenerationOptions opt, CodeGenera return; if (!iface.AssemblyQualifiedName.Contains ('/')) { - if (iface.Methods.Any (m => m.CanHaveStringOverload) || iface.Methods.Any (m => m.Asyncify || (!m.IsStatic && m.KotlinSuspendReturnType != null))) + if (iface.Methods.Any (m => m.CanHaveStringOverload) || iface.Methods.Any (m => m.Asyncify || (!m.IsStatic && KotlinSuspendMethodWrapper.ShouldGenerate (m, iface)))) post_sibling_types.Add (new InterfaceExtensionsClass (iface, null, opt)); } diff --git a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs index da4e05c2ddc..b18ddd72600 100644 --- a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs +++ b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs @@ -30,6 +30,7 @@ public KotlinSuspendMethodWrapper (Method method, CodeGenerationOptions opt, str SourceWriterExtensions.AddSupportedOSPlatform (Attributes, method, opt); SourceWriterExtensions.AddObsolete (Attributes, method.Deprecated, opt, deprecatedSince: method.DeprecatedSince); + SourceWriterExtensions.AddRestrictToWarning (Attributes, method.AnnotatedVisibility, false, opt); if (selfType != null) Parameters.Add (new MethodParameterWriter ("self", new TypeReferenceWriter (selfType)) { IsExtension = true }); @@ -52,8 +53,9 @@ public KotlinSuspendMethodWrapper (Method method, CodeGenerationOptions opt, str var result = GetResultType (method.KotlinSuspendReturnType, opt); var generic = result == null ? "" : $"<{result}>"; + var nullable = method.KotlinSuspendReturnType.EndsWith ("?", StringComparison.Ordinal); ReturnType = new TypeReferenceWriter ("global::System.Threading.Tasks.Task" + generic); - Body.Add ($"return {Runtime}.InvokeAsync{generic} ({invoke}, {token});"); + Body.Add ($"return {Runtime}.{(nullable ? "InvokeNullableAsync" : "InvokeAsync")}{generic} ({invoke}, {token});"); } // Maps the Kotlin result type (e.g. `kotlin/Int?`) to a C# type. @@ -83,8 +85,8 @@ static string GetResultType (string kotlinType, CodeGenerationOptions opt) string reference; if (name == "kotlin/String") reference = "string"; - // Inline classes are boxed in this position; invalid or non-public types are not generated. - else if (opt.SymbolTable.Lookup (name.Replace ('/', '.')) is GenBase { IsValid: true, RawVisibility: "public" } gen && gen is not ClassGen { IsKotlinInlineClass: true }) + // Inline classes are boxed in this position; generic, invalid or non-public types are not generated. + else if (opt.SymbolTable.Lookup (name.Replace ('/', '.')) is GenBase { IsValid: true, IsGeneric: false, RawVisibility: "public" } gen && gen is not ClassGen { IsKotlinInlineClass: true }) reference = opt.GetOutputName (gen.FullName); else reference = "global::Java.Lang.Object"; diff --git a/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/SuspendFunctions.kt b/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/SuspendFunctions.kt index df2dc483f56..55531a68d5b 100644 --- a/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/SuspendFunctions.kt +++ b/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/SuspendFunctions.kt @@ -5,6 +5,7 @@ import kotlin.coroutines.Continuation class SuspendFunctions { suspend fun getInt(value: Int): Int = value suspend fun getNullableString(): String? = null + suspend fun getNullableInt(): Int? = null suspend fun doWork() { } suspend fun echo(value: T): T = value diff --git a/tests/generator-Tests/Unit-Tests/KotlinInlineClassEndToEndTests.cs b/tests/generator-Tests/Unit-Tests/KotlinInlineClassEndToEndTests.cs index 0d2fb3f1b9e..44d0021a166 100644 --- a/tests/generator-Tests/Unit-Tests/KotlinInlineClassEndToEndTests.cs +++ b/tests/generator-Tests/Unit-Tests/KotlinInlineClassEndToEndTests.cs @@ -237,14 +237,20 @@ internal static string BuildApiXmlFromKotlinFixture (params string [] resources) "")); // Like CodeGenerator, run class-parse output through the JavaTypeSystem adjuster. - // `java.lang.String`, `java.lang.CharSequence` and `java.util.List` come from the reference API in a real build. + // These reference types come from the reference API and assemblies in a real build. var references = Java.Interop.Tools.JavaTypeSystem.JavaXmlApiImporter.ParseString ( "" + "" + "" + + "" + "" + "" + "" + + "" + + "" + + "" + + "" + + "" + ""); var types = new Java.Interop.Tools.JavaTypeSystem.Models.JavaTypeCollection (); foreach (var reference in references.TypesFlattened.Values) @@ -257,7 +263,7 @@ internal static string BuildApiXmlFromKotlinFixture (params string [] resources) return adjusted.ToString (); } - internal static ClassFile LoadClassFile (string resource) + static ClassFile LoadClassFile (string resource) { var assembly = typeof (KotlinInlineClassEndToEndTests).Assembly; var name = assembly.GetManifestResourceNames () diff --git a/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs b/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs index 187cb57a532..496226dfed5 100644 --- a/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs +++ b/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs @@ -1,25 +1,27 @@ -using System.Collections.Generic; -using System.IO; using System.Xml.Linq; using NUnit.Framework; -using Xamarin.Android.Tools.Bytecode; namespace generatortests { - // Drives the real Kotlin `SuspendFunctions` class (compiled by - // tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/) through - // class-parse and the generator, and checks the `Task` wrappers. + // Drives the real Kotlin `SuspendFunctions` class through class-parse, the adjuster and the generator. [TestFixture] public class KotlinSuspendTests { const string Invoke = "global::Android.Runtime.KotlinCoroutines.InvokeAsync"; + const string InvokeNullable = "global::Android.Runtime.KotlinCoroutines.InvokeNullableAsync"; const string Continuation = "global::Android.Runtime.Extensions.JavaCast (__continuation)"; const string Token = "global::System.Threading.CancellationToken cancellationToken = default"; [Test] public void GeneratesTaskWrappersForSuspendFunctions () { - var output = KotlinInlineClassEndToEndTests.GenerateCSharp (BuildApiXml (), out _); + // In a real build, `Continuation` comes from the Kotlin.StdLib reference assembly. + var api = XDocument.Parse (KotlinInlineClassEndToEndTests.BuildApiXmlFromKotlinFixture ("SuspendFunctions.class")); + api.Root.AddFirst (XElement.Parse ( + "" + + "" + + "")); + var output = KotlinInlineClassEndToEndTests.GenerateCSharp (api.ToString (), out _); // The bound method that takes the Continuation is unchanged. StringAssert.Contains ("public Java.Lang.Object GetInt (int value, Kotlin.Coroutines.IContinuation _completion)", output); @@ -28,7 +30,10 @@ public void GeneratesTaskWrappersForSuspendFunctions () StringAssert.Contains ($"return {Invoke} (__continuation => GetInt (value, {Continuation}), cancellationToken);", output); StringAssert.Contains ($"public global::System.Threading.Tasks.Task GetNullableStringAsync ({Token})", output); - StringAssert.Contains ($"return {Invoke} (__continuation => GetNullableString ({Continuation}), cancellationToken);", output); + StringAssert.Contains ($"return {InvokeNullable} (__continuation => GetNullableString ({Continuation}), cancellationToken);", output); + + StringAssert.Contains ($"public global::System.Threading.Tasks.Task GetNullableIntAsync ({Token})", output); + StringAssert.Contains ($"return {InvokeNullable} (__continuation => GetNullableInt ({Continuation}), cancellationToken);", output); StringAssert.Contains ($"public global::System.Threading.Tasks.Task DoWorkAsync ({Token})", output); StringAssert.Contains ($"return {Invoke} (__continuation => DoWork ({Continuation}), cancellationToken);", output); @@ -38,29 +43,5 @@ public void GeneratesTaskWrappersForSuspendFunctions () StringAssert.DoesNotContain ("NotSuspendAsync", output); } - - static string BuildApiXml () - { - var classes = new List { KotlinInlineClassEndToEndTests.LoadClassFile ("SuspendFunctions.class") }; - KotlinFixups.Fixup (classes); - - var classPath = new ClassPath { ApiSource = "class-parse" }; - foreach (var c in classes) - classPath.Add (c); - - var sw = new StringWriter (); - classPath.SaveXmlDescription (sw); - - var doc = XDocument.Parse (sw.ToString ()); - doc.Root.AddFirst (XElement.Parse ( - "" + - "" + - "")); - doc.Root.AddFirst (XElement.Parse ( - "" + - "" + - "")); - return doc.ToString (); - } } } From 95f2a72d8599929ced7ba75e4213795843bd33f1 Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 23 Nov 2026 11:19:10 -0600 Subject: [PATCH 06/13] [Mono.Android] Name KotlinCoroutines methods after what they do Only generated bindings call Android.Runtime.KotlinCoroutines, so: * Mark it [EditorBrowsable (EditorBrowsableState.Never)], like ResourceIdManager and GeneratedEnumAttribute. * Rename InvokeAsync/InvokeNullableAsync to CallSuspendFunctionAsync/CallNullableSuspendFunctionAsync, after the JNIEnv.Call*Method pattern. * Remove the non-generic InvokeAsync. A Unit result uses CallNullableSuspendFunctionAsync, because Task is a Task. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/Mono.Android/Android.Runtime/KotlinCoroutines.cs | 12 ++++-------- .../PublicAPI/API-35/PublicAPI.Unshipped.txt | 5 ++--- .../PublicAPI/API-36.1/PublicAPI.Unshipped.txt | 5 ++--- .../PublicAPI/API-36/PublicAPI.Unshipped.txt | 5 ++--- .../PublicAPI/API-37.1/PublicAPI.Unshipped.txt | 5 ++--- .../PublicAPI/API-37.2/PublicAPI.Unshipped.txt | 5 ++--- .../PublicAPI/API-37/PublicAPI.Unshipped.txt | 5 ++--- .../Xamarin.Android.Build.Tests/BindingBuildTest.cs | 2 +- .../SourceWriters/KotlinSuspendMethodWrapper.cs | 10 ++++++---- .../generator-Tests/Unit-Tests/KotlinSuspendTests.cs | 12 ++++++------ 10 files changed, 29 insertions(+), 37 deletions(-) diff --git a/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs b/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs index b30a84ad8e0..e333907da45 100644 --- a/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs +++ b/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs @@ -1,5 +1,6 @@ #nullable enable using System; +using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -20,19 +21,14 @@ namespace Android.Runtime { /// build-time dependency on Kotlin. When kotlinx.coroutines is in the app, the continuation context /// is a kotlinx.coroutines.Job, and cancellation of the token also cancels that job. /// + [EditorBrowsable (EditorBrowsableState.Never)] public static class KotlinCoroutines { const DynamicallyAccessedMemberTypes Constructors = DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors; - /// Runs a Kotlin suspend function that returns Unit. - /// Calls the bound method with the supplied kotlin.coroutines.Continuation. - /// Cancels the operation. - public static Task InvokeAsync (Func invoke, CancellationToken cancellationToken = default) => - InvokeCoreAsync (invoke, cancellationToken); - /// Runs a Kotlin suspend function with a non-null result and converts the result to . /// Calls the bound method with the supplied kotlin.coroutines.Continuation. /// Cancels the operation. - public static async Task InvokeAsync< + public static async Task CallSuspendFunctionAsync< [DynamicallyAccessedMembers (Constructors)] T > (Func invoke, CancellationToken cancellationToken = default) @@ -47,7 +43,7 @@ public static async Task InvokeAsync< /// For a nullable value type, use a type argument, for example int?. /// Calls the bound method with the supplied kotlin.coroutines.Continuation. /// Cancels the operation. - public static async Task InvokeNullableAsync< + public static async Task CallNullableSuspendFunctionAsync< [DynamicallyAccessedMembers (Constructors)] T > (Func invoke, CancellationToken cancellationToken = default) diff --git a/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt index 8587014d5e2..62550c310d4 100644 --- a/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt @@ -6049,6 +6049,5 @@ static Java.Interop.JniMarshalTyped.Invoke_X(nint jnienv, nint self, dele *REMOVED*override Android.Graphics.ColorValueMarshaler.DestroyGenericArgumentState(Android.Graphics.Color value, ref Java.Interop.JniValueMarshalerState state, System.Reflection.ParameterAttributes synchronize) -> void *REMOVED*override Android.Graphics.ColorValueMarshaler.MarshalType.get -> System.Type! Android.Runtime.KotlinCoroutines -static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.InvokeNullableAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt index 12984f2331a..157eacebc83 100644 --- a/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt @@ -6117,6 +6117,5 @@ static Java.Interop.JniMarshalTyped.Invoke_X(nint jnienv, nint self, dele *REMOVED*override Android.Graphics.ColorValueMarshaler.DestroyGenericArgumentState(Android.Graphics.Color value, ref Java.Interop.JniValueMarshalerState state, System.Reflection.ParameterAttributes synchronize) -> void *REMOVED*override Android.Graphics.ColorValueMarshaler.MarshalType.get -> System.Type! Android.Runtime.KotlinCoroutines -static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.InvokeNullableAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt index 0306625aad6..06b5ae89763 100644 --- a/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt @@ -10390,6 +10390,5 @@ virtual Java.Util.IdentityHashMap.Replace(Java.Lang.Object? key, Java.Lang.Objec *REMOVED*override Android.Graphics.ColorValueMarshaler.DestroyGenericArgumentState(Android.Graphics.Color value, ref Java.Interop.JniValueMarshalerState state, System.Reflection.ParameterAttributes synchronize) -> void *REMOVED*override Android.Graphics.ColorValueMarshaler.MarshalType.get -> System.Type! Android.Runtime.KotlinCoroutines -static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.InvokeNullableAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt index a5fa46297a3..507913b512c 100644 --- a/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt @@ -11704,6 +11704,5 @@ static Android.Runtime.JNIEnv.NewArray(ulong[]? array) -> nint *REMOVED*static Android.Runtime.JNIEnv.NewArray(ushort[]! array) -> nint static Android.Runtime.JNIEnv.NewArray(ushort[]? array) -> nint Android.Runtime.KotlinCoroutines -static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.InvokeNullableAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt index f17325e9419..fd9a97a5400 100644 --- a/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt @@ -12856,6 +12856,5 @@ static Android.Runtime.JNIEnv.NewArray(ulong[]? array) -> nint *REMOVED*static Android.Runtime.JNIEnv.NewArray(ushort[]! array) -> nint static Android.Runtime.JNIEnv.NewArray(ushort[]? array) -> nint Android.Runtime.KotlinCoroutines -static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.InvokeNullableAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt index 5ade9e4d9f7..ee4a63bc67a 100644 --- a/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt @@ -11342,6 +11342,5 @@ static Android.Runtime.JNIEnv.NewArray(ulong[]? array) -> nint *REMOVED*static Android.Runtime.JNIEnv.NewArray(ushort[]! array) -> nint static Android.Runtime.JNIEnv.NewArray(ushort[]? array) -> nint Android.Runtime.KotlinCoroutines -static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.InvokeAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.InvokeNullableAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs index 67c1bb721f2..8b69a4e6a9f 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs @@ -1307,7 +1307,7 @@ public void KotlinSuspendFunctionsAsTasks () Assert.IsTrue (File.Exists (cs_file)); var code = File.ReadAllText (cs_file); Assert.Contains ("public static global::System.Threading.Tasks.Task EditAsync (global::AndroidX.DataStore.Core.IDataStore obj, global::Kotlin.Jvm.Functions.IFunction2 transform, global::System.Threading.CancellationToken cancellationToken = default)", code); - Assert.Contains ("global::Android.Runtime.KotlinCoroutines.InvokeAsync (__continuation => Edit (", code); + Assert.Contains ("global::Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync (__continuation => Edit (", code); } [TestMethod] diff --git a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs index b18ddd72600..3c8340f6673 100644 --- a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs +++ b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs @@ -51,11 +51,13 @@ public KotlinSuspendMethodWrapper (Method method, CodeGenerationOptions opt, str var target = selfType != null ? "self." + method.AdjustedName : method.AdjustedName; var invoke = $"__continuation => {target} ({args})"; + // A `kotlin/Unit` result is a non-generic `Task`, which `Task` is. var result = GetResultType (method.KotlinSuspendReturnType, opt); - var generic = result == null ? "" : $"<{result}>"; - var nullable = method.KotlinSuspendReturnType.EndsWith ("?", StringComparison.Ordinal); - ReturnType = new TypeReferenceWriter ("global::System.Threading.Tasks.Task" + generic); - Body.Add ($"return {Runtime}.{(nullable ? "InvokeNullableAsync" : "InvokeAsync")}{generic} ({invoke}, {token});"); + var call = result == null || method.KotlinSuspendReturnType.EndsWith ("?", StringComparison.Ordinal) + ? "CallNullableSuspendFunctionAsync" + : "CallSuspendFunctionAsync"; + ReturnType = new TypeReferenceWriter ("global::System.Threading.Tasks.Task" + (result == null ? "" : $"<{result}>")); + Body.Add ($"return {Runtime}.{call}<{result ?? "global::Java.Lang.Object"}> ({invoke}, {token});"); } // Maps the Kotlin result type (e.g. `kotlin/Int?`) to a C# type. diff --git a/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs b/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs index 496226dfed5..581c2b121cf 100644 --- a/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs +++ b/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs @@ -7,8 +7,8 @@ namespace generatortests [TestFixture] public class KotlinSuspendTests { - const string Invoke = "global::Android.Runtime.KotlinCoroutines.InvokeAsync"; - const string InvokeNullable = "global::Android.Runtime.KotlinCoroutines.InvokeNullableAsync"; + const string Call = "global::Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync"; + const string CallNullable = "global::Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync"; const string Continuation = "global::Android.Runtime.Extensions.JavaCast (__continuation)"; const string Token = "global::System.Threading.CancellationToken cancellationToken = default"; @@ -27,16 +27,16 @@ public void GeneratesTaskWrappersForSuspendFunctions () StringAssert.Contains ("public Java.Lang.Object GetInt (int value, Kotlin.Coroutines.IContinuation _completion)", output); StringAssert.Contains ($"public global::System.Threading.Tasks.Task GetIntAsync (int value, {Token})", output); - StringAssert.Contains ($"return {Invoke} (__continuation => GetInt (value, {Continuation}), cancellationToken);", output); + StringAssert.Contains ($"return {Call} (__continuation => GetInt (value, {Continuation}), cancellationToken);", output); StringAssert.Contains ($"public global::System.Threading.Tasks.Task GetNullableStringAsync ({Token})", output); - StringAssert.Contains ($"return {InvokeNullable} (__continuation => GetNullableString ({Continuation}), cancellationToken);", output); + StringAssert.Contains ($"return {CallNullable} (__continuation => GetNullableString ({Continuation}), cancellationToken);", output); StringAssert.Contains ($"public global::System.Threading.Tasks.Task GetNullableIntAsync ({Token})", output); - StringAssert.Contains ($"return {InvokeNullable} (__continuation => GetNullableInt ({Continuation}), cancellationToken);", output); + StringAssert.Contains ($"return {CallNullable} (__continuation => GetNullableInt ({Continuation}), cancellationToken);", output); StringAssert.Contains ($"public global::System.Threading.Tasks.Task DoWorkAsync ({Token})", output); - StringAssert.Contains ($"return {Invoke} (__continuation => DoWork ({Continuation}), cancellationToken);", output); + StringAssert.Contains ($"return {CallNullable} (__continuation => DoWork ({Continuation}), cancellationToken);", output); // A type parameter result is not inferred. StringAssert.Contains ("public global::System.Threading.Tasks.Task EchoAsync (Java.Lang.Object value, ", output); From b0a4c18c384fb39e1d60039874d910313c163481 Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 23 Nov 2026 11:45:06 -0600 Subject: [PATCH 07/13] [generator] Avoid name collisions in Kotlin suspend wrappers; test Kotlin-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> --- .../KotlinSuspendMethodWrapper.cs | 27 +++++++++++++------ .../Tests/KotlinSuspendTests.cs | 21 ++++++++++++--- .../kotlin-gradle.targets | 1 + .../src/main/kotlin/SuspendFunctions.kt | 5 ++++ .../Unit-Tests/KotlinSuspendTests.cs | 6 ++++- tests/generator-Tests/generator-Tests.csproj | 1 + 6 files changed, 48 insertions(+), 13 deletions(-) diff --git a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs index 3c8340f6673..3cf7450764d 100644 --- a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs +++ b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using MonoDroid.Generation; using Xamarin.SourceWriter; @@ -32,24 +33,34 @@ public KotlinSuspendMethodWrapper (Method method, CodeGenerationOptions opt, str SourceWriterExtensions.AddObsolete (Attributes, method.Deprecated, opt, deprecatedSince: method.DeprecatedSince); SourceWriterExtensions.AddRestrictToWarning (Attributes, method.AnnotatedVisibility, false, opt); - if (selfType != null) - Parameters.Add (new MethodParameterWriter ("self", new TypeReferenceWriter (selfType)) { IsExtension = true }); - var parameters = new ParameterList (); foreach (var p in method.Parameters.Take (method.Parameters.Count - 1)) parameters.Add (p); - this.AddMethodParameters (parameters, opt); - var token = parameters.Any (p => opt.GetSafeIdentifier (p.Name) == "cancellationToken") ? "__cancellationToken" : "cancellationToken"; + // The generated names must not collide with Kotlin parameter names. + var names = new HashSet (parameters.Select (p => opt.GetSafeIdentifier (p.Name))); + string GetFreeName (string name) + { + while (!names.Add (name)) + name = "_" + name; + return name; + } + var self = GetFreeName ("self"); + var token = GetFreeName ("cancellationToken"); + var continuation = GetFreeName ("__continuation"); + + if (selfType != null) + Parameters.Add (new MethodParameterWriter (self, new TypeReferenceWriter (selfType)) { IsExtension = true }); + this.AddMethodParameters (parameters, opt); Parameters.Add (new MethodParameterWriter (token, new TypeReferenceWriter ("global::System.Threading.CancellationToken")) { DefaultValue = "default" }); var continuation_type = opt.GetOutputName (method.Parameters [method.Parameters.Count - 1].Type); var args = parameters.GetCall (opt); if (args.Length > 0) args += ", "; - args += $"global::Android.Runtime.Extensions.JavaCast<{continuation_type}> (__continuation)"; - var target = selfType != null ? "self." + method.AdjustedName : method.AdjustedName; - var invoke = $"__continuation => {target} ({args})"; + args += $"global::Android.Runtime.Extensions.JavaCast<{continuation_type}> ({continuation})"; + var target = selfType != null ? $"{self}.{method.AdjustedName}" : method.AdjustedName; + var invoke = $"{continuation} => {target} ({args})"; // A `kotlin/Unit` result is a non-generic `Task`, which `Task` is. var result = GetResultType (method.KotlinSuspendReturnType, opt); diff --git a/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs b/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs index 70edd8ea8f5..b4aa92c4efa 100644 --- a/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs +++ b/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs @@ -38,7 +38,15 @@ suspend fun nothing(): String? = null suspend fun fail(message: String): Int = suspendCoroutine { c -> Thread { c.resumeWith(Result.failure(IllegalStateException(message))) }.start() } - suspend fun waitForCancel() = delay(Long.MAX_VALUE) + @Volatile var stopped = false + private set + suspend fun waitForCancel() { + try { + delay(Long.MAX_VALUE) + } finally { + stopped = true + } + } } """, }, @@ -99,12 +107,17 @@ async void RunKotlin () } catch (Java.Lang.IllegalStateException e) { failure = e.Message; } + // Cancel after the coroutine suspends, and check that the Kotlin code stops too. bool canceled = false; - using var cts = new System.Threading.CancellationTokenSource (100); + using var cts = new System.Threading.CancellationTokenSource (); + var wait = kotlin.WaitForCancelAsync (cts.Token); + cts.Cancel (); try { - await kotlin.WaitForCancelAsync (cts.Token); + await wait; } catch (System.OperationCanceledException) { - canceled = true; + for (int i = 0; i < 50 && !kotlin.Stopped; i++) + await System.Threading.Tasks.Task.Delay (100); + canceled = kotlin.Stopped; } Android.Util.Log.Info ("KotlinSuspend", $"KotlinSuspend: sum={sum} greeting={greeting} nothing={nothing == null} failure={failure} canceled={canceled}"); } catch (System.Exception e) { diff --git a/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle.targets b/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle.targets index 7cd0df2bb6b..83047937c7f 100644 --- a/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle.targets +++ b/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle.targets @@ -22,6 +22,7 @@ + diff --git a/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/SuspendFunctions.kt b/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/SuspendFunctions.kt index 55531a68d5b..a2855cc4c66 100644 --- a/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/SuspendFunctions.kt +++ b/tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/SuspendFunctions.kt @@ -12,3 +12,8 @@ class SuspendFunctions { // Not `suspend`: it only looks like the suspend ABI. fun notSuspend(continuation: Continuation): Any? = null } + +// Parameter names that the generated extension method also uses. +interface SuspendCallback { + suspend fun merge(self: Boolean, cancellationToken: Int): Int +} diff --git a/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs b/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs index 581c2b121cf..9adbc8e6c4c 100644 --- a/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs +++ b/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs @@ -16,7 +16,7 @@ public class KotlinSuspendTests public void GeneratesTaskWrappersForSuspendFunctions () { // In a real build, `Continuation` comes from the Kotlin.StdLib reference assembly. - var api = XDocument.Parse (KotlinInlineClassEndToEndTests.BuildApiXmlFromKotlinFixture ("SuspendFunctions.class")); + var api = XDocument.Parse (KotlinInlineClassEndToEndTests.BuildApiXmlFromKotlinFixture ("SuspendFunctions.class", "SuspendCallback.class")); api.Root.AddFirst (XElement.Parse ( "" + "" + @@ -42,6 +42,10 @@ public void GeneratesTaskWrappersForSuspendFunctions () StringAssert.Contains ("public global::System.Threading.Tasks.Task EchoAsync (Java.Lang.Object value, ", output); StringAssert.DoesNotContain ("NotSuspendAsync", output); + + // Generated names do not collide with Kotlin parameter names. + StringAssert.Contains ("MergeAsync (this Xat.Bytecode.Tests.ISuspendCallback _self, bool self, int cancellationToken, global::System.Threading.CancellationToken _cancellationToken = default)", output); + StringAssert.Contains ("(__continuation => _self.Merge (self, cancellationToken, ", output); } } } diff --git a/tests/generator-Tests/generator-Tests.csproj b/tests/generator-Tests/generator-Tests.csproj index 1ef10f586b7..66a2822235e 100644 --- a/tests/generator-Tests/generator-Tests.csproj +++ b/tests/generator-Tests/generator-Tests.csproj @@ -47,6 +47,7 @@ + From b71bb5090292257cf4a621758fe36613b1dabb5e Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 30 Nov 2026 11:45:51 -0600 Subject: [PATCH 08/13] [tests] Move Kotlin suspend tests to MSTest; guard obsolete warnings in *Async wrappers Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../KotlinSuspendMethodWrapper.cs | 10 ++++++ .../Tests/KotlinSuspendTests.cs | 8 ++--- .../KotlinSuspendTests.cs | 6 ++-- .../Unit-Tests/KotlinSuspendTests.cs | 34 +++++++++---------- 4 files changed, 34 insertions(+), 24 deletions(-) diff --git a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs index 3cf7450764d..cf610003d38 100644 --- a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs +++ b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs @@ -13,6 +13,8 @@ public class KotlinSuspendMethodWrapper : MethodWriter { const string Runtime = "global::Android.Runtime.KotlinCoroutines"; + readonly bool suppress_obsolete_warning; + public static bool ShouldGenerate (Method method, GenBase type) => method.KotlinSuspendReturnType != null && method.IsValid && @@ -69,6 +71,14 @@ string GetFreeName (string name) : "CallSuspendFunctionAsync"; ReturnType = new TypeReferenceWriter ("global::System.Threading.Tasks.Task" + (result == null ? "" : $"<{result}>")); Body.Add ($"return {Runtime}.{call}<{result ?? "global::Java.Lang.Object"}> ({invoke}, {token});"); + + suppress_obsolete_warning = !SourceWriterExtensions.IsTypeObsolete (method.DeclaringType, opt) && + SourceWriterExtensions.ReferencesObsoleteType (method, opt); + } + + public override void Write (CodeWriter writer) + { + SourceWriterExtensions.WriteWithWarningsDisabled (writer, suppress_obsolete_warning, "0618", () => base.Write (writer)); } // Maps the Kotlin result type (e.g. `kotlin/Int?`) to a C# type. diff --git a/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs b/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs index b4aa92c4efa..25fd96d6df9 100644 --- a/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs +++ b/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs @@ -1,17 +1,17 @@ using System.IO; -using NUnit.Framework; +using Microsoft.VisualStudio.TestTools.UnitTesting; using Xamarin.Android.Tasks; using Xamarin.ProjectTools; namespace Xamarin.Android.Build.Tests { - [TestFixture] - [Category ("UsesDevice")] + [TestClass] + [TestCategory ("UsesDevice")] public class KotlinSuspendTests : DeviceTest { // Binds a Gradle module with Kotlin `suspend` functions and awaits the generated `*Async` methods. // R8 checks the keep rules for the Kotlin members that KotlinCoroutines finds by name. - [Test] + [TestMethod] public void SuspendFunctionsAsTasks () { const string Expected = "KotlinSuspend: sum=5 greeting=Hello, Kotlin nothing=True failure=boom canceled=True"; diff --git a/tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinSuspendTests.cs b/tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinSuspendTests.cs index bc26c0dfabe..e52b91dcfee 100644 --- a/tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinSuspendTests.cs +++ b/tests/Xamarin.Android.Tools.Bytecode-Tests/KotlinSuspendTests.cs @@ -1,14 +1,14 @@ using System.Collections.Generic; using System.Linq; -using NUnit.Framework; +using Microsoft.VisualStudio.TestTools.UnitTesting; using Xamarin.Android.Tools.Bytecode; namespace Xamarin.Android.Tools.BytecodeTests { - [TestFixture] + [TestClass] public class KotlinSuspendTests : ClassFileFixture { - [Test] + [TestMethod] public void Fixup_SetsKotlinSuspendReturnType () { var klass = LoadClassFile ("SuspendFunctions.class"); diff --git a/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs b/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs index 9adbc8e6c4c..5f4b87e1ddd 100644 --- a/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs +++ b/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs @@ -1,10 +1,10 @@ using System.Xml.Linq; -using NUnit.Framework; +using Microsoft.VisualStudio.TestTools.UnitTesting; namespace generatortests { // Drives the real Kotlin `SuspendFunctions` class through class-parse, the adjuster and the generator. - [TestFixture] + [TestClass] public class KotlinSuspendTests { const string Call = "global::Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync"; @@ -12,7 +12,7 @@ public class KotlinSuspendTests const string Continuation = "global::Android.Runtime.Extensions.JavaCast (__continuation)"; const string Token = "global::System.Threading.CancellationToken cancellationToken = default"; - [Test] + [TestMethod] public void GeneratesTaskWrappersForSuspendFunctions () { // In a real build, `Continuation` comes from the Kotlin.StdLib reference assembly. @@ -21,31 +21,31 @@ public void GeneratesTaskWrappersForSuspendFunctions () "" + "" + "")); - var output = KotlinInlineClassEndToEndTests.GenerateCSharp (api.ToString (), out _); + var output = KotlinInlineClassEndToEndTests.GenerateCSharp (api.ToString ()).Output; // The bound method that takes the Continuation is unchanged. - StringAssert.Contains ("public Java.Lang.Object GetInt (int value, Kotlin.Coroutines.IContinuation _completion)", output); + Assert.Contains ("public Java.Lang.Object GetInt (int value, Kotlin.Coroutines.IContinuation _completion)", output); - StringAssert.Contains ($"public global::System.Threading.Tasks.Task GetIntAsync (int value, {Token})", output); - StringAssert.Contains ($"return {Call} (__continuation => GetInt (value, {Continuation}), cancellationToken);", output); + Assert.Contains ($"public global::System.Threading.Tasks.Task GetIntAsync (int value, {Token})", output); + Assert.Contains ($"return {Call} (__continuation => GetInt (value, {Continuation}), cancellationToken);", output); - StringAssert.Contains ($"public global::System.Threading.Tasks.Task GetNullableStringAsync ({Token})", output); - StringAssert.Contains ($"return {CallNullable} (__continuation => GetNullableString ({Continuation}), cancellationToken);", output); + Assert.Contains ($"public global::System.Threading.Tasks.Task GetNullableStringAsync ({Token})", output); + Assert.Contains ($"return {CallNullable} (__continuation => GetNullableString ({Continuation}), cancellationToken);", output); - StringAssert.Contains ($"public global::System.Threading.Tasks.Task GetNullableIntAsync ({Token})", output); - StringAssert.Contains ($"return {CallNullable} (__continuation => GetNullableInt ({Continuation}), cancellationToken);", output); + Assert.Contains ($"public global::System.Threading.Tasks.Task GetNullableIntAsync ({Token})", output); + Assert.Contains ($"return {CallNullable} (__continuation => GetNullableInt ({Continuation}), cancellationToken);", output); - StringAssert.Contains ($"public global::System.Threading.Tasks.Task DoWorkAsync ({Token})", output); - StringAssert.Contains ($"return {CallNullable} (__continuation => DoWork ({Continuation}), cancellationToken);", output); + Assert.Contains ($"public global::System.Threading.Tasks.Task DoWorkAsync ({Token})", output); + Assert.Contains ($"return {CallNullable} (__continuation => DoWork ({Continuation}), cancellationToken);", output); // A type parameter result is not inferred. - StringAssert.Contains ("public global::System.Threading.Tasks.Task EchoAsync (Java.Lang.Object value, ", output); + Assert.Contains ("public global::System.Threading.Tasks.Task EchoAsync (Java.Lang.Object value, ", output); - StringAssert.DoesNotContain ("NotSuspendAsync", output); + Assert.DoesNotContain ("NotSuspendAsync", output); // Generated names do not collide with Kotlin parameter names. - StringAssert.Contains ("MergeAsync (this Xat.Bytecode.Tests.ISuspendCallback _self, bool self, int cancellationToken, global::System.Threading.CancellationToken _cancellationToken = default)", output); - StringAssert.Contains ("(__continuation => _self.Merge (self, cancellationToken, ", output); + Assert.Contains ("MergeAsync (this Xat.Bytecode.Tests.ISuspendCallback _self, bool self, int cancellationToken, global::System.Threading.CancellationToken _cancellationToken = default)", output); + Assert.Contains ("(__continuation => _self.Merge (self, cancellationToken, ", output); } } } From 937eee0c5eb59b25ac860f40bf4073490c72b4a2 Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 30 Nov 2026 14:52:10 -0600 Subject: [PATCH 09/13] [generator] Clarify the kotlin/Unit comment in KotlinSuspendMethodWrapper Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs index cf610003d38..9bff9f5f9b1 100644 --- a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs +++ b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs @@ -64,7 +64,7 @@ string GetFreeName (string name) var target = selfType != null ? $"{self}.{method.AdjustedName}" : method.AdjustedName; var invoke = $"{continuation} => {target} ({args})"; - // A `kotlin/Unit` result is a non-generic `Task`, which `Task` is. + // For `kotlin/Unit`, the `Task` is returned as a non-generic `Task`. var result = GetResultType (method.KotlinSuspendReturnType, opt); var call = result == null || method.KotlinSuspendReturnType.EndsWith ("?", StringComparison.Ordinal) ? "CallNullableSuspendFunctionAsync" From 6485a58455849341b1200401129a0411b5d2ddae Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 30 Nov 2026 15:24:32 -0600 Subject: [PATCH 10/13] [generator] Generate the Kotlin coroutine helper into each binding 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> --- .../Android.Runtime/KotlinCoroutines.cs | 191 ------------------ src/Mono.Android/Mono.Android.csproj | 1 - .../PublicAPI/API-35/PublicAPI.Unshipped.txt | 3 - .../API-36.1/PublicAPI.Unshipped.txt | 3 - .../PublicAPI/API-36/PublicAPI.Unshipped.txt | 3 - .../API-37.1/PublicAPI.Unshipped.txt | 3 - .../API-37.2/PublicAPI.Unshipped.txt | 3 - .../PublicAPI/API-37/PublicAPI.Unshipped.txt | 3 - .../Resources/proguard_typemap.cfg | 7 - .../Resources/proguard_typemap_coreclr.cfg | 7 - .../Resources/proguard_xamarin.cfg | 8 - .../BindingBuildTest.cs | 6 +- src/generator/CodeGenerationOptions.cs | 3 + src/generator/CodeGenerator.cs | 4 + src/generator/SourceWriters/BoundClass.cs | 6 +- src/generator/SourceWriters/BoundInterface.cs | 4 +- .../SourceWriters/InterfaceExtensionsClass.cs | 2 +- .../SourceWriters/KotlinCoroutinesHelper.cs | 143 +++++++++++++ .../KotlinSuspendMethodWrapper.cs | 83 ++++---- .../Tests/KotlinSuspendTests.cs | 2 +- .../Unit-Tests/KotlinSuspendTests.cs | 67 ++++-- 21 files changed, 261 insertions(+), 291 deletions(-) delete mode 100644 src/Mono.Android/Android.Runtime/KotlinCoroutines.cs create mode 100644 src/generator/SourceWriters/KotlinCoroutinesHelper.cs diff --git a/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs b/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs deleted file mode 100644 index e333907da45..00000000000 --- a/src/Mono.Android/Android.Runtime/KotlinCoroutines.cs +++ /dev/null @@ -1,191 +0,0 @@ -#nullable enable -using System; -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using Java.Interop; -using Java.Lang; -using Java.Lang.Reflect; - -using Exception = System.Exception; - -namespace Android.Runtime { - - /// - /// Runs Kotlin suspend functions as objects. - /// Generated bindings call these methods from their *Async methods. - /// - /// - /// The kotlin.coroutines.Continuation is a java.lang.reflect.Proxy, so this type has no - /// build-time dependency on Kotlin. When kotlinx.coroutines is in the app, the continuation context - /// is a kotlinx.coroutines.Job, and cancellation of the token also cancels that job. - /// - [EditorBrowsable (EditorBrowsableState.Never)] - public static class KotlinCoroutines { - const DynamicallyAccessedMemberTypes Constructors = DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors; - - /// Runs a Kotlin suspend function with a non-null result and converts the result to . - /// Calls the bound method with the supplied kotlin.coroutines.Continuation. - /// Cancels the operation. - public static async Task CallSuspendFunctionAsync< - [DynamicallyAccessedMembers (Constructors)] - T - > (Func invoke, CancellationToken cancellationToken = default) - where T : notnull - { - var value = await InvokeCoreAsync (invoke, cancellationToken).ConfigureAwait (false); - return JavaConvert.FromJavaObject (value) ?? - throw new InvalidOperationException ("Kotlin returned null for a non-null result."); - } - - /// Runs a Kotlin suspend function with a nullable result and converts the result to . - /// For a nullable value type, use a type argument, for example int?. - /// Calls the bound method with the supplied kotlin.coroutines.Continuation. - /// Cancels the operation. - public static async Task CallNullableSuspendFunctionAsync< - [DynamicallyAccessedMembers (Constructors)] - T - > (Func invoke, CancellationToken cancellationToken = default) - { - var value = await InvokeCoreAsync (invoke, cancellationToken).ConfigureAwait (false); - return JavaConvert.FromJavaObject (value); - } - - static Task InvokeCoreAsync (Func invoke, CancellationToken cancellationToken) - { - ArgumentNullException.ThrowIfNull (invoke); - if (cancellationToken.IsCancellationRequested) - return Task.FromCanceled (cancellationToken); - - var handler = new ContinuationHandler (cancellationToken); - try { - var result = invoke (handler.Continuation); - if (!ContinuationHandler.IsSuspended (result)) - handler.SetResult (result); - } catch (Exception e) { - handler.SetException (e); - } - return handler.Task; - } - - sealed class ContinuationHandler : Java.Lang.Object, IInvocationHandler { - - static readonly KotlinTypes types = new KotlinTypes (); - - readonly TaskCompletionSource completion = new (TaskCreationOptions.RunContinuationsAsynchronously); - readonly CancellationToken cancellationToken; - readonly CancellationTokenRegistration registration; - readonly Java.Lang.Object? job; - - public ContinuationHandler (CancellationToken cancellationToken) - { - this.cancellationToken = cancellationToken; - // Job(parent: Job?) with no parent. - job = types.CreateJob?.Invoke (null, new Java.Lang.Object [1]); - Continuation = Proxy.NewProxyInstance (types.Loader, new [] { types.Continuation }, this); - registration = cancellationToken.Register (Cancel); - } - - public Java.Lang.Object Continuation { get; } - - public Task Task => completion.Task; - - public static bool IsSuspended (Java.Lang.Object? value) => - value != null && JNIEnv.IsSameObject (value.Handle, types.Suspended.Handle); - - public void SetResult (Java.Lang.Object? value) - { - completion.TrySetResult (value); - registration.Unregister (); - } - - public void SetException (Exception e) - { - if (e is Java.Util.Concurrent.CancellationException) - completion.TrySetCanceled (cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken (true)); - else - completion.TrySetException (e); - registration.Unregister (); - } - - void Cancel () - { - // With kotlinx.coroutines, also cancel the Kotlin work. Not all suspend functions observe the Job. - try { - if (job != null) - types.CancelJob?.Invoke (job, new Java.Lang.Object [1]); - } finally { - completion.TrySetCanceled (cancellationToken); - } - } - - public Java.Lang.Object? Invoke (Java.Lang.Object? proxy, Method? method, Java.Lang.Object []? args) - { - switch (method?.Name) { - case "getContext": - return job ?? types.EmptyContext; - case "resumeWith": - Resume (args?.Length > 0 ? args [0] : null); - return null; - case "hashCode": - return Integer.ValueOf (JavaSystem.IdentityHashCode (proxy)); - case "equals": - return Java.Lang.Boolean.ValueOf (proxy != null && args?.Length > 0 && args [0] != null && JNIEnv.IsSameObject (proxy.Handle, args [0].Handle)); - case "toString": - return new Java.Lang.String ("Android.Runtime.KotlinCoroutines continuation"); - default: - throw new UnsupportedOperationException (method?.Name); - } - } - - void Resume (Java.Lang.Object? value) - { - // `kotlin.Result` is an inline class: a failure is a `kotlin.Result$Failure`, and a success is the value. - if (!types.Failure.IsInstance (value)) { - SetResult (value); - return; - } - var throwable = types.FailureException.Get (value); - var reference = throwable?.PeerReference ?? default; - var exception = JniEnvironment.Runtime.GetExceptionForThrowable (ref reference, JniObjectReferenceOptions.Copy); - GC.KeepAlive (throwable); - SetException (exception ?? new InvalidOperationException ("Kotlin returned an invalid failure.")); - } - } - - sealed class KotlinTypes { - public readonly ClassLoader? Loader; - public readonly Class Continuation; - public readonly Java.Lang.Object EmptyContext; - public readonly Java.Lang.Object Suspended; - public readonly Class Failure; - public readonly Field FailureException; - public readonly Method? CreateJob; - public readonly Method? CancelJob; - - public KotlinTypes () - { - // The app class loader, which also loads the Kotlin standard library. - Loader = Class.FromType (typeof (ContinuationHandler)).ClassLoader; - Continuation = Class.ForName ("kotlin.coroutines.Continuation", false, Loader); - EmptyContext = GetStaticField ("kotlin.coroutines.EmptyCoroutineContext", "INSTANCE"); - Suspended = GetStaticField ("kotlin.coroutines.intrinsics.CoroutineSingletons", "COROUTINE_SUSPENDED"); - Failure = Class.ForName ("kotlin.Result$Failure", false, Loader); - FailureException = Failure.GetField ("exception"); - - try { - var job = Class.ForName ("kotlinx.coroutines.Job", false, Loader); - CreateJob = Class.ForName ("kotlinx.coroutines.JobKt", false, Loader).GetMethod ("Job", job); - CancelJob = job.GetMethod ("cancel", Class.FromType (typeof (Java.Util.Concurrent.CancellationException))); - } catch (Throwable) { - CreateJob = CancelJob = null; - } - } - - Java.Lang.Object GetStaticField (string className, string fieldName) => - Class.ForName (className, false, Loader).GetField (fieldName).Get (null) ?? - throw new InvalidOperationException ($"Could not read {className}.{fieldName}."); - } - } -} diff --git a/src/Mono.Android/Mono.Android.csproj b/src/Mono.Android/Mono.Android.csproj index 55a77152b07..30d17e3521d 100644 --- a/src/Mono.Android/Mono.Android.csproj +++ b/src/Mono.Android/Mono.Android.csproj @@ -234,7 +234,6 @@ - diff --git a/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt index 62550c310d4..afcc72d9abc 100644 --- a/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-35/PublicAPI.Unshipped.txt @@ -6048,6 +6048,3 @@ static Java.Interop.JniMarshalTyped.Invoke_X(nint jnienv, nint self, dele *REMOVED*override Android.Graphics.ColorValueMarshaler.CreateReturnValueFromManagedExpression(Java.Interop.Expressions.JniValueMarshalerContext! context, System.Linq.Expressions.ParameterExpression! sourceValue) -> System.Linq.Expressions.Expression! *REMOVED*override Android.Graphics.ColorValueMarshaler.DestroyGenericArgumentState(Android.Graphics.Color value, ref Java.Interop.JniValueMarshalerState state, System.Reflection.ParameterAttributes synchronize) -> void *REMOVED*override Android.Graphics.ColorValueMarshaler.MarshalType.get -> System.Type! -Android.Runtime.KotlinCoroutines -static Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt index 157eacebc83..69bf7a889e2 100644 --- a/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-36.1/PublicAPI.Unshipped.txt @@ -6116,6 +6116,3 @@ static Java.Interop.JniMarshalTyped.Invoke_X(nint jnienv, nint self, dele *REMOVED*override Android.Graphics.ColorValueMarshaler.CreateReturnValueFromManagedExpression(Java.Interop.Expressions.JniValueMarshalerContext! context, System.Linq.Expressions.ParameterExpression! sourceValue) -> System.Linq.Expressions.Expression! *REMOVED*override Android.Graphics.ColorValueMarshaler.DestroyGenericArgumentState(Android.Graphics.Color value, ref Java.Interop.JniValueMarshalerState state, System.Reflection.ParameterAttributes synchronize) -> void *REMOVED*override Android.Graphics.ColorValueMarshaler.MarshalType.get -> System.Type! -Android.Runtime.KotlinCoroutines -static Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt index 06b5ae89763..c499b1bf19c 100644 --- a/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt @@ -10389,6 +10389,3 @@ virtual Java.Util.IdentityHashMap.Replace(Java.Lang.Object? key, Java.Lang.Objec *REMOVED*override Android.Graphics.ColorValueMarshaler.CreateReturnValueFromManagedExpression(Java.Interop.Expressions.JniValueMarshalerContext! context, System.Linq.Expressions.ParameterExpression! sourceValue) -> System.Linq.Expressions.Expression! *REMOVED*override Android.Graphics.ColorValueMarshaler.DestroyGenericArgumentState(Android.Graphics.Color value, ref Java.Interop.JniValueMarshalerState state, System.Reflection.ParameterAttributes synchronize) -> void *REMOVED*override Android.Graphics.ColorValueMarshaler.MarshalType.get -> System.Type! -Android.Runtime.KotlinCoroutines -static Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt index 507913b512c..000c8b28a5c 100644 --- a/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-37.1/PublicAPI.Unshipped.txt @@ -11703,6 +11703,3 @@ static Android.Runtime.JNIEnv.NewArray(uint[]? array) -> nint static Android.Runtime.JNIEnv.NewArray(ulong[]? array) -> nint *REMOVED*static Android.Runtime.JNIEnv.NewArray(ushort[]! array) -> nint static Android.Runtime.JNIEnv.NewArray(ushort[]? array) -> nint -Android.Runtime.KotlinCoroutines -static Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt index fd9a97a5400..ede15278eb2 100644 --- a/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-37.2/PublicAPI.Unshipped.txt @@ -12855,6 +12855,3 @@ static Android.Runtime.JNIEnv.NewArray(uint[]? array) -> nint static Android.Runtime.JNIEnv.NewArray(ulong[]? array) -> nint *REMOVED*static Android.Runtime.JNIEnv.NewArray(ushort[]! array) -> nint static Android.Runtime.JNIEnv.NewArray(ushort[]? array) -> nint -Android.Runtime.KotlinCoroutines -static Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt b/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt index ee4a63bc67a..c555f2c72c9 100644 --- a/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt +++ b/src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt @@ -11341,6 +11341,3 @@ static Android.Runtime.JNIEnv.NewArray(uint[]? array) -> nint static Android.Runtime.JNIEnv.NewArray(ulong[]? array) -> nint *REMOVED*static Android.Runtime.JNIEnv.NewArray(ushort[]! array) -> nint static Android.Runtime.JNIEnv.NewArray(ushort[]? array) -> nint -Android.Runtime.KotlinCoroutines -static Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! -static Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync(System.Func! invoke, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap.cfg b/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap.cfg index b6be648e511..725f8454f46 100644 --- a/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap.cfg +++ b/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap.cfg @@ -21,13 +21,6 @@ # Loaded by name from managed code. -keep class net.dot.android.ApplicationRegistration { *; } -keep class net.dot.android.crypto.** { *; (...); } -# Android.Runtime.KotlinCoroutines finds these Kotlin members by name. --keep interface kotlin.coroutines.Continuation { *; } --keep class kotlin.coroutines.EmptyCoroutineContext { public static ** INSTANCE; } --keep enum kotlin.coroutines.intrinsics.CoroutineSingletons { public static ** COROUTINE_SUSPENDED; } --keep class kotlin.Result$Failure { java.lang.Throwable exception; } --keep class kotlinx.coroutines.JobKt { public static ** Job(kotlinx.coroutines.Job); } --keep interface kotlinx.coroutines.Job { void cancel(java.util.concurrent.CancellationException); } # Native hosts resolve these package-private fields by name during startup. -keepclassmembers class mono.android.Runtime { static java.lang.Class *; diff --git a/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap_coreclr.cfg b/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap_coreclr.cfg index 2bd8ff0c1b5..aeaafda0687 100644 --- a/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap_coreclr.cfg +++ b/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap_coreclr.cfg @@ -11,13 +11,6 @@ -keep class mono.android.GCUserPeer { *; } -keep class net.dot.android.ApplicationRegistration { *; } -keep class net.dot.android.crypto.** { *; (...); } -# Android.Runtime.KotlinCoroutines finds these Kotlin members by name. --keep interface kotlin.coroutines.Continuation { *; } --keep class kotlin.coroutines.EmptyCoroutineContext { public static ** INSTANCE; } --keep enum kotlin.coroutines.intrinsics.CoroutineSingletons { public static ** COROUTINE_SUSPENDED; } --keep class kotlin.Result$Failure { java.lang.Throwable exception; } --keep class kotlinx.coroutines.JobKt { public static ** Job(kotlinx.coroutines.Job); } --keep interface kotlinx.coroutines.Job { void cancel(java.util.concurrent.CancellationException); } # Managed interface proxy selection observes Class.getInterfaces(). -keep,allowshrinking class * implements ** diff --git a/src/Xamarin.Android.Build.Tasks/Resources/proguard_xamarin.cfg b/src/Xamarin.Android.Build.Tasks/Resources/proguard_xamarin.cfg index 6051f1fba1c..4f9bf7748e6 100644 --- a/src/Xamarin.Android.Build.Tasks/Resources/proguard_xamarin.cfg +++ b/src/Xamarin.Android.Build.Tasks/Resources/proguard_xamarin.cfg @@ -24,14 +24,6 @@ -keep class net.dot.android.ApplicationRegistration { *; } -keep class net.dot.android.crypto.** { *; (...); } -# Android.Runtime.KotlinCoroutines finds these Kotlin members by name. --keep interface kotlin.coroutines.Continuation { *; } --keep class kotlin.coroutines.EmptyCoroutineContext { public static ** INSTANCE; } --keep enum kotlin.coroutines.intrinsics.CoroutineSingletons { public static ** COROUTINE_SUSPENDED; } --keep class kotlin.Result$Failure { java.lang.Throwable exception; } --keep class kotlinx.coroutines.JobKt { public static ** Job(kotlinx.coroutines.Job); } --keep interface kotlinx.coroutines.Job { void cancel(java.util.concurrent.CancellationException); } - # Android's template misses fluent setters... -keepclassmembers class * extends android.view.View { *** set*(...); diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs index 8b69a4e6a9f..3df5e8e9d01 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs @@ -1307,7 +1307,11 @@ public void KotlinSuspendFunctionsAsTasks () Assert.IsTrue (File.Exists (cs_file)); var code = File.ReadAllText (cs_file); Assert.Contains ("public static global::System.Threading.Tasks.Task EditAsync (global::AndroidX.DataStore.Core.IDataStore obj, global::Kotlin.Jvm.Functions.IFunction2 transform, global::System.Threading.CancellationToken cancellationToken = default)", code); - Assert.Contains ("global::Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync (__continuation => Edit (", code); + Assert.Contains ("global::__KotlinCoroutines.InvokeAsync (__continuation => Edit (", code); + + // DataStore references kotlinx.coroutines, so cancellation uses a `Job`. + var helper = File.ReadAllText (b.Output.GetIntermediaryPath (Path.Combine ("generated", "src", "__KotlinCoroutines__.cs"))); + Assert.Contains ("JobKt.Job (null)", helper); } [TestMethod] diff --git a/src/generator/CodeGenerationOptions.cs b/src/generator/CodeGenerationOptions.cs index 9353553cf8f..2bf7d728921 100644 --- a/src/generator/CodeGenerationOptions.cs +++ b/src/generator/CodeGenerationOptions.cs @@ -41,6 +41,9 @@ public SymbolTable SymbolTable { readonly SortedSet jni_marshal_delegates = new SortedSet (StringComparer.Ordinal); readonly Lock jni_marshal_delegates_lock = new Lock (); + // Set when a Kotlin `suspend` function gets a `*Async` wrapper; see KotlinCoroutinesHelper. + internal bool UsesKotlinCoroutines { get; set; } + public string ApiXmlFile { get; set; } public bool UseGlobal { get; set; } public bool IgnoreNonPublicType { get; set; } diff --git a/src/generator/CodeGenerator.cs b/src/generator/CodeGenerator.cs index 164642136f7..6f342e9426c 100644 --- a/src/generator/CodeGenerator.cs +++ b/src/generator/CodeGenerator.cs @@ -16,6 +16,7 @@ using Java.Interop.Tools.JavaTypeSystem; using System.Text; using generator; +using generator.SourceWriters; namespace Xamarin.Android.Binder { @@ -248,6 +249,9 @@ static void Run (CodeGeneratorOptions options, DirectoryAssemblyResolver resolve new NamespaceMapping (gens).Generate (opt, gen_info); + if (opt.UsesKotlinCoroutines) + KotlinCoroutinesHelper.Generate (opt, gen_info); + ClassGen.GenerateEnumList (gen_info); // Create the .cs files for the enums diff --git a/src/generator/SourceWriters/BoundClass.cs b/src/generator/SourceWriters/BoundClass.cs index 474c9cbaaf4..cc9fd07f0ea 100644 --- a/src/generator/SourceWriters/BoundClass.cs +++ b/src/generator/SourceWriters/BoundClass.cs @@ -90,7 +90,7 @@ public BoundClass (ClassGen klass, CodeGenerationOptions opt, CodeGeneratorConte // Sibling classes if (!klass.AssemblyQualifiedName.Contains ('/')) { foreach (InterfaceExtensionInfo nestedIface in klass.GetNestedInterfaceTypes ()) - if (nestedIface.Type.Methods.Any (m => m.CanHaveStringOverload) || nestedIface.Type.Methods.Any (m => m.Asyncify || (!m.IsStatic && KotlinSuspendMethodWrapper.ShouldGenerate (m, nestedIface.Type)))) + if (nestedIface.Type.Methods.Any (m => m.CanHaveStringOverload) || nestedIface.Type.Methods.Any (m => m.Asyncify || (!m.IsStatic && KotlinSuspendMethodWrapper.ShouldGenerate (m, nestedIface.Type, opt)))) sibling_types.Add (new InterfaceExtensionsClass (nestedIface.Type, nestedIface.DeclaringType, opt)); } @@ -309,7 +309,7 @@ void AddAbstractMethodDeclaration (GenBase klass, Method method, InterfaceGen if if (method.Asyncify) Methods.Add (new MethodAsyncWrapper (method, opt, klass)); - if (KotlinSuspendMethodWrapper.ShouldGenerate (method, klass)) + if (KotlinSuspendMethodWrapper.ShouldGenerate (method, klass, opt)) Methods.Add (new KotlinSuspendMethodWrapper (method, opt)); } @@ -326,7 +326,7 @@ void AddMethod (GenBase klass, Method method, CodeGenerationOptions opt) if (method.Asyncify) Methods.Add (new MethodAsyncWrapper (method, opt, klass)); - if (KotlinSuspendMethodWrapper.ShouldGenerate (method, klass)) + if (KotlinSuspendMethodWrapper.ShouldGenerate (method, klass, opt)) Methods.Add (new KotlinSuspendMethodWrapper (method, opt)); } diff --git a/src/generator/SourceWriters/BoundInterface.cs b/src/generator/SourceWriters/BoundInterface.cs index e5e4562cb33..6e0373606a1 100644 --- a/src/generator/SourceWriters/BoundInterface.cs +++ b/src/generator/SourceWriters/BoundInterface.cs @@ -79,7 +79,7 @@ public BoundInterface (InterfaceGen iface, CodeGenerationOptions opt, CodeGenera return; if (!iface.AssemblyQualifiedName.Contains ('/')) { - if (iface.Methods.Any (m => m.CanHaveStringOverload) || iface.Methods.Any (m => m.Asyncify || (!m.IsStatic && KotlinSuspendMethodWrapper.ShouldGenerate (m, iface)))) + if (iface.Methods.Any (m => m.CanHaveStringOverload) || iface.Methods.Any (m => m.Asyncify || (!m.IsStatic && KotlinSuspendMethodWrapper.ShouldGenerate (m, iface, opt)))) post_sibling_types.Add (new InterfaceExtensionsClass (iface, null, opt)); } @@ -244,7 +244,7 @@ void AddMethods (InterfaceGen iface, CodeGenerationOptions opt) if (method.Asyncify) Methods.Add (new MethodAsyncWrapper (method, opt, iface)); - if (method.IsStatic && KotlinSuspendMethodWrapper.ShouldGenerate (method, iface)) + if (method.IsStatic && KotlinSuspendMethodWrapper.ShouldGenerate (method, iface, opt)) Methods.Add (new KotlinSuspendMethodWrapper (method, opt)); } } diff --git a/src/generator/SourceWriters/InterfaceExtensionsClass.cs b/src/generator/SourceWriters/InterfaceExtensionsClass.cs index 2480734ce27..617034d8a79 100644 --- a/src/generator/SourceWriters/InterfaceExtensionsClass.cs +++ b/src/generator/SourceWriters/InterfaceExtensionsClass.cs @@ -33,7 +33,7 @@ public InterfaceExtensionsClass (InterfaceGen iface, string declaringTypeName, C if (method.Asyncify) Methods.Add (new MethodExtensionAsyncWrapper (method, opt, iface.FullName)); - if (KotlinSuspendMethodWrapper.ShouldGenerate (method, iface)) + if (KotlinSuspendMethodWrapper.ShouldGenerate (method, iface, opt)) Methods.Add (new KotlinSuspendMethodWrapper (method, opt, iface.FullName)); } } diff --git a/src/generator/SourceWriters/KotlinCoroutinesHelper.cs b/src/generator/SourceWriters/KotlinCoroutinesHelper.cs new file mode 100644 index 00000000000..a51dc73e295 --- /dev/null +++ b/src/generator/SourceWriters/KotlinCoroutinesHelper.cs @@ -0,0 +1,143 @@ +using MonoDroid.Generation; + +namespace generator.SourceWriters +{ + // Writes `__KotlinCoroutines`, which the generated `*Async` methods for Kotlin `suspend` functions call. + // It uses the bound Kotlin types, so Mono.Android needs no Kotlin-specific code, and R8 keeps + // these Java types because managed code uses them. + public static class KotlinCoroutinesHelper + { + public const string TypeName = "global::__KotlinCoroutines"; + + public static bool IsSupported (CodeGenerationOptions opt) => + GetTypeName (opt, "kotlin.coroutines.Continuation") != null && + GetTypeName (opt, "kotlin.coroutines.CoroutineContext") != null && + GetTypeName (opt, "kotlin.coroutines.EmptyCoroutineContext") != null && + GetTypeName (opt, "kotlin.coroutines.intrinsics.IntrinsicsKt") != null; + + static string GetTypeName (CodeGenerationOptions opt, string javaName) => + opt.SymbolTable.Lookup (javaName) is GenBase gen ? "global::" + gen.FullName : null; + + public static void Generate (CodeGenerationOptions opt, GenerationInfo gen_info) + { + var continuation = GetTypeName (opt, "kotlin.coroutines.Continuation"); + var context = GetTypeName (opt, "kotlin.coroutines.CoroutineContext"); + var empty_context = GetTypeName (opt, "kotlin.coroutines.EmptyCoroutineContext"); + var intrinsics = GetTypeName (opt, "kotlin.coroutines.intrinsics.IntrinsicsKt"); + + // With kotlinx.coroutines, the context is a `Job`, so cancellation also stops cancellable Kotlin code. + var job = GetTypeName (opt, "kotlinx.coroutines.Job"); + var job_kt = GetTypeName (opt, "kotlinx.coroutines.JobKt"); + var use_job = job != null && job_kt != null; + + using var sw = gen_info.OpenStream (opt.GetFileName ("__KotlinCoroutines__")); + sw.Write ($$""" + // Generated for Kotlin `suspend` functions. + #nullable disable + + using System; + using System.Threading; + using System.Threading.Tasks; + + static class __KotlinCoroutines + { + public static Task InvokeAsync (Func<{{continuation}}, global::Java.Lang.Object> invoke, CancellationToken cancellationToken) => + Continuation.Start (invoke, cancellationToken); + + public static async Task InvokeAsync (Func<{{continuation}}, global::Java.Lang.Object> invoke, Func convert, CancellationToken cancellationToken) => + convert (await Continuation.Start (invoke, cancellationToken).ConfigureAwait (false)); + + sealed class Continuation : global::Java.Lang.Object, {{continuation}} + { + // A failed `kotlin.Result` is a `kotlin.Result$Failure`; a successful one is the value. + static readonly global::Java.Interop.JniType failure = new global::Java.Interop.JniType ("kotlin/Result$Failure"); + static readonly global::Java.Interop.JniFieldInfo failure_exception = failure.GetInstanceField ("exception", "Ljava/lang/Throwable;"); + + readonly TaskCompletionSource completion = new TaskCompletionSource (TaskCreationOptions.RunContinuationsAsynchronously); + readonly CancellationToken cancellationToken; + readonly CancellationTokenRegistration registration; + + """); + if (use_job) + sw.Write ($$""" + readonly {{job}} job = {{job_kt}}.Job (null); + + """); + sw.Write ($$""" + + Continuation (CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + registration = cancellationToken.Register (Cancel); + } + + public static Task Start (Func<{{continuation}}, global::Java.Lang.Object> invoke, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + return Task.FromCanceled (cancellationToken); + + var continuation = new Continuation (cancellationToken); + try { + var result = invoke (continuation); + if (result == null || !global::Android.Runtime.JNIEnv.IsSameObject (result.Handle, {{intrinsics}}.COROUTINE_SUSPENDED.Handle)) + continuation.SetResult (result); + } catch (Exception e) { + continuation.SetException (e); + } + return continuation.completion.Task; + } + + public {{context}} Context => {{(use_job ? "job" : empty_context + ".Instance")}}; + + public void ResumeWith (global::Java.Lang.Object result) + { + if (result == null || !failure.IsInstanceOfType (result.PeerReference)) { + SetResult (result); + return; + } + var throwable = global::Java.Interop.JniEnvironment.InstanceFields.GetObjectField (result.PeerReference, failure_exception); + GC.KeepAlive (result); + SetException (global::Java.Interop.JniEnvironment.Runtime.GetExceptionForThrowable (ref throwable, global::Java.Interop.JniObjectReferenceOptions.CopyAndDispose)); + } + + void SetResult (global::Java.Lang.Object value) + { + completion.TrySetResult (value); + registration.Unregister (); + } + + void SetException (Exception e) + { + if (e is global::Java.Util.Concurrent.CancellationException) + completion.TrySetCanceled (cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken (true)); + else + completion.TrySetException (e); + registration.Unregister (); + } + + """); + if (use_job) + sw.Write (""" + void Cancel () + { + try { + job.Cancel (null); + } finally { + completion.TrySetCanceled (cancellationToken); + } + } + + """); + else + sw.Write (""" + void Cancel () => completion.TrySetCanceled (cancellationToken); + + """); + sw.Write (""" + } + } + + """); + } + } +} diff --git a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs index 9bff9f5f9b1..ee31f316437 100644 --- a/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs +++ b/src/generator/SourceWriters/KotlinSuspendMethodWrapper.cs @@ -8,24 +8,25 @@ namespace generator.SourceWriters { // Exposes a Kotlin `suspend` function as a `Task`-returning `*Async` method. // The bound method keeps its trailing `Continuation` parameter; - // `Android.Runtime.KotlinCoroutines` supplies that parameter at run time. + // the generated `__KotlinCoroutines` type (see KotlinCoroutinesHelper) supplies it at run time. public class KotlinSuspendMethodWrapper : MethodWriter { - const string Runtime = "global::Android.Runtime.KotlinCoroutines"; - readonly bool suppress_obsolete_warning; - public static bool ShouldGenerate (Method method, GenBase type) => + public static bool ShouldGenerate (Method method, GenBase type, CodeGenerationOptions opt) => method.KotlinSuspendReturnType != null && method.IsValid && !method.IsOverride && string.IsNullOrEmpty (method.ExplicitInterface) && method.Parameters.Count > 0 && !method.Asyncify && - !type.ContainsName (method.AdjustedName + "Async"); + !type.ContainsName (method.AdjustedName + "Async") && + KotlinCoroutinesHelper.IsSupported (opt); public KotlinSuspendMethodWrapper (Method method, CodeGenerationOptions opt, string selfType = null) { + opt.UsesKotlinCoroutines = true; + Name = method.AdjustedName + "Async"; IsStatic = method.IsStatic || selfType != null; @@ -50,27 +51,28 @@ string GetFreeName (string name) var self = GetFreeName ("self"); var token = GetFreeName ("cancellationToken"); var continuation = GetFreeName ("__continuation"); + var value = GetFreeName ("__value"); if (selfType != null) Parameters.Add (new MethodParameterWriter (self, new TypeReferenceWriter (selfType)) { IsExtension = true }); this.AddMethodParameters (parameters, opt); Parameters.Add (new MethodParameterWriter (token, new TypeReferenceWriter ("global::System.Threading.CancellationToken")) { DefaultValue = "default" }); - var continuation_type = opt.GetOutputName (method.Parameters [method.Parameters.Count - 1].Type); var args = parameters.GetCall (opt); if (args.Length > 0) args += ", "; - args += $"global::Android.Runtime.Extensions.JavaCast<{continuation_type}> ({continuation})"; + args += continuation; var target = selfType != null ? $"{self}.{method.AdjustedName}" : method.AdjustedName; var invoke = $"{continuation} => {target} ({args})"; - // For `kotlin/Unit`, the `Task` is returned as a non-generic `Task`. - var result = GetResultType (method.KotlinSuspendReturnType, opt); - var call = result == null || method.KotlinSuspendReturnType.EndsWith ("?", StringComparison.Ordinal) - ? "CallNullableSuspendFunctionAsync" - : "CallSuspendFunctionAsync"; - ReturnType = new TypeReferenceWriter ("global::System.Threading.Tasks.Task" + (result == null ? "" : $"<{result}>")); - Body.Add ($"return {Runtime}.{call}<{result ?? "global::Java.Lang.Object"}> ({invoke}, {token});"); + var result = GetResult (method.KotlinSuspendReturnType, value, opt); + if (result.Type == null) { + ReturnType = new TypeReferenceWriter ("global::System.Threading.Tasks.Task"); + Body.Add ($"return {KotlinCoroutinesHelper.TypeName}.InvokeAsync ({invoke}, {token});"); + } else { + ReturnType = new TypeReferenceWriter ($"global::System.Threading.Tasks.Task<{result.Type}>"); + Body.Add ($"return {KotlinCoroutinesHelper.TypeName}.InvokeAsync<{result.Type}> ({invoke}, {value} => {result.Convert}, {token});"); + } suppress_obsolete_warning = !SourceWriterExtensions.IsTypeObsolete (method.DeclaringType, opt) && SourceWriterExtensions.ReferencesObsoleteType (method, opt); @@ -81,40 +83,45 @@ public override void Write (CodeWriter writer) SourceWriterExtensions.WriteWithWarningsDisabled (writer, suppress_obsolete_warning, "0618", () => base.Write (writer)); } - // Maps the Kotlin result type (e.g. `kotlin/Int?`) to a C# type. - // Returns null for `kotlin/Unit`, which becomes a non-generic `Task`. - static string GetResultType (string kotlinType, CodeGenerationOptions opt) + // Maps the Kotlin result type (e.g. `kotlin/Int?`) to a C# type, and an expression that converts `value` to it. + // Returns a null type for `kotlin/Unit`, which becomes a non-generic `Task`. + static (string Type, string Convert) GetResult (string kotlinType, string value, CodeGenerationOptions opt) { var nullable = kotlinType.EndsWith ("?", StringComparison.Ordinal); var name = nullable ? kotlinType.Substring (0, kotlinType.Length - 1) : kotlinType; - - var value_type = name switch { - "kotlin/Boolean" => "bool", - "kotlin/Byte" => "sbyte", - "kotlin/Char" => "char", - "kotlin/Short" => "short", - "kotlin/Int" => "int", - "kotlin/Long" => "long", - "kotlin/Float" => "float", - "kotlin/Double" => "double", - _ => null, + var deref = nullable ? "?" : opt.NullForgivingOperator; + + (string type, string box, string getter) primitive = name switch { + "kotlin/Boolean" => ("bool", "Boolean", "BooleanValue"), + "kotlin/Byte" => ("sbyte", "Byte", "ByteValue"), + "kotlin/Char" => ("char", "Character", "CharValue"), + "kotlin/Short" => ("short", "Short", "ShortValue"), + "kotlin/Int" => ("int", "Integer", "IntValue"), + "kotlin/Long" => ("long", "Long", "LongValue"), + "kotlin/Float" => ("float", "Float", "FloatValue"), + "kotlin/Double" => ("double", "Double", "DoubleValue"), + _ => default, }; - if (value_type != null) - return nullable ? value_type + "?" : value_type; + if (primitive.type != null) + return (nullable ? primitive.type + "?" : primitive.type, + $"{JavaCast ($"global::Java.Lang.{primitive.box}", value)}{deref}.{primitive.getter} ()"); if (name == "kotlin/Unit" && !nullable) - return null; + return (null, null); - string reference; + var reference_nullable = nullable ? opt.NullableOperator : ""; if (name == "kotlin/String") - reference = "string"; + return ("string" + reference_nullable, $"{value}{deref}.ToString ()" + (nullable ? "" : opt.NullForgivingOperator)); + // Inline classes are boxed in this position; generic, invalid or non-public types are not generated. - else if (opt.SymbolTable.Lookup (name.Replace ('/', '.')) is GenBase { IsValid: true, IsGeneric: false, RawVisibility: "public" } gen && gen is not ClassGen { IsKotlinInlineClass: true }) - reference = opt.GetOutputName (gen.FullName); - else - reference = "global::Java.Lang.Object"; + if (opt.SymbolTable.Lookup (name.Replace ('/', '.')) is GenBase { IsValid: true, IsGeneric: false, RawVisibility: "public" } gen && gen is not ClassGen { IsKotlinInlineClass: true }) { + var type = opt.GetOutputName (gen.FullName); + return (type + reference_nullable, JavaCast (type, value) + (nullable ? "" : opt.NullForgivingOperator)); + } - return nullable ? reference + opt.NullableOperator : reference; + return ("global::Java.Lang.Object" + reference_nullable, value); } + + static string JavaCast (string type, string value) => $"global::Android.Runtime.Extensions.JavaCast<{type}> ({value})"; } } diff --git a/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs b/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs index 25fd96d6df9..c9db8f0bbf4 100644 --- a/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs +++ b/tests/MSBuildDeviceIntegration/Tests/KotlinSuspendTests.cs @@ -10,7 +10,7 @@ namespace Xamarin.Android.Build.Tests public class KotlinSuspendTests : DeviceTest { // Binds a Gradle module with Kotlin `suspend` functions and awaits the generated `*Async` methods. - // R8 checks the keep rules for the Kotlin members that KotlinCoroutines finds by name. + // R8 checks that the Java types the generated `__KotlinCoroutines` uses are kept. [TestMethod] public void SuspendFunctionsAsTasks () { diff --git a/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs b/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs index 5f4b87e1ddd..73f17b66655 100644 --- a/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs +++ b/tests/generator-Tests/Unit-Tests/KotlinSuspendTests.cs @@ -1,5 +1,8 @@ +using System.IO; using System.Xml.Linq; +using generator.SourceWriters; using Microsoft.VisualStudio.TestTools.UnitTesting; +using MonoDroid.Generation; namespace generatortests { @@ -7,36 +10,41 @@ namespace generatortests [TestClass] public class KotlinSuspendTests { - const string Call = "global::Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync"; - const string CallNullable = "global::Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync"; - const string Continuation = "global::Android.Runtime.Extensions.JavaCast (__continuation)"; + const string Call = "global::__KotlinCoroutines.InvokeAsync"; const string Token = "global::System.Threading.CancellationToken cancellationToken = default"; + // In a real build, these types come from the Kotlin standard library binding. + const string KotlinStdLib = + "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; + [TestMethod] public void GeneratesTaskWrappersForSuspendFunctions () { - // In a real build, `Continuation` comes from the Kotlin.StdLib reference assembly. var api = XDocument.Parse (KotlinInlineClassEndToEndTests.BuildApiXmlFromKotlinFixture ("SuspendFunctions.class", "SuspendCallback.class")); - api.Root.AddFirst (XElement.Parse ( - "" + - "" + - "")); + api.Root.AddFirst (XElement.Parse ("" + KotlinStdLib + "").Elements ()); var output = KotlinInlineClassEndToEndTests.GenerateCSharp (api.ToString ()).Output; // The bound method that takes the Continuation is unchanged. Assert.Contains ("public Java.Lang.Object GetInt (int value, Kotlin.Coroutines.IContinuation _completion)", output); Assert.Contains ($"public global::System.Threading.Tasks.Task GetIntAsync (int value, {Token})", output); - Assert.Contains ($"return {Call} (__continuation => GetInt (value, {Continuation}), cancellationToken);", output); + Assert.Contains ($"return {Call} (__continuation => GetInt (value, __continuation), __value => global::Android.Runtime.Extensions.JavaCast (__value).IntValue (), cancellationToken);", output); Assert.Contains ($"public global::System.Threading.Tasks.Task GetNullableStringAsync ({Token})", output); - Assert.Contains ($"return {CallNullable} (__continuation => GetNullableString ({Continuation}), cancellationToken);", output); + Assert.Contains ("__value => __value?.ToString ()", output); Assert.Contains ($"public global::System.Threading.Tasks.Task GetNullableIntAsync ({Token})", output); - Assert.Contains ($"return {CallNullable} (__continuation => GetNullableInt ({Continuation}), cancellationToken);", output); + Assert.Contains ("__value => global::Android.Runtime.Extensions.JavaCast (__value)?.IntValue ()", output); Assert.Contains ($"public global::System.Threading.Tasks.Task DoWorkAsync ({Token})", output); - Assert.Contains ($"return {CallNullable} (__continuation => DoWork ({Continuation}), cancellationToken);", output); + Assert.Contains ($"return {Call} (__continuation => DoWork (__continuation), cancellationToken);", output); // A type parameter result is not inferred. Assert.Contains ("public global::System.Threading.Tasks.Task EchoAsync (Java.Lang.Object value, ", output); @@ -45,7 +53,40 @@ public void GeneratesTaskWrappersForSuspendFunctions () // Generated names do not collide with Kotlin parameter names. Assert.Contains ("MergeAsync (this Xat.Bytecode.Tests.ISuspendCallback _self, bool self, int cancellationToken, global::System.Threading.CancellationToken _cancellationToken = default)", output); - Assert.Contains ("(__continuation => _self.Merge (self, cancellationToken, ", output); + Assert.Contains ("(__continuation => _self.Merge (self, cancellationToken, __continuation), ", output); + } + + [TestMethod] + public void UsesKotlinxJobWhenAvailable () + { + string Generate (string extraApi) + { + var opt = new CodeGenerationOptions (); + foreach (var gen in XmlApiImporter.Parse (XDocument.Parse ("" + KotlinStdLib + extraApi + ""), opt)) + opt.SymbolTable.AddType (gen); + Assert.IsTrue (KotlinCoroutinesHelper.IsSupported (opt)); + + var dir = Path.Combine (Path.GetTempPath (), Path.GetRandomFileName ()); + try { + KotlinCoroutinesHelper.Generate (opt, new GenerationInfo (dir, "", "MyAssembly")); + return File.ReadAllText (Path.Combine (dir, "__KotlinCoroutines__.cs")); + } finally { + Directory.Delete (dir, recursive: true); + } + } + + var without_kotlinx = Generate (""); + Assert.Contains ("public global::Kotlin.Coroutines.ICoroutineContext Context => global::Kotlin.Coroutines.EmptyCoroutineContext.Instance;", without_kotlinx); + Assert.DoesNotContain ("Job", without_kotlinx); + + var with_kotlinx = Generate ( + "" + + "" + + "" + + ""); + Assert.Contains ("readonly global::Kotlinx.Coroutines.IJob job = global::Kotlinx.Coroutines.JobKt.Job (null);", with_kotlinx); + Assert.Contains ("public global::Kotlin.Coroutines.ICoroutineContext Context => job;", with_kotlinx); + Assert.Contains ("job.Cancel (null);", with_kotlinx); } } } From 612da8c3c22a588fe3ebec20fb5f196074224418 Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 30 Nov 2026 15:36:57 -0600 Subject: [PATCH 11/13] [generator] Simplify the generated Kotlin coroutine helper 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> --- .../SourceWriters/KotlinCoroutinesHelper.cs | 37 ++++--------------- 1 file changed, 8 insertions(+), 29 deletions(-) diff --git a/src/generator/SourceWriters/KotlinCoroutinesHelper.cs b/src/generator/SourceWriters/KotlinCoroutinesHelper.cs index a51dc73e295..6328b39d728 100644 --- a/src/generator/SourceWriters/KotlinCoroutinesHelper.cs +++ b/src/generator/SourceWriters/KotlinCoroutinesHelper.cs @@ -3,8 +3,7 @@ namespace generator.SourceWriters { // Writes `__KotlinCoroutines`, which the generated `*Async` methods for Kotlin `suspend` functions call. - // It uses the bound Kotlin types, so Mono.Android needs no Kotlin-specific code, and R8 keeps - // these Java types because managed code uses them. + // It uses the bound Kotlin types, which R8 keeps because managed code uses them. public static class KotlinCoroutinesHelper { public const string TypeName = "global::__KotlinCoroutines"; @@ -29,6 +28,9 @@ public static void Generate (CodeGenerationOptions opt, GenerationInfo gen_info) var job = GetTypeName (opt, "kotlinx.coroutines.Job"); var job_kt = GetTypeName (opt, "kotlinx.coroutines.JobKt"); var use_job = job != null && job_kt != null; + var job_field = use_job ? $"readonly {job} job = {job_kt}.Job (null);" : ""; + var context_value = use_job ? "job" : empty_context + ".Instance"; + var cancel_job = use_job ? " job.Cancel (null);" : ""; using var sw = gen_info.OpenStream (opt.GetFileName ("__KotlinCoroutines__")); sw.Write ($$""" @@ -56,14 +58,7 @@ sealed class Continuation : global::Java.Lang.Object, {{continuation}} readonly TaskCompletionSource completion = new TaskCompletionSource (TaskCreationOptions.RunContinuationsAsynchronously); readonly CancellationToken cancellationToken; readonly CancellationTokenRegistration registration; - - """); - if (use_job) - sw.Write ($$""" - readonly {{job}} job = {{job_kt}}.Job (null); - - """); - sw.Write ($$""" + {{job_field}} Continuation (CancellationToken cancellationToken) { @@ -87,7 +82,7 @@ sealed class Continuation : global::Java.Lang.Object, {{continuation}} return continuation.completion.Task; } - public {{context}} Context => {{(use_job ? "job" : empty_context + ".Instance")}}; + public {{context}} Context => {{context_value}}; public void ResumeWith (global::Java.Lang.Object result) { @@ -115,29 +110,13 @@ void SetException (Exception e) registration.Unregister (); } - """); - if (use_job) - sw.Write (""" void Cancel () { - try { - job.Cancel (null); - } finally { - completion.TrySetCanceled (cancellationToken); - } + completion.TrySetCanceled (cancellationToken);{{cancel_job}} } - - """); - else - sw.Write (""" - void Cancel () => completion.TrySetCanceled (cancellationToken); - - """); - sw.Write (""" } } - """); - } + """); } } } From 65636c8079b0632689ab95fc74a0e061b04c2dfa Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Tue, 1 Dec 2026 16:03:45 -0600 Subject: [PATCH 12/13] [tests] Bind kotlinx-coroutines-android in KotlinSuspendFunctionsAsTasks 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> --- .../BindingBuildTest.cs | 32 ++++++------------- 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs index 3df5e8e9d01..d045fd5c559 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs @@ -1276,40 +1276,26 @@ static BuildItem CreateMavenLibrary (string artifact) [DoNotParallelize] // Shares the Maven cache with the other AndroidMavenLibrary tests public void KotlinSuspendFunctionsAsTasks () { - // androidx.datastore has real Kotlin `suspend` APIs, such as `PreferencesKt.edit`. - // The NuGet packages for its dependencies are at 1.2.1. - var datastore = new BuildItem ("AndroidMavenLibrary", "androidx.datastore:datastore-preferences-core-jvm"); - datastore.Metadata.Add ("Version", "1.2.1"); - datastore.Metadata.Add ("Repository", TestEnvironment.DotNetPublicMaven); + // kotlinx-coroutines-android has a real Kotlin `suspend` API: `suspend fun awaitFrame(): Long`. + var library = new BuildItem ("AndroidMavenLibrary", "org.jetbrains.kotlinx:kotlinx-coroutines-android"); + library.Metadata.Add ("Version", "1.10.2"); + library.Metadata.Add ("Repository", TestEnvironment.DotNetPublicMaven); var proj = new XamarinAndroidBindingProject { - Jars = { datastore }, + Jars = { library }, PackageReferences = { - new Package { Id = "Xamarin.AndroidX.DataStore.Core.Jvm", Version = "1.2.1.1" }, - new Package { Id = "Xamarin.AndroidX.DataStore.Core.OkIO.Jvm", Version = "1.2.1.1" }, - new Package { Id = "Xamarin.AndroidX.DataStore.Preferences.Proto", Version = "1.2.1.1" }, - new Package { Id = "Square.OkIO.JVM", Version = "3.17.0.1" }, + new Package { Id = "Xamarin.KotlinX.Coroutines.Core.Jvm", Version = "1.10.2.3" }, new Package { Id = "Xamarin.Kotlin.StdLib", Version = "2.4.0.1" }, }, - // The serializers need the generic-interface fixes from dotnet/android-libraries; this test does not use them. - MetadataXml = """ - - - - - """, }; using var b = CreateDllBuilder (); Assert.IsTrue (b.Build (proj), "Build should have succeeded."); - var cs_file = b.Output.GetIntermediaryPath (Path.Combine ("generated", "src", "Androidx.Datastore.Preferences.Core.PreferencesKt.cs")); - Assert.IsTrue (File.Exists (cs_file)); - var code = File.ReadAllText (cs_file); - Assert.Contains ("public static global::System.Threading.Tasks.Task EditAsync (global::AndroidX.DataStore.Core.IDataStore obj, global::Kotlin.Jvm.Functions.IFunction2 transform, global::System.Threading.CancellationToken cancellationToken = default)", code); - Assert.Contains ("global::__KotlinCoroutines.InvokeAsync (__continuation => Edit (", code); + var code = File.ReadAllText (b.Output.GetIntermediaryPath (Path.Combine ("generated", "src", "Kotlinx.Coroutines.Android.HandlerDispatcherKt.cs"))); + Assert.Contains ("public static global::System.Threading.Tasks.Task AwaitFrameAsync (global::System.Threading.CancellationToken cancellationToken = default)", code); - // DataStore references kotlinx.coroutines, so cancellation uses a `Job`. + // The binding references kotlinx.coroutines, so cancellation uses a `Job`. var helper = File.ReadAllText (b.Output.GetIntermediaryPath (Path.Combine ("generated", "src", "__KotlinCoroutines__.cs"))); Assert.Contains ("JobKt.Job (null)", helper); } From b88db3bfd08153f6aab78be4b25558a9c6f170e1 Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Wed, 2 Dec 2026 10:17:09 -0600 Subject: [PATCH 13/13] [generator] Keep JNI peers alive in the COROUTINE_SUSPENDED check 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> --- src/generator/SourceWriters/KotlinCoroutinesHelper.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/generator/SourceWriters/KotlinCoroutinesHelper.cs b/src/generator/SourceWriters/KotlinCoroutinesHelper.cs index 6328b39d728..daeca8f0c64 100644 --- a/src/generator/SourceWriters/KotlinCoroutinesHelper.cs +++ b/src/generator/SourceWriters/KotlinCoroutinesHelper.cs @@ -54,6 +54,7 @@ sealed class Continuation : global::Java.Lang.Object, {{continuation}} // A failed `kotlin.Result` is a `kotlin.Result$Failure`; a successful one is the value. static readonly global::Java.Interop.JniType failure = new global::Java.Interop.JniType ("kotlin/Result$Failure"); static readonly global::Java.Interop.JniFieldInfo failure_exception = failure.GetInstanceField ("exception", "Ljava/lang/Throwable;"); + static readonly global::Java.Lang.Object suspended = {{intrinsics}}.COROUTINE_SUSPENDED; readonly TaskCompletionSource completion = new TaskCompletionSource (TaskCreationOptions.RunContinuationsAsynchronously); readonly CancellationToken cancellationToken; @@ -74,7 +75,9 @@ sealed class Continuation : global::Java.Lang.Object, {{continuation}} var continuation = new Continuation (cancellationToken); try { var result = invoke (continuation); - if (result == null || !global::Android.Runtime.JNIEnv.IsSameObject (result.Handle, {{intrinsics}}.COROUTINE_SUSPENDED.Handle)) + var is_suspended = result != null && global::Android.Runtime.JNIEnv.IsSameObject (result.Handle, suspended.Handle); + GC.KeepAlive (result); + if (!is_suspended) continuation.SetResult (result); } catch (Exception e) { continuation.SetException (e);