Skip to content

[generator] Generate C# overloads for Kotlin default arguments - #13582

Open
jonathanpeppers wants to merge 12 commits into
mainfrom
jonathanpeppers-kotlin-default-arguments
Open

jonathanpeppers wants to merge 12 commits into
mainfrom
jonathanpeppers-kotlin-default-arguments

Conversation

@jonathanpeppers

@jonathanpeppers jonathanpeppers commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Kotlin parameters can have default values:

class DefaultArguments (val name: String, val count: Int = 1) {
    fun greet (greeting: String, times: Int = 2, loud: Boolean = false): String
}

Kotlin callers can leave out the parameters that have defaults, but the C# binding requires every argument. Today, C# must write:

var d = new DefaultArguments ("bob", 1);
d.Greet ("hi", 2, false);

With this change, the binding also has overloads that leave out the trailing parameters with default values, so C# can write:

var d = new DefaultArguments ("bob");
d.Greet ("hi");
d.Greet ("hi", 5);

The binding gets one new overload for each trailing parameter with a default value. For the class above, it has these members:

public string Greet (string greeting, int times, bool loud)  // existing, calls greet
public string Greet (string greeting, int times)             // new, calls greet$default, mask 0b100
public string Greet (string greeting)                        // new, calls greet$default, mask 0b110

public DefaultArguments (string name, int count)             // existing
public DefaultArguments (string name)                        // new, calls the DefaultConstructorMarker constructor

greeting and name have no default values, so there is no Greet () and no DefaultArguments ().
Kotlin, not C#, computes the default values. This means a default such as count: Int = items.size also 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 an int bit mask. Each bit in the mask tells Kotlin to use the default value for that parameter. Constructors get a similar synthetic constructor with a DefaultConstructorMarker parameter. 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-signature and kotlin-default-parameters). The generator then creates overloads that call the helper. Here is the generated Greet (string) (part of the JNI marshaling code is removed):

// Kotlin default arguments: calls 'greet$default' to compute the omitted parameters.
public string Greet (string greeting)
{
	var __self = this;
	var times = default (int);  // ignored: bit 1 is set
	var loud = default (bool);  // ignored: bit 2 is set
	const int __mask0 = 6;
	var __marker = default (global::Java.Lang.Object);
	const string __id = "greet$default.(Lxat/bytecode/tests/DefaultArguments;Ljava/lang/String;IZILjava/lang/Object;)Ljava/lang/String;";
	...
	var __rm = _members.StaticMethods.InvokeObjectMethod (__id, __args);
	return JNIEnv.GetString (__rm.Handle, JniHandleOwnership.TransferLocalRef);
}

And the generated constructor:

// Kotlin default arguments: calls the 'DefaultConstructorMarker' constructor to compute the omitted parameters.
public DefaultArguments (string name) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
	var count = default (int);
	const int __mask0 = 2;
	var __marker = default (global::Java.Lang.Object);
	const string __id = "(Ljava/lang/String;IILkotlin/jvm/internal/DefaultConstructorMarker;)V";
	...
}

Instance methods pass this to the static helper, so Kotlin still calls the overriding method of a subclass. With $(AndroidR8ObfuscationMode) set to runtime-remapping, R8 keeps the names of $default methods, 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 (), or cause: 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 $default helper. So the binding cannot generate Greet (string greeting, int times = 2, bool loud = false), because it does not know 2 or false. 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 null cannot 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:

  • The helper is not found with the exact expected signature. This includes helpers that exist only on an interface's $DefaultImpls class (older Kotlin), because R8 can remove that class.
  • A defaulted parameter is not at the end: fun middle (first: Int = 1, second: Int) gets no Middle (int second).
  • The function is an extension function or a suspend function, because the extra parameters move the mask bits.
  • A member with the same C# signature already exists, for example from @JvmOverloads, a string overload, a base class, an inherited interface, or a default-argument overload of a base type.
  • The class is not final. A C# subclass is created through its Java Callable Wrapper, which does not have the synthetic constructor. (This applies to constructors only.)
  • The constructor is 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 object member, such as ToString (), is marked new.

Validation

  • dotnet test tests/generator-Tests/generator-Tests.csproj: 495 passed. KotlinDefaultArgumentsTests runs real kotlinc output from kotlin-gradle/src/main/kotlin/DefaultArguments.kt through 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.
  • Local SDK build (before the last generator cleanup commit, which does not change the generated code), then dotnet-local.cmd test bin/TestDebug/net11.0/Xamarin.Android.Build.Tests.dll --filter "FullyQualifiedName~R8Tests|Name=KotlinDefaultArgumentOverloads|Name=AndroidMavenLibrary_KotlinValueClasses": 33 passed. KotlinDefaultArgumentOverloads binds androidx.datastore:datastore-core-jvm 1.2.1 and checks that class CorruptionException (message: String, cause: Throwable? = null) gets a CorruptionException (string message) constructor.
  • On-device, Mono.Android.NET-Tests (Debug, CoreCLR, API 37 x86_64 emulator): 1111 passed, 8 skipped. KotlinDefaultArgumentTests calls the new overloads of a Kotlin library in tests/Mono.Android-Tests.Gradle and checks the values that Kotlin computes: a default computed from another argument (offset: Int = factor + 1), a constructor default (step: Int = start * 2), and an open method that the $default helper calls through virtual dispatch on a Kotlin subclass. The constructor overloads pass a kotlin.jvm.internal.DefaultConstructorMarker, so the test app now gets kotlin-stdlib from Maven without binding it. Real Kotlin bindings already depend on Xamarin.Kotlin.StdLib.
  • I did not run a published app with R8.

Copilot AI balanced review requested due to automatic review settings November 16, 2026 18:46
@jonathanpeppers jonathanpeppers changed the title jonathanpeppers kotlin default arguments [generator] Bind Kotlin default arguments as C# overloads Nov 16, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment on lines +156 to +157
if (hasReceiver)
body.Add ($"var {Receiver} = this;");

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jonathanpeppers
jonathanpeppers force-pushed the jonathanpeppers-kotlin-default-arguments branch from 46af2b1 to ad3b534 Compare November 16, 2026 22:43
@jonathanpeppers
jonathanpeppers force-pushed the jonathanpeppers-kotlin-default-arguments branch from ad3b534 to c54f826 Compare November 20, 2026 18:16
Base automatically changed from jonathanpeppers-kotlin-value-class-support to main November 23, 2026 15:27
jonathanpeppers and others added 7 commits November 23, 2026 09:27
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]>
@jonathanpeppers
jonathanpeppers force-pushed the jonathanpeppers-kotlin-default-arguments branch from 0613918 to 8be1df4 Compare November 23, 2026 15:27
jonathanpeppers and others added 2 commits November 23, 2026 10:08
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]>
@jonathanpeppers jonathanpeppers changed the title [generator] Bind Kotlin default arguments as C# overloads [generator] Generate C# overloads for Kotlin default arguments Nov 23, 2026
@jonathanpeppers

Copy link
Copy Markdown
Member Author

/review

@jonathanpeppers jonathanpeppers added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Nov 23, 2026
@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

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

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ 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 minimal failed with CS9363 in unchanged Java.Interop/JniNativeMethodRegistration.cs lines 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 quiet failed because the configured JDK 25 javac could 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

jonathanpeppers and others added 2 commits November 23, 2026 11:36
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]>
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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants