Skip to content

[generator] Marshal Kotlin value classes across JNI - #13581

Open
jonathanpeppers wants to merge 8 commits into
mainfrom
jonathanpeppers-kotlin-value-class-support
Open

jonathanpeppers wants to merge 8 commits into
mainfrom
jonathanpeppers-kotlin-value-class-support

Conversation

@jonathanpeppers

@jonathanpeppers jonathanpeppers commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Context: #11844

Background

A Kotlin @JvmInline value class wraps one value. kotlinc erases it to that value on the JVM, and mangles the names of functions that use it. For example, a file Lengths.kt:

package example

@JvmInline
value class Meters(val value: Double) {
    init { require(value >= 0) { "Meters cannot be negative" } }
}

@JvmInline
value class Id(val value: Long)

fun add(a: Meters, b: Meters): Meters = Meters(a.value + b.value)
fun Meters.doubled(): Meters = Meters(value * 2)
fun orZero(meters: Meters?): Meters = meters ?: Meters(0.0)
fun findId(value: Long): Id? = if (value >= 0) Id(value) else null

The top-level functions go into the JVM class example.LengthsKt (the "file facade"; @file:JvmName changes its name):

Kotlin JVM method in LengthsKt
add(a: Meters, b: Meters): Meters add-…(DD)D
Meters.doubled(): Meters doubled-…(D)D
orZero(meters: Meters?): Meters orZero-…(Lexample/Meters;)D
findId(value: Long): Id? findId(J)Lexample/Id;

A non-null Meters is passed as a double. A nullable Meters? (and a value class in a generic type argument or field) is passed as the boxed Meters object. Every value class also gets static box-impl/constructor-impl methods and an instance unbox-impl method.

main already binds a value class as a C# readonly partial struct and handles the unboxed case in class-parse output. Real bindings failed:

  • The api.xml adjuster (JavaXmlApiImporter/JavaXmlApiExporter) dropped the kotlin-inline-class* attributes and managedName, so a real binding build never produced the structs.
  • For a boxed Foo?, the generated code called GetObject<Foo> on a struct, which does not compile.
  • Extension receivers (Meters.doubled()) were not projected, and value-class parameters were named p0.
  • Callbacks relied on an implicit conversion, which fails for overloads such as Density.roundToPx(Dp)/roundToPx(TextUnit) with error CS0121: The call is ambiguous.

Binding output

Each value class becomes a struct with a [Register] attribute (so other assemblies and the build can find it) and helpers that call the Kotlin *-impl methods:

namespace Example;

[Register ("example/Id", DoNotGenerateAcw=true)]
public readonly partial struct Id : IEquatable<Id> {
	public readonly long Value;
	public Id (long value) { Value = value; }

	public static implicit operator long (Id value) => value.Value;
	public static implicit operator Id (long value) => new Id (value);
	// Equals, ==, GetHashCode, ToString …

	// For values from Java.
	[EditorBrowsable (EditorBrowsableState.Never)]
	public static Id FromJniValue (long value) { … }

	// Calls Kotlin's `box-impl`. The caller owns the returned JNI local reference.
	public static IntPtr ToLocalJniHandle (Id? value) { … }
	// Calls Kotlin's `unbox-impl` on a boxed value, then releases `handle` as `transfer` specifies.
	public static Id? FromJniHandle (IntPtr handle, JniHandleOwnership transfer) { … }
}

Members use the struct, with unmangled names. Unboxed values are passed as the primitive; boxed values go through the helpers:

public sealed partial class LengthsKt : Java.Lang.Object {
	[Register ("add-…", "(DD)D", "")]
	public static Meters Add (Meters a, Meters b);        // JniArgumentValue (a), return Meters.FromJniValue (__rm)

	[Register ("doubled-…", "(D)D", "")]
	public static Meters Doubled (Meters obj);            // extension receiver, bound as a static method

	[Register ("orZero-…", "(Lexample/Meters;)D", "")]
	public static Meters OrZero (Meters? meters);         // Meters.ToLocalJniHandle (meters)

	[Register ("findId", "(J)Lexample/Id;", "")]
	public static Id? FindId (long value);                // Id.FromJniHandle (__rm.Handle, JniHandleOwnership.TransferLocalRef)
}

C# and Kotlin callers:

using Example;
using static Example.LengthsKt;

