Skip to content

Identify trimmable styles by assembly-qualified name so NativeAOT can remove unused handlers - #40952

Merged
kubaflo merged 1 commit into
mainfrom
simonrozsival-trimmable-styles-typeof-retention
Dec 1, 2026
Merged

kubaflo merged 1 commit into
mainfrom
simonrozsival-trimmable-styles-typeof-retention

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: 104dba74af898b0de2de5ecb752be7e1186d07b1

Dimension Assessment Rationale
Change confidence 8/10 ↑ Android NativeAOT template app: APK −204,800 B, .so −584,048 B (98% of the unused-styles-deleted ceiling).
↑ 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.
Diagnosis confidence 9/10 ↑ ILC scan DGML on main shows ActivityIndicator type metadata plus the get_CustomAttributes conditional node leading to the handler ctor; with this change ActivityIndicatorHandler has 0 nodes (350 on main).
↑ A console NativeAOT probe reproduces the retention with typeof and its removal with a string.
Evidence fit 9/10 ↑ The removed handlers (ActivityIndicator, DatePicker, Picker, Slider, Switch, TimePicker, RefreshView, SwipeItemMenuItem) are exactly the unused style targets in the template's Styles.xaml.

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

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

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

Trimmable styles (#33561) generate a style whose setters are behind an is T check, so NativeAOT can remove them when T is never instantiated. The merged version creates the style with new Style(typeof(T)), on the assumption that typeof(T) only keeps a small type descriptor. In a MAUI app it keeps much more:

  1. typeof(T) (ldtoken) gives T reflection metadata in NativeAOT.
  2. MauiHandlersFactory.FindElementHandlerAttributes calls GetCustomAttribute<ElementHandlerAttribute>(), so ILC keeps the [ElementHandler] attribute on every type that has metadata.
  3. The attribute's constructor parameter and GetHandlerType() are annotated [DynamicallyAccessedMembers(PublicConstructors)], so the handler's constructors are kept, and with them its mappers and platform code (both Handler and Handler2 when UseMaterial3 is unset).

So every style target in Styles.xaml keeps 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 keep typeof(T), because their assembly-qualified names depend on reference assemblies. The Hot Reload fix and the MauiXamlTrimmableStyles = PublishAot default from the merged version are kept.

Changes:

  • Style(string assemblyQualifiedTargetTypeName) constructor, [EditorBrowsable(Never)].
  • Style.TargetType resolves the name lazily with Type.GetType (IL2057 suppressed).
  • Style matching, implicit-style keys (ResourceDictionary) and the mismatch warning use the target type's full name.
  • IStyle.TargetType is nullable; MergedStyle and BasedOn validation handle null.
  • The source generator emits the assembly-qualified name (CreateValuesVisitor, ISymbolExtensions.GetAssemblyQualifiedName).
  • docs/trimmable-styles-spec.md explains why typeof is not used.

Size (plain dotnet new maui, Release, net12.0-android, android-arm64, PublishAot=true)

Build Signed APK (B) libTrimProbe.so (B)
main (typeof) 16,030,802 20,727,560
This PR 15,826,002 (−204,800) 20,143,512 (−584,048)
main with unused styles deleted from Styles.xaml (ceiling) 15,821,906 20,115,936

The handler constructors of ActivityIndicator, DatePicker, Picker, Slider, Switch, TimePicker, RefreshView and SwipeItemMenuItem are gone from the map. In the ILC scan graph, ActivityIndicatorHandler appears 0 times (350 on main) and ActivityIndicator has no metadata node.

Tradeoffs

  • New hidden public API: Style(string) (added to PublicAPI.Unshipped.txt). Runtime-inflated XAML, XamlC, Hot Reload and user code keep using the Type constructor.
  • Type.GetType on a string needs an IL2057 suppression and costs a one-time lookup on first TargetType read.
  • Style.TargetType can be null, 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 (its TargetType => typeof(T) keeps metadata), and keying styles without any Type would break the public Style.TargetType.

Possible longer-term follow-up: make handler discovery independent of type metadata (instead of GetCustomAttribute + DynamicallyAccessedMembers on [ElementHandler]). That would also stop other typeof(Control) uses (DataTemplate, x:Type, BindableProperty owner types) from keeping whole handlers.

Validation

  • Published the template app with Android NativeAOT using packages built from this branch; sizes above.
  • Ran it on an API 35 arm64 emulator: cold start OK, screenshot pixel-identical to main, no crash, no "Style TargetType ... is not compatible" warning.
  • 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.
  • Not run: iOS/Mac Catalyst NativeAOT size comparison.

Issues Fixed

Follow-up to #33561. No separate issue filed.

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.

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>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 10:36
@github-actions

This comment has been minimized.

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/autopilot-running MAUI Autopilot loop is running; remove this label to stop it label Dec 1, 2026
@github-actions

This comment has been minimized.

@github-actions github-actions Bot added the s/autopilot-reviewing MAUI Autopilot: MAUI expert review in progress label Dec 1, 2026

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

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.TargetType lazily 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();

@github-actions github-actions Bot 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.

Expert Review — 3 findings

Reviewed commit 104dba7.

See inline comments for details.

{
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)

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.

[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)

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.

[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>();

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.

[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.

@github-actions github-actions Bot added s/autopilot-fixing MAUI Autopilot: fixing review findings or failing tests (GPT-6.2 Sol vs MAI Code 2) and removed s/autopilot-reviewing MAUI Autopilot: MAUI expert review in progress s/autopilot-running MAUI Autopilot loop is running; remove this label to stop it s/autopilot-fixing MAUI Autopilot: fixing review findings or failing tests (GPT-6.2 Sol vs MAI Code 2) labels Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

MAUI Autopilot — Stopped

@kubaflo ❌ The last fix round found nothing more it could fix. Decide how to continue, or comment /review autopilot to run it again.

Why

No fixes were published: the push was blocked by the existing change to docs/trimmable-styles-spec.md in the PR history. The three fix commits only touch src/; the review threads remain open.

[Run](https://github.com/dotnet/maui/actions/runs/46634661235).

@github-actions github-actions Bot added the s/autopilot-needs-maintainer-decision MAUI Autopilot stopped: a maintainer needs to decide how to continue label Dec 1, 2026
@kubaflo
kubaflo merged commit d3bc493 into main Dec 1, 2026
16 of 17 checks passed
@kubaflo
kubaflo deleted the simonrozsival-trimmable-styles-typeof-retention branch December 1, 2026 14:30
kubaflo added a commit that referenced this pull request Dec 1, 2026
<!-- 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>

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 104dba74 Deployed Dec 1, 2026 by simonrozsival via conclusion #3588
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

s/autopilot-needs-maintainer-decision MAUI Autopilot stopped: a maintainer needs to decide how to continue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants