Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> bag, string [] names)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1272,6 +1272,34 @@ static BuildItem CreateMavenLibrary (string artifact)
}
}

[TestMethod]
[DoNotParallelize] // Shares the Maven cache with the other AndroidMavenLibrary tests
public void KotlinSuspendFunctionsAsTasks ()
{
// 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 = { library },
PackageReferences = {
new Package { Id = "Xamarin.KotlinX.Coroutines.Core.Jvm", Version = "1.10.2.3" },
new Package { Id = "Xamarin.Kotlin.StdLib", Version = "2.4.0.1" },
},
};

using var b = CreateDllBuilder ();
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");

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<long> AwaitFrameAsync (global::System.Threading.CancellationToken cancellationToken = default)", code);

// 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);
}

[TestMethod]
[DoNotParallelize] // All tests download androidx.core:core into the same Maven cache
public void AndroidMavenLibrary_FailsDueToUnverifiedDependency ()
Expand Down
15 changes: 15 additions & 0 deletions src/Xamarin.Android.Tools.Bytecode/Kotlin/KotlinFixups.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -429,6 +433,17 @@ static void FixupDefaultArguments (MethodInfo? method, List<KotlinValueParameter
method.KotlinDefaultParameters = defaults;
}

// Type parameters have no class name, so they become `kotlin/Any?`.
// Platform types (`T!`) from Java can be null.
static string GetSuspendReturnType (KotlinType? type)
{
var name = type?.ClassName?.TrimEnd (';');
if (type is null || name is null || name.Length == 0)
return "kotlin/Any?";
var nullable = type.Nullable || type.FlexibleUpperBound != null || type.FlexibleTypeCapabilitiesId != null;
return nullable ? name + "?" : name;
}

static string PascalCase (string name)
{
if (string.IsNullOrEmpty (name) || char.IsUpper (name [0]))
Expand Down
3 changes: 3 additions & 0 deletions src/Xamarin.Android.Tools.Bytecode/Methods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ public sealed class MethodInfo {
public string? KotlinDefaultJniSignature { get; set; }
public int[]? KotlinDefaultParameters { get; set; }

// Kotlin result type of a `suspend` function (e.g. `kotlin/Int?`), which the JVM erases to `Object`.
public string? KotlinSuspendReturnType { get; set; }

public MethodInfo (ConstantPool constantPool, ClassFile declaringType, Stream stream)
{
ConstantPool = constantPool;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,7 @@ XElement GetMethod (string element, string name, MethodInfo method, string? retu
ret,
jniRet,
GetKotlinInlineClassReturnJniType (method),
method.KotlinSuspendReturnType != null ? new XAttribute ("kotlin-suspend-return-type", method.KotlinSuspendReturnType) : null,
new XAttribute ("static", (method.AccessFlags & MethodAccessFlags.Static) != 0),
GetSynchronized (method),
new XAttribute ("visibility", GetVisibility (method.AccessFlags)),
Expand Down
4 changes: 4 additions & 0 deletions src/Xamarin.SourceWriter/Models/MethodParameterWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public class MethodParameterWriter
public List<AttributeWriter> Attributes { get; } = new List<AttributeWriter> ();
public string Name { get; set; }
public bool IsExtension { get; set; }
public string DefaultValue { get; set; }

public MethodParameterWriter (string name, TypeReferenceWriter type)
{
Expand All @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions src/generator/CodeGenerationOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ public SymbolTable SymbolTable {
readonly SortedSet<string> jni_marshal_delegates = new SortedSet<string> (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; }
Expand Down
4 changes: 4 additions & 0 deletions src/generator/CodeGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Java.Interop.Tools.JavaTypeSystem;
using System.Text;
using generator;
using generator.SourceWriters;

namespace Xamarin.Android.Binder
{
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@ public static Method CreateMethod (GenBase declaringType, XElement elem, CodeGen
ManagedOverride = elem.XGetAttribute ("managedOverride"),
ManagedReturn = elem.XGetAttribute ("managedReturn"),
KotlinInlineClassReturnJniType = elem.Attribute ("kotlin-inline-class-return-jni-type") != null ? elem.XGetAttribute ("kotlin-inline-class-return-jni-type") : null,
KotlinSuspendReturnType = elem.Attribute ("kotlin-suspend-return-type")?.Value,
PropertyNameOverride = elem.XGetAttribute ("propertyName"),
Return = elem.XGetAttribute ("return"),
ReturnNotNull = elem.XGetAttribute ("return-not-null") == "true",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ public Method (GenBase declaringType) : base (declaringType)
public string ManagedOverride { get; set; }
public string ManagedReturn { get; set; }
public string KotlinInlineClassReturnJniType { get; set; }
// Kotlin result type of a `suspend` function (e.g. `kotlin/Int?`), or null.
public string KotlinSuspendReturnType { get; set; }
public string PropertyNameOverride { get; set; }
public string Return { get; set; }
public bool ReturnNotNull { get; set; }
Expand Down Expand Up @@ -159,6 +161,7 @@ public Method Clone (GenBase declaringType)
clone.ManagedOverride = ManagedOverride;
clone.ManagedReturn = ManagedReturn;
clone.KotlinInlineClassReturnJniType = KotlinInlineClassReturnJniType;
clone.KotlinSuspendReturnType = KotlinSuspendReturnType;
clone.PropertyNameOverride = PropertyNameOverride;
clone.Return = Return;
clone.ReturnNotNull = ReturnNotNull;
Expand Down
8 changes: 7 additions & 1 deletion src/generator/SourceWriters/BoundClass.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
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));
}

Expand Down Expand Up @@ -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, opt))
Methods.Add (new KotlinSuspendMethodWrapper (method, opt));
}

void AddMethod (GenBase klass, Method method, CodeGenerationOptions opt)
Expand All @@ -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, opt))
Methods.Add (new KotlinSuspendMethodWrapper (method, opt));
}

