Skip to content

[generator] Fix nullable and obsolete warnings in Mono.Android bindings - #13585

Merged
simonrozsival merged 4 commits into
mainfrom
jonathanpeppers-generator-warning-fixes
Nov 18, 2026
Merged

simonrozsival merged 4 commits into
mainfrom
jonathanpeppers-generator-warning-fixes

Conversation

@jonathanpeppers

@jonathanpeppers jonathanpeppers commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

On main, the generated Mono.Android bindings build with these warnings:

  • CS8604 and CS8768 in IConcurrentMap, ISortedSet and String.CompareTo
  • CS0672 for an override of an obsolete member
  • CS0169 for unused weak_implementor_* fields
  • CS8625 in MediaSessionManager

Default interface methods

A default interface method can override a method that has different nullability. After FixupMethodOverrides (), the generator now merges the annotations along the override chain. A return value is non-null if any overridden method returns non-null. A parameter is non-null only if all of the overridden methods declare it non-null. Where the code can pass a null value to a non-null target, the generated code throws Java.Lang.NullPointerException.

Overrides

If an abstract class gets an abstract method only from an interface, the class does not declare that method itself. Its abstract declaration is added later, when the generator writes the class. FixupMethodOverrides () did not find these methods. A method in a derived class was then generated as virtual instead of override, and it did not get [Obsolete]. The lookup now also checks the interfaces of an abstract base class. It skips methods in skipInterfaceMethods and methods that are generated as explicit interface implementations.

Listener events

  • The generator adds the weak_implementor_* field only when it creates the event that uses it.
  • The listener connector method must also match the listener interface. Before, the generator matched only by name.
  • The listener property setter did not give the handler to a newly created implementor, so the first handler was lost.

generator.dll is now an input of the _GenerateBinding target, so a change to the generator regenerates the bindings.

Two CS8603 warnings remain, in the View.IOnApplyWindowInsetsListener and LoudnessCodecController.IOnLoudnessCodecUpdateListener implementors.

Validation

  • dotnet test tests/generator-Tests/generator-Tests.csproj: 489 passed.
  • dotnet-local.cmd build src\Mono.Android\Mono.Android.csproj -t:Rebuild -p:BuildProjectReferences=false: 0 errors, and only the 2 CS8603 warnings above.

jonathanpeppers and others added 3 commits November 16, 2026 12:28
The `Mono.Android` build on `main` reports these compiler warnings in generated bindings:

  * CS8604 and CS8768 in `IConcurrentMap`, `ISortedSet` and `String.CompareTo`
  * CS0672 for an override of an obsolete member that is not marked obsolete
  * CS0169 for `weak_implementor_*` fields that are never used
  * CS8625 in `MediaSessionManager`

### Default interface method nullability

A default interface method (DIM) that overrides another interface method can have different nullability annotations than the method it overrides. Calls dispatch through the original signature, which gives CS8604/CS8768.

`GenBase.FixupInterfaceMethodNullability ()` runs after `FixupMethodOverrides ()` when default interface methods are enabled. A DIM return is non-null if any overridden contract is non-null. A DIM parameter is non-null only if all contracts are non-null. When a non-null value can be null at the call site, the generated callbacks, invokers and generic explicit interface implementations throw `Java.Lang.NullPointerException` instead of using the null-forgiving operator.

### Override inference

`FixupMethodOverrides ()` did not find abstract methods that a class receives only from its interfaces. The generator emits these methods later, during class generation. A derived class method was therefore `virtual` instead of `override`, and the generator did not copy `[Obsolete]` to it (CS0672). The fix also searches the interfaces of an abstract base class, and skips methods listed in `skipInterfaceMethods` and explicitly implemented methods. The base method check also uses `ContainsMethod (m, false, false)`, so only matching base methods mark a method as `override`.

