Repository navigation
[generator] Bind Kotlin default arguments as C# overloads - #13582
jonathanpeppers wants to merge 7 commits into
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Generated overloads can fail to compile when helper names collide with parameters, while missing retention and remapping metadata for $default helpers can cause runtime lookup failures in R8-enabled apps.
4 open issues
What changed in this PR
Adds Kotlin default-argument support to the .NET for Android binding pipeline, generating C# overloads that omit trailing defaulted parameters and delegate default-value computation to Kotlin helpers.
Changes:
- Detects Kotlin default helpers and preserves their metadata through API XML processing.
- Generates method, interface, and eligible constructor overloads with default-argument masks.
- Adds Kotlin fixtures, generator assertions, and a binding build test.
| File | Description |
|---|---|
tests/Xamarin.Android.Tools.Bytecode-Tests/Resources/JvmOverloadsConstructor.xml |
Updates expected constructor metadata. |
tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle/src/main/kotlin/DefaultArguments.kt |
Adds Kotlin default-argument fixtures. |
tests/Xamarin.Android.Tools.Bytecode-Tests/kotlin-gradle.targets |
Tracks the new fixture output. |
tests/generator-Tests/Unit-Tests/KotlinInlineClassEndToEndTests.cs |
Shares fixture and generation helpers. |
tests/generator-Tests/Unit-Tests/KotlinDefaultArgumentsTests.cs |
Checks generated overloads and helper calls. |
tests/generator-Tests/generator-Tests.csproj |
Embeds compiled Kotlin fixtures. |
src/Xamarin.Android.Tools.Bytecode/XmlClassDeclarationBuilder.cs |
Emits default-argument XML attributes. |
src/Xamarin.Android.Tools.Bytecode/Methods.cs |
Stores Kotlin helper metadata. |
src/Xamarin.Android.Tools.Bytecode/Kotlin/KotlinFixups.cs |
Finds matching default helpers. |
src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BindingBuildTest.cs |
Adds a constructor-overload binding test. |
src/Java.Interop.Tools.JavaTypeSystem/Adapters/JavaXmlApiImporter.cs |
Preserves metadata during API adjustment. |
src/generator/SourceWriters/KotlinDefaultArguments.cs |
Implements overload and helper-call generation. |
src/generator/SourceWriters/BoundInterface.cs |
Integrates interface overload generation. |
src/generator/SourceWriters/BoundClass.cs |
Integrates class and constructor overload generation. |
src/generator/Java.Interop.Tools.Generator.ObjectModel/MethodBase.cs |
Adds generator-side default-argument metadata. |
src/generator/Java.Interop.Tools.Generator.Importers/XmlApiImporter.cs |
Imports default-argument attributes. |
Review effort: Balanced
| if (hasReceiver) | ||
| body.Add ($"var {Receiver} = this;"); |
There was a problem hiding this comment.
Not changing this. Every generated binding method already declares fixed locals (__id, __args, __rm, native_*) that a Java parameter with the same name would collide with. Parameters named __self, __mask0, or __marker are the same kind of case, so they follow that existing convention.
46af2b1 to
ad3b534
Compare
Context: https://github.com/Redth/AndroidBindingsExperiments Kotlin functions and constructors with default parameter values are bound with every argument required, because the `$default` helpers and the `DefaultConstructorMarker` constructors that kotlinc emits are synthetic and are hidden. class-parse now records, for each public Kotlin function or constructor that has parameters with `DeclaresDefaultValue`, the exact JNI signature of its helper (`name$default (receiver?, params..., int masks..., Object)` on the declaring type or its `$DefaultImpls` class, or `<init> (params..., int masks..., DefaultConstructorMarker)`), as `kotlin-default-jni-signature`, `kotlin-default-owner`, and `kotlin-default-parameters` attributes. The helper must exist with the expected descriptor; otherwise nothing is recorded and the full-argument API is kept. Functions with extension receivers, continuations, or outer-class parameters are skipped, because they change the mask bit positions. Java.Interop.Tools.JavaTypeSystem keeps these attributes when it rewrites api.xml. The generator then creates one overload for each trailing parameter that can be omitted. The overload declares locals for the omitted parameters, sets one `int` mask bit for each of them (one mask for each 32 parameters), and calls the helper through JNI: * Class methods (instance and static) call the static `$default` helper with `this` as the receiver, so Kotlin still dispatches virtually. * Interface methods become default interface methods (only when `SupportDefaultInterfaceMethods` is on) and use a private `JniPeerMembers` for the helper owner. * Constructors are generated only for final classes: a derived managed type is created through its Java Callable Wrapper, which does not have the synthetic constructor. They have no `[Register]`. An overload is not generated when a member with the same name and parameter types already exists (for example, from `@JvmOverloads`). Defaults in the middle of the parameter list are not exposed. Validation: * `dotnet test tests/generator-Tests/generator-Tests.csproj`: 479 passed (new end-to-end test uses real kotlinc output through class-parse, JavaTypeSystem, and the generator) * `dotnet test tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj`: 132 passed, 2 skipped * `dotnet test tests/Java.Interop.Tools.JavaTypeSystem-Tests/Java.Interop.Tools.JavaTypeSystem-Tests.csproj`: 18 passed * `dotnet test tests/Java.Interop.Tools.Generator-Tests`: 18 passed * Full SDK build and on-device tests were not run. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Remove the redundant JavaTypeSystem round-trip test; the generator end-to-end test already runs class-parse output through JavaXmlApiImporter/JavaXmlApiExporter. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Rubber-duck review fixes: * Detect existing overloads by C# parameter types, using the generated members (string overloads, abstract interface members) and inherited methods. JNI types missed collections and inline classes that map to the same or different C# types. * Mark overloads such as ToString () with \ ew\ when they hide a System.Object member. * Skip protected constructors on sealed classes, and members with generated enum parameters or returns, whose helper clone loses the enum type. * Ignore empty kotlin-default-* attributes (for example, cleared in Metadata.xml). * Add the interface JniPeerMembers field only when an overload uses it. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…verload datastore-core-jvm 1.2.1 has \class CorruptionException (message: String, cause: Throwable? = null)\. The test binds it with <AndroidMavenLibrary> (class-parse, api-xml-adjuster, generator) and checks that the binding has a CorruptionException (string) constructor that calls the DefaultConstructorMarker constructor. The library also has @jvmoverloads methods (DataStoreFactory.create), so the build also confirms that no duplicate overloads are generated. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…helper The rebased KotlinInlineClassEndToEndTests helper now runs class-parse output through the JavaTypeSystem adjuster and resolves types, so the test no longer does its own round trip. Add java.lang.String to the helper's reference API, which a real build gets from Mono.Android. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
ad3b534 to
c54f826
Compare
* Detect existing overloads from the generator model: the type's methods, inherited class methods, and methods of implemented or inherited interfaces. A child interface no longer hides an inherited method with the same C# parameters. The signature keeps the \?\ of boxed Kotlin value classes and ignores nullable reference annotations. * Do not use \\\ helpers. That class has no managed peer, so R8 can remove it. * Keep \\\ method names in AndroidR8ObfuscationMode=runtime-remapping, because the overloads call them by name over JNI. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Since \\\ helpers are no longer used, the helper is always on the declaring type. Remove the kotlin-default-owner attribute and its properties, and use the interface's \_members\ field instead of a separate one. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>


