Skip to content

[generator][Mono.Android] Emit new and override for inherited member hiding - #13771

Merged
simonrozsival merged 5 commits into
mainfrom
simonrozsival-mono-android-hiding-warnings
Nov 27, 2026
Merged

simonrozsival merged 5 commits into
mainfrom
simonrozsival-mono-android-hiding-warnings

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

src/Mono.Android/Mono.Android.csproj suppresses CS0108 (514 warnings on API 37.0) and CS0114 (349 warnings on API 37.0) in <NoWarn> because MCW-generated bindings redeclare inherited members—interface methods/properties, const fields, properties/methods colliding with base members, widened Clone (), nested types, and internal *Invoker methods—without new or override.

Modifier ordering in Xamarin.SourceWriter

FieldWriter.WriteSignature emitted const/static/readonly before new (IsShadow), producing invalid C# (public const new ..., CS1585) for shadowing constants. Emit new ahead of static/readonly/const in FieldWriter and ahead of static in PropertyWriter, with a unit test covering public new const.

Inherited member hiding in generator

Extend member-hiding detection in GenBase via private protected overrides (HidesInheritedMember, PopulateEmittedMembers) on ClassGen and InterfaceGen, backed by a lazily cached per-type EmittedMemberTable:

  • Follow C# hiding rules without introducing redundant new (CS0109): non-methods hide any accessible inherited member with the same name, while methods hide same-signature base methods and any same-named base non-method.
  • Keep IJavaObject/IJavaPeerable/IDisposable interface members separate from Java.Lang.Object's publicly/protectedly inherited handwritten members so explicitly implemented IJavaPeerable methods do not trigger CS0109 on subclasses.
  • Walk ancestor classes (including private members of enclosing base classes for _members and MethodCallback in both legacy and UnmanagedCallersOnly modes) and emitted base interfaces, covering fields/consts, properties, methods, string/async overloads, ICharSequence enumerators, nested types, nested EventArgs, delegates, nested *Invoker types, and InterfaceConsts.
  • Emit new (never override) on public classes to preserve C# legality, public API compatibility, and exact IL newslot/vtable layout.
  • On internal InterfaceInvoker classes, emit override where signature, visibility, and return type match Java.Lang.Object virtuals (Equals, GetHashCode, ToString) and new otherwise (Clone, Handle); on ClassInvokerClass, force override for DIM-backed abstract methods (ClockInvoker.WithZone).
  • Scope InterfaceConstsClass and InterfaceMemberAlternativeClass hiding checks to their actual System.Object / Java.Lang.Object base classes to avoid CS0109, and support managedOverride="new" across method and property writers.

Enforcing CS0108 and CS0114 in Mono.Android

  • Remove 0108;0114 from <NoWarn> in src/Mono.Android/Mono.Android.csproj.
  • Mark CellInfo subclasses' getCellIdentity and getCellSignalStrength with managedOverride="new" (api-since="30") in src/Mono.Android/metadata, since the base CellInfo properties are removed from API XML and hand-written as virtual in Android.Telephony/CellInfo.cs.

Validation

  • dotnet test tests/Xamarin.SourceWriter-Tests/Xamarin.SourceWriter-Tests.csproj: 12/12 passed.
  • dotnet test tests/Java.Interop.Tools.Generator-Tests/Java.Interop.Tools.Generator-Tests.csproj: 18/18 passed.
  • dotnet test tests/generator-Tests/generator-Tests.csproj: 494/494 passed (3 expected golden files updated for newly emitted new on interface methods).
  • ./dotnet-local.sh build src/Mono.Android/Mono.Android.csproj -c Debug -f net12.0 --no-dependencies and -c Release across API 37.0, 37.1, and 37.2: all 6 builds succeeded with 0 CS0108, 0 CS0114, 0 CS0109, 0 RS0016/RS0017, and CheckApiCompatibility Total Issues: 0.
  • ./dotnet-local.sh build src/Mono.Android/Mono.Android.csproj -c Debug -f net12.0 --no-dependencies -p:AndroidApiLevel=37 -p:AndroidPlatformId=37.0 -p:AndroidFrameworkVersion=v17.0 -p:_MonoAndroidEnableUnmanagedCallersOnlyCallbacks=true: succeeded with 0 CS0108, 0 CS0114, 0 CS0109.
  • Mono.Cecil metadata and vtable comparison against pre-change API 37.0 Mono.Android.dll and ref/Mono.Android.dll: 0 public/protected diffs (types, signatures, fields, properties, Overrides, and MethodAttributes); internal diffs are exclusively the intended override slots on internal *Invoker classes.

