Repository navigation
[generator] Generate C# overloads for Kotlin default arguments - #13582
jonathanpeppers wants to merge 12 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
ad3b534 to
c54f826
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
…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 <[email protected]>
…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 <[email protected]>
* 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 <[email protected]>
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 <[email protected]>
0613918 to
8be1df4
Compare
Review fixes: * Also detect the string overload of a method that returns CharSequence (it uses the plain name, not the \Formatted\ name). * Ignore \params\ when comparing signatures; \params string[]\ and \string[]\ are the same C# signature. * Also detect methods of interfaces implemented by base classes, and the default-argument overloads of base classes and parent interfaces. * Declare an omitted boxed Kotlin value class as \ ull\, not as a boxed default value, to avoid a JNI box call. Co-authored-by: Copilot App <[email protected]>
Use one GetParameterCounts () helper instead of three loops over the trailing defaulted parameters, check enum return types in IsSupported (), and remove the Take () helper. Co-authored-by: Copilot App <[email protected]>
|
/review |
|
✅ Android PR Reviewer completed successfully! Warning Firewall blocked 1 domainThe following domain was blocked by the firewall during workflow execution:
To allow these domains, add them to the network:
allowed:
- defaults
- "169.254.169.254"See Network Configuration for more information.
|
There was a problem hiding this comment.
⚠️ Needs Changes
Findings: 0 errors, 1 warning, 0 suggestions. No confirmed correctness regression found; the inline warning concerns missing runtime coverage for the newly generated JNI calls.
The exact-helper matching, trailing-default restriction, final-class constructor guard, and inherited/string/params signature checks are appropriately conservative. The new attributes survive the JavaTypeSystem import/export path. I also traced the R8 configuration: retained typemap peers receive all-member keep rules, and the added runtime-remapping rule preserves $default method names. I am not repeating the previously resolved helper-retention finding.
CI: GitHub reports 2 successful checks, 4 running checks, and the aggregate dotnet-android check queued for Azure build 1695305; no failed checks were returned. CI is not yet verified green. The Azure build-status query was blocked by the CLI's authentication requirement.
Local validation: Neither focused test attempt reached test execution:
dotnet test tests/generator-Tests/generator-Tests.csproj --filter FullyQualifiedName~KotlinDefaultArgumentsTests -v minimalfailed with CS9363 in unchangedJava.Interop/JniNativeMethodRegistration.cslines 50–51 using SDK 11.0.100.dotnet test tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj --filter FullyQualifiedName~JvmOverloadsConstructorTests -v quietfailed because the configured JDK 25javaccould not run (exit 127).
Reviewed the full sources for all 18 changed files and relevant generator/R8 callers. No tracked files were modified.
Warning
Firewall blocked 1 domain
The following domain was blocked by the firewall during workflow execution:
169.254.169.254
To allow these domains, add them to the network.allowed list in your workflow frontmatter:
network:
allowed:
- defaults
- "169.254.169.254"See Network Configuration for more information.
Generated by Android PR Reviewer for #13582 · copilot · gpt61 · 74.2 AIC · ⌖ 8.07 AIC · ⊞ 20.3K
Comment /review to run again
Add Kotlin functions and classes with default arguments to the Mono.Android-Tests.Gradle library, and on-device tests that call the new overloads and check the values that Kotlin computes: a default computed from another argument, a constructor default, and an override that the \\\ helper calls through virtual dispatch. The constructor overloads pass a kotlin.jvm.internal.DefaultConstructorMarker, so the test app now gets kotlin-stdlib from Maven without binding it. Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
The Kotlin test library now has a virtual method, so its binding generates a _JniMarshal_PPII_I delegate. Mono.Android has an internal type with the same name, which this project sees through InternalsVisibleTo. CI builds treat the warning as an error. Co-authored-by: Copilot App <[email protected]>


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:
The binding gets one new overload for each trailing parameter with a default value. For the class above, it has these members:
greetingandnamehave no default values, so there is noGreet ()and noDefaultArguments ().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.Why overloads, not C# optional parameters
A C# optional parameter needs a compile-time constant, and the compiler copies that constant into the code of each caller. A Kotlin default is any expression that is evaluated at run time, for example
count: Int = items.size,list: List<T> = emptyList (), orcause: Throwable? = RuntimeException (). The Kotlin metadata only says that a parameter has a default (DeclaresDefaultValue). It does not contain the value. The value exists only as bytecode in the$defaulthelper. So the binding cannot generateGreet (string greeting, int times = 2, bool loud = false), because it does not know2orfalse. If it guessed, and a later version of the library changed its default, compiled apps would keep the old value.Optional parameters with a "not specified" marker value would let callers skip a parameter in the middle with a named argument. But that needs a new public marker type, because
nullcannot mean "not specified" for nullable Kotlin parameters. Overloads cover the common case, leaving out the last parameters, with plain C# types and no new API.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, an inherited interface, or a default-argument overload of a base type.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.Mono.Android.NET-Tests(Debug, CoreCLR, API 37 x86_64 emulator): 1111 passed, 8 skipped.KotlinDefaultArgumentTestscalls the new overloads of a Kotlin library intests/Mono.Android-Tests.Gradleand checks the values that Kotlin computes: a default computed from another argument (offset: Int = factor + 1), a constructor default (step: Int = start * 2), and anopenmethod that the$defaulthelper calls through virtual dispatch on a Kotlin subclass. The constructor overloads pass akotlin.jvm.internal.DefaultConstructorMarker, so the test app now getskotlin-stdlibfrom Maven without binding it. Real Kotlin bindings already depend onXamarin.Kotlin.StdLib.