### Listener events

  * The generator added the `weak_implementor_*` field reference before it knew whether an event was created. It now adds the reference only when it adds an event, so no unused fields are generated (CS0169).
  * The listener connector lookup matched by name only, and could select a method for a different listener interface (CS8625). The lookup now also matches `ListenerType`, and prefers the overload with the fewest parameters.
  * The listener property setter assigned the handler only in the `else` branch, so the generated code lost the first handler when it created a new implementor. The setter now always assigns the handler.

### Incremental builds

`generator.dll` is now an input of the `_GenerateBinding` target, so a generator change regenerates the bindings.

### Validation

  * `bin\Debug\dotnet\dotnet.exe test tests/generator-Tests/generator-Tests.csproj`: passed.
  * `dotnet-local.cmd build src\Mono.Android\Mono.Android.csproj -t:Rebuild -p:BuildProjectReferences=false`: 0 errors. The only warnings are 2 existing CS8603 warnings in the `View.IOnApplyWindowInsetsListenerImplementor` and `LoudnessCodecController` listener implementors.

Co-authored-by: Copilot App <[email protected]>
The override check read ExplicitlyImplementedInterfaceMethods before
FixupExplicitImplementation fills it. Check the covariant, generic
return, and explicit-interface cases directly. Add a test for the
listener property setter and update its expected output.

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

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

Both the listener overload-resolution fix and the generic-to-string nullability fix lack regression tests that exercise the changed paths and compile the generated code under the required conditions.

2 open issues
What changed in this PR

This PR updates the binding generator to reduce warnings in Mono.Android and correct listener handler assignment.

Changes:

  • Merge default-interface nullability contracts and detect overrides inherited through abstract classes’ interfaces.
  • Fix listener connector selection, unused implementor fields, and first-handler assignment.
  • Add regression tests and regenerate bindings when generator.dll changes.
File Description
tests/​generator-Tests/​Unit-Tests/​DefaultInterfaceMethodsTests.cs Tests multilevel nullability merging and warning-free generated code.
tests/​generator-Tests/​Unit-Tests/​CodeGeneratorTests.cs Adds override, obsolete, and listener-property tests.
tests/​generator-Tests/​Unit-Tests/​CodeGeneratorTestBase.cs Applies nullability fixups during test setup.
tests/​generator-Tests/​Unit-Tests/​CodeGeneratorExpectedResults/​XAJavaInterop1-NRT/​WriteInterfaceListenerProperty.txt Updates nullable listener-property expectations.
tests/​generator-Tests/​Unit-Tests/​CodeGeneratorExpectedResults/​Common/​WriteInterfaceListenerProperty.txt Updates shared listener-property expectations.
tests/​generator-Tests/​Integration-Tests/​Compiler.cs Allows compilation tests to reject warnings.
src/​Mono.Android/​Mono.Android.targets Adds generator.dll to binding-generation inputs.
src/​generator/​SourceWriters/​MethodCallback.cs Adjusts default-interface callback null handling.
src/​generator/​SourceWriters/​InterfaceListenerProperty.cs Assigns the first handler to new implementors.
src/​generator/​SourceWriters/​GenericExplicitInterfaceImplementationMethod.cs Guards non-null generic-to-string arguments.
src/​generator/​SourceWriters/​Extensions/​SourceWriterExtensions.cs Refines listener generation and default-interface return checks.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​GenBase.cs Improves override discovery and merges interface nullability.
src/​generator/​CodeGenerator.cs Runs the new nullability fixup pass.

Review effort: Balanced

@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 17, 2026
@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.

Reviewed 39a5e36f against main at 46c6a36f (13 files). This is a static, read-only review.

The new nullability pass runs after FixupMethodOverrides and before FixupExplicitImplementation, and only for DIM output. In GenBase, the abstract-base interface lookup still finds every real slot, so changing ContainsMethod(m, true) to (m, false, false) only drops override where there was no matching base slot. The nullability merge across the override chain is monotonic, so type order doesn't matter. The listener fixes look right: weak_implementor_* is now emitted only alongside an event, the connector lookup filters by listener type and prefers the shortest overload, and InterfaceListenerProperty always assigns the handler. Both WriteInterfaceListenerProperty baselines (Common and XAJavaInterop1-NRT) are updated, and both earlier Copilot findings are now covered by tests.

