Skip to content

[Xamarin.Android.Tools.Bytecode] Use Kotlin metadata for nullability - #13577

Merged
jonathanpeppers merged 6 commits into
mainfrom
jonathanpeppers-kotlin-nullability-annotations
Nov 17, 2026
Merged

jonathanpeppers merged 6 commits into
mainfrom
jonathanpeppers-kotlin-nullability-annotations

Conversation

@jonathanpeppers

@jonathanpeppers jonathanpeppers commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Context: dotnet/java-interop#468
Context: https://github.com/Redth/AndroidBindingsExperiments

The generator emits C# nullable annotations from the not-null and return-not-null attributes in api.xml. class-parse sets these attributes from Java annotations such as @NonNull. kotlinc writes @org.jetbrains.annotations.NotNull/@Nullable, but as RuntimeInvisible annotations, and tools such as R8 often remove them from published .aar files. When this occurs, every reference type in a Kotlin library binding is "oblivious", and users get no nullable warnings.

The kotlin.Metadata annotation stays in the class file, and it tells which types can be null. KotlinFixups now records non-null reference types from this metadata on:

  • constructor and function parameters
  • extension receivers
  • function and property getter return types
  • property setter parameters
  • fields

XmlClassDeclarationBuilder uses this information only after the Java declaration and type-use annotations, so explicit annotations still win. The result goes through the existing not-null path; the generator needs no change.

These are not marked as non-null:

  • type parameters such as T, because they can be null
  • platform (flexible) types from Java
  • unboxed value classes, such as value class Maybe(val value: String?); a type is only marked when the Kotlin type maps to the JVM type
  • lateinit fields, because they are null until set

The existing getter, setter, field and constructor lookups match loosely by name and type, so nullability is only set on an exact match: the Java accessor or field must have the JVM name from the Kotlin property signature, extension properties are skipped, and a constructor must match only one Java constructor. Otherwise, an unrelated fun getX(): String? next to @get:JvmName("fetchX") val x: String would become non-null.

Validation

A new Kotlin Gradle fixture (Nullability.kt) and the NullabilityFromKotlinMetadata test remove the invisible annotations, as R8 can, then check api.xml. The test fails without the fix.

  • dotnet test tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj: passed (133 passed, 2 skipped)
  • dotnet test tests/generator-Tests/generator-Tests.csproj (with the SDK from eng/install-dotnet.ps1): passed (478 passed)

jonathanpeppers and others added 2 commits November 16, 2026 09:17
kotlinc writes @NotNull/@nullable annotations, but these are
RuntimeInvisible and tools such as R8 can remove them. The Kotlin
metadata (kept at runtime) still tells which types can be null.

KotlinFixups now records non-null reference types from Kotlin metadata
on constructor and function parameters, extension receivers, return
types, property getters/setters and fields. XmlClassDeclarationBuilder
uses this as a fallback after Java annotations, so api.xml gets the
same not-null/return-not-null attributes and the generator emits the
correct C# nullable annotations.

Type parameters, platform (flexible) types, lateinit fields and suspend
function return types are not marked as non-null.

Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 16, 2026 16:58

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

Nullability inference can incorrectly mark platform types with ID-based flexible upper bounds and unboxed value classes with nullable backing types as non-null, producing unsound contracts.

2 open issues
What changed in this PR

Adds Kotlin metadata as a nullability fallback in class-parse when Java annotations have been stripped from libraries. This feeds the existing api.xml attributes used for C# nullable annotations without changing the generator.

Changes:

  • Records inferred non-null information for parameters, receivers, returns, properties, and fields.
  • Uses Kotlin inference after explicit Java declaration and type-use annotations.
  • Adds a Kotlin fixture and regression test that remove invisible annotations before checking XML output.