simonrozsival and others added 4 commits November 25, 2026 09:43
Move 'new' (IsShadow) ahead of 'static'/'readonly'/'const' in FieldWriter
and ahead of 'static' in PropertyWriter so shadowing const fields emit
valid C# ('public new const ...') rather than 'public const new ...'
(CS1585).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Extend GenBase member-hiding detection and SourceWriters to eliminate
CS0108 and CS0114 warnings without introducing CS0109 or altering public
API / vtable slots:
- Walk ancestor classes (including private members of enclosing base
  classes) and emitted base interfaces following C# hiding rules for
  fields/consts, properties, methods, string/async overloads,
  CharSequence enumerators, nested types, and nested EventArgs.
- Support managedOverride='new' on methods and properties for cases
  hiding hand-written partial-class members.
- Emit 'override' on internal InterfaceInvoker methods matching
  Java.Lang.Object virtuals (Equals/GetHashCode/ToString) and 'new'
  otherwise (Clone/Handle), and force 'override' in ClassInvokerClass
  for DIM-backed abstract methods.
- Emit 'new' on _members and MethodCallback members when a nested class
  inherits from an enclosing class declaring the same member.
- Keep InterfaceConstsClass and InterfaceMemberAlternativeClass scoped
  to their actual System.Object / Java.Lang.Object base classes to avoid
  CS0109.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Remove 0108 and 0114 from Mono.Android.csproj <NoWarn>, and mark
CellInfo subclasses' getCellIdentity/getCellSignalStrength with
managedOverride='new' to match the hand-written virtual properties in
Android.Telephony/CellInfo.cs.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Address findings from local code review:
- Replace 'this is ClassGen'/'this is InterfaceGen' checks in GenBase
  with private protected overrides on ClassGen and InterfaceGen
  (HidesInheritedMember, PopulateEmittedMembers).
- Unify name-only and signature hiding lookups into a single lazily
  cached EmittedMemberTable per type (cutting Mono.Android
  _GenerateBinding time from ~14.1s to ~8.9s) and merge Throwable
  reflection into one case-sensitive table.
- Separate IJavaObject/IJavaPeerable/IDisposable members (adding
  JniIdentityHashCode and JniObjectReferenceControlBlock) from
  Java.Lang.Object's publicly/protectedly inherited handwritten members
  so explicitly implemented IJavaPeerable methods don't trigger CS0109
  on subclasses.
- Handle DelegateWriter, nested *Invoker classes, and InterfaceConsts
  in nested-member hiding, and stop claiming non-emitted async/string
  variants on abstract interface members.
- Deduplicate ClassGen.GetMethodsToDeclare, GetAbstractInterfaceMethods,
  GetAbstractInterfaceProperties, and GenBase.MethodEmitsStringOverload;
  cache enclosing-ancestor callback entries; avoid computing-then-
  overwriting IsShadow; remove redundant ClassGen.NeedsNew and dead
  branches; honor managedOverride='new' on abstract member writers.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 25, 2026 09:37

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 can emit invalid C#, notably new sealed methods for final overrides, while other member-hiding and override-metadata errors remain.

7 open issues
What changed in this PR

This PR updates .NET for Android’s binding generator to explicitly mark inherited-member hiding, reducing compiler warnings while preserving public API and virtual-method compatibility.

Changes:

  • Add inherited-member detection and apply new or override across generated bindings and internal invokers.
  • Correct modifier ordering and add metadata for handwritten CellInfo base properties.
  • Remove CS0108/CS0114 suppression and update regression expectations.
File Description
tests/​Xamarin.SourceWriter-Tests/​FieldWriterTests.cs Tests new const modifier ordering.
tests/​generator-Tests/​Unit-Tests/​CodeGeneratorExpectedResults/​XAJavaInterop1/​WriteInterfaceRedeclaredDefaultMethod.txt Expects new on a redeclared interface method.
tests/​generator-Tests/​expected.xaji/​TestInterface/​Java.Util.IQueue.cs Updates inherited-method hiding output.
tests/​generator-Tests/​expected.xaji/​TestInterface/​Java.Util.IDeque.cs Updates inherited-method hiding output.
src/​Xamarin.SourceWriter/​Models/​PropertyWriter.cs Emits new before static.
src/​Xamarin.SourceWriter/​Models/​FieldWriter.cs Emits new before field modifiers.
src/​Mono.Android/​Mono.Android.csproj Removes CS0108 and CS0114 suppression.
src/​Mono.Android/​metadata Marks derived CellInfo accessors as hiding members.
src/​generator/​SourceWriters/​MethodCallback.cs Detects callback hiding in enclosing base classes.
src/​generator/​SourceWriters/​MethodAsyncWrapper.cs Adds hiding detection to async wrappers.
src/​generator/​SourceWriters/​InterfaceMemberAlternativeClass.cs Checks hiding against the actual Java object base.
src/​generator/​SourceWriters/​InterfaceInvokerProperty.cs Marks invoker properties that hide base members.
src/​generator/​SourceWriters/​InterfaceInvokerMethod.cs Selects invoker method overrides or hiding.
src/​generator/​SourceWriters/​Extensions/​SourceWriterExtensions.cs Scopes constant-container checks to System.Object.
src/​generator/​SourceWriters/​ClassInvokerClass.cs Forces overrides for abstract method implementations.
src/​generator/​SourceWriters/​BoundPropertyStringVariant.cs Detects hiding for string properties.
src/​generator/​SourceWriters/​BoundProperty.cs Supports explicit and inferred property hiding.
src/​generator/​SourceWriters/​BoundMethodStringOverload.cs Detects hiding for string overloads.
src/​generator/​SourceWriters/​BoundMethodAbstractDeclaration.cs Applies hiding metadata to abstract methods.
src/​generator/​SourceWriters/​BoundMethod.cs Supports forced overrides and explicit hiding metadata.
src/​generator/​SourceWriters/​BoundInterfacePropertyDeclaration.cs Marks redeclared interface properties.
src/​generator/​SourceWriters/​BoundInterfaceMethodDeclaration.cs Marks redeclared interface methods.
src/​generator/​SourceWriters/​BoundInterface.cs Applies hiding checks to interface members and nested types.
src/​generator/​SourceWriters/​BoundFieldAsProperty.cs Detects hiding for field-backed properties.
src/​generator/​SourceWriters/​BoundField.cs Detects hiding for constants.
src/​generator/​SourceWriters/​BoundClass.cs Integrates hiding checks across generated class members.
src/​generator/​SourceWriters/​BoundAbstractProperty.cs Adds explicit hiding support for abstract properties.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​InterfaceGen.cs Tracks emitted interface members and inherited interfaces.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​GenBase.cs Adds cached member matching and base-member inventories.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​ClassGen.cs Tracks emitted class members and enclosing-base callbacks.

Review effort: Balanced

- BoundMethod: clear IsSealed when managedOverride='new' so final Java
  overrides do not emit invalid 'public new sealed'.
- BoundAbstractProperty / BoundClass: check managedOverride='new' before
  baseProp lookup so forced-new abstract properties emit 'new abstract'
  with their own callbacks instead of 'abstract override'.
- ClassGen: filter class-declared fields in HasInterfaceConsts to match
  InterfaceConstsClass.ShouldGenerate, and exclude 'internal' members
  and internal '*Invoker' nested types from external (!IsGeneratable)
  base classes in PopulateEmittedMembers.
- GenBase: strip leading 'params ' in NormalizeCSharpType so array and
  varargs parameter signatures compare equal.
- InterfaceGen / BoundInterface: move FixupInvokerMethodNames onto
  InterfaceGen with a one-time guard and run it before
  PopulateEmittedMembers so cached base interface names are independent
  of generation order.
- Add focused regression tests in CodeGeneratorTests covering these edge
  cases and compiled InterfaceInvoker override/new virtual dispatch.

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

Copy link
Copy Markdown

Reviewed as a maintainer. I checked the generator hiding detection (GenBase.EmittedMemberTable, ClassGen/InterfaceGen.PopulateEmittedMembers and HidesInheritedMember), the writers that consume it (BoundMethod, BoundProperty, BoundField/BoundFieldAsProperty, BoundAbstractProperty, BoundInterfaceMethodDeclaration/BoundInterfacePropertyDeclaration, InterfaceInvokerMethod/InterfaceInvokerProperty, InterfaceMemberAlternativeClass, MethodCallback enclosing-ancestor handling), the FieldWriter/PropertyWriter modifier-ordering fix (new before static/const, covered by the new ShadowConstField test), and the CellInfo managedOverride="new" metadata.

I also verified Copilot's 7 points are addressed in the current head: IsSealed is cleared in the managedOverride="new" branch of BoundMethod (no more new sealed), params is stripped in NormalizeCSharpType so varargs signatures compare equal, FixupInvokerMethodNames moved onto InterfaceGen with a one-time guard so emitted names are finalized regardless of generation order, internal members are only added to the accessible table for IsGeneratable types, HasInterfaceConsts filters against class-declared fields, forced-new abstract properties are handled before baseProp resolution in both BoundAbstractProperty and BoundClass, and the new InterfaceInvokerMethod_OverrideAndNewSelection and HidingEdgeCases_VarargsInterfaceConstsExternalInternalAndOrder tests cover the invoker override/new selection (including IL NewSlot assertions) and the varargs/consts/external-internal/order edge cases.