Context: #13581
Note
This PR is stacked on #13581. Review only the commits in this PR.
Kotlin parameters can have default values:
Kotlin callers can leave out the parameters that have defaults, but the C# binding requires every argument. Today, C# must write:
With this change, the binding also has overloads that leave out the trailing parameters with default values, so C# can write:
Kotlin, not C#, computes the default values. This means a default such as
count: Int = items.sizealso works.How it works
For each function with default values, kotlinc emits a static helper,
greet$default. Its arguments are the receiver, all the parameters, and anintbit mask. Each bit in the mask tells Kotlin to use the default value for that parameter. Constructors get a similar synthetic constructor with aDefaultConstructorMarkerparameter. These helpers are synthetic, so the binding generator hides them today.class-parse now finds the exact helper and writes its JNI signature to api.xml (
kotlin-default-jni-signatureandkotlin-default-parameters). The generator then creates overloads that call the helper. Here is the generatedGreet (string)(part of the JNI marshaling code is removed):And the generated constructor:
Instance methods pass
thisto the static helper, so Kotlin still calls the overriding method of a subclass. With$(AndroidR8ObfuscationMode)set toruntime-remapping, R8 keeps the names of$defaultmethods, because the overloads call them by name.What does not get overloads
The generator keeps the full-argument API, and makes no overloads, when:
$DefaultImplsclass (older Kotlin), because R8 can remove that class.fun middle (first: Int = 1, second: Int)gets noMiddle (int second).suspendfunction, because the extra parameters move the mask bits.@JvmOverloads, a string overload, a base class, or an inherited interface.final. A C# subclass is created through its Java Callable Wrapper, which does not have the synthetic constructor. (This applies to constructors only.)protected, or a parameter or return type is a generated enum.Interface overloads are generated only when default interface methods are enabled. An overload that hides an
objectmember, such asToString (), is markednew.Validation
dotnet test tests/generator-Tests/generator-Tests.csproj: 495 passed.KotlinDefaultArgumentsTestsruns real kotlinc output fromkotlin-gradle/src/main/kotlin/DefaultArguments.ktthrough class-parse, the api.xml adjuster, and the generator.dotnet test tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj: 138 passed, 2 skipped.dotnet test tests/Java.Interop.Tools.JavaTypeSystem-Tests/Java.Interop.Tools.JavaTypeSystem-Tests.csproj: 17 passed.dotnet-local.cmd test bin/TestDebug/net11.0/Xamarin.Android.Build.Tests.dll --filter "FullyQualifiedName~R8Tests|Name=KotlinDefaultArgumentOverloads|Name=AndroidMavenLibrary_KotlinValueClasses": 33 passed.KotlinDefaultArgumentOverloadsbindsandroidx.datastore:datastore-core-jvm1.2.1 and checks thatclass CorruptionException (message: String, cause: Throwable? = null)gets aCorruptionException (string message)constructor.