File Description
tests/​Xamarin.Android.Tools.Bytecode-Tests/​Xamarin.Android.Tools.Bytecode-Tests.csproj Embeds the compiled nullability fixture.
tests/​Xamarin.Android.Tools.Bytecode-Tests/​KotlinFixupsTests.cs Tests metadata-derived nullability after annotation removal.
tests/​Xamarin.Android.Tools.Bytecode-Tests/​kotlin-gradle/​src/​main/​kotlin/​Nullability.kt Defines nullable and non-null Kotlin test cases.
tests/​Xamarin.Android.Tools.Bytecode-Tests/​kotlin-gradle.targets Registers the fixture’s compiled output.
src/​Xamarin.Android.Tools.Bytecode/​XmlClassDeclarationBuilder.cs Applies Kotlin nullability when emitting XML attributes.
src/​Xamarin.Android.Tools.Bytecode/​Methods.cs Stores inferred return and parameter nullability.
src/​Xamarin.Android.Tools.Bytecode/​Kotlin/​KotlinFixups.cs Infers non-null reference types from Kotlin metadata.
src/​Xamarin.Android.Tools.Bytecode/​Fields.cs Stores inferred field nullability.

Review effort: Balanced

A value class with a nullable backing type, such as
\�alue class Maybe(val value: String?)\, is unboxed to a nullable
JVM type. Only mark a type as non-null when the Kotlin type maps to
the JVM descriptor. Also reject any type with flexible capabilities.

Co-authored-by: Copilot App <[email protected]>
@jonathanpeppers

Copy link
Copy Markdown
Member Author

/review

@jonathanpeppers

Copy link
Copy Markdown
Member Author

@dalexsoto review

@github-actions

github-actions Bot commented Nov 16, 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 #13577

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

⏳ CI pending — no blocking code findings

Findings: 0 errors, 0 warnings, 1 non-blocking inline testing suggestion. Reviewed all eight changed files in full and traced metadata matching, JVM descriptor conversion, annotation precedence, and the existing XML consumer. The fallback stays within the existing generator contract, and the guards for flexible types and unboxed value classes address the earlier findings.

Local validation: dotnet test tests/Xamarin.Android.Tools.Bytecode-Tests/Xamarin.Android.Tools.Bytecode-Tests.csproj --filter FullyQualifiedName~KotlinFixupsTests --verbosity minimal -p:JavaSdkDirectory=/usr/lib/jvm/temurin-25-jdk-amd64 passed all 23 focused tests. The complete bytecode suite, run with --no-build --no-restore, passed 133 tests with 2 skipped. No source changes were made.

CI: GitHub reported the Windows/Linux/macOS build checks and Android Tools Tests on Windows/macOS successful, with the remaining checks still queued or in progress for Azure build 1683754. No failing checks were reported in the retrieved results. Azure CLI access required authentication, so the detailed Azure build/timeline result could not be confirmed; this review does not establish that CI is green.

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 #13577 · copilot · gpt61 · 49.4 AIC · ⌖ 7.95 AIC · ⊞ 20.3K
Comment /review to run again

@dalexsoto dalexsoto left a comment

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.

Reviewed dd57e904 against main at 185f6b4c (merge-base 9b17cce5). This was a static, read-only review. I didn't build or run anything.

LGTM. KotlinFixups marks a type non-null only when all of these hold: the Kotlin type is non-nullable, not flexible/platform (both FlexibleUpperBound and FlexibleTypeCapabilitiesId are rejected), and not a type parameter, and ConvertKotlinTypeSignature matches the JVM reference descriptor exactly. That exact match rules out unboxed value classes, unsigned scalars, primitives and erased generics. Suspend returns and lateinit fields are also excluded. $default, @JvmOverloads and bridge overloads, DefaultConstructorMarker constructors and companion members aren't matched, so none of them get marked. In XmlClassDeclarationBuilder, explicit Java declaration and type-use annotations still take precedence over the Kotlin flag. Non-Kotlin output is unchanged because the new flags default to false. The Nullability.kt fixture is wired in through both the gradle targets and the embedded resources.

Non-blocking: property accessors are still matched by get<Name>, so an unusual @get:JvmName next to an unrelated nullable getX() could be stamped non-null when @Nullable has been stripped. Small fixtures for suspend fun …: Any, arrays and @JvmOverloads would document the guards.

The JVM return type of a suspend function is Object, so the exact
descriptor check already skips other Kotlin return types. A suspend
function that returns a non-null Any returns a non-null Object.

Co-authored-by: Copilot App <[email protected]>
@jonathanpeppers