var sum = Add (new Meters (1.5), new Meters (2)); // 3.5
var zero = OrZero (null);                         // 0
var id = FindId (-1);                             // null (Id?)
new Meters (-1);                                  // throws Java.Lang.IllegalArgumentException
val sum = add(Meters(1.5), Meters(2.0))
val zero = orZero(null)
val id = findId(-1)
Meters(-1.0) // throws IllegalArgumentException

tests/Mono.Android-Tests.Gradle has this Kotlin code (in package net.dot.android.test.kotlin, facade ValueClasses).

Construction and cost

In Kotlin, Meters(-1.0) runs the init block. To match, the C# constructor calls Java only for value classes that have an init block. class-parse checks the primary constructor-impl (T)T (secondary constructors compile to constructor-impl with other signatures). Without an init block, kotlinc writes it as "load, return":

public static long constructor-impl(long);      // Id: no init block
   0: lload_0
   1: lreturn

public static double constructor-impl(double);  // Meters: init { require(value >= 0) }
   0: dload_0
   …                                             // if (value < 0) throw new IllegalArgumentException(…)
  36: dload_2
  37: dreturn
No init block (Id; also Compose's Dp, TextUnit, most others) init block (Meters)
new Foo (v) stores v; no JNI call Value = ConstructorImpl (v): one JNI call to the static constructor-impl, which throws like Kotlin
T → Foo conversion implicit explicit (implicit conversions must not throw)
Values from Java (returns, callbacks, unbox-impl) FromJniValue: stores the value FromJniValue: stores the value; Kotlin already ran the init block

constructor-impl is a static method that takes and returns the primitive, so new Meters (5) does not create a Java object (the only new in it is the exception). Kotlin also cannot change the value there: the property is a val set from the parameter, so constructor-impl returns its input or throws.

Java objects are created only where Kotlin itself passes the boxed value:

Position Java allocation C# allocation
Foo parameter or return none, only the primitive none (struct)
Foo? passed to Java (box-impl) one boxed Foo, plus a JNI local reference that is deleted after the call none (Nullable<Foo>)
Foo? returned from Java (unbox-impl) none new none
List<Foo> one box per item (made by Kotlin) one Java.Lang.Object peer per item read (#13668 tracks a typed IList<Foo>)

default (Foo) and array elements do not run the init block, as for any C# struct.

Changes

  • The adjuster keeps the value-class attributes. class-parse adds kotlin-inline-class-has-init.

  • The generator writes the struct helpers above, binds Foo? as C# Foo?, and binds nested value classes and fields of a value-class type. A value class in a generic type argument becomes Java.Lang.Object.

  • class-parse projects extension receivers and applies Kotlin parameter names. Callbacks wrap the value explicitly (var dp = Dp.FromJniValue (native_dp);).

  • Across binding assemblies: [Register] now allows structs (API-compatibility baseline updated). When a binding references another binding's struct, CecilApiImporter imports it as a value class, and class-parse marks a value class from another library (a non-kotlin/ class erased to a primitive). The generator projects it only when the referenced struct has the same underlying type. For example, ui-text's TextIndent.FirstLine uses ui-unit's TextUnit struct.

  • R8: the helpers call box-impl/unbox-impl/constructor-impl by name, so R8 must keep them, but only for value classes the app uses. JavaPeerScanner gives each [Register] struct a typemap entry with no proxy, whose trim target is the struct. The existing typemap and acw-map.txt R8 rules then keep the Kotlin class only when the struct survives trimming:

    -keep class example.Meters
    -keepclassmembers class example.Meters { *; }
    

    The entry has no JavaPeerProxy, so runtime typemap lookups are unchanged. GenerateProguardConfiguration (used when typemap R8 trimming is off) keeps all members of a [Register] struct, and AndroidR8ObfuscationMode=runtime-remapping keeps the helper names.

Limitations

  • List<Foo> becomes IList<Java.Lang.Object>; convert items with Foo.FromJniHandle (item.Handle, JniHandleOwnership.DoNotTransfer).
  • Members that use arrays of value classes, or types nested in a value class (for example Companion), are skipped.
  • Value classes backed by a reference type (for example String) are not projected.
  • A value class named Value keeps the peer-class binding, because the struct's Value field cannot have the type's name.
  • Kotlin interfaces and open classes with value-class parameters have mangled names, so C# cannot implement or override them.

Follow-ups: #13667 (members declared in value classes), #13668 (IList<Foo>), #13669 (implementing interfaces with value-class parameters), #13670 (reference-backed value classes), #13671 (extension methods).

Validation

BindingBuildTest.AndroidMavenLibrary_KotlinValueClasses binds androidx.compose.ui:ui-unit-android 1.12.1, and TextIndent from ui-text-android in a second binding project that references it. It checks the Dp struct, CoerceAtLeast (Dp obj, Dp minimumValue) from coerceAtLeast-YgX7TsA(FF)F, Lerp (DpSize …), and TextIndent.FirstLine using TextUnit from the other assembly.

Mono.Android.NET-Tests now binds the test Kotlin library (tests/Mono.Android-Tests.Gradle) with <AndroidGradleProject>, using the repository's Gradle wrapper through a new private $(_AndroidGradleWrapperDirectory). KotlinValueClassTests runs in the existing Debug, Release, NoAab and NativeAOT lanes.

  • Xamarin.Android.Build.Tests --filter Name~AndroidMavenLibrary_KotlinValueClasses: passed
  • generator-Tests: 494 passed
  • Xamarin.Android.Tools.Bytecode-Tests: 138 passed, 2 skipped
  • Java.Interop.Tools.JavaTypeSystem-Tests: 17 passed
  • Microsoft.Android.Build.Tasks.Tests: 1037 passed, 50 skipped
  • AndroidGradleProjectTests.BindLibrary and InvalidItemRefError: passed
  • Mono.Android.NET-Tests, Debug on an API 29 emulator: KotlinValueClassTests passed. Two unrelated tests failed (a flaky GC bridge test, and ExceptionTest.ManagedExceptionRoundTripPreservesIdentity, which aborts the process).
  • Mono.Android.NET-Tests, Release (R8, full trimming) on a Pixel 10: 1094 passed, 0 failed, and the generated R8 rules keep Meters and Id. After the constructor change, all 7 KotlinValueClassTests passed again, including ConstructorRunsInitBlock; the run stopped at the same unrelated ManagedExceptionRoundTripPreservesIdentity crash.
  • Release with AndroidR8ObfuscationMode=runtime-remapping on a Pixel 10: KotlinValueClassTests passed, and the R8 mapping keeps the helper names. The [Export] tests fail in this mode; no CI lane runs it.

Copilot AI balanced review requested due to automatic review settings November 16, 2026 18:46
@jonathanpeppers jonathanpeppers changed the title jonathanpeppers kotlin value class support [generator] Marshal Kotlin value classes across JNI 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

Unresolved generator defects cause compilation failures for value-class bindings, while missing R8 retention metadata and array boxing support can cause runtime failures.

6 open issues
What changed in this PR

This PR extends Kotlin value-class support in the .NET for Android binding pipeline, preserving metadata through JavaTypeSystem adjustment and adding marshaling for boxed values.

Changes:

  • Preserve value-class metadata and identify value-class extension receivers.
  • Generate JNI boxing/unboxing helpers and adapt parameter, return, callback, and generic projections.
  • Add metadata round-trip, generator, and Maven binding tests.
File Description
tests/​Xamarin.Android.Tools.Bytecode-Tests/​KotlinInlineClassCollisionTests.cs Tests extension-receiver metadata.
tests/​Xamarin.Android.Tools.Bytecode-Tests/​kotlin-gradle/​src/​main/​kotlin/​InlineClassCollisions.kt Adds nullable, generic, extension, and callback fixtures.
tests/​Java.Interop.Tools.JavaTypeSystem-Tests/​JavaTypeModelsTests.cs Tests value-class attribute round-tripping.
tests/​generator-Tests/​Unit-Tests/​KotlinInlineClassEndToEndTests.cs Tests adjusted metadata and boxed-value code generation.
tests/​generator-Tests/​generator-Tests.csproj Embeds the callback fixture.
src/​Xamarin.Android.Tools.Bytecode/​Kotlin/​KotlinFixups.cs Recognizes value-class parameters and extension receivers.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​BindingBuildTest.cs Adds a Compose value-class binding test.
src/​Java.Interop.Tools.JavaTypeSystem/​JavaModels/​JavaParameterModel.cs Adds parameter metadata storage.
src/​Java.Interop.Tools.JavaTypeSystem/​Adapters/​JavaXmlApiImporter.cs Imports value-class attributes.
src/​Java.Interop.Tools.JavaTypeSystem/​Adapters/​JavaXmlApiExporter.cs Preserves value-class attributes during export.
src/​generator/​SourceWriters/​KotlinInlineClassStruct.cs Emits construction, boxing, and unboxing helpers.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​Symbols/​KotlinInlineClassBoxedSymbol.cs Adds boxed-value marshaling and generic projection.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​Symbols/​GenericSymbol.cs Projects value-class generic arguments as Java objects.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​ReturnValue.cs Projects boxed returns as nullable structs.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​Parameter.cs Handles boxed parameters and explicit callback conversions.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​GenericParameterList.cs Applies value-class generic-argument projection.
src/​generator/​CodeGenerationOptions.cs Avoids null-forgiving operators for value-class projections.

Review effort: Balanced

@jonathanpeppers
jonathanpeppers force-pushed the jonathanpeppers-kotlin-value-class-support branch 2 times, most recently from 079b2c4 to 55d4bf2 Compare November 17, 2026 23:15
Base automatically changed from jonathanpeppers-kotlin-ambiguous-metadata-warning to main November 18, 2026 15:17
@jonathanpeppers
jonathanpeppers force-pushed the jonathanpeppers-kotlin-value-class-support branch 3 times, most recently from 63f5f5f to e416b5e Compare November 18, 2026 22:44
Kotlin `@JvmInline value class` types backed by a primitive are bound as a C# `readonly partial struct` where the JVM passes the underlying primitive. Other cases did not work:

  * The api.xml adjuster (`JavaXmlApiImporter`/`JavaXmlApiExporter`) dropped the value-class attributes from class-parse output (`kotlin-inline-class`, `kotlin-inline-class-underlying-jni-type`, `kotlin-inline-class-return-jni-type`, `kotlin-inline-class-jni-type`) and the unmangled `managedName`. The generator reads the adjusted file, so in a real binding build no value-class struct projection happened. This bug is also on `main`.
  * Where the JVM passes the *boxed* value class (Kotlin `Foo?`, generic type arguments), the generator emitted `GetObject<Foo>` and `JNIEnv.ToLocalJniHandle (foo)` for a struct, which does not compile.
  * An extension receiver (`fun Dp.coerceAtLeast(…)`) was not projected, and Kotlin parameter names were not applied to value-class parameters (they became `p0`).
  * Java-to-C# callbacks passed the raw primitive and relied on an implicit conversion. With overloads such as `Density.roundToPx(Dp)` and `roundToPx(TextUnit)` this fails with `error CS0121: The call is ambiguous between the following methods or properties`.
  * With nullable reference types enabled, value-class arguments got the `!` operator.

### Changes

  * The adjuster keeps the value-class attributes in `PropertyBag` and writes them back. `JavaParameterModel` gets a `PropertyBag`.
  * The generated struct gets `Create (T)`, `ToLocalJniHandle (Foo?)` and `FromJniHandle (IntPtr, JniHandleOwnership)`. They call the Kotlin `constructor-impl`, `box-impl` and `unbox-impl` helpers. kotlinc always generates these helpers with fixed signatures, so the generator derives the signatures from the underlying JNI type.
  * A boxed `Foo?` is projected as C# `Foo?` and marshaled with these helpers. In generic type arguments the value class becomes `Java.Lang.Object`, because `JavaList<T>` cannot hold a struct.
  * class-parse projects the extension receiver and passes the inline-class map to `TypesMatch`, so parameter names are applied.
  * Callbacks construct the struct explicitly: `var dp = new MyDp (native_dp);`.
  * No `!` is emitted for value-class parameters or return values.
  * Nested value classes use the struct writer, and Java fields of a value-class type are projected like parameters.
  * The struct helpers use `unsafe { }` blocks, so they compile with `MemorySafetyRulesVersion=2`.
  * R8: the structs call `box-impl`/`unbox-impl`/`constructor-impl` by name, so R8 must keep them, but only for value classes the app uses. `JavaPeerScanner` adds each `[Register]` struct to the trimmable typemap as an entry with no proxy (key: the Kotlin class; proxy and trim target: the struct). The typemap-based R8 rules and acw-map.txt then keep the Kotlin class and its members only when the struct survives trimming. The entry has no `JavaPeerProxy`, so runtime lookups still fall back to `java/lang/Object`. `GenerateProguardConfiguration` (used when typemap R8 trimming is off) keeps all members of a `[Register]` struct. With `AndroidR8ObfuscationMode=runtime-remapping`, a `-keepclassmembernames` rule keeps the helper names, which the remapping tables do not cover.
  * Across binding assemblies: `[Register]` now allows structs (`AttributeTargets.Struct`; added to the API-compatibility baseline), and the struct gets `[Register ("jni/name", DoNotGenerateAcw=true)]`. `CecilApiImporter` imports such a struct as a value class, and binds a `Foo` or `Foo?` parameter or return from a referenced assembly from the JNI type in its `[Register]` signature (otherwise `Foo` became `Foo?`, which breaks overrides and invokers). class-parse marks a value class from another library when the Kotlin type is a non-`kotlin/` class and the JVM type is a primitive, and the generator projects it only when the referenced struct has the same underlying type.

### Limitations

  * `List<Foo>` becomes `IList<Java.Lang.Object>`; callers convert items with `Foo.FromJniHandle`.
  * Members that use arrays of value classes are skipped.
  * Value classes backed by a reference type (for example `String`) are not projected.
  * Types nested in a value class (for example `Companion`) are not bound; members that use them are skipped.
  * `new Foo (v)` and the implicit conversions do not run Kotlin `init` checks; `Foo.Create` does.

### Validation

`BindingBuildTest.AndroidMavenLibrary_KotlinValueClasses` binds the real `androidx.compose.ui:ui-unit-android` 1.12.1 library with `MemorySafetyRulesVersion=2`, and `TextIndent` from `ui-text-android` in a second binding project that references it (about 16 s). It checks that `Dp` is a registered struct, that `CoerceAtLeast (Dp obj, Dp minimumValue)` is generated from `coerceAtLeast-YgX7TsA(FF)F`, that the mangled `lerp-…` overloads become `Lerp (DpSize …)`, and that `TextIndent.FirstLine` uses the `TextUnit` struct from the other assembly. This test found the receiver, parameter-name and callback bugs. The new unit tests fail without their fixes.

  * `dotnet-local.cmd build Microsoft.Android.slnx` and `dotnet-local.cmd build Microsoft.Android.slnx -t:PackDotNet`: succeeded
  * `dotnet-local.cmd test bin\TestDebug\net11.0\Xamarin.Android.Build.Tests.dll --filter Name~AndroidMavenLibrary_KotlinValueClasses` (with `TEST_ANDROID_JDK_PATH` set to JDK 21): 1 passed
  * `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`: 17 passed
  * `dotnet-local.cmd test tests\generator-Tests\generator-Tests.csproj`: 493 passed
  * `dotnet-local.cmd test src\Microsoft.Android.Build.Tasks\Tests\Microsoft.Android.Build.Tasks.Tests\Microsoft.Android.Build.Tasks.Tests.csproj`: 1037 passed, 50 skipped

On device, `Mono.Android.NET-Tests` binds a small Kotlin library (`tests/Mono.Android-Tests.Gradle`) with `<AndroidGradleProject>`. It uses the repository's Gradle wrapper through a new private `$(_AndroidGradleWrapperDirectory)` property. `KotlinValueClassTests` calls unboxed and boxed parameters and returns, an extension receiver, a property, a `List<Meters>` return, and `Create` (the Kotlin `init` block runs). CI runs these tests in the existing Debug, Release (R8, full trimming), NoAab and NativeAOT lanes.

  * `dotnet-local.cmd build -t:Install -c Debug tests\Mono.Android-Tests\Mono.Android-Tests\Mono.Android.NET-Tests.csproj -p:Device=emulator-5554`, then `dotnet-local.cmd test Mono.Android.NET-Tests.csproj --no-build -c Debug -p:Device=emulator-5554` (API 29 x86_64 emulator): all `KotlinValueClassTests` passed. `JavaMarshalGCBridgeTests.ManagedPeerCycleSurvivesJavaRootAndIsCollectedAfterRelease` failed once and passed on a rerun with `-p:IncludeCategories=GCBridge`. `ExceptionTest.ManagedExceptionRoundTripPreservesIdentity (False)` aborted the process; it is not related to this change.
  * Release (R8, `TrimMode=full`), same commands with `-c Release` on a Pixel 10: 1094 passed, 0 failed; all 7 `KotlinValueClassTests` passed. `proguard_project_references.cfg` has `-keep class net.dot.android.test.kotlin.Meters` and `…Id` from the typemap keys.
  * `AndroidGradleProjectTests.BindLibrary` (4 passed) and `InvalidItemRefError` (2 passed) with the new property.
  * `-c Release -p:AndroidR8ObfuscationMode=runtime-remapping` on the Pixel 10: all 7 `KotlinValueClassTests` passed, and the R8 mapping keeps `box-impl`/`unbox-impl`/`constructor-impl` while it renames other members. (The `[Export]` tests fail in this mode; no CI lane runs it.)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Real builds import referenced types lazily (`UseShallowReferencedTypes`).
`CecilApiImporter.CreateClass ()` returns early for a `[Register]`
struct and sets no `PopulateAction`, so `SymbolTable.EnsurePopulated ()`
threw a `NullReferenceException` when a dependent binding used the
value class (`AndroidMavenLibrary_KotlinValueClasses` on CI).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@jonathanpeppers jonathanpeppers removed the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Nov 19, 2026
jonathanpeppers and others added 3 commits November 19, 2026 09:52
C# users expect `new Meters (-1)` to fail like Kotlin's `Meters(-1.0)`.
class-parse now marks value classes with an `init` block: without one,
kotlinc writes `constructor-impl` as only "load; return" (2 bytes). It
writes `kotlin-inline-class-has-init`, which the adjuster keeps.

  * With an `init` block, the struct constructor calls
    `constructor-impl`, and the conversion from the primitive is
    `explicit`, because implicit conversions must not throw.
  * Without one (`Dp`, `TextUnit`, …), the constructor only stores the
    value and makes no JNI call.
  * Generated marshaling code uses a hidden `FromJniValue ()`, because
    Java already ran the `init` block.
  * `Create ()` is removed.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
  * class-parse checks the *primary* `constructor-impl` for an `init`
    block. Secondary constructors also compile to `constructor-impl`,
    with other signatures, and made a class without an `init` block
    look like it had one.
  * A value class replaces a primitive only when the primitive is the
    struct's `Value` type. Comparing JNI names let a `ulong` (for
    example from Metadata.xml) match a `long` struct, which does not
    compile.
  * `ReturnValue.Clone ()` keeps the value-class marshaling flag.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@jonathanpeppers

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 19, 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 #13581

@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

2 ❌ errors · 0 ⚠️ warnings · 0 💡 suggestions

The adjuster attribute round-trip, explicit callback conversions, and value-class retention wiring address important gaps in real binding builds. The cross-assembly and on-device coverage are valuable. Two generated-code failures remain, detailed inline:

  1. The newly supported nested Outer.Value produces a struct named Value containing a field named Value (CS0542).
  2. External value-class annotations prevent overload deduplication even when no matching struct is available, producing duplicate primitive signatures when consuming older bindings.

Verification: Built the standalone generator successfully and reproduced both generated-output shapes through its class-parse XML/adjuster pipeline. An isolated compilation confirmed CS0542 for the nested struct. The focused NUnit run could not execute because compilation of unchanged Java.Interop sources failed with CS9363 under the installed .NET SDK 11.0.100; those diagnostics are not attributed to this PR.

CI: The latest GitHub check results show all 47 checks completed: 46 succeeded and 1 skipped, including a successful overall dotnet-android check. Direct Azure DevOps build/timeline retrieval required authentication, so independent Azure status verification was unavailable.

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 #13581 · copilot · gpt61 · 289.7 AIC · ⌖ 4.09 AIC · ⊞ 21K
Comment /review to run again

Comment on lines +139 to +143
// Without an `init` block, kotlinc writes the primary `constructor-impl` as "load the argument, return it" (2 bytes).
// Secondary constructors also compile to `constructor-impl`, with other signatures.
var primary = $"({backing.Descriptor}){backing.Descriptor}";
c.KotlinInlineClassHasInit = c.Methods.FirstOrDefault (m => m.Name == "constructor-impl" && m.Descriptor == primary)?.Attributes.Get<CodeAttribute> ()?.ByteCode is { Length: > 2 };

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm glad we can detect empty constructor-impl so easily. If if we had to call a pinvoke every time somebody creates an instance of Dp, it could add up (unless Dp has inits, but maybe it has secondary constructors, so we can't tell those from init blocks?).

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.

We can tell them apart: a secondary constructor compiles to its own constructor-impl with a different signature (e.g. constructor(value: Int) on a ULong class is constructor-impl(I)J), and class-parse only checks the primary constructor-impl(T)T. The MyColor fixture has a secondary constructor, and Fixup_StampsKotlinInlineClassUnderlyingJniType checks it is still "no init block".

@simonrozsival

Copy link
Copy Markdown
Member

Do we support @JvmName when binding methods?

@JvmName("computeUInt")
fun compute(x: UInt) { }

  * A value class named `Value` keeps the peer-class binding: the
    struct's `Value` field cannot have the type's name (CS0542).
  * Before removing colliding mangled overloads, clear the value-class
    mark on parameters whose type is not a value class in the symbol
    table (for example a peer class from an older binding). They stay
    the primitive, so they collide like the primitive, as before.
  * Test `@JvmName` on value-class functions (`Compute (uint)` next to
    `Compute (int)`), and compile the generated code in two tests.
  * Mono.Android-Tests.Gradle: `compileSdk = 37`, `minSdk = 24`.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@jonathanpeppers

Copy link
Copy Markdown
Member Author

@simonrozsival yes. The C# name comes from the Kotlin name, and JNI uses the @JvmName. aba68e0 adds this to the Kotlin test fixture:

@JvmName("computeUInt")
fun compute(x: UInt) { }
fun compute(x: Int) { }
@JvmName("tintColor")
fun tintWith(color: MyColor) { }

and GeneratorMarshalsBoxedKotlinInlineClasses checks the result:

[Register ("computeUInt", "(I)V", "")]
public void Compute (uint x)
[Register ("compute", "(I)V", "")]
public void Compute (int x)
[Register ("tintColor", "(J)V", "")]
public void TintWith (MyColor color)

So @JvmName overloads become normal C# overloads, and a value-class parameter on a @JvmName function is still projected. The "Kotlin name when it differs from the JVM name" rule came from dotnet/java-interop#1440; this PR doesn't change it.

jonathanpeppers and others added 2 commits November 20, 2026 11:59
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@jonathanpeppers

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 20, 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 #13581

@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.

Review: ⚠️ Validation pending

Findings: 0 errors, 0 warnings, 1 non-blocking testing suggestion posted inline. No new blocking correctness issue identified in the 48-file change. I checked the full changed sources and relevant callers, including attribute round-tripping, boxed/unboxed marshaling, nested generation, referenced-binding imports, and typemap-to-R8 retention. The current code addresses the earlier field, nested-type, ownership-context, and fallback-collision findings; the documented unsupported projections were treated as intentional limitations.

The separation between constructor validation and FromJniValue is sound, and retaining registered structs without creating Java-peer proxies keeps the R8 integration appropriately scoped.

Validation: The focused KotlinInlineClassCollisionTests run passed 10/10 using dotnet test tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj --filter FullyQualifiedName~KotlinInlineClassCollisionTests with explicit paths to the installed JDK. The focused generator run (dotnet test tests/generator-Tests/generator-Tests.csproj --filter 'FullyQualifiedName~KotlinInlineClass|FullyQualifiedName~KotlinFixups') could not reach test execution: compilation reported CS9363 in the unchanged src/Java.Interop/Java.Interop/JniNativeMethodRegistration.cs, lines 50–51. No source changes were made to work around that failure, and I did not independently run the Android device/R8 matrix.

CI: The returned checks for Azure build 1692967 still show four jobs in progress and the aggregate check queued, with no failures reported so far. Direct Azure build/timeline access was blocked by an authentication requirement, so CI is not confirmed green and this is not an LGTM/merge-readiness verdict.

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 #13581 · copilot · gpt61 · 168.4 AIC · ⌖ 4.31 AIC · ⊞ 21K
Comment /review to run again

var lengths = ValueClasses.Lengths (3);
Assert.AreEqual (3, lengths.Count);
Assert.AreEqual (new Meters (2), Meters.FromJniHandle (lengths [2].Handle, Android.Runtime.JniHandleOwnership.DoNotTransfer));
}

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.

🤖 💡 Testing — Could we add a direct boxing-helper round-trip test covering TransferLocalRef, TransferGlobalRef, and DoNotTransfer? The current tests exercise local transfers indirectly through generated calls and this borrowed-reference path, but never the new global-transfer cleanup branch. Use live references created by ToLocalJniHandle/JNIEnv.NewGlobalRef, verify the returned value, and verify that a borrowed reference remains usable before explicitly releasing it. This would protect the ownership contract independently of the value/null assertions.

{Rule: Test JNI reference ownership and cleanup paths.}

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants