You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Make CodeBehind generator incremental to fix EnC rude edits on x:Name changes - #39281
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!
Description of Change
Renaming, removing, or retyping an x:Name during XAML Incremental Hot Reload caused the CodeBehind generator to regenerate its field list from the current XAML. Roslyn Edit-and-Continue treats a generated field being deleted or retyped as a rude edit (ENC0020/ENC0033), even though no hand-written C# changed.
This PR makes generated code-behind fields additive for the lifetime of a generator-driver session:
Previously generated fields are retained when an x:Name is removed or renamed.
A field keeps its original declaration type and access modifier when the name is reused with an incompatible type.
New fields are appended without changing existing field definitions.
Mutable field and XAML history is isolated per generator-driver through a weakly keyed HotReloadSessionToken, preventing overlapping compilations from sharing state.
Field compatibility is evaluated against the compilation containing generated code-behind, preserving inheritance relationships declared by generated partial types.
Declaration and assignment checks use Roslyn implicit conversions, including boxing, and retain the original XmlType for nested, generic, and special types.
Invalid identifiers and unresolved types are not persisted into field history. x:Name values are normalized consistently before declaration and assignment.
Live x:Name changes are applied in place when the existing element can be retained:
All affected old names are unregistered before any new names are registered, allowing sibling-name swaps.
New names are registered before dependent property and binding updates, supporting forward x:Reference.
Generated fields and StyleId are updated for added or renamed names.
Root names and non-BindableObject roots are handled without invalid namescope access.
Template-local name changes use structural fallback rather than mutating the page namescope.
Unregistration only removes a name when it still refers to the element being patched.
The field-history behavior remains gated by the existing EnableIncrementalHotReload setting.
Validation
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --no-restore
… changes
Renaming, removing, or retyping an x:Name'd element during live Hot
Reload caused the CodeBehind generator to regenerate its whole field
list from scratch, which Roslyn's EnC engine flags as a rude edit
(ENC0020/ENC0033 - deleting/renaming a field requires restarting the
application), even though no hand-written C# was touched.
CodeBehindCodeWriter now accumulates named fields across Hot Reload
generations (XamlHotReloadState.AccumulatedCodeBehindFields) instead
of recomputing them from the current XAML parse alone. Fields are
only ever added, never removed or retyped: a field whose x:Name was
removed or reused with an incompatible type becomes a 'ghost' field
that keeps its original type/access and is left at its default value,
while MemberNotNullAttribute emission and the generated FindByName<T>
assignments skip ghost fields. SetFieldsForXNamesVisitor was updated
to skip emitting an assignment to a ghost field when the element's
type no longer matches the originally generated field type.
Also fixes XamlHotReloadState.TryGetPrevious, which could report a
bogus 'previous generation' purely from the new field-bookkeeping
cache entry, suppressing UpdateComponent emission on the very first
generation. A new CacheEntry.HasGeneratedOutput flag distinguishes
real prior generations from bookkeeping-only entries.
The whole fix is gated behind ProjectItem.EnableIncrementalHotReload
(Debug-only), so Release/CI builds are unaffected.
Fixes#38993
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: c95b3039-fd19-4865-94d8-591f6237b063
The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.
…date tests
Address multi-model review findings on PR #39281:
- Replace strict string-equality type comparison with real Roslyn
assignability checks (TryResolveSimpleTypeSymbol/IsAssignableToGhostField
in GeneratorHelpers.cs), used by both CodeBehindCodeWriter's
ReconcileNamedFieldsForHotReload and SetFieldsForXNamesVisitor. This fixes
the case where an x:Name is reused with a derived type (e.g. Label ->
MyLabel : Label) incorrectly being treated as an incompatible "ghost"
field and losing its assignment.
- Add RunGeneratorWithChangesAndUpdateCompilation to SourceGeneratorDriver
so hot-reload-style second-generation tests can assert the generated
code actually compiles, not just string-match the generated source.
- Add two tests in CodeBehindFieldStabilityTests.cs that reuse an x:Name
across generations with an assignable derived type (field stays
assigned) and an incompatible type (assignment correctly skipped),
verifying both that the field is (or isn't assigned in
InitializeComponent output and that the resulting code compiles.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: c95b3039-fd19-4865-94d8-591f6237b063
EOF
)
RegisterName throws when the new name already exists, even when it points to the same element. Replaying a rename patch therefore aborts the remaining updates: the guarded old-name removal does nothing, then this registration throws. Queued runtime-handler invocations can execute the same latest UpdateComponent body. Skip registration when the mapping already matches the target, as EmitNewElementNameScope does, and test applying the rename patch twice.
✅ Passed (compilation-dependent baseline). The tests require API added by the fix, so the without-fix baseline could not compile. The with-fix run passed; no runtime failure-to-pass reproduction is claimed.
🧪 Unit tests
Test group
Without fix
With fix
BindingAndMarkupHotReloadTests
⚠ Build blocked
✅ Passed (23s)
CodeBehindFieldStabilityTests
⚠ Build blocked
✅ Passed (17s)
StructuralHotReloadTests
⚠ Build blocked
✅ Passed (19s)
UpdateComponentCodeWriterTests
⚠ Build blocked
✅ Passed (14s)
XamlIncrementalHotReloadCSharpExpressionTests
⚠ Build blocked
✅ Passed (19s)
XamlIncrementalHotReloadE2ETests
⚠ Build blocked
✅ Passed (18s)
XamlIncrementalHotReloadPipelineTests
⚠ Build blocked
✅ Passed (21s)
XamlNodeDiffTests
⚠ Build blocked
✅ Passed (20s)
Execution log excerpts
Without fixBindingAndMarkupHotReloadTests
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1081,26): error CS0246: The type or namespace name 'HotReloadSessionToken' could not be found (are you missing a using directive or an assembly reference?) [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1093,22): error CS1503: Argument 2: cannot convert from 'Microsoft.Maui.Controls.SourceGen.SGRootNode' to 'System.Collections.Generic.IAsyncEnumerable<char>?' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1110,26): error CS0246: The type or namespace name 'HotReloadSessionToken' could not be found (are you missing a using directive or an assembly reference?) [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1116,27): error CS0246: The type or namespace name 'HotReloadFieldContract' could not be found (are you missing a using directive or an assembly reference?) [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1112,22): error CS0117: 'XamlHotReloadState' does not contain a definition for 'SetAccumulatedCodeBehindFields' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1081,26): error CS0246: The type or namespace name 'HotReloadSessionToken' could not be found (are you missing a using directive or an assembly reference?) [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1093,22): error CS1503: Argument 2: cannot convert from 'Microsoft.Maui.Controls.SourceGen.SGRootNode' to 'System.Collections.Generic.IAsyncEnumerable<char>?' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1110,26): error CS0246: The type or namespace name 'HotReloadSessionToken' could not be found (are you missing a using directive or an assembly reference?) [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1116,27): error CS0246: The type or namespace name 'HotReloadFieldContract' could not be found (are you missing a using directive or an assembly reference?) [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/XamlIncrementalHotReloadPipelineTests.cs(1112,22): error CS0117: 'XamlHotReloadState' does not contain a definition for 'SetAccumulatedCodeBehindFields' [/home/vsts/work/1/s/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj]
var targetVar = isRoot ? "this" : $"__nameTarget_{phase}_{changeIndex}";
if (!isRoot)
{
codeWriter.WriteLine($"if (global::Microsoft.Maui.Controls.Xaml.XamlComponentRegistry.TryGet(this, \"{EscapeString(nodeDiff.NodeId)}\", out var {targetVar}))");
The reason will be displayed to describe this comment to others. Learn more.
[moderate] Logic and Correctness - Adding x:Name to a previously lazy resource leaves its generated field unassigned. With SourceGen, incremental Hot Reload and the default LazyRD setting, start a ResourceDictionary subclass with <SolidColorBrush x:Key="brush" Color="Red" />, then add x:Name="namedBrush" without changing its key or type. IsLazyResource excludes the original resource from the outer Variables dictionary, and AddLazyResourceToResourceDictionary's factory never registers its node ID, even after realization. The new name-only patch therefore misses this TryGet and skips the field assignment; namedBrush remains null on the live dictionary, whereas fresh initialization makes the named resource eager and assigns it. Resolve this transition through the owning dictionary/key or another supported fallback, and add a regression covering an initially unnamed lazy resource.
The reason will be displayed to describe this comment to others. Learn more.
[moderate] XAML & Bindings - In-place x:Name changes do not update RuntimeNameProperty. In a SourceGen ResourceDictionary subclass, rename <VisualState x:Key="state" x:Name="OldState" /> to x:Name="NewState". InitializeComponent originally sets VisualState.Name through SetPropertiesVisitor.TrySetRuntimeName, but this name-change pass only updates namescope/field/StyleId state, and the subsequent property pass explicitly skips x:Name. The retained resource consequently keeps Name == "OldState", unlike a freshly inflated dictionary. If that resource is used in a VisualStateGroup, GetState still matches the old name, so GoToState(element, "NewState") cannot select it. Apply the RuntimeNameProperty contract when patching retained names and cover this case.
…kups (#39568)
<!-- 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!
<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->
### Description of Change
<!-- Enter description of the fix in this section -->
Intentionally targets **net11.0**, where #39281 introduced this
regression.
`CodeBehindCodeWriter.GetNamedFields` trims `x:Name` for field identity
and Hot Reload reconciliation. The runtime XAML loader still registers
the original name. For the existing `x:Name=" label0"` fixture,
generated runtime initialization therefore looks up `"label0"` instead
of `" label0"`, leaving the generated field null.
Keep the original XAML name alongside the trimmed field identifier and
use it for runtime `FindByName` calls, including conditional assignments
after Hot Reload type changes. Reconciliation uses the current XAML
lookup name while preserving existing field contracts. Quote lookup keys
with Roslyn's string-literal formatter.
Runtime parsing, namescope registration, `StyleId`, and `x:Reference`
semantics are unchanged. The original `Maui27121` fixture and
`Assert.NotNull(page.label0)` are unchanged. Add generator coverage for
whitespace-only name edits with incremental Hot Reload enabled and
disabled, including generated-code compilation.
The original assertion is already failing in the target branch's [build
1643728](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1643728).
This is a focused baseline repair, not a change to GC tests, device
fixtures, packages, or pipelines.
**Validation**
Used the repository-pinned `11.0.100-rtm.26514.118` SDK in a private
installation, with platform-neutral `net11.0` unit execution only. No
Apple UI/XCTest execution.
The exact `Maui27121.Tests.XNameAreTrimmed(inflator: Runtime)` case was
**baseline red → fix green → fix reverted red → fix restored green**.
Both red runs failed the original `Assert.NotNull` at
`Maui27121.xaml.cs:30`. The full verification script ended with
`VERIFICATION PASSED`; the worktree was clean after restoration.
Commands and results:
```sh
# PASS: prerequisite build, zero warnings/errors
dotnet build Microsoft.Maui.BuildTasks.slnf -p:BuildTaskOnlyBuild=true -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false -v:quiet
# PASS: formatting, exit 0
dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/CodeBehindCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/CodeBehindFieldStabilityTests.cs --verbosity quiet
# PASS: 96 generator/code-behind/Hot Reload tests
dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --no-restore --filter 'FullyQualifiedName~CodeBehindFieldStabilityTests|FullyQualifiedName~SourceGenXamlCodeBehindTests|FullyQualifiedName~XamlIncrementalHotReloadPipelineTests' -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false -v:quiet
# PASS: 49 related name tests in Debug, including all three Maui27121 inflators
dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj --no-restore --filter 'FullyQualifiedName~Maui27121|FullyQualifiedName~NameScopeTests|FullyQualifiedName~FindByName|FullyQualifiedName~SetStyleIdFromXName|FullyQualifiedName~XReference' -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false -v:quiet
# VERIFICATION PASSED: reverted Runtime 1 failed; restored Runtime 1 passed
# "unknown" is the runner's output-folder sentinel for this then-unpublished PR.
pwsh -NoProfile -File .github/skills/verify-tests-fail-without-fix/scripts/verify-tests-fail.ps1 -PRNumber unknown -TestType XamlUnitTest -TestFilter 'FullyQualifiedName~Maui27121&DisplayName~Runtime' -BaseBranch 3c9c033 -FixFiles src/Controls/src/SourceGen/CodeBehindCodeWriter.cs -RequireFullVerification
# PASS: 49 related name tests in Release, including all three Maui27121 inflators
dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj -c Release --no-restore --filter 'FullyQualifiedName~Maui27121|FullyQualifiedName~NameScopeTests|FullyQualifiedName~FindByName|FullyQualifiedName~SetStyleIdFromXName|FullyQualifiedName~XReference' '-p:DefaultItemExcludesInProjectFolder=**/Generated/**' -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false -v:quiet
```
The first Release attempt included previously emitted Debug `Generated`
sources and failed with duplicate declarations. The command-only
exclusion above removed those duplicate inputs; no project or pipeline
configuration was changed. Full suites, Windows execution, and hosted CI
are not claimed by these local results.
Validated against base `3c9c033482797b64d878ef3f59bc6ac8a92f6ebd`. The
subsequent target update to `7b0ea7800db3f3faccbaecb665d32b7c61eaf932`
does not change the relevant XAML source, tests, or dependency inputs.
Open and recently merged upstream PRs were checked for the same
issue/files/mechanism; no equivalent net11.0 fix was found. The
cumulative inflight PR retains older raw-name handling but does not
contain the net11.0 field reconciliation that this fix preserves.
**Hosted validation — build 1645738**
Actual uploaded `testResults.xml` files from [maui-pr
1645738](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1645738),
not aggregate badges, confirm the following for head
`e4d0c17f19b64b0bb20c9fafc96f0f77fa43371e` / merge
`9177af7ae9323da1e620ec8d6418f8e5b6bb8d7b`:
| Configuration | Maui27121 Runtime / XamlC / SourceGen | New generator
cases (off / on) | Assembly results (passed / skipped) |
|---|---|---|---|
| macOS Debug | 3/3 pass | 2/2 pass | XAML 2147/8; generator 626/38 |
| Windows Debug | 3/3 pass | 2/2 pass | XAML 2147/8; generator 626/38 |
| macOS Release | 3/3 pass | 2/2 pass | XAML 2127/14; generator 626/38 |
| Windows Release | 3/3 pass | 2/2 pass | XAML 2127/14; generator 626/38
|
All eight assembly result files have **zero failures and zero errors**.
The new cases are
`CodeBehindFieldStabilityTests.RuntimeInflation_PreservesXNameWhitespaceInNameScopeLookup(enableIncrementalHotReload:
False/True)`.
Direct XML evidence: [macOS Debug
XAML](https://helixr1107v0xdeko0k025g8.blob.core.windows.net/dotnet-maui-refs-pull-39568-merge-26482b1441b344e898/Microsoft.Maui.Controls.Xaml.UnitTests.dll/1/testResults.xml?helixlogtype=result),
[Windows Debug
XAML](https://helixr1107v0xdeko0k025g8.blob.core.windows.net/dotnet-maui-refs-pull-39568-merge-49b6e89f7fec47bb82/Microsoft.Maui.Controls.Xaml.UnitTests.dll/1/testResults.xml?helixlogtype=result),
[macOS Release
XAML](https://helixr1107v0xdeko0k025g8.blob.core.windows.net/dotnet-maui-refs-pull-39568-merge-85b4282be7464f77b1/Microsoft.Maui.Controls.Xaml.UnitTests.dll/1/testResults.xml?helixlogtype=result),
[Windows Release
XAML](https://helixr1107v0xdeko0k025g8.blob.core.windows.net/dotnet-maui-refs-pull-39568-merge-f7f51120b4a84e9ca4/Microsoft.Maui.Controls.Xaml.UnitTests.dll/1/testResults.xml?helixlogtype=result).
Generator XML files are in the same respective containers under
`Microsoft.Maui.Controls.SourceGen.UnitTests.dll/1/testResults.xml`.
The raw Azure Helix monitor log reports four jobs processed, zero
jobs/work items resubmitted, 46 work items submitted, and zero failed.
**At the bounded observation cutoff (2026-10-22 19:46 UTC), the overall
build was still in progress: 28 of 31 jobs had succeeded; `Blazor
windows`, `Build windows`, and `Samples macOS` integration jobs remained
active. No failed timeline records were present at that cutoff.** The
focused unit-test evidence above is complete, but no overall CI or
merge-readiness verdict is implied. The observation watch ended at its
fixed deadline; no additional dispatches or retries were requested.
### 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. -->
Fixes the runtime regression of #27121 introduced by #39281,
demonstrated by the existing `Maui27121.Tests.XNameAreTrimmed`
assertion.
<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: ba91d542-6d91-4dc8-b270-c1b5b57a958c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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!
Description of Change
Renaming, removing, or retyping an
x:Nameduring XAML Incremental Hot Reload caused the CodeBehind generator to regenerate its field list from the current XAML. Roslyn Edit-and-Continue treats a generated field being deleted or retyped as a rude edit (ENC0020/ENC0033), even though no hand-written C# changed.This PR makes generated code-behind fields additive for the lifetime of a generator-driver session:
x:Nameis removed or renamed.HotReloadSessionToken, preventing overlapping compilations from sharing state.XmlTypefor nested, generic, and special types.x:Namevalues are normalized consistently before declaration and assignment.Live
x:Namechanges are applied in place when the existing element can be retained:x:Reference.StyleIdare updated for added or renamed names.BindableObjectroots are handled without invalid namescope access.The field-history behavior remains gated by the existing
EnableIncrementalHotReloadsetting.Validation
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj --no-restoreCoverage includes rename, removal, incompatible retyping, unresolved types, whitespace-normalized names, nested/generic types, boxing, fresh and overlapping generator sessions, root names, sibling swaps, forward references, template fallback, generated-source compilation, metadata deltas, namescope registration, bindings,
StyleId, and retained live-element identity.Issues Fixed
Fixes #38993