Repository navigation
[generator][Mono.Android] Emit new and override for inherited member hiding - #13771
Conversation
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>
There was a problem hiding this comment.
🟡 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
Clear IsSealed when managedOverride forces a new method · New Match InterfaceConsts generation checks to emitted class fields · New Exclude inaccessible internal members from inherited-member checks · New Normalize params arrays when matching redeclared interface methods · New Finalize interface method names before populating inherited-member tables · New Honor forced-new metadata for abstract property redeclarations · New Add regression tests for invoker override and hiding selection · New
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
neworoverrideacross generated bindings and internal invokers. - Correct modifier ordering and add metadata for handwritten
CellInfobase 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>
|
Reviewed as a maintainer. I checked the generator hiding detection ( I also verified Copilot's 7 points are addressed in the current head: Checked the golden updates too ( |
|
@dalexsoto review |
dalexsoto
left a comment
There was a problem hiding this comment.
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.
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.
…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`.



src/Mono.Android/Mono.Android.csprojsuppressesCS0108(514 warnings on API 37.0) andCS0114(349 warnings on API 37.0) in<NoWarn>because MCW-generated bindings redeclare inherited members—interface methods/properties,constfields, properties/methods colliding with base members, widenedClone (), nested types, and internal*Invokermethods—withoutneworoverride.Modifier ordering in
Xamarin.SourceWriterFieldWriter.WriteSignatureemittedconst/static/readonlybeforenew(IsShadow), producing invalid C# (public const new ...,CS1585) for shadowing constants. Emitnewahead ofstatic/readonly/constinFieldWriterand ahead ofstaticinPropertyWriter, with a unit test coveringpublic new const.Inherited member hiding in
generatorExtend member-hiding detection in
GenBaseviaprivate protectedoverrides (HidesInheritedMember,PopulateEmittedMembers) onClassGenandInterfaceGen, backed by a lazily cached per-typeEmittedMemberTable: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.IJavaObject/IJavaPeerable/IDisposableinterface members separate fromJava.Lang.Object's publicly/protectedly inherited handwritten members so explicitly implementedIJavaPeerablemethods do not triggerCS0109on subclasses._membersandMethodCallbackin both legacy andUnmanagedCallersOnlymodes) and emitted base interfaces, covering fields/consts, properties, methods, string/async overloads,ICharSequenceenumerators, nested types, nestedEventArgs, delegates, nested*Invokertypes, andInterfaceConsts.new(neveroverride) on public classes to preserve C# legality, public API compatibility, and exact ILnewslot/vtable layout.InterfaceInvokerclasses, emitoverridewhere signature, visibility, and return type matchJava.Lang.Objectvirtuals (Equals,GetHashCode,ToString) andnewotherwise (Clone,Handle); onClassInvokerClass, forceoverridefor DIM-backed abstract methods (ClockInvoker.WithZone).InterfaceConstsClassandInterfaceMemberAlternativeClasshiding checks to their actualSystem.Object/Java.Lang.Objectbase classes to avoidCS0109, and supportmanagedOverride="new"across method and property writers.Enforcing
CS0108andCS0114inMono.Android0108;0114from<NoWarn>insrc/Mono.Android/Mono.Android.csproj.CellInfosubclasses'getCellIdentityandgetCellSignalStrengthwithmanagedOverride="new"(api-since="30") insrc/Mono.Android/metadata, since the baseCellInfoproperties are removed from API XML and hand-written asvirtualinAndroid.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 emittednewon interface methods)../dotnet-local.sh build src/Mono.Android/Mono.Android.csproj -c Debug -f net12.0 --no-dependenciesand-c Releaseacross API 37.0, 37.1, and 37.2: all 6 builds succeeded with 0CS0108, 0CS0114, 0CS0109, 0RS0016/RS0017, andCheckApiCompatibilityTotal 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 0CS0108, 0CS0114, 0CS0109.Mono.Android.dllandref/Mono.Android.dll: 0 public/protected diffs (types, signatures, fields, properties,Overrides, andMethodAttributes); internal diffs are exclusively the intendedoverrideslots on internal*Invokerclasses.