Copy link
Copy Markdown
Member Author

@dalexsoto review

@jonathanpeppers
jonathanpeppers enabled stacked auto-merge (squash) November 16, 2026 21:54

@dalexsoto dalexsoto left a comment

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.

Reviewed e7c18525 against main at b0843532 (merge-base 9b17cce5). This was a static, read-only review; I didn't build or run anything. This supersedes my earlier approval on dd57e904, which missed the issue below.

Blocking: a property's non-null type can be stamped onto an unrelated get…/set… function

FixupProperty writes getter.KotlinReturnNotNull (KotlinFixups.cs:453) and the setter parameter's KotlinNotNull (:467), but FindJavaPropertyGetter/FindJavaPropertySetter (:569-610) still match only by get{Name}/set{Name} and parameter count. Functions are fixed up first (:57-61) and properties afterwards (:63-71), so the property write overwrites the correct result from FixupFunction. Before this PR that loose match was harmless; now it becomes a return-not-null="true" / not-null="true" attribute that the adjuster keeps and the generator turns into a non-nullable C# API, which is exactly the R8-stripped case this PR targets.

These all compile (no JVM declaration clash) and get the wrong attribute:

class A {
    @get:JvmName("fetchX") val x: String = "v"
    fun getX(): String? = null              // return-not-null="true"
}
class B {
    val String.label: String get() = this   // real getter: getLabel(String)
    fun getLabel(): String? = null          // return-not-null="true"
    var String.tag: String get() = this; set(v) {}
    fun setTag(v: String?) {}               // parameter not-null="true"
}
class C {
    val isReady: String = ""                // real getter: isReady()
    fun getIsReady(): String? = null        // return-not-null="true"
}

The exact accessor signatures are already in the metadata: JvmPropertySignature.Getter/Setter (KotlinProtobufDefinition.cs:1270-1287, GetPropertySignature at :1377), but KotlinProperty.FromProtobuf (KotlinClassMetadata.cs:300-318) doesn't read them. Suggested fix: read the getter/setter JVM name and descriptor into KotlinProperty and only stamp nullability on an exact match. At minimum, skip properties with a ReceiverType and skip Java methods already matched to a KotlinFunction. Fixtures for the three cases above in Nullability.kt would catch a regression.

Non-blocking, lower confidence (depends on kotlinc metadata ordering):

  • FindJavaConstructor (:510-520) returns the first overload whose types loosely match, and TypesMatch accepts a Java Object for any Kotlin type (:649-650), so :294-300 can stamp not-null onto the wrong constructor, e.g. class C(a: String?, b: Any) { constructor(a: String, b: Int) : this(a, b) }. Comparing against the descriptor built from ValueParameters (or the constructorSignature extension, KotlinProtobufDefinition.cs:1359) would make this exact.
  • The same name-only matching applies to fields (FindJavaFieldProperty, :560-566): an extension property next to a same-named @JvmField val label: String? could stamp the field non-null depending on property order.

The parameter filtering (GetFilteredParameters returns the cached ParameterInfo objects, indices line up with the XML builder) and the receiver/suspend/value-class/type-parameter guards look right.

… matches

FindJavaPropertyGetter/Setter, FindJavaFieldProperty and
FindJavaConstructor match loosely by name and type. Before, this was
harmless; with nullability it can put not-null on an unrelated member,
such as `fun getX(): String?` next to `@get:JvmName("fetchX") val x`.

Read the getter, setter and field JVM names from the property
signature, and only set nullability when the Java member has that
name and the property has no receiver. Only set constructor
nullability when one Java constructor matches.

Co-authored-by: Copilot App <[email protected]>
@jonathanpeppers

Copy link
Copy Markdown
Member Author

@dalexsoto thanks, all three are fixed in a40c4b3:

  • Accessors: KotlinProperty now reads the getter/setter JVM names from JvmPropertySignature. Nullability is set only when the Java method has that exact name and the property has no receiver. This covers @get:JvmName("fetchX") + getX(), String.label + getLabel(), and isReady + getIsReady(). I did not change the shared lookup, because the visibility, rename and unsigned fixups also use it.
  • Fields: nullability is set only when the property signature has a backing field with that name, so an extension property cannot mark a same-named @JvmField.
  • Constructors: nullability is set only when exactly one Java constructor matches the Kotlin constructor. I chose this instead of an exact descriptor compare so that Int? (Java Integer) parameters keep working.