void AddProperties (ClassGen klass, CodeGenerationOptions opt)
Expand Down
5 changes: 4 additions & 1 deletion src/generator/SourceWriters/BoundInterface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.IsStatic && KotlinSuspendMethodWrapper.ShouldGenerate (m, iface, opt))))
post_sibling_types.Add (new InterfaceExtensionsClass (iface, null, opt));
}

Expand Down Expand Up @@ -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, opt))
Methods.Add (new KotlinSuspendMethodWrapper (method, opt));
}
}

Expand Down
3 changes: 3 additions & 0 deletions src/generator/SourceWriters/InterfaceExtensionsClass.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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, opt))
Methods.Add (new KotlinSuspendMethodWrapper (method, opt, iface.FullName));
}
}

Expand Down
125 changes: 125 additions & 0 deletions src/generator/SourceWriters/KotlinCoroutinesHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
using MonoDroid.Generation;

namespace generator.SourceWriters
{
// Writes `__KotlinCoroutines`, which the generated `*Async` methods for Kotlin `suspend` functions call.
// It uses the bound Kotlin types, which R8 keeps 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;
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 ($$"""
// 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<T> InvokeAsync<T> (Func<{{continuation}}, global::Java.Lang.Object> invoke, Func<global::Java.Lang.Object, T> 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;");
static readonly global::Java.Lang.Object suspended = {{intrinsics}}.COROUTINE_SUSPENDED;

readonly TaskCompletionSource<global::Java.Lang.Object> completion = new TaskCompletionSource<global::Java.Lang.Object> (TaskCreationOptions.RunContinuationsAsynchronously);
readonly CancellationToken cancellationToken;
readonly CancellationTokenRegistration registration;
{{job_field}}

Continuation (CancellationToken cancellationToken)
{
this.cancellationToken = cancellationToken;
registration = cancellationToken.Register (Cancel);
}

public static Task<global::Java.Lang.Object> Start (Func<{{continuation}}, global::Java.Lang.Object> invoke, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<global::Java.Lang.Object> (cancellationToken);

var continuation = new Continuation (cancellationToken);
try {
var result = invoke (continuation);
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);
}
return continuation.completion.Task;
}

public {{context}} Context => {{context_value}};

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 ();
}

void Cancel ()
{
completion.TrySetCanceled (cancellationToken);{{cancel_job}}
}
}
}

"""); }
}
}
Loading
Loading