Non-blocking:

  • GenericExplicitInterfaceImplementationMethod.cs:44: the ?? throw isn't gated on nullable-enabled output, unlike MethodCallback.cs:141 and SourceWriterExtensions.cs:403. It also uses the interface's annotation rather than the target method's, so a target taking string? still throws on null. That's a runtime change for non-NRT bindings.
  • Not mentioned in the description: when Java passes null to a non-null DIM-override parameter, MethodCallback.cs:150 now throws Java.Lang.NullPointerException instead of passing null through. DIM override returns also throw when any method up the chain declares the return non-null. It may be worth calling this out.
  • The two new reviewer-driven tests and the weak_implementor (CS0169) change are only checked as generated text; none of that output is compiled.

LGTM.

@simonrozsival
simonrozsival merged commit 18b8940 into main Nov 18, 2026
38 checks passed
@simonrozsival
simonrozsival deleted the jonathanpeppers-generator-warning-fixes branch November 18, 2026 10:25
simonrozsival added a commit that referenced this pull request Nov 21, 2026
The rebase onto cc7cbf6 kept the pre-rebase MSTest conversions of
files that main had changed since aa688ac, which reverted those
changes and broke the build. For each affected file, convert main's
old and new NUnit versions with the same converter and merge the
difference into the MSTest file:

  * cca255c (#13592): drop the Android lint tests and assertions.
  * 5b32fb1 (#13602): add RelativeDirectoriesUseProjectDirectory and
    the -mt CollectNonEmptyDirectories coverage.
  * 78ef747 (#13655): add OpenGenericProxiesKeepTheReflectionActivationConstructor.
  * 18b8940 (#13585): add the generator nullability/obsolete tests.
  * dcbd008 (#13580): add the AmbiguousFunctionMetadata_* tests.
  * 667e27a (#13621): add the sdkmanager package ID tests.
  * 5ecb8f7 (#13614): drop RunWithLoggingEnablesManagedTimingLogger.
  * 8287b17 (#13680), 4bfcc92 (#13681): restore the re-enabled
    tests and removed TODOs.
  * 5d81a0f (#13666): expect platform-tools 37.0.3.
  * 8442c75 (#13601): assert the pulled device TRX is deleted.

Also drop the EnableNUnitRunner/OutputType lines that 857f463
(#13563) added to Xamarin.Android.Build.Tests and MSBuildDeviceIntegration;
MSTestReferences.projitems sets both.

Co-authored-by: Copilot App <[email protected]>
jonathanpeppers added a commit that referenced this pull request Nov 23, 2026
Context: #13585

Complete Mono.Android's C# memory-safety-rules v2 compatibility adjustments.

Under v2, an `unsafe` declaration makes the member caller-unsafe (`RequiresUnsafe`). Keep implementation-only unsafe operations in method bodies where existing managed callers must remain supported. Preserve the released raw-handle constructor behavior, including generated base initializers, and keep the typed-marshaler template and checked-in output consistent. Update the typed helpers' Unshipped API entries to match their safe-callable declarations; Shipped inventories are unchanged.

### Compatibility

The compatibility exceptions do not validate JNI references, buffers, callback ABIs, thread affinity, ownership or lifetime. Their documented `<safety>` obligations still apply even where the compiler does not enforce them.

The five **new, unshipped UTF-8 allocation and construction overloads retain `unsafe`**. `ReadOnlySpan<byte>` does not guarantee NUL-terminated backing storage, and its length does not bound JNI's native read. These APIs therefore retain caller acknowledgement under v2 rather than inheriting the released-constructor exception. Their implementations are unchanged.

The unrelated javac option change was removed; `java-runtime.targets` matches the selected main base.

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

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.

4 participants