Repository navigation
[generator] Fix nullable and obsolete warnings in Mono.Android bindings - #13585
Conversation
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]>
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]>
There was a problem hiding this comment.
🟡 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.dllchanges.
| 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
Co-authored-by: Copilot App <[email protected]>
|
@dalexsoto review |
dalexsoto
left a comment
There was a problem hiding this comment.
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?? throwisn't gated on nullable-enabled output, unlikeMethodCallback.cs:141andSourceWriterExtensions.cs:403. It also uses the interface's annotation rather than the target method's, so a target takingstring?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:150now throwsJava.Lang.NullPointerExceptioninstead 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.
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]>
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]>

On
main, the generatedMono.Androidbindings build with these warnings:IConcurrentMap,ISortedSetandString.CompareToweak_implementor_*fieldsMediaSessionManagerDefault 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 throwsJava.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 asvirtualinstead ofoverride, and it did not get[Obsolete]. The lookup now also checks the interfaces of an abstract base class. It skips methods inskipInterfaceMethodsand methods that are generated as explicit interface implementations.Listener events
weak_implementor_*field only when it creates the event that uses it.generator.dllis now an input of the_GenerateBindingtarget, so a change to the generator regenerates the bindings.Two CS8603 warnings remain, in the
View.IOnApplyWindowInsetsListenerandLoudnessCodecController.IOnLoudnessCodecUpdateListenerimplementors.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.