Nullability.kt now has these cases, and the test fails without the fix. Xamarin.Android.Tools.Bytecode-Tests: 133 passed, 2 skipped. generator-Tests: 478 passed.

The exact descriptor compare already rejects null and non-matching
descriptors, and FindJavaConstructors already requires the same
parameter count.

Co-authored-by: Copilot App <[email protected]>
@jonathanpeppers

Copy link
Copy Markdown
Member Author

@dalexsoto review

@dalexsoto dalexsoto left a comment

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.

Re-reviewed 4de4931 against main at 0402b6b (merge-base 9b17cce); this was a static, read-only review and I didn't build or run anything. All three issues from my previous review are fixed. Property accessors are now stamped only when the Java method name equals the getter/setter name from JvmPropertySignature and the property has no receiver (KotlinFixups.cs:456-480). Fields need a matching backing-field name (:500), and constructors are stamped only when exactly one Java constructor matches (:47-50, :296-303). I checked the kotlinc signature serializer: getter and setter names are always written, and the field name is omitted only when it equals the property name, which is what KotlinClassMetadata.cs:321-324 expects. A name collision with a different descriptor stays safe, because IsNotNullReference requires an exact descriptor match. Accessors and constructors that don't match exactly simply get no Kotlin nullability, so nothing is marked non-null wrongly. Commits on main since the merge-base don't touch any of these files. LGTM.

@jonathanpeppers
jonathanpeppers merged commit aa688ac into main Nov 17, 2026
38 checks passed
@jonathanpeppers
jonathanpeppers deleted the jonathanpeppers-kotlin-nullability-annotations branch November 17, 2026 23:15
jonathanpeppers added a commit that referenced this pull request Nov 18, 2026
…13580)

Context: #13577

`KotlinFixups.FindKotlinFunctionMetadata()` finds the Kotlin metadata function for each Java method. It had two problems when more than one Kotlin function matched:

  * The `JvmSignature` check and the constructed-signature check used `SingleOrDefault()`. With more than one match, it threw. The `catch` in `KotlinFixups.Fixup()` then logged `Unable to parse Kotlin metadata` with a stack trace and skipped all the remaining Kotlin fixups for the class.
  * The fallback type check returned the first match silently. For example, for this Kotlin code, kotlinc emits a synthetic bridge `put(Ljava/lang/Object;)V`:

    ```kotlin
    abstract class AmbiguousBase<T> { abstract fun put(value: T) }
    class AmbiguousOverloads : AmbiguousBase<String>() {
        @PublishedApi internal fun put(count: Int) { }
        override fun put(value: String) { }
    }
    ```

    Both `put` functions match the bridge. The `internal` function is first in the metadata, so the bridge was hidden.

Now all three checks collect every match. If more than one Kotlin function matches, the Java method gets no Kotlin fixups, and it is bound as a usual Java method. For a public or protected method, class-parse writes `class-parse: warning XA4268: ...`. The `<ClassParse/>` task reports it as a coded MSBuild warning:

```
warning XA4268: The Kotlin metadata for Java method 'com/example/Widget.put(Ljava/lang/Object;)V' matches more than one Kotlin function: put(I)V, put(Ljava/lang/String;)V. The Kotlin fixups for this method are skipped.
```

Synthetic methods (such as bridges), private methods, and package-private methods are not bound API. For these methods, class-parse writes only a debug message. Normal Kotlin libraries have many bridges, so a warning for each one would only be noise.

The message is in the English `Java.Interop.Localization` resources, the same place as the other class-parse and generator messages. So `Xamarin.Android.Tools.Bytecode` now references `Java.Interop.Localization`. This assembly is already in the SDK `tools` folder next to `class-parse.dll`.

With code that kotlinc produced, the two signature checks did not find more than one match in the cases tested. A real ambiguity was seen only in the fallback check, for bridge methods.

Co-authored-by: Copilot App <[email protected]>
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