Repository navigation
Identify trimmable styles by assembly-qualified name so NativeAOT can remove unused handlers - #40952
Conversation
With NativeAOT, typeof(T) gives T reflection metadata. MauiHandlersFactory reads [ElementHandler] with GetCustomAttribute, and the attribute's DynamicallyAccessedMembers annotation then keeps the handler, its mappers and its platform code for every style target, even unused ones. Generated styles use Style(string assemblyQualifiedTargetTypeName) again (typeof stays for generic targets). On the Android NativeAOT template app this saves 204,800 B of APK and 584,048 B of native code. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
🟡 Changes recommended
Style matching loses assembly identity and can select the wrong style for identically named types across assemblies, while the new string-backed runtime behavior lacks regression coverage.
2 open issues
What changed in this PR
This follow-up to #33561 changes how generated trimmable styles identify their target types, allowing NativeAOT to remove unused control handlers that typeof(T) would otherwise retain.
Changes:
- Generate assembly-qualified target names for non-generic styles, retaining
typeof(T)for generic targets. - Resolve
Style.TargetTypelazily and adapt resource registration, matching, and validation for unresolved types. - Update public API declarations, generator assertions, and trimming documentation.
| File | Description |
|---|---|
src/Controls/tests/SourceGen.UnitTests/StyleSourceGenTests.cs |
Expect string-based style construction. |
src/Controls/src/SourceGen/Visitors/CreateValuesVisitor.cs |
Emit target names for non-generic styles. |
src/Controls/src/SourceGen/ISymbolExtensions.cs |
Build assembly-qualified type names. |
src/Controls/src/Core/Style.cs |
Add string constructor, lazy resolution, and revised matching. |
src/Controls/src/Core/ResourceDictionary.cs |
Register implicit styles using stored target names. |
src/Controls/src/Core/PublicAPI/net/PublicAPI.Unshipped.txt |
Declare the new constructor for .NET. |
src/Controls/src/Core/PublicAPI/net-windows/PublicAPI.Unshipped.txt |
Declare the new constructor for Windows. |
src/Controls/src/Core/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt |
Declare the new constructor for Mac Catalyst. |
src/Controls/src/Core/PublicAPI/net-ios/PublicAPI.Unshipped.txt |
Declare the new constructor for iOS. |
src/Controls/src/Core/PublicAPI/net-android/PublicAPI.Unshipped.txt |
Declare the new constructor for Android. |
src/Controls/src/Core/MergedStyle.cs |
Handle unresolved style targets in compatibility warnings. |
src/Controls/src/Core/IStyle.cs |
Allow a nullable target type. |
docs/trimmable-styles-spec.md |
Explain name-based identity and the generic fallback. |
Review effort: Balanced
| { | ||
| if (TargetType == targetType) | ||
| // Use FullName comparison to avoid resolving the type (which may have been trimmed) | ||
| if (targetType.FullName is not null && TargetTypeFullName == targetType.FullName) |
| /// Gets the type to which this style applies. | ||
| /// </summary> | ||
| public Type TargetType { get; } | ||
| public Type TargetType => _targetType ??= ResolveTargetType(); |
| { | ||
| if (TargetType == targetType) | ||
| // Use FullName comparison to avoid resolving the type (which may have been trimmed) | ||
| if (targetType.FullName is not null && TargetTypeFullName == targetType.FullName) |
There was a problem hiding this comment.
[major] Logic and Correctness Verification - FullName loses assembly identity for class styles, including existing Style(Type) styles. If assemblies A and B both define Widgets.Badge : Label and register an "accent" class style, MergedStyle.OnClassStyleChanged now accepts A's first-listed style for a B badge instead of selecting B's style. Eager styles apply A's setters; generated lazy styles reject the target in their type guard, but the correct style is never considered. This also occurs with MauiXamlTrimmableStyles=false. Preserve assembly-aware identity in both this comparison and the base-type comparison below. Add a regression test with same-FullName controls from different assemblies; MultipleStylesCanShareTheSameClassName only uses distinct Button/Label names.
| var basedOnTargetType = value.TargetType; | ||
| var thisTargetType = TargetType; | ||
|
|
||
| if (basedOnTargetType is null || thisTargetType is null) |
There was a problem hiding this comment.
[moderate] Regression Prevention and Test Coverage - The new unresolved-TargetType branch has no discriminating runtime regression test: the Core lazy-style tests still construct Style(typeof(Label)), and the changed generator assertions only check emitted text. They cannot catch a null dereference when a name-backed target is unavailable. Add deterministic tests using a nonexistent type name in an existing assembly: assert TargetType is null, implicit resource registration preserves the stored full name, and BasedOn assignment tolerates either unresolved side. Include a resolvable Label/Entry pair that must still throw, so unconditionally accepting BasedOn cannot satisfy the test. No trimmed publish or device is needed for these cases.
| public static string GetAssemblyQualifiedName(this INamedTypeSymbol type) | ||
| { | ||
| var metadataName = type.GetMetadataFullName(); | ||
| var typeArguments = new List<INamedTypeSymbol>(); |
There was a problem hiding this comment.
[minor] Complexity Reduction - The generic-name serializer is unreachable from its only external caller: TryCreateTrimmableStyle calls GetAssemblyQualifiedName only when IsGenericType is false, while generic targets deliberately use typeof. The type-argument collection, unsupported-argument branch, and recursive formatting therefore implement a path the caller excludes. Reduce this helper to GetMetadataFullName() plus ContainingAssembly.Identity and retain the generic typeof fallback.
MAUI Autopilot — Stopped@kubaflo ❌ The last fix round found nothing more it could fix. Decide how to continue, or comment WhyNo fixes were published: the push was blocked by the existing change to |
<!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `898590c165cbc37424a1e0738ff3d6bcd837cf20` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 9.5/10 | ↑ Six Android device cases pass for base and derived controls.<br>↑ Native AOT probes match all 180 baseline named-size results and render all three controls.<br>↓ Validation used Android API 29, not a second Android version. | | Diagnosis confidence | 10/10 | ↑ Controlled A/B removes EntryHandler, EditorHandler and SearchBarHandler from the unused-feature ILC map.<br>↑ The only product changes replace the concrete control type checks. | | Evidence fit | 10/10 | ↑ Current-main A/B reduces the APK by 40,960 B and its native library by 103,384 B with matching compiler-input assembly hashes. | <!-- /copilot-assessment --> <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change <!-- Enter description of the fix in this section --> Android's `FontNamedSizeService` refers to `typeof(Entry)`, `typeof(Editor)` and `typeof(SearchBar)` solely to categorize text-input controls. These references retain the controls and their default handlers even when the application does not use them. Replace them with `IEntry`, `IEditor` and `ISearchBar` assignability checks, allowing the unused controls and handlers to trim after #40952. Preserve the existing default-size distinction: Entry and Editor use the EditText size in both modes; SearchBar uses it only for legacy sizes and still uses the medium size in modern mode. Subclasses remain supported. Other named-size branches are unchanged. Add six Android device-test cases for these base/derived-control defaults. #### Current-main Native AOT measurement Measured against `3600ee0ee1` using the same `dotnet new maui` template, SDK `12.0.100-alpha.1.26523.103`, Android workload and `android-arm64` settings. Only the candidate Controls assembly differs between the two publish lanes. A lane-local NuGet cache and package-source mapping exclude stale SDK library-pack packages; SHA-256 hashes of the actual ILC input assemblies were verified against the locally built assemblies. | Artifact | Before | After | Change | |---|---:|---:|---:| | Signed APK | 15,641,682 B | 15,600,722 B | **−40,960 B (40 KiB)** | | `libTrimProbe.so` (uncompressed) | 19,668,920 B | 19,565,536 B | **−103,384 B** | | DEX (uncompressed) | 12,828,592 B | 12,828,592 B | 0 B | ILC-map symbol matches: `EntryHandler` **136 → 0**, `EditorHandler` **113 → 0**, `SearchBarHandler` **209 → 0**. Both template publishes and both feature-used probe publishes produce **zero trim/AOT warnings**. These measurements supersede the earlier prototype numbers because they use current main, including subsequent trimming changes. Publish command (run independently for baseline and candidate): ```sh dotnet publish TrimProbe.csproj -c Release -f net12.0-android -r android-arm64 \ -p:TargetFrameworks=net12.0-android -p:PublishAot=true -p:PublishAotUsingRuntimePack=true \ -p:AndroidPackageFormats=apk -p:AndroidNdkDirectory=<NDK-27.2.12479018> \ -p:IlcGenerateMapFile=true -p:IlcTreatWarningsAsErrors=false -p:TrimmerSingleWarn=false \ -p:UseSharedCompilation=false /nodeReuse:false --nologo -v:minimal ``` Result: both passed. The compiler-input hashes differ only for `Microsoft.Maui.Controls.dll`. #### Behavior validation - **Passed, 6/6:** `pwsh -NoProfile .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -DeviceUdid emulator-5570 -IncludeClasses Microsoft.Maui.DeviceTests.FontNamedSizeServiceTests`. Genuine native and host TRX reports confirm exactly the six requested cases on Android API 29. - **Passed:** baseline and candidate Native AOT feature apps resolve all ten named sizes in both legacy/modern modes for Entry, Editor, SearchBar, their subclasses, Label, Button and View: **all 180 results match**. The candidate also renders Entry, Editor and SearchBar, and their handlers remain in its feature-used ILC map. - **Passed, zero warnings/errors:** `dotnet build src/Controls/src/Core/Controls.Core.csproj -c Release -f net12.0-android37.0 --no-restore -p:UseSharedCompilation=false /nodeReuse:false --nologo -v:q`. - **Passed:** `dotnet format whitespace src/Controls/src/Core/Controls.Core.csproj --no-restore --include src/Controls/src/Core/Compatibility/Android/FontNamedSizeService.cs --verbosity quiet` and `dotnet format whitespace src/Controls/tests/DeviceTests/Controls.DeviceTests.csproj --no-restore --include src/Controls/tests/DeviceTests/Services/FontNamedSizeServiceTests.Android.cs --verbosity quiet`. Local device validation used a temporary unique application ID, explicit Android SDK forwarding/APK deployment, and disabled shared build servers. Current main's unrelated Svg.Skia dependency/Resizetizer packaging failure required a working previously packaged Resizetizer for image generation. These validation-only workarounds are **not included** in the PR. ### Issues Fixed <!-- Please make sure that there is a bug logged for the issue being fixed. The bug should describe the problem and how to reproduce it. --> N/A — Native AOT trimming improvement following #40952. ### Let AI finish this PR - [ ] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>


Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
104dba74af898b0de2de5ecb752be7e1186d07b1↑ Emulator screenshot (API 35) pixel-identical to main; no crash or style warning.
↑ Style tests: Controls.Core 255/255, Xaml 100/100, SourceGen 964 passed / 0 failed.
↓ Only one app (the template) measured; iOS/Mac Catalyst NativeAOT not measured.
↓ CI not yet run.
↑ A console NativeAOT probe reproduces the retention with typeof and its removal with a string.
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Target Branch
mainnet11, for reviewFor .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into
net11; agents must not retarget or merge.Description of Change
Trimmable styles (#33561) generate a style whose setters are behind an
is Tcheck, so NativeAOT can remove them whenTis never instantiated. The merged version creates the style withnew Style(typeof(T)), on the assumption thattypeof(T)only keeps a small type descriptor. In a MAUI app it keeps much more:typeof(T)(ldtoken) givesTreflection metadata in NativeAOT.MauiHandlersFactory.FindElementHandlerAttributescallsGetCustomAttribute<ElementHandlerAttribute>(), so ILC keeps the[ElementHandler]attribute on every type that has metadata.GetHandlerType()are annotated[DynamicallyAccessedMembers(PublicConstructors)], so the handler's constructors are kept, and with them its mappers and platform code (both Handler and Handler2 whenUseMaterial3is unset).So every style target in
Styles.xamlkeeps its handler, even when the app never uses the control.This PR goes back to the earlier design from #33561: generated styles use
new Style("Namespace.Type, Assembly")for non-generic targets. Generic targets keeptypeof(T), because their assembly-qualified names depend on reference assemblies. The Hot Reload fix and theMauiXamlTrimmableStyles=PublishAotdefault from the merged version are kept.Changes:
Style(string assemblyQualifiedTargetTypeName)constructor,[EditorBrowsable(Never)].Style.TargetTyperesolves the name lazily withType.GetType(IL2057 suppressed).ResourceDictionary) and the mismatch warning use the target type's full name.IStyle.TargetTypeis nullable;MergedStyleandBasedOnvalidation handle null.CreateValuesVisitor,ISymbolExtensions.GetAssemblyQualifiedName).docs/trimmable-styles-spec.mdexplains whytypeofis not used.Size (plain
dotnet new maui, Release, net12.0-android, android-arm64,PublishAot=true)typeof)The handler constructors of ActivityIndicator, DatePicker, Picker, Slider, Switch, TimePicker, RefreshView and SwipeItemMenuItem are gone from the map. In the ILC scan graph,
ActivityIndicatorHandlerappears 0 times (350 on main) andActivityIndicatorhas no metadata node.Tradeoffs
Style(string)(added toPublicAPI.Unshipped.txt). Runtime-inflated XAML, XamlC, Hot Reload and user code keep using theTypeconstructor.Type.GetTypeon a string needs an IL2057 suppression and costs a one-time lookup on firstTargetTyperead.Style.TargetTypecan benull, but only for a generator-created style whose target type was trimmed away (that style can never be applied).Alternatives considered: a generic
Style<T>still keeps the handler (itsTargetType => typeof(T)keeps metadata), and keying styles without anyTypewould break the publicStyle.TargetType.Possible longer-term follow-up: make handler discovery independent of type metadata (instead of
GetCustomAttribute+DynamicallyAccessedMemberson[ElementHandler]). That would also stop othertypeof(Control)uses (DataTemplate,x:Type,BindablePropertyowner types) from keeping whole handlers.Validation
dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~Style": passed (255/255).dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj --filter "FullyQualifiedName~Style": passed (100/100).dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj: passed (964 passed, 0 failed); 4 assertions updated to expect the assembly-qualified name.Issues Fixed
Follow-up to #33561. No separate issue filed.
Let AI finish this PR