Checked the golden updates too (IDeque/IQueue new bool Add, WriteInterfaceRedeclaredDefaultMethod new void DoSomething). The new/override selection matches the stated intent: new on public classes to preserve API/vtable layout, override only where signature, visibility, and return type match a Java.Lang.Object virtual. No issues found.

@simonrozsival

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 the 31-file change and affected generator/writer integration, including inherited-member hiding, modifier ordering, JNI callback generation, generated expectations and the current target's Kotlin default-argument path. The earlier review findings are addressed, and the maintainer's accepted new-versus-override/vtable policy is preserved. No blocking correctness issue found in static review. I did not run builds or tests.

@simonrozsival
simonrozsival merged commit 128c554 into main Nov 27, 2026
38 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-mono-android-hiding-warnings branch November 27, 2026 14:20
simonrozsival added a commit that referenced this pull request Nov 27, 2026
Converts the tests that #13771 and #13795 added after the last rebase,
and the [SetCulture] tests from #13794: each culture is now a [DataRow]
that sets and restores CultureInfo.CurrentCulture.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
simonrozsival added a commit that referenced this pull request Nov 27, 2026
Context: #13771

`Mono.Android.csproj` currently suppresses `0618`, `0809`, and `0465` in `$(NoWarn)` because both handwritten `AndroidMessageHandler` code and MCW-generated bindings emit obsolete-usage (`CS0618`), obsolete-override (`CS0809`), and parameterless `Finalize()` (`CS0465`) warnings. Removing these suppressions is needed to burn down `Mono.Android.csproj` compiler warnings ahead of enabling warnings as errors, without changing the public API or runtime behavior.

### Handwritten `AndroidMessageHandler` `CS0618` warnings

8 handwritten `CS0618` warnings referenced obsolete `Xamarin.Android.Net.AndroidMessageHandler`:

  * Share the internal `"DOTNET-net"` log tag via `Android.Runtime.Logger.NetLogTag` so `AndroidHttpResponseMessage` and `AuthModuleDigest` do not reference `AndroidMessageHandler` for a string constant, and make `AndroidMessageHandler.LOG_APP` private.
  * Mark the internal `NegotiateAuthenticationHelper` helper class `[Obsolete]`, matching its only caller (`AndroidMessageHandler`).
  * Wrap the legacy `AndroidEnvironment.GetHttpMessageHandler ()` factory call in a narrowly scoped `#pragma warning disable CS0618` / `restore`.

### Generated `CS0618`, `CS0809`, and `CS0465` warnings

  * Propagate `[Obsolete]` / `[ObsoletedOSPlatform]` to generated internal `ClassInvokerClass` and `InterfaceEventHandlerImplClass` types when their target type is deprecated.
  * Track nested type declarations (`GenBase.DeclaringType`), overridden base methods (`GenBase.FindOverriddenBaseMethod`), array element symbols (`ArraySymbol.ElementSymbol`), and collection type arguments (`CollectionSymbol.TypeParams`) to detect when a non-obsolete generated member references an obsolete type or overrides a non-obsolete base member.
  * Emit narrowly scoped `#pragma warning disable 0618` / `restore` around non-obsolete generated class/interface signatures, constructors, methods, properties, string variants, callbacks, async wrappers, event args, and listener helpers that reference obsolete types or members.
  * Omit redundant `[Obsolete]` on internal `ClassInvokerClass` property overrides (because `BoundAbstractProperty` never emits `[Obsolete]`) and emit scoped `#pragma warning disable 0809` / `restore` on `BoundMethod` and `BoundProperty` overrides that are deprecated while their base member is not.
  * Emit scoped `#pragma warning disable 0465` / `restore` in `BoundMethod` for bound parameterless `Finalize ()` methods.
  * Remove `0618;0809;0465` from `Mono.Android.csproj` `$(NoWarn)`, leaving `8764;8765;8766;8767;RS0041` for follow-up changes.
simonrozsival added a commit that referenced this pull request Nov 27, 2026
Converts the tests that #13771 and #13795 added after the last rebase,
and the [SetCulture] tests from #13794: each culture is now a [DataRow]
that sets and restores CultureInfo.CurrentCulture.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
simonrozsival added a commit that referenced this pull request Nov 28, 2026
Converts the tests that #13771 and #13795 added after the last rebase,
and the [SetCulture] tests from #13794: each culture is now a [DataRow]
that sets and restores CultureInfo.CurrentCulture.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
simonrozsival added a commit that referenced this pull request Nov 28, 2026
Resolve conflict in src/Mono.Android/Mono.Android.csproj <NoWarn> by
preserving the warning removals merged on main (#13771, #13773) while
removing RS0041.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
simonrozsival added a commit that referenced this pull request Nov 29, 2026
…arnings as errors (#13776)

Context: #13770, #13771, #13772, #13773

`Mono.Android.csproj` was the last project exempted from `$(TreatWarningsAsErrors)` via `$(_AllowProjectWarnings)` in `Directory.Build.props` and suppressed `CS8764`–`CS8767` in `$(NoWarn)` due to generated nullability variance mismatches across overrides/interfaces, two `CS8603` warnings in generated `*Implementor` classes, and pre-existing `RS0025` duplicate entries in API 37.1/37.2 `PublicAPI.Shipped.txt` files.

### Nullability variance (`CS8764`–`CS8767`)

  * Extended `GenBase.FixupInterfaceMethodNullability` to reconcile return and parameter nullability across class overrides, base properties, and implemented interfaces (processing base types and interfaces first, excluding base override contracts when metadata disables overriding via `managedOverride`, and emitting `[global::System.Diagnostics.CodeAnalysis.AllowNull]` when both a non-null getter contract and a nullable setter contract apply, while preserving `[AllowNull]` in `CecilApiImporter`).
  * Added `CodeGenerationOptions.IsValueTypeEnum` so `GeneratedEnumSymbol` arrays remain nullable reference types unless `NotNull` is set.
  * Scoped `#pragma warning disable 8764` in `BoundProperty` to the existing `ShouldForceOverride` workaround for `AbsSpinner.Adapter`.
  * Reconciled internal `*Invoker` overrides of `Java.Lang.Object` methods (fixing 46 `CS8764` warnings on internal `*Invoker.ToString ()` overrides introduced after #13771) via `GenBase.FindOverriddenJavaObjectMethod` (with lazy `GetValidatedJavaObject` for imported `java.lang.Object`) and `InterfaceInvokerMethod`, matching `Java.Lang.Object.ToString ()`'s non-null return without changing public interface signatures.
  * Added missing `?` return annotations on `IXmlResourceParser` (`PositionDescription`, `GetAttributeName`, `GetAttributeValue`).
  * Recorded the 288 NRT variance updates in `PublicAPI.Unshipped.txt` (`*REMOVED*` + updated signature) across API 37, 37.1, and 37.2 without editing shipped NRT lines in `PublicAPI.Shipped.txt`.

### Generated `*Implementor` `CS8603`

  * Added `CodeGenerationOptions.IsNonNullableReferenceType` and updated `InterfaceEventHandlerImplClass` to emit null-forgiveness on `default (T)` only for non-nullable reference return types, keeping value types, nullable reference types, and runtime behavior unchanged.

### API 37.1/37.2 `RS0025` and `PublicAPI.Unshipped.txt` baseline sync (separate commit)

  * Removed the two duplicate `VP9Profile2HDR`/`VP9Profile3HDR` lines from `API-37.1/PublicAPI.Shipped.txt` and `API-37.2/PublicAPI.Shipped.txt` (`9f724c342b`), which previously triggered `RS0025` and caused `PublicApiAnalyzers` to abort symbol analysis on those API levels.
  * Synced the uncovered pre-existing baseline drift in `PublicAPI.Unshipped.txt` (`API-37.1`: +107 `*REMOVED*`, +4,865 added; `API-37.2`: +113 `*REMOVED*`, +6,012 added) in that dedicated commit so all three API levels pass with `$(RunAnalyzers)` enabled under `$(TreatWarningsAsErrors)`.

### Warnings as errors on `Mono.Android.csproj`

  * Removed `8764;8765;8766;8767` from `$(NoWarn)` in `src/Mono.Android/Mono.Android.csproj` (leaving only `RS0041` until independent #13772 merges).
  * Set `<TreatWarningsAsErrors>true</TreatWarningsAsErrors>` on `src/Mono.Android/Mono.Android.csproj` (preserving `$(WarningsNotAsErrors)` for `RS0016;RS0017` when `$(BuildingInsideVisualStudio)` is `True`) and removed the now-empty `$(_AllowProjectWarnings)` exemption from `Directory.Build.props`.
simonrozsival added a commit that referenced this pull request Nov 29, 2026
Converts the tests that #13771 and #13795 added after the last rebase,
and the [SetCulture] tests from #13794: each culture is now a [DataRow]
that sets and restores CultureInfo.CurrentCulture.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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.

4 participants