diff --git a/docs/_pipeline/templates/modifier-system.md.dt b/docs/_pipeline/templates/modifier-system.md.dt index 252f6b8928..a9c3fb036b 100644 --- a/docs/_pipeline/templates/modifier-system.md.dt +++ b/docs/_pipeline/templates/modifier-system.md.dt @@ -85,6 +85,21 @@ would pin it permanently rather than hand the property back to the style. Render a themed `Button` with `.Padding(24)` and then without `.Padding()` and you get the *themed* padding back, not `0`. + +The four transform modifiers are the current exception. `.Scale()`, +`.Rotation()`, `.Translation()` and `.CenterPoint()` have no unset arm yet, +so dropping one leaves the last value on the element. An un-animated write +goes straight to the XAML facade property, so a future fix can clear those +the usual way; but when an animation curve is in scope the value is driven +by a composition animation on the element's visual, which outranks the +property — releasing that case has to stop the animation as well, which is +why this is not simply a missing `ClearValue`. Until it is fixed, reset +these by writing the identity value explicitly — `.Scale(1f)`, +`.Rotation(0f)`, `.Translation(0f, 0f, 0f)` and `.CenterPoint(Vector3.Zero)` +— rather than by omitting the call. Note `.CenterPoint()` takes only a +`Vector3`, so it has no component-wise overload to spell the identity with. + + Reference modifiers are the exception to "just write this value" in the implementation, but not in the authoring model. `.Ref(cell)` binds the current element into an `ElementRef` cell; reference-property modifiers diff --git a/docs/guide/modifier-system.md b/docs/guide/modifier-system.md index bcee3dfc81..be63672074 100644 --- a/docs/guide/modifier-system.md +++ b/docs/guide/modifier-system.md @@ -114,6 +114,19 @@ would pin it permanently rather than hand the property back to the style. Render a themed `Button` with `.Padding(24)` and then without `.Padding()` and you get the *themed* padding back, not `0`. +> **Caveat:** The four transform modifiers are the current exception. `.Scale()`, +> `.Rotation()`, `.Translation()` and `.CenterPoint()` have no unset arm yet, +> so dropping one leaves the last value on the element. An un-animated write +> goes straight to the XAML facade property, so a future fix can clear those +> the usual way; but when an animation curve is in scope the value is driven +> by a composition animation on the element's visual, which outranks the +> property — releasing that case has to stop the animation as well, which is +> why this is not simply a missing `ClearValue`. Until it is fixed, reset +> these by writing the identity value explicitly — `.Scale(1f)`, +> `.Rotation(0f)`, `.Translation(0f, 0f, 0f)` and `.CenterPoint(Vector3.Zero)` +> — rather than by omitting the call. Note `.CenterPoint()` takes only a +> `Vector3`, so it has no component-wise overload to spell the identity with. + Reference modifiers are the exception to "just write this value" in the implementation, but not in the authoring model. `.Ref(cell)` binds the current element into an `ElementRef` cell; reference-property modifiers diff --git a/src/Reactor/Core/Reconciler.cs b/src/Reactor/Core/Reconciler.cs index f25dd69266..cfecdea590 100644 --- a/src/Reactor/Core/Reconciler.cs +++ b/src/Reactor/Core/Reconciler.cs @@ -412,6 +412,18 @@ internal sealed class ReactorState // (pool return / ClearCurrentEventHandlers / DetachReactorState) so a // stale arm can't suppress the first real event of a later lifecycle. public Func? PendingEchoMatch; + // Issue #986 — the AutomationId a deferred LabeledBy resolution is still + // waiting to bind. ApplyAccessibilityModifiers can only resolve LabeledBy + // once the element is in the visual tree, so an unresolved request parks a + // Loaded handler. That handler outlives the render that created it, so it + // must not write blindly: by the time Loaded fires the modifier may have + // been dropped (reset arm) or retargeted at a different id, and a blind + // write would stomp the reset and re-pin the stale label forever. The + // handler therefore compares its captured id against this slot and no-ops + // on a mismatch. Cleared on resolve, on unset, and everywhere the echo + // state is cleared (pool return / ClearCurrentEventHandlers / + // DetachReactorState) so a stale arm can't fire into a later lifecycle. + public string? PendingLabeledBy; // Spec 042 Phase 1 — keyed-list reconciliation state. Set when the // host element is a templated items control (ListView/GridView/ // ItemsRepeater). The internal ObservableCollection in @@ -714,6 +726,7 @@ internal static void ClearCurrentEventHandlers(FrameworkElement fe) state.EchoSuppressCount = 0; state.EchoSuppressScopeDepth = 0; state.PendingEchoMatch = null; + state.PendingLabeledBy = null; } } @@ -741,6 +754,7 @@ public static void DetachReactorState(FrameworkElement fe) state.EchoSuppressCount = 0; state.EchoSuppressScopeDepth = 0; state.PendingEchoMatch = null; + state.PendingLabeledBy = null; } // ════════════════════════════════════════════════════════════════════ @@ -1022,6 +1036,7 @@ public void ReturnControl(T control, PoolPolicy? policy = null) where T : rs.EchoSuppressCount = 0; rs.EchoSuppressScopeDepth = 0; rs.PendingEchoMatch = null; + rs.PendingLabeledBy = null; rs.Element = null; } // Clear Reactor-set DataContext (FrameworkElement-only DP). @@ -3804,6 +3819,14 @@ internal void ApplyModifiers(FrameworkElement fe, ElementModifiers? oldM, Elemen // clearing the XAML DP does not cancel it — neither did the previous // `fe.Opacity = 1.0`, so this is not a regression. fe.ClearValue(UIElement.OpacityProperty); + // Transform family — Scale / Rotation / Translation / CenterPoint deliberately have + // NO unset arm yet (issue #1001). These are XAML facade properties whose live value + // lives on the element's composition visual: when a curve is ambient the set path + // above calls visual.StartAnimation, which outranks the DP and leaves no local value + // for ClearValue to release. Undoing that needs a StopAnimation companion and a + // selftest that exercises the animated path, so it is tracked separately rather than + // given the mechanical arm the plain-DP modifiers below get. + // ModifierUnsetClearValueTests.MissingUnsetArmExceptions records the same four names. if (m.Scale.HasValue && m.Scale != oldM?.Scale) AnimationHelper.SetOrAnimateVector3(fe, "Scale", m.Scale.Value); if (m.Rotation.HasValue && m.Rotation != oldM?.Rotation) @@ -3963,15 +3986,26 @@ internal void ApplyModifiers(FrameworkElement fe, ElementModifiers? oldM, Elemen fe.ClearValue(WinUI.TitleBar.IsDragRegionProperty); // ElementSoundMode (on Control, not FrameworkElement) + // The reset arm re-tests `fe is Control` under its own pattern variable rather than + // reusing `ctrl`: reaching the `else` only proves the whole set condition was false, + // which a non-Control satisfies while still having the modifier set. Without the + // re-test a Border that carries `.SoundMode(...)` would take the reset branch and + // clear a property it never had. Same shape as IsEnabled above (issue #986). if (m.ElementSoundMode.HasValue && m.ElementSoundMode != oldM?.ElementSoundMode && fe is WinUI.Control ctrl) ctrl.ElementSoundMode = m.ElementSoundMode.Value; + else if (!m.ElementSoundMode.HasValue && oldM?.ElementSoundMode.HasValue == true && fe is WinUI.Control ctrlSnd) + ctrlSnd.ClearValue(WinUI.Control.ElementSoundModeProperty); // ── Accessibility — Tier 1 (inline properties) ────────────── if (m.HeadingLevel.HasValue && m.HeadingLevel != oldM?.HeadingLevel) Microsoft.UI.Xaml.Automation.AutomationProperties.SetHeadingLevel(fe, m.HeadingLevel.Value); + else if (!m.HeadingLevel.HasValue && oldM?.HeadingLevel.HasValue == true) + fe.ClearValue(Microsoft.UI.Xaml.Automation.AutomationProperties.HeadingLevelProperty); if (m.IsTabStop.HasValue && m.IsTabStop != oldM?.IsTabStop) fe.IsTabStop = m.IsTabStop.Value; + else if (!m.IsTabStop.HasValue && oldM?.IsTabStop.HasValue == true) + fe.ClearValue(UIElement.IsTabStopProperty); if (m.IsHitTestVisible.HasValue && m.IsHitTestVisible != oldM?.IsHitTestVisible) fe.IsHitTestVisible = m.IsHitTestVisible.Value; @@ -3980,6 +4014,8 @@ internal void ApplyModifiers(FrameworkElement fe, ElementModifiers? oldM, Elemen if (m.TabIndex.HasValue && m.TabIndex != oldM?.TabIndex && fe is WinUI.Control tabIdxCtrl) tabIdxCtrl.TabIndex = m.TabIndex.Value; + else if (!m.TabIndex.HasValue && oldM?.TabIndex.HasValue == true && fe is WinUI.Control tabIdxCtrl2) + tabIdxCtrl2.ClearValue(WinUI.Control.TabIndexProperty); if (m.AccessKey is not null && m.AccessKey != oldM?.AccessKey) fe.AccessKey = m.AccessKey; @@ -3988,6 +4024,8 @@ internal void ApplyModifiers(FrameworkElement fe, ElementModifiers? oldM, Elemen if (m.XYFocusKeyboardNavigation.HasValue && m.XYFocusKeyboardNavigation != oldM?.XYFocusKeyboardNavigation) fe.XYFocusKeyboardNavigation = m.XYFocusKeyboardNavigation.Value; + else if (!m.XYFocusKeyboardNavigation.HasValue && oldM?.XYFocusKeyboardNavigation.HasValue == true) + fe.ClearValue(UIElement.XYFocusKeyboardNavigationProperty); // ── Accessibility — Tier 2/3 (lazy sub-record) ───────────── var a11y = m.Accessibility; @@ -4223,60 +4261,116 @@ private static void AssertTypedRefMatch(Microsoft.UI.Reactor.Input.ElementRef r, // Accessibility modifiers (Tier 2/3 sub-record) // ════════════════════════════════════════════════════════════════ + /// + /// Applies the Tier 2/3 accessibility sub-record. + /// + /// + /// Called whenever either bag is non-null, which includes the case where the whole + /// sub-record was dropped this render ( null, + /// not). That is why there is no a is null early return any more: it swallowed + /// exactly the transition it needed to handle, so dropping .HelpText(...) — or the + /// entire accessibility bag — left every automation property pinned on the control forever + /// (issue #986). Every property is therefore null-tolerant on — set + /// arms guard with a is not null && a.X…, reset arms read a?.X — so the + /// dropped-bag case takes the same reset path as dropping one modifier from a surviving bag. + /// + /// Resets go through ClearValue, never through writing the property's default: a + /// local value outranks every Style setter in WinUI's precedence order, so the + /// assignment would pin the default rather than hand the property back (issue #952). + /// + /// private static void ApplyAccessibilityModifiers(FrameworkElement fe, AccessibilityModifiers? oldA, AccessibilityModifiers? a) { - if (a is null) return; + if (a is null && oldA is null) return; - if (a.HelpText is not null && a.HelpText != oldA?.HelpText) + if (a is not null && a.HelpText is not null && a.HelpText != oldA?.HelpText) Microsoft.UI.Xaml.Automation.AutomationProperties.SetHelpText(fe, a.HelpText); + else if (a?.HelpText is null && oldA?.HelpText is not null) + fe.ClearValue(Microsoft.UI.Xaml.Automation.AutomationProperties.HelpTextProperty); - if (a.FullDescription is not null && a.FullDescription != oldA?.FullDescription) + if (a is not null && a.FullDescription is not null && a.FullDescription != oldA?.FullDescription) Microsoft.UI.Xaml.Automation.AutomationProperties.SetFullDescription(fe, a.FullDescription); + else if (a?.FullDescription is null && oldA?.FullDescription is not null) + fe.ClearValue(Microsoft.UI.Xaml.Automation.AutomationProperties.FullDescriptionProperty); - if (a.LandmarkType.HasValue && a.LandmarkType != oldA?.LandmarkType) + if (a is not null && a.LandmarkType.HasValue && a.LandmarkType != oldA?.LandmarkType) Microsoft.UI.Xaml.Automation.AutomationProperties.SetLandmarkType(fe, a.LandmarkType.Value); + else if (a?.LandmarkType.HasValue != true && oldA?.LandmarkType.HasValue == true) + fe.ClearValue(Microsoft.UI.Xaml.Automation.AutomationProperties.LandmarkTypeProperty); - if (a.AccessibilityView.HasValue && a.AccessibilityView != oldA?.AccessibilityView) + if (a is not null && a.AccessibilityView.HasValue && a.AccessibilityView != oldA?.AccessibilityView) Microsoft.UI.Xaml.Automation.AutomationProperties.SetAccessibilityView(fe, a.AccessibilityView.Value); + else if (a?.AccessibilityView.HasValue != true && oldA?.AccessibilityView.HasValue == true) + fe.ClearValue(Microsoft.UI.Xaml.Automation.AutomationProperties.AccessibilityViewProperty); - if (a.IsRequiredForForm.HasValue && a.IsRequiredForForm != oldA?.IsRequiredForForm) + if (a is not null && a.IsRequiredForForm.HasValue && a.IsRequiredForForm != oldA?.IsRequiredForForm) Microsoft.UI.Xaml.Automation.AutomationProperties.SetIsRequiredForForm(fe, a.IsRequiredForForm.Value); + else if (a?.IsRequiredForForm.HasValue != true && oldA?.IsRequiredForForm.HasValue == true) + fe.ClearValue(Microsoft.UI.Xaml.Automation.AutomationProperties.IsRequiredForFormProperty); - if (a.LiveSetting.HasValue && a.LiveSetting != oldA?.LiveSetting) + if (a is not null && a.LiveSetting.HasValue && a.LiveSetting != oldA?.LiveSetting) Microsoft.UI.Xaml.Automation.AutomationProperties.SetLiveSetting(fe, a.LiveSetting.Value); + else if (a?.LiveSetting.HasValue != true && oldA?.LiveSetting.HasValue == true) + fe.ClearValue(Microsoft.UI.Xaml.Automation.AutomationProperties.LiveSettingProperty); - if (a.PositionInSet.HasValue && a.PositionInSet != oldA?.PositionInSet) + if (a is not null && a.PositionInSet.HasValue && a.PositionInSet != oldA?.PositionInSet) Microsoft.UI.Xaml.Automation.AutomationProperties.SetPositionInSet(fe, a.PositionInSet.Value); + else if (a?.PositionInSet.HasValue != true && oldA?.PositionInSet.HasValue == true) + fe.ClearValue(Microsoft.UI.Xaml.Automation.AutomationProperties.PositionInSetProperty); - if (a.SizeOfSet.HasValue && a.SizeOfSet != oldA?.SizeOfSet) + if (a is not null && a.SizeOfSet.HasValue && a.SizeOfSet != oldA?.SizeOfSet) Microsoft.UI.Xaml.Automation.AutomationProperties.SetSizeOfSet(fe, a.SizeOfSet.Value); + else if (a?.SizeOfSet.HasValue != true && oldA?.SizeOfSet.HasValue == true) + fe.ClearValue(Microsoft.UI.Xaml.Automation.AutomationProperties.SizeOfSetProperty); - if (a.Level.HasValue && a.Level != oldA?.Level) + if (a is not null && a.Level.HasValue && a.Level != oldA?.Level) Microsoft.UI.Xaml.Automation.AutomationProperties.SetLevel(fe, a.Level.Value); + else if (a?.Level.HasValue != true && oldA?.Level.HasValue == true) + fe.ClearValue(Microsoft.UI.Xaml.Automation.AutomationProperties.LevelProperty); - if (a.ItemStatus is not null && a.ItemStatus != oldA?.ItemStatus) + if (a is not null && a.ItemStatus is not null && a.ItemStatus != oldA?.ItemStatus) Microsoft.UI.Xaml.Automation.AutomationProperties.SetItemStatus(fe, a.ItemStatus); + else if (a?.ItemStatus is null && oldA?.ItemStatus is not null) + fe.ClearValue(Microsoft.UI.Xaml.Automation.AutomationProperties.ItemStatusProperty); - if (a.TabFocusNavigation.HasValue && a.TabFocusNavigation != oldA?.TabFocusNavigation) + if (a is not null && a.TabFocusNavigation.HasValue && a.TabFocusNavigation != oldA?.TabFocusNavigation) fe.TabFocusNavigation = a.TabFocusNavigation.Value; + else if (a?.TabFocusNavigation.HasValue != true && oldA?.TabFocusNavigation.HasValue == true) + fe.ClearValue(UIElement.TabFocusNavigationProperty); // LabeledBy — resolve AutomationId string to the target element in the visual tree. // During mount the element may not be in the visual tree yet (XamlRoot is null), // so defer resolution to the Loaded event if needed. - if (a.LabeledBy is not null && a.LabeledBy != oldA?.LabeledBy) + if (a is not null && a.LabeledBy is not null && a.LabeledBy != oldA?.LabeledBy) { var target = FindByAutomationId(fe, a.LabeledBy); if (target is not null) { + // Resolved synchronously — retire any deferred request from an + // earlier render so its parked handler can't overwrite this one. + // TryGet, not GetOrCreate: with no state there is no parked handler + // and nothing to retire, and this is the common path — allocating and + // attaching a ReactorState here would cost one per element that ever + // resolves a LabeledBy synchronously. + if (TryGetReactorState(fe, out var resolvedState)) + resolvedState.PendingLabeledBy = null; Microsoft.UI.Xaml.Automation.AutomationProperties.SetLabeledBy(fe, target); } else { - // Element not yet in visual tree — defer until Loaded. + // Element not yet in visual tree — defer until Loaded. The handler + // outlives this render, so publish the request first and have the + // handler re-check it: if LabeledBy is dropped or retargeted before + // Loaded fires, the stale handler must no-op rather than stomp the + // reset arm below (issue #986). var labelId = a.LabeledBy; + GetOrCreateReactorState(fe).PendingLabeledBy = labelId; void OnLoaded(object sender, RoutedEventArgs _) { fe.Loaded -= OnLoaded; + if (!TryGetReactorState(fe, out var pending) || pending.PendingLabeledBy != labelId) + return; + pending.PendingLabeledBy = null; var deferred = FindByAutomationId(fe, labelId); if (deferred is not null) Microsoft.UI.Xaml.Automation.AutomationProperties.SetLabeledBy(fe, deferred); @@ -4284,8 +4378,12 @@ void OnLoaded(object sender, RoutedEventArgs _) fe.Loaded += OnLoaded; } } - else if (a.LabeledBy is null && oldA?.LabeledBy is not null) + else if (a?.LabeledBy is null && oldA?.LabeledBy is not null) { + // Cancel a still-parked deferred resolution before clearing, or it would + // re-apply the dropped label the moment the element loads. + if (TryGetReactorState(fe, out var pendingState)) + pendingState.PendingLabeledBy = null; fe.ClearValue(Microsoft.UI.Xaml.Automation.AutomationProperties.LabeledByProperty); } } diff --git a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/ModifierEventFixtures.cs b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/ModifierEventFixtures.cs index 9c0b6ab280..2be30adc28 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/ModifierEventFixtures.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/ModifierEventFixtures.cs @@ -5,6 +5,8 @@ using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.Primitives; using static Microsoft.UI.Reactor.Factories; +using AP = Microsoft.UI.Xaml.Automation.AutomationProperties; +using APeers = Microsoft.UI.Xaml.Automation.Peers; namespace Microsoft.UI.Reactor.AppTests.Host.SelfTest.Fixtures; @@ -514,6 +516,14 @@ public override async Task RunAsync() internal class ModifierClearResets(Harness h) : SelfTestFixtureBase(h) { + /// + /// The IsTabStop value the phase-0 bag asks for. Named rather than repeated as + /// a literal so the "applied" and "released" checks below are visibly reading the same + /// value the bag wrote — the release check asserts the effective value has moved + /// away from it, deliberately not towards a guessed WinUI default. + /// + private const bool Phase0IsTabStop = false; + public override async Task RunAsync() { var host = H.CreateHost(); @@ -550,7 +560,7 @@ public override async Task RunAsync() Foreground = brush, AutomationName = "clear-name", AutomationId = "clear-id", - IsTabStop = false, + IsTabStop = Phase0IsTabStop, IsHitTestVisible = false, TabIndex = 7, AccessKey = "C", @@ -597,6 +607,29 @@ public override async Task RunAsync() H.Check("ModifierClear_ContentAlignmentInitial", initial.HorizontalContentAlignment == HorizontalAlignment.Right && initial.VerticalContentAlignment == VerticalAlignment.Bottom); + + // Issue #986 — load-bearing for the five ModifierClear_*Cleared checks + // below. Those read ReadLocalValue(dp) == UnsetValue, which a property + // that was NEVER written also satisfies, so without this the release + // checks would pass against a reconciler whose *set* arms were deleted. + // Assert both that a local value exists and that the effective value is + // the deliberately non-default one the phase-0 bag asked for. + H.Check("ModifierClear_Tier1Applied_IsTabStop", + initial.ReadLocalValue(UIElement.IsTabStopProperty) != DependencyProperty.UnsetValue + && initial.IsTabStop == Phase0IsTabStop); + H.Check("ModifierClear_Tier1Applied_TabIndex", + initial.ReadLocalValue(Control.TabIndexProperty) != DependencyProperty.UnsetValue + && initial.TabIndex == 7); + H.Check("ModifierClear_Tier1Applied_XYFocusKeyboardNavigation", + initial.ReadLocalValue(UIElement.XYFocusKeyboardNavigationProperty) != DependencyProperty.UnsetValue + && initial.XYFocusKeyboardNavigation + == Microsoft.UI.Xaml.Input.XYFocusKeyboardNavigationMode.Enabled); + H.Check("ModifierClear_Tier1Applied_ElementSoundMode", + initial.ReadLocalValue(Control.ElementSoundModeProperty) != DependencyProperty.UnsetValue + && initial.ElementSoundMode == ElementSoundMode.Off); + H.Check("ModifierClear_Tier1Applied_HeadingLevel", + initial.ReadLocalValue(AP.HeadingLevelProperty) != DependencyProperty.UnsetValue + && AP.GetHeadingLevel(initial) == APeers.AutomationHeadingLevel.Level2); } H.ClickButton("ClearModifierPhase"); @@ -662,6 +695,51 @@ public override async Task RunAsync() H.Check("ModifierClear_BorderCleared", button.ReadLocalValue(Control.BorderThicknessProperty) == DependencyProperty.UnsetValue && button.ReadLocalValue(Control.CornerRadiusProperty) == DependencyProperty.UnsetValue); + + // Issue #986 — these five were written on phase 0 above and had no unset + // arm at all, so before the fix they stayed pinned on the control through + // every later render. They were already in the phase-0 bag before this + // change and simply never asserted on, which is why the gap was invisible + // here. Each check reads the same DP its set arm writes, so a reset that + // targeted a *different* identifier (Control.IsTabStopProperty vs + // UIElement.IsTabStopProperty, for instance) would still fail. + // + // The release oracle is ReadLocalValue == UnsetValue and nothing else. The + // effective-value comparison used to be folded into the same check, but + // that conflated two different failures: a reconciler that failed to + // release, and a phase-0 bag value that happens to equal the control's + // default. Only the first is a product bug; the second means this fixture + // stopped proving anything and needs a different phase-0 value. Splitting + // them keeps the non-vacuity guard — without it a property whose default + // already equals the phase-0 value would satisfy the release oracle + // trivially — while making a failure self-attributing. + H.Check("ModifierClear_IsTabStopCleared", + button.ReadLocalValue(UIElement.IsTabStopProperty) == DependencyProperty.UnsetValue); + H.Check("ModifierClear_TabIndexCleared", + button.ReadLocalValue(Control.TabIndexProperty) == DependencyProperty.UnsetValue); + H.Check("ModifierClear_XYFocusKeyboardNavigationCleared", + button.ReadLocalValue(UIElement.XYFocusKeyboardNavigationProperty) == DependencyProperty.UnsetValue); + H.Check("ModifierClear_ElementSoundModeCleared", + button.ReadLocalValue(Control.ElementSoundModeProperty) == DependencyProperty.UnsetValue); + H.Check("ModifierClear_HeadingLevelCleared", + button.ReadLocalValue(AP.HeadingLevelProperty) == DependencyProperty.UnsetValue); + + // Non-vacuity. Read *after* the release, so each asserts "the value this + // control falls back to differs from the one phase 0 forced" — i.e. the + // phase-0 write was observable and the release above is a real transition + // rather than a no-op. A failure here is a fixture problem, not a + // regression: pick a phase-0 value that is not the control's default. + H.Check("ModifierClear_IsTabStopPhase0WasDistinct", + button.IsTabStop != Phase0IsTabStop); + H.Check("ModifierClear_TabIndexPhase0WasDistinct", + button.TabIndex != 7); + H.Check("ModifierClear_XYFocusKeyboardNavigationPhase0WasDistinct", + button.XYFocusKeyboardNavigation + != Microsoft.UI.Xaml.Input.XYFocusKeyboardNavigationMode.Enabled); + H.Check("ModifierClear_ElementSoundModePhase0WasDistinct", + button.ElementSoundMode != ElementSoundMode.Off); + H.Check("ModifierClear_HeadingLevelPhase0WasDistinct", + AP.GetHeadingLevel(button) != APeers.AutomationHeadingLevel.Level2); } var border = H.FindControl(b => b.Child is TextBlock tb && tb.Text == "ClearBorderChild"); @@ -1242,4 +1320,182 @@ inlineOnly is not null == DependencyProperty.UnsetValue); } } + + // ════════════════════════════════════════════════════════════════════ + // Issue #986, accessibility half — ApplyAccessibilityModifiers opened + // with `if (a is null) return;` while its caller invokes it whenever + // EITHER bag is non-null. So the one transition it most needed to + // handle — the whole Accessibility sub-record dropped this render — + // returned immediately and released nothing. Ten of its eleven + // properties additionally had no per-property unset arm even when the + // bag survived. + // + // Both mechanisms are covered here, in that order: phase 1 keeps the + // bag and drops every property but one, phase 2 drops the bag itself. + // Phase 0 asserts the values actually landed first — every release + // check below reads UnsetValue on a property that was never written, + // so without the phase-0 check the whole fixture would pass against a + // reconciler that ignored the bag entirely. + // ════════════════════════════════════════════════════════════════════ + + internal class AccessibilityModifierClearResets(Harness h) : SelfTestFixtureBase(h) + { + public override async Task RunAsync() + { + var host = H.CreateHost(); + + host.Mount(ctx => + { + var (phase, setPhase) = ctx.UseState(0); + + var mods = phase switch + { + 0 => new ElementModifiers + { + Accessibility = new AccessibilityModifiers + { + HelpText = "a11y-help", + FullDescription = "a11y-full", + LandmarkType = APeers.AutomationLandmarkType.Navigation, + AccessibilityView = APeers.AccessibilityView.Raw, + IsRequiredForForm = true, + LiveSetting = APeers.AutomationLiveSetting.Assertive, + PositionInSet = 3, + SizeOfSet = 9, + Level = 4, + ItemStatus = "a11y-status", + TabFocusNavigation = Microsoft.UI.Xaml.Input.KeyboardNavigationMode.Cycle, + LabeledBy = "a11y-label-target", + }, + }, + // Bag survives, one property kept: isolates the per-property arms from + // the whole-bag path below, so a fix that only handled `a is null` + // still fails here. + 1 => new ElementModifiers + { + Accessibility = new AccessibilityModifiers { HelpText = "a11y-help" }, + }, + // Sub-record gone entirely — the transition the early return swallowed. + _ => new ElementModifiers(), + }; + + return VStack( + Button("A11yClearPhase", () => setPhase(phase + 1)), + TextBlock("A11yLabelSource") with + { + Modifiers = new ElementModifiers { AutomationId = "a11y-label-target" }, + }, + Button("A11yClearTarget") with { Modifiers = mods }); + }); + + // "Released" and "never written" both read UnsetValue, so this discriminates + // only in combination with the phase-0 applied check below. + static bool Released(FrameworkElement fe, DependencyProperty dp) => + fe.ReadLocalValue(dp) == DependencyProperty.UnsetValue; + + // The element LabeledBy is expected to resolve to. Re-read each time rather + // than captured once: a null here would make the ReferenceEquals below + // trivially satisfiable against another null, so it is asserted non-null. + TextBlock? labelSource() => + H.FindControl(t => t.Text == "A11yLabelSource"); + + static bool NonHelpTextPropertiesReleased(FrameworkElement fe) => + Released(fe, AP.FullDescriptionProperty) + && Released(fe, AP.LandmarkTypeProperty) + && Released(fe, AP.AccessibilityViewProperty) + && Released(fe, AP.IsRequiredForFormProperty) + && Released(fe, AP.LiveSettingProperty) + && Released(fe, AP.PositionInSetProperty) + && Released(fe, AP.SizeOfSetProperty) + && Released(fe, AP.LevelProperty) + && Released(fe, AP.ItemStatusProperty) + && Released(fe, UIElement.TabFocusNavigationProperty); + + await Harness.Render(); + var applied = H.FindButton("A11yClearTarget"); + H.Check("A11yClear_Phase0_Present", applied is not null); + if (applied is not null) + { + H.Check("A11yClear_Phase0_Applied", + AP.GetHelpText(applied) == "a11y-help" + && AP.GetFullDescription(applied) == "a11y-full" + && AP.GetLandmarkType(applied) == APeers.AutomationLandmarkType.Navigation + && AP.GetAccessibilityView(applied) == APeers.AccessibilityView.Raw + && AP.GetIsRequiredForForm(applied) + && AP.GetLiveSetting(applied) == APeers.AutomationLiveSetting.Assertive + && AP.GetPositionInSet(applied) == 3 + && AP.GetSizeOfSet(applied) == 9 + && AP.GetLevel(applied) == 4 + && AP.GetItemStatus(applied) == "a11y-status" + && applied.TabFocusNavigation == Microsoft.UI.Xaml.Input.KeyboardNavigationMode.Cycle); + + // LabeledBy resolves an AutomationId against the visual tree, which can fail + // during mount and get deferred to Loaded — an eventual condition, which is + // the one shape WaitFor is sound for. But "eventual" requires the predicate + // to be false at t=0, and ReferenceEquals(null, null) is true: with the + // label source not yet discoverable *and* LabeledBy not yet resolved, the + // wait returns immediately at zero elapsed time and the check below then + // fails spuriously on a still-null source. Requiring the source inside the + // same lambda is what makes the wait actually wait. + // Load-bearing for A11yClear_Phase1_LabeledByReleased below in the same way + // Phase0_Applied is for the rest. + var resolved = await Harness.WaitFor(() => + { + var source = labelSource(); + return source is not null && ReferenceEquals(AP.GetLabeledBy(applied), source); + }); + H.Check("A11yClear_Phase0_LabeledByResolved", + resolved && labelSource() is not null); + } + + H.ClickButton("A11yClearPhase"); + await Harness.Render(); + + var partial = H.FindButton("A11yClearTarget"); + H.Check("A11yClear_Phase1_Present", partial is not null); + if (partial is not null) + { + H.Check("A11yClear_Phase1_KeptPropertySurvives", + AP.GetHelpText(partial) == "a11y-help"); + H.Check("A11yClear_Phase1_DroppedPropertiesReleased", + NonHelpTextPropertiesReleased(partial)); + // LabeledBy already had an unset arm before issue #986; what is new is that + // the arm now also cancels a still-parked deferred resolution, so a dropped + // label cannot be re-applied by a Loaded handler from an earlier render. + // The race itself is not driven here — the harness cannot hold Loaded open + // across a re-render — so the guard is pinned structurally instead, by + // ModifierUnsetClearValueTests.Deferred_LabeledBy_Rechecks_Pending_Request. + H.Check("A11yClear_Phase1_LabeledByReleased", + Released(partial, AP.LabeledByProperty)); + H.Check("A11yClear_Phase1_LabeledByEffectiveNull", + AP.GetLabeledBy(partial) is null); + } + + H.ClickButton("A11yClearPhase"); + await Harness.Render(); + + var dropped = H.FindButton("A11yClearTarget"); + H.Check("A11yClear_Phase2_Present", dropped is not null); + if (dropped is not null) + { + H.Check("A11yClear_Phase2_WholeBagReleased", + Released(dropped, AP.HelpTextProperty) + && NonHelpTextPropertiesReleased(dropped)); + // Effective-value spot check: on a Button these DPs have no style setter, so + // this cannot replace the local-value reads above — it only rules out a reset + // that released the local value while leaving the property reading the + // previous render's value some other way. Split per-property so a failure + // names the property instead of just "one of four". + H.Check("A11yClear_Phase2_HelpTextDefaulted", + AP.GetHelpText(dropped) != "a11y-help"); + H.Check("A11yClear_Phase2_ItemStatusDefaulted", + AP.GetItemStatus(dropped) != "a11y-status"); + H.Check("A11yClear_Phase2_PositionInSetDefaulted", + AP.GetPositionInSet(dropped) != 3); + H.Check("A11yClear_Phase2_TabFocusNavigationDefaulted", + dropped.TabFocusNavigation + != Microsoft.UI.Xaml.Input.KeyboardNavigationMode.Cycle); + } + } + } } diff --git a/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs b/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs index c38faa85ec..7c3eb0f675 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs @@ -422,6 +422,7 @@ internal static class SelfTestFixtureRegistry "ModifierEvent_PoolClearValueControl", "ModifierEvent_InlineMarginCarryForward", "ModifierEvent_InlineDropRestoresPhysical", + "ModifierEvent_AccessibilityClearResets", // Rare control mount + update tests "RareControl_ColorPicker", "RareControl_TeachingTip", @@ -2049,6 +2050,7 @@ internal static class SelfTestFixtureRegistry "ModifierEvent_PoolClearValueControl" => new ModifierEventFixtures.ModifierPoolClearValueControl(harness), "ModifierEvent_InlineMarginCarryForward" => new ModifierEventFixtures.ModifierInlineMarginCarryForward(harness), "ModifierEvent_InlineDropRestoresPhysical" => new ModifierEventFixtures.ModifierInlineDropRestoresPhysical(harness), + "ModifierEvent_AccessibilityClearResets" => new ModifierEventFixtures.AccessibilityModifierClearResets(harness), // Rare control tests "RareControl_ColorPicker" => new RareControlFixtures.ColorPickerMountUpdate(harness), "RareControl_TeachingTip" => new RareControlFixtures.TeachingTipMount(harness), diff --git a/tests/Reactor.Tests/AnalyzerTests/ModifierUnsetClearValueTests.cs b/tests/Reactor.Tests/AnalyzerTests/ModifierUnsetClearValueTests.cs index 5e7226ee2e..077d02b3f9 100644 --- a/tests/Reactor.Tests/AnalyzerTests/ModifierUnsetClearValueTests.cs +++ b/tests/Reactor.Tests/AnalyzerTests/ModifierUnsetClearValueTests.cs @@ -13,9 +13,10 @@ namespace Microsoft.UI.Reactor.Tests.AnalyzerTests; /// /// Pins the reset half of the modifier protocol: unsetting a modifier must -/// ClearValue the dependency property, never assign the property's default. +/// ClearValue the dependency property, never assign the property's default — and, +/// since #986, must exist at all. /// -/// The two are indistinguishable when you read the effective value on a control with no +/// The two writes are indistinguishable when you read the effective value on a control with no /// relevant style, which is exactly why issue #952 survived for so long. They are not /// equivalent: a local value outranks every Style setter in WinUI's precedence /// order, so writing HorizontalAlignment.Stretch on unset does not restore the @@ -34,12 +35,78 @@ namespace Microsoft.UI.Reactor.Tests.AnalyzerTests; public class ModifierUnsetClearValueTests { /// - /// Statements in an unset arm that are legitimately not ClearValue calls, keyed - /// by the assignment target as written. Empty on purpose — every unset arm in - /// ApplyModifiers can and does clear its dependency property. An entry here is a - /// claim that a property has no DP to clear; add one only with a reason. + /// The reconciler methods scanned here, with the identifier each one uses for the new + /// and the previous modifier bag. ApplyAccessibilityModifiers joined the scan with + /// issue #986: it used to open with if (a is null) return;, which swallowed exactly + /// the transition it needed to handle, so dropping the whole accessibility sub-record + /// released nothing. /// - private static readonly Dictionary ApplyModifiersAssignmentExceptions = new(StringComparer.Ordinal); + private static readonly (string Method, string Bag, string OldBag, int MinArms, int MinUnsetArms)[] ScannedMethods = + [ + // Both are per-method non-vacuity floors, deliberately close to the real count. A + // single total floor is not enough: if the matcher stopped recognizing + // ApplyAccessibilityModifiers entirely, ApplyModifiers alone would still clear a + // global threshold and the a11y half would go unchecked in silence — which is exactly + // the half issue #986 found broken. + // + // MinArms governs the *set*-arm scan (Every_Diff_Guarded_Modifier_Has_An_Unset_Arm); + // MinUnsetArms governs the *unset*-arm scan and is enforced inside ReadUnsetArms, so + // every consumer of that helper inherits it rather than having to remember a floor. + // They are separate populations and must not be collapsed into one constant. + // + // Real counts when these were set: set arms 37 / 12, unset arms 36 / 12. Read them out + // of the assertion message (raise the floor to 99999 and run) rather than re-deriving + // with a text scan — the scan walks syntax nodes, so a line-scoped regex undercounts. + ("ApplyModifiers", "m", "oldM", 32, 31), + ("ApplyAccessibilityModifiers", "a", "oldA", 10, 10), + ]; + + /// + /// Assignments inside an unset arm that are legitimately not ClearValue calls, keyed + /// by the assignment target's trailing identifier. An entry is a claim that the target is + /// not a dependency property at all — reconciler bookkeeping that happens to live inside the + /// arm — so the #952 precedence argument does not apply to it. Add one only with a reason; + /// anything that is a DP must go through ClearValue. + /// + /// Scoped to every method in , not to ApplyModifiers alone — + /// the sole entry below comes from ApplyAccessibilityModifiers. + /// + /// + private static readonly Dictionary UnsetArmAssignmentExceptions = + new(StringComparer.Ordinal) + { + ["PendingLabeledBy"] = + "ReactorState.PendingLabeledBy is a plain field, not a dependency property. The " + + "LabeledBy unset arm nulls it to retire a still-parked deferred resolution so a " + + "Loaded handler from an earlier render cannot re-apply the label the user just " + + "dropped (issue #986). There is no DP here to clear, and the DP that does exist " + + "(LabeledByProperty) is cleared in the same arm.", + }; + + /// + /// Diff-guarded modifiers that deliberately have no unset arm, keyed + /// Method.Modifier. Every entry must still describe a genuinely missing arm — + /// fails on a stale entry too, + /// so landing the arm forces the exception to be deleted rather than left to rot. + /// + private static readonly Dictionary MissingUnsetArmExceptions = + new(StringComparer.Ordinal) + { + // Issue #1001. These four are XAML *facade* properties. With no ambient curve the + // set path (AnimationHelper.SetOrAnimate / SetOrAnimateVector3) falls through to + // SetVector3Direct and assigns the facade property, which a mechanical ClearValue + // arm would release normally. But when a curve *is* ambient the same path calls + // visual.StartAnimation instead, and a running composition animation outranks the + // DP while leaving no local value for ClearValue to release — so the mechanical + // arm every other modifier gets would silently do nothing in exactly the case + // that matters. The fix needs a StopAnimation companion plus a + // selftest that actually exercises the animated path; deleting these four entries + // is the first commit of #1001. + ["ApplyModifiers.Scale"] = "Compositor-backed facade property — issue #1001.", + ["ApplyModifiers.Rotation"] = "Compositor-backed facade property — issue #1001.", + ["ApplyModifiers.Translation"] = "Compositor-backed facade property — issue #1001.", + ["ApplyModifiers.CenterPoint"] = "Compositor-backed facade property — issue #1001.", + }; /// /// Direct fe.PROP = … writes allowed to remain in CleanElement's FE-common @@ -53,64 +120,539 @@ public class ModifierUnsetClearValueTests ["Tag"] = "framework-internal element-identity slot, never style-provided", }; + /// + /// Every unset arm in — both ApplyModifiers and + /// ApplyAccessibilityModifiers — must reset through ClearValue rather than + /// assigning a value. + /// [Fact] - public void Every_ApplyModifiers_Unset_Arm_Clears_The_Dependency_Property() + public void Every_Unset_Arm_Clears_The_Dependency_Property() { + // The non-vacuity floor lives inside ReadUnsetArms and is enforced *per method*, so a + // shape change that silently stops matching one of the two scanned methods fails here + // rather than hiding behind the other method's arm count. var arms = ReadUnsetArms(); - // A parser that finds nothing would make every assertion below vacuous. The method - // has ~30 unset arms today; 20 is a floor that survives ordinary churn but not a - // shape change that silently stops matching. - Assert.True( - arms.Count >= 20, - $"Only {arms.Count} modifier-unset arm(s) were read out of Reconciler.ApplyModifiers. " + - "The unset-transition shape ('!m.X.HasValue && oldM?.X.HasValue == true' or " + - "'m.X is null && oldM?.X is not null') has probably changed, which would make this " + - "whole test pass without checking anything."); - var offenders = new List(); - foreach (var (modifier, arm) in arms) + foreach (var (method, modifier, arm) in arms) { foreach (var assignment in arm.DescendantNodes().OfType()) { var target = assignment.Left.ToString(); var property = target.Contains('.') ? target[(target.LastIndexOf('.') + 1)..] : target; - if (ApplyModifiersAssignmentExceptions.ContainsKey(property)) continue; + if (UnsetArmAssignmentExceptions.ContainsKey(property)) continue; - offenders.Add($"{modifier}: `{assignment.ToString().Trim()}`"); + offenders.Add($"{method}.{modifier}: `{assignment.ToString().Trim()}`"); } } Assert.True( offenders.Count == 0, - "These unset arms in Reconciler.ApplyModifiers write a value instead of calling " + + "These unset arms in the reconciler write a value instead of calling " + "ClearValue(Property). A local value outranks Style setters, so the write does " + "not restore the styled value — it permanently overrides it (issue #952):\n " + string.Join("\n ", offenders)); } /// - /// The positive half of : + /// The positive half of : /// an arm that neither assigns nor clears would satisfy that test while resetting nothing. + /// Same scope — every method in . /// [Fact] - public void Every_ApplyModifiers_Unset_Arm_Actually_Resets_Something() + public void Every_Unset_Arm_Actually_Resets_Something() { var inert = ReadUnsetArms() .Where(entry => !entry.Arm.DescendantNodes() .OfType() .Any(invocation => invocation.Expression is MemberAccessExpressionSyntax { Name.Identifier.Text: "ClearValue" })) .Where(entry => !entry.Arm.DescendantNodes().OfType().Any()) - .Select(entry => entry.Modifier) + .Select(entry => entry.Method + "." + entry.Modifier) .ToList(); Assert.True( inert.Count == 0, - "These unset arms in Reconciler.ApplyModifiers neither clear nor write anything, so " + + "These unset arms in the reconciler neither clear nor write anything, so " + $"the modifier is never reset on a set → unset update: [{string.Join(", ", inert)}]"); } + /// + /// The half neither test above can see: a modifier with no unset arm at all. + /// Both of them only inspect arms that already exist, so a set arm written without its + /// reset is invisible to them — which is how IsTabStop, TabIndex, + /// XYFocusKeyboardNavigation, HeadingLevel, ElementSoundMode and the + /// whole of ApplyAccessibilityModifiers shipped with the last render's value pinned + /// on the control forever (issue #986). + /// + /// + /// Scoped to diff-guarded set arms — conditions that name both bag.X and + /// oldBag.X. That is the shape of "write this property when present, compared + /// against the previous render", and it is precisely the shape that owes a reset. It + /// deliberately does not try to read the three arms that compute a local first + /// (Margin, Padding, BorderThickness overlay their BiDi-aware inline + /// variants into resolvedX): their conditions never name m.X, and + /// Padding's reset is guarded by wantsPadding/hadPadding rather than + /// by the bag at all, so matching them loosely enough to see the set arm would report a + /// missing reset that is right there. Those three are covered behaviourally by + /// ModifierEvent_InlineDropRestoresPhysical instead. + /// + [Fact] + public void Every_Diff_Guarded_Modifier_Has_An_Unset_Arm() + { + var missing = new List(); + + foreach (var (method, bag, oldBag, minArms, _) in ScannedMethods) + { + var unset = ReadUnsetModifierNames(method, bag, oldBag); + var found = 0; + foreach (var modifier in ReadDiffGuardedModifiers(method, bag, oldBag)) + { + found++; + if (!unset.Contains(modifier)) missing.Add($"{method}.{modifier}"); + } + + // Per-method non-vacuity floor: a matcher that stops recognizing the set-arm + // shape in one method would report zero missing arms for it and pass, which is + // the failure mode this whole test exists to prevent. + Assert.True( + found >= minArms, + $"Only {found} diff-guarded modifier(s) were read out of {method} (expected at " + + $"least {minArms}). The set-arm shape ('{bag}.X.HasValue && {bag}.X != " + + $"{oldBag}?.X') has probably changed, which would make this test pass without " + + "checking anything."); + } + + var offenders = missing.Where(entry => !MissingUnsetArmExceptions.ContainsKey(entry)).ToList(); + + Assert.True( + offenders.Count == 0, + "These modifiers are written when present but never released when dropped, so the " + + "previous render's value stays pinned on the control forever (issue #986): " + + $"[{string.Join(", ", offenders)}]. Add an `else if` arm calling " + + "ClearValue(Property), or record the exemption in MissingUnsetArmExceptions " + + "with a reason."); + + // A stale exemption is worse than none: it silently re-opens the hole for a modifier + // whose arm was later deleted. Landing an arm must delete its entry here. + var stale = MissingUnsetArmExceptions.Keys.Where(key => !missing.Contains(key)).ToList(); + + Assert.True( + stale.Count == 0, + "These MissingUnsetArmExceptions entries no longer describe a missing unset arm — " + + "either the arm was added (delete the entry) or the modifier was renamed/removed " + + $"(update it): [{string.Join(", ", stale)}]"); + } + + /// + /// Every control type a modifier is written to must also be a control type it is + /// cleared on — and a modifier written anywhere must be released somewhere. + /// + /// + /// asks a per-property + /// question, so it is satisfied the moment a property has any reset at all. Several arms + /// are not a single write but an if (fe is WinUI.X) … else if (fe is WinUI.Y) … + /// type-dispatch chain, and those chains get widened one control type at a time — #970 + /// added TextBlock to Padding, #1003 adds Grid/RelativePanel to + /// Padding and Grid/StackPanel/RelativePanel to + /// CornerRadius. Widening only the write half leaves a control type that can have + /// the property set and never released: the #986 bug again, one type down, and invisible + /// to a property-level scan because the property's reset still exists for its original + /// types. + /// + /// That asymmetry is also the standing merge hazard on this file. The two halves live in + /// different hunks, so a rebase can auto-merge the widened write while the widened clear + /// conflicts — resolving that conflict in favour of either side alone reinstates the bug + /// while the arm a reviewer reads first still looks correct. This test is the tripwire: + /// it fails on the merge result, naming the property and the orphaned type. + /// + /// + /// The second obligation exists because the per-property sibling test is not total. Its + /// exclusion list covers the three modifiers that compute a local before testing it — + /// Margin, Padding, BorderThickness — whose conditions never name + /// m.X, so it cannot see them at all. Deleting BorderThickness's whole unset + /// arm while keeping its two type-gated writes therefore left every test in this file green: + /// the sibling excludes it, both floors have slack, and the property simply vanished from + /// clears and was skipped. Those three are exactly the properties this file's other + /// tripwires talk about most, which is what made the hole comfortable to look at. + /// + /// + /// Verified by mutation — deleting a single else if (fe is WinUI.T …) …ClearValue(…) + /// branch while leaving its write branch in place reddens this test and nothing else, naming + /// the property and the orphaned type; deleting an entire unset arm reddens it naming the + /// property alone. + /// + /// + [Fact] + public void Every_Type_Gated_Write_Has_A_Matching_Type_Gated_Clear() + { + var writes = new Dictionary>(StringComparer.Ordinal); + var clears = new Dictionary>(StringComparer.Ordinal); + + foreach (var (method, _, _, _, _) in ScannedMethods) + { + var gated = ReadIfStatements(method) + .Select(ifStatement => (ifStatement, Gate: ReadTypeGate(ifStatement))) + .Where(entry => entry.Gate is not null); + + foreach (var (ifStatement, gate) in gated) + { + var (typeName, variable) = gate!.Value; + + // The gate's own branch only. An `else if` chain nests the next gate inside + // this one's Else clause, so including the else would attribute every later + // control type's writes to the first type in the chain and mask the exact + // asymmetry this test looks for. + var branch = ifStatement.Statement; + + foreach (var property in ReadWrittenProperties(branch, variable)) + Add(writes, property, typeName); + + foreach (var property in ReadClearedProperties(branch, variable)) + Add(clears, property, typeName); + } + } + + // Non-vacuity floor. A matcher that stopped recognizing the `fe is WinUI.T v` gate + // would collect nothing, find no asymmetry and pass — the failure mode this test + // exists to prevent. There are 28 type-gated write pairs today over 11 properties; + // the two longest chains are Padding (6 types) and CornerRadius (5). + // + // The floor is deliberately close to the real count, for the same reason MinArms is. + // A floor low enough to survive losing a whole chain does not protect the chains this + // test exists for: at 10 the scanner could drop Padding *and* CornerRadius entirely — + // the two properties #970, #986 and #1003 all widened — and still report 17, passing + // while blind to precisely the arms under active merge pressure. At 24 the loss of + // either chain trips it, with four arms of slack for a legitimate narrowing. + // + // Read this count out of the assertion message rather than re-deriving it by hand: a + // line-scoped text scan misses the writes nested inside a gate's block (it reports 22, + // silently dropping HorizontalContentAlignment and VerticalContentAlignment), and + // calibrating the floor against that number would sit it below the real population. + var pairs = writes.Sum(entry => entry.Value.Count); + + Assert.True( + pairs >= 24, + $"Only {pairs} type-gated modifier write(s) were read out of the reconciler " + + "(expected at least 24). The `if (fe is WinUI.T v) v.Prop = …` shape has probably " + + "changed, which would make this test pass without checking anything. Properties " + + $"seen: [{string.Join(", ", writes.Keys)}]"); + + // The floor above is computed from `writes` alone, so it is structurally incapable of + // noticing a failure confined to the *clear* side — and the `continue` below turns that + // blindness into a pass rather than an error. If ReadClearedProperties stops matching + // (the reconciler routes clears through a helper, the invocation shape changes, the + // matcher regresses), `clears` is empty, every property takes the `continue`, `offenders` + // is empty, and `Assert.True(offenders.Count == 0, …)` is vacuously true. Both arms of + // this test then agree that nothing is wrong, and no other test calls that reader. + // + // Measured through this test's own parser rather than a text scan, for the reason given + // above: 28 type-gated clears over the same 11 properties, mirroring the write side + // exactly (Padding 6, CornerRadius 5, Background 3, six properties at 2, the two + // ContentAlignment properties at 1). Same floor and same calibration as its sibling — + // losing either of the two longest chains trips it, with four arms of slack. + var clearPairs = clears.Sum(entry => entry.Value.Count); + + Assert.True( + clearPairs >= 24, + $"Only {clearPairs} type-gated modifier clear(s) were read out of the reconciler " + + "(expected at least 24), while the write side still reads " + pairs + ". Either the " + + "unset arms were removed wholesale, or the `v.ClearValue(WinUI.T.PropProperty)` " + + "shape has changed and this test can no longer see the clears it compares against — " + + "in which case the comparison below passes without checking anything. Properties " + + $"seen: [{string.Join(", ", clears.Keys)}]"); + + var offenders = new List(); + var unreleased = new List(); + + // Receiver-blind: is the property released *at all*, through any + // `x.ClearValue(WinUI.T.PropProperty)`? The gate-bound reader above cannot answer that, + // because an arm is free to clear through the method's own `fe` rather than a gate's + // pattern variable. Both readers share one extraction, so this is a superset of `clears` + // by construction — which is precisely what makes the assert below a check on the one + // axis that can independently break: the *scope* it walks. + var releasedSomehow = ReadAnyClearedProperties(); + + Assert.True( + clears.Keys.All(releasedSomehow.Contains), + "The receiver-blind ClearValue reader missed a property the gate-bound reader found. " + + "It matches a superset of the same invocations, so this only happens if it walked the " + + "wrong scope — and a reader that walks nothing turns the branch below into the " + + "unconditional `continue` it replaced. Gate-bound: " + + $"[{string.Join(", ", clears.Keys)}]; receiver-blind: " + + $"[{string.Join(", ", releasedSomehow.OrderBy(name => name, StringComparer.Ordinal))}]"); + + foreach (var (property, writtenTypes) in writes) + { + if (!clears.TryGetValue(property, out var clearedTypes)) + { + // No type-dispatch chain to compare against. Legitimate for an arm that expresses + // its clear as an ungated `fe.ClearValue(…)` instead of through the gate's own + // pattern variable: semantically identical, and correctly not a chain. Only an arm + // that already dispatches on type is asked to dispatch over the same set of types. + // + // Not legitimate when the property is released nowhere — that is the #986 defect + // itself, and skipping it unconditionally is how this test used to certify it. + // Every_Diff_Guarded_Modifier_Has_An_Unset_Arm does not cover the gap: it + // deliberately excludes the three modifiers that compute a local first (Margin, + // Padding, BorderThickness — see its remarks), so for exactly those three a + // deleted unset arm is invisible to both tests. Verified by mutation — deleting + // BorderThickness's whole unset arm while keeping its two type-gated writes left + // all seven tests in this file green before this branch existed. The write-side + // floor cannot catch it either: `writes` is untouched by a clear-side deletion, + // and the clear-side floor only falls from 28 to 26, still over 24. + if (!releasedSomehow.Contains(property)) unreleased.Add(property); + continue; + } + + foreach (var type in writtenTypes.Except(clearedTypes)) + offenders.Add($"{property} on {type}"); + } + + Assert.True( + unreleased.Count == 0, + "These modifiers are written to at least one control type and released on none of " + + "them — no type-gated clear, and no ungated `fe.ClearValue(…)` either — so the value " + + "stays pinned on the control forever once the modifier is dropped from the chain " + + $"(issue #986): [{string.Join(", ", unreleased)}]. Restore the unset arm. If you " + + "reached this after resolving a Reconciler.cs merge conflict, the resolution dropped " + + "the whole arm — reapply it rather than deleting the write."); + + Assert.True( + offenders.Count == 0, + "These control types can have a modifier written but never released — the write " + + "half of a type-dispatch chain was widened without the clear half, so the value " + + "stays pinned on that control type forever (issue #986): " + + $"[{string.Join(", ", offenders)}]. Add the matching " + + "`else if (fe is WinUI. v) v.ClearValue(WinUI..Property);` " + + "branch to the unset arm. If you reached this after resolving a Reconciler.cs " + + "merge conflict, the conflict resolution dropped the clear branch — reapply it " + + "rather than deleting the write."); + } + + /// + /// The fe is WinUI.T v shape used to gate a modifier write on the control type, + /// or null when the condition is not a type gate. + /// + private static (string TypeName, string Variable)? ReadTypeGate(IfStatementSyntax ifStatement) + { + if (ifStatement.Condition is not IsPatternExpressionSyntax pattern) return null; + if (pattern.Expression is not IdentifierNameSyntax { Identifier.Text: "fe" }) return null; + if (pattern.Pattern is not DeclarationPatternSyntax declaration) return null; + if (declaration.Designation is not SingleVariableDesignationSyntax designation) return null; + + var qualified = declaration.Type.ToString(); + var typeName = qualified[(qualified.LastIndexOf('.') + 1)..]; + return typeName.Length == 0 ? null : (typeName, designation.Identifier.Text); + } + + /// Properties assigned through variable.Prop = … inside the branch. + private static IEnumerable ReadWrittenProperties(SyntaxNode branch, string variable) => + branch.DescendantNodesAndSelf() + .OfType() + .Select(assignment => assignment.Left) + .OfType() + .Where(access => access.Expression is IdentifierNameSyntax id + && id.Identifier.Text == variable) + .Select(access => access.Name.Identifier.Text); + + /// + /// Properties released through variable.ClearValue(WinUI.T.PropProperty) inside the + /// branch, named by the modifier rather than the DP field so they key the same as the + /// writes. + /// + private static IEnumerable ReadClearedProperties(SyntaxNode branch, string variable) => + ReadClearedPropertyNames(branch, variable); + + /// + /// The ClearValue shape, in one place. restricts the + /// receiver; accepts any. Both callers share this so the gate-bound + /// and receiver-blind readers cannot drift into disagreeing about what a clear looks like. + /// + private static IEnumerable ReadClearedPropertyNames(SyntaxNode scope, string? variable) => + scope.DescendantNodesAndSelf() + .OfType() + .Where(invocation => invocation.Expression is MemberAccessExpressionSyntax access + && access.Name.Identifier.Text == "ClearValue" + && access.Expression is IdentifierNameSyntax id + && (variable is null || id.Identifier.Text == variable)) + .SelectMany(invocation => invocation.ArgumentList.Arguments) + .Select(argument => argument.Expression) + .OfType() + .Select(access => access.Name.Identifier.Text) + .Where(name => name.EndsWith("Property", StringComparison.Ordinal)) + .Select(name => name[..^"Property".Length]); + + /// + /// Every property released through ClearValue(WinUI.T.PropProperty) anywhere in the + /// scanned methods, whatever the receiver. + /// + /// + /// Answers "is this released at all", which the gate-bound reader cannot: a clear expressed + /// as an ungated fe.ClearValue(…) is invisible to it, and treating that absence as + /// "nothing to compare" is indistinguishable from the arm having been deleted outright. + /// Whole-method scope on purpose — an unset arm need not sit inside a type gate, and reading + /// gates only would reproduce the blind spot in a new place. + /// + private static HashSet ReadAnyClearedProperties() + { + var scanned = ScannedMethods + .Select(entry => entry.Method) + .ToHashSet(StringComparer.Ordinal); + + var methods = ReconcilerRoot.Value + .DescendantNodes() + .OfType() + .Where(method => scanned.Contains(method.Identifier.Text)) + .ToList(); + + Assert.True( + methods.Count > 0, + $"None of the scanned methods ({string.Join(", ", scanned)}) were found in " + + "Reconciler.cs, so the receiver-blind clear scan would report every property as " + + "never released."); + + return methods + .SelectMany(method => ReadClearedPropertyNames(method, variable: null)) + .ToHashSet(StringComparer.Ordinal); + } + + private static void Add(Dictionary> map, string key, string value) + { + if (!map.TryGetValue(key, out var set)) + { + set = new SortedSet(StringComparer.Ordinal); + map[key] = set; + } + + set.Add(value); + } + + /// + /// The deferred LabeledBy resolution must re-check that its request is still the + /// current one before writing. + /// + /// + /// ApplyAccessibilityModifiers cannot resolve a LabeledBy AutomationId until + /// the element is in the visual tree, so an unresolved request parks a Loaded + /// handler that outlives the render which created it. If that handler writes + /// unconditionally, this sequence re-pins a label the user dropped: render A requests a + /// not-yet-present id and parks the handler; render B drops the modifier and the unset arm + /// clears the property; the element then loads and the stale handler resolves the *old* id + /// and sets it again — permanently, since no later render will clear a property whose + /// modifier is already absent. That defeats the reset arm for exactly the property the arm + /// exists to release (issue #986). + /// + /// Pinned structurally rather than behaviourally because driving it needs Loaded + /// held open across a re-render, which the selftest harness cannot do — a fixture that + /// merely dropped the modifier and re-rendered would pass whether or not the guard is + /// present, which is the vacuous shape this repo rejects. The reachable half (drop + /// releases the property) is covered by + /// ModifierEvent_AccessibilityClearResets' A11yClear_Phase1_LabeledByReleased. + /// + /// + [Fact] + public void Deferred_LabeledBy_Rechecks_Pending_Request() + { + // The LabeledBy set/unset pair: the only if-statement in the method whose condition + // names LabeledBy and which has an else. Located through the syntax tree rather than + // by text search so a match cannot be satisfied by an enclosing statement's text. + var labeledBy = ReadIfStatements("ApplyAccessibilityModifiers") + .Where(statement => statement.Condition.ToString().Contains("LabeledBy", StringComparison.Ordinal)) + .FirstOrDefault(statement => statement.Else is not null); + + Assert.True( + labeledBy is not null, + "No `if (... LabeledBy ...) { } else { }` pair found in ApplyAccessibilityModifiers. " + + "If LabeledBy stopped deferring resolution this test is obsolete — delete it; if it " + + "moved, retarget it. Leaving it matching nothing would silently stop guarding the " + + "stale-write bug."); + + // The deferred handler itself — the local function registered on Loaded. Scoped to the + // function body, not the enclosing branch: the branch also *publishes* the request + // (`PendingLabeledBy = labelId`), so a branch-wide search for the field name passes + // even with the handler's re-check deleted. Verified by mutation. + var handler = labeledBy!.Statement + .DescendantNodes() + .OfType() + .FirstOrDefault(fn => fn.ParameterList.Parameters.Count == 2); + + Assert.True( + handler is not null, + "The LabeledBy set arm no longer declares a local Loaded handler. If deferral was " + + "removed entirely the stale-write bug is gone and this test should be deleted; if " + + "the handler merely moved or changed shape, retarget the test."); + + var handlerBody = handler!.Body?.ToString() ?? handler.ExpressionBody?.ToString() ?? ""; + + Assert.True( + handlerBody.Contains("Loaded -=", StringComparison.Ordinal), + "The deferred LabeledBy handler no longer unsubscribes itself, so it can fire on " + + $"every later load. Handler body reads: {handlerBody}"); + + Assert.True( + handlerBody.Contains("PendingLabeledBy", StringComparison.Ordinal), + "The deferred LabeledBy handler no longer consults ReactorState.PendingLabeledBy. " + + "Without that re-check it writes the id captured at request time, so a LabeledBy " + + "dropped before the element loads gets re-applied after the unset arm cleared it " + + $"and stays pinned forever (issue #986). Handler body reads: {handlerBody}"); + + // The unset arm must retire the pending request, or cancelling is impossible however + // carefully the handler re-checks. Read from the else clause alone. + var unsetArm = labeledBy.Else!.Statement.ToString(); + + Assert.True( + unsetArm.Contains("ClearValue", StringComparison.Ordinal) + && unsetArm.Contains("LabeledByProperty", StringComparison.Ordinal), + "The LabeledBy unset arm no longer clears LabeledByProperty, so a dropped label " + + $"stays pinned on the control (issue #986). Arm reads: {unsetArm}"); + + Assert.True( + unsetArm.Contains("PendingLabeledBy", StringComparison.Ordinal), + "The LabeledBy unset arm clears the dependency property without also clearing " + + "ReactorState.PendingLabeledBy, so a parked Loaded handler will still consider its " + + $"request current and re-apply the dropped label (issue #986). Arm reads: {unsetArm}"); + + // Ordering, not just presence. Two handlers can be parked on one element at once: the + // set arm's `a.LabeledBy != oldA?.LabeledBy` diff guard means the second park always + // carries a *different* labelId, so on Loaded the stale handler runs first and the live + // one second. The stale handler is harmless only because its staleness guard precedes + // the clear — it bails before touching a token that now belongs to the live request. + // Hoist the clear above that guard and the stale handler cancels the live one, which + // then no-ops and leaves the label unresolved forever. Nothing else pins this ordering. + // + // Located by syntax span, not by string index. Keying on the first `return` in the body + // is vacuous: the handler opens with an unrelated `TryGetReactorState` bail-out, so a + // clear hoisted above the *staleness* guard still sorts after that first return and the + // assertion passes while the bug is present. Verified by mutation. + var stalenessGuard = handler.Body? + .DescendantNodes() + .OfType() + .FirstOrDefault(statement => + statement.Condition.ToString().Contains("labelId", StringComparison.Ordinal)); + + var retire = handler.Body? + .DescendantNodes() + .OfType() + .FirstOrDefault(assignment => + assignment.Left.ToString().Contains("PendingLabeledBy", StringComparison.Ordinal) + && assignment.Right.ToString() == "null"); + + Assert.True( + stalenessGuard is not null && retire is not null, + "Could not locate both the labelId staleness guard and the `PendingLabeledBy = null` " + + "retirement in the deferred LabeledBy handler, so their ordering cannot be checked " + + $"and this assertion would pass vacuously. Handler body reads: {handlerBody}"); + + Assert.True( + stalenessGuard!.Span.End < retire!.SpanStart, + "The deferred LabeledBy handler retires ReactorState.PendingLabeledBy before the " + + "guard that returns when the captured labelId is no longer the current request. A " + + "handler parked by an earlier render would therefore cancel a *later* render's " + + "still-pending request before returning, and the live handler would then see a null " + + $"token, no-op, and leave the label unresolved (issue #986). Handler body reads: {handlerBody}"); + } + /// /// Dependency properties CleanElement's FE-common block must release. Absence of a /// default-value assignment is not enough on its own: deleting a ClearValue line @@ -193,43 +735,144 @@ public void CleanElement_Releases_Every_Modifier_Backed_Dependency_Property() // ── Source-scanning helpers ───────────────────────────────────────────── - /// - /// Every else-arm in Reconciler.ApplyModifiers guarded by an unset - /// transition — the modifier is absent now and was present on the previous render. - /// - private static List<(string Modifier, StatementSyntax Arm)> ReadUnsetArms() + /// Reconciler.cs, parsed once per test run rather than once per helper call. + private static readonly Lazy ReconcilerRoot = new(() => { var root = RepoRootFinder.FindRepoRoot(); Assert.NotNull(root); var file = Path.Join(root!, "src", "Reactor", "Core", "Reconciler.cs"); Assert.True(File.Exists(file), $"Reconciler.cs not found at {file}"); + return CSharpSyntaxTree.ParseText(File.ReadAllText(file)).GetRoot(); + }); - var methods = CSharpSyntaxTree.ParseText(File.ReadAllText(file)) - .GetRoot() + /// Every if statement in the named reconciler method(s). + private static List ReadIfStatements(string methodName) + { + var methods = ReconcilerRoot.Value .DescendantNodes() .OfType() - .Where(method => method.Identifier.Text == "ApplyModifiers") + .Where(method => method.Identifier.Text == methodName) .ToList(); - Assert.True(methods.Count > 0, "No ApplyModifiers method found in Reconciler.cs"); + Assert.True(methods.Count > 0, $"No {methodName} method found in Reconciler.cs"); - var arms = new List<(string, StatementSyntax)>(); + return methods + .SelectMany(method => method.DescendantNodes().OfType()) + .ToList(); + } + + /// + /// Every else-arm in the scanned reconciler methods guarded by an unset + /// transition — the modifier is absent now and was present on the previous render. + /// + private static List<(string Method, string Modifier, StatementSyntax Arm)> ReadUnsetArms() + { + var arms = new List<(string, string, StatementSyntax)>(); - foreach (var ifStatement in methods.SelectMany(method => method.DescendantNodes().OfType())) + foreach (var (method, bag, oldBag, _, minUnsetArms) in ScannedMethods) { - var modifier = UnsetTransitionModifier(ifStatement.Condition) - ?? ElseOfSetArmModifier(ifStatement); - if (modifier is null) continue; - - // Only the arm's own body — an `else if` chain nests the next arm inside this - // one's Else clause, and attributing that arm's statements here would report - // every following modifier under the first one's name. - arms.Add((modifier, ifStatement.Statement)); + var found = 0; + foreach (var ifStatement in ReadIfStatements(method)) + { + var modifier = UnsetTransitionModifier(ifStatement.Condition, bag, oldBag) + ?? ElseOfSetArmModifier(ifStatement, bag, oldBag); + if (modifier is null) continue; + + // Only the arm's own body — an `else if` chain nests the next arm inside this + // one's Else clause, and attributing that arm's statements here would report + // every following modifier under the first one's name. + arms.Add((method, modifier, ifStatement.Statement)); + found++; + } + + // Per-method non-vacuity floor, asserted here rather than at the call sites so no + // consumer can forget it — Every_Unset_Arm_Actually_Resets_Something had no floor + // at all, and Every_Unset_Arm_Clears_The_Dependency_Property had only a combined + // one. A combined floor cannot see a single method disappear: the ~37 arms in + // ApplyModifiers clear any plausible total on their own, so the a11y half could + // stop matching entirely and both tests would still report zero offenders. + Assert.True( + found >= minUnsetArms, + $"Only {found} modifier-unset arm(s) were read out of {method} (expected at " + + $"least {minUnsetArms}). The unset-transition shape ('!{bag}.X.HasValue && " + + $"{oldBag}?.X.HasValue == true' or '{bag}.X is null && {oldBag}?.X is not " + + "null') has probably changed, which would make every caller of ReadUnsetArms " + + "pass without checking anything."); } return arms; } + /// + /// Every modifier name covered by an unset arm in the named method. Unlike + /// this returns all names an arm releases, not just + /// the first: the ToolTip/RichToolTip pair share one arm, and reporting only one of them + /// would make the other look unreleased. + /// + private static HashSet ReadUnsetModifierNames(string methodName, string bag, string oldBag) + { + var names = new HashSet(StringComparer.Ordinal); + + foreach (var ifStatement in ReadIfStatements(methodName)) + { + var text = ifStatement.Condition.ToString(); + var unset = ModifierNames(ifStatement.Condition, bag, oldBag) + .Where(name => AbsentNow(text, bag, name) && PresentBefore(text, oldBag, name)); + + foreach (var name in unset) names.Add(name); + + var implicitElse = ElseOfSetArmModifier(ifStatement, bag, oldBag); + if (implicitElse is not null) names.Add(implicitElse); + } + + return names; + } + + /// + /// Modifiers written under a diff guard in the named method — the condition names both + /// bag.X and oldBag.X and does not test for absence, i.e. "write X when + /// present, compared against the previous render". Every one of these owes a reset. + /// + private static HashSet ReadDiffGuardedModifiers(string methodName, string bag, string oldBag) + { + var names = new HashSet(StringComparer.Ordinal); + + foreach (var ifStatement in ReadIfStatements(methodName)) + { + var text = ifStatement.Condition.ToString(); + var diffGuarded = ModifierNames(ifStatement.Condition, bag, oldBag) + // The unset arm itself names both bags too; excluding absence tests keeps this + // to the set arms, which are the ones that owe a reset. + .Where(name => !AbsentNow(text, bag, name)) + .Where(name => MentionsCurrent(text, bag, name)) + .Where(name => PresentBefore(text, oldBag, name) || MentionsDiff(text, oldBag, name)); + + foreach (var name in diffGuarded) names.Add(name); + } + + return names; + } + + /// "this modifier is absent on the current render", in every shape used. + private static bool AbsentNow(string text, string bag, string name) => + text.Contains($"!{bag}.{name}.HasValue", StringComparison.Ordinal) + || text.Contains($"{bag}.{name} is null", StringComparison.Ordinal) + || text.Contains($"{bag}?.{name} is null", StringComparison.Ordinal) + || text.Contains($"{bag}?.{name}.HasValue != true", StringComparison.Ordinal); + + /// "this modifier was present on the previous render", in every shape used. + private static bool PresentBefore(string text, string oldBag, string name) => + text.Contains($"{oldBag}?.{name}.HasValue == true", StringComparison.Ordinal) + || text.Contains($"{oldBag}?.{name} is not null", StringComparison.Ordinal); + + /// The previous render's value is read at all — a diff guard, not a reset test. + private static bool MentionsDiff(string text, string oldBag, string name) => + Regex.IsMatch(text, $@"(?The current render's value is read at all. + private static bool MentionsCurrent(string text, string bag, string name) => + Regex.IsMatch(text, $@"(? /// The modifier name when is an unset transition — /// !m.X.HasValue && oldM?.X.HasValue == true or @@ -240,16 +883,13 @@ public void CleanElement_Releases_Every_Modifier_Backed_Dependency_Property() /// diff guard. Only the conjunction means "was set, now isn't", which is the transition /// that has to release the local value. /// - private static string? UnsetTransitionModifier(ExpressionSyntax condition) + private static string? UnsetTransitionModifier(ExpressionSyntax condition, string bag, string oldBag) { var text = condition.ToString(); - foreach (var name in ModifierNames(condition).Distinct(StringComparer.Ordinal)) + foreach (var name in ModifierNames(condition, bag, oldBag).Distinct(StringComparer.Ordinal)) { - var absentNow = text.Contains($"!m.{name}.HasValue") || text.Contains($"m.{name} is null"); - var presentBefore = text.Contains($"oldM?.{name}.HasValue == true") - || text.Contains($"oldM?.{name} is not null"); - if (absentNow && presentBefore) return name; + if (AbsentNow(text, bag, name) && PresentBefore(text, oldBag, name)) return name; } // Padding and BorderThickness are computed into a local first (to overlay the @@ -258,7 +898,7 @@ public void CleanElement_Releases_Every_Modifier_Backed_Dependency_Property() var resolved = Regex.Match(text, @"!\s*(resolved\w+)\.HasValue"); if (resolved.Success) { - var oldHalf = Regex.Match(text, @"oldM\?\.(\w+)\.HasValue == true"); + var oldHalf = Regex.Match(text, $@"{Regex.Escape(oldBag)}\?\.(\w+)\.HasValue == true"); if (oldHalf.Success) return oldHalf.Groups[1].Value; } @@ -273,44 +913,41 @@ public void CleanElement_Releases_Every_Modifier_Backed_Dependency_Property() /// cannot see it. ContextFlyout is written /// this way; without this the arm would be silently skipped and its reset untested. /// - private static string? ElseOfSetArmModifier(IfStatementSyntax ifStatement) + private static string? ElseOfSetArmModifier(IfStatementSyntax ifStatement, string bag, string oldBag) { if (ifStatement.Parent is not ElseClauseSyntax { Parent: IfStatementSyntax setArm }) return null; var text = ifStatement.Condition.ToString(); - var oldHalf = Regex.Match(text, @"oldM\?\.(\w+)(?:\.HasValue == true| is not null)"); + var oldHalf = Regex.Match(text, $@"{Regex.Escape(oldBag)}\?\.(\w+)(?:\.HasValue == true| is not null)"); if (!oldHalf.Success) return null; var name = oldHalf.Groups[1].Value; // If the condition tests `m.X` itself, UnsetTransitionModifier already owns it (or // deliberately rejected it); only the implicit-else shape belongs here. - if (text.Contains($"m.{name}", StringComparison.Ordinal) - && !text.Contains($"oldM?.{name}", StringComparison.Ordinal)) return null; - if (Regex.IsMatch(text, $@"(?Modifier names read off m. / oldM. / oldM?. in a condition. - private static IEnumerable ModifierNames(SyntaxNode node) + /// Modifier names read off the bag identifiers in a condition. + private static IEnumerable ModifierNames(SyntaxNode node, string bag, string oldBag) { foreach (var descendant in node.DescendantNodesAndSelf()) { switch (descendant) { - case MemberAccessExpressionSyntax { Expression: IdentifierNameSyntax bag } access - when bag.Identifier.Text is "m" or "oldM": + case MemberAccessExpressionSyntax { Expression: IdentifierNameSyntax bagId } access + when bagId.Identifier.Text == bag || bagId.Identifier.Text == oldBag: yield return access.Name.Identifier.Text; break; - case ConditionalAccessExpressionSyntax { Expression: IdentifierNameSyntax bag } conditional - when bag.Identifier.Text is "m" or "oldM": + case ConditionalAccessExpressionSyntax { Expression: IdentifierNameSyntax bagId } conditional + when bagId.Identifier.Text == bag || bagId.Identifier.Text == oldBag: { var binding = conditional.WhenNotNull .DescendantNodesAndSelf() @@ -331,6 +968,29 @@ private static IEnumerable ModifierNames(SyntaxNode node) /// reset content slots (Content, Child, Source) whose correct empty /// state really is a written null, so they are not subject to this rule. /// + /// + /// The boundary is located through Roslyn syntax nodes, not a text scan, and that is + /// load-bearing rather than stylistic. Any text form — IndexOf("switch (fe)") or an + /// anchored ^\s*switch regex alike — can be made to match inside a comment, which + /// silently truncates the region and turns every absence-shaped assertion over it vacuous + /// while still reporting green. A line comment defeats the unanchored form and a block + /// comment whose inner line begins with the dispatch text defeats the anchored one; a + /// cannot be forged by a comment of any shape. + /// Do not "simplify" this back to a string search. + /// + /// Closing the forgery route does not make the presence-shaped detectors redundant, and + /// they must not be deleted on that reasoning. The two halves guard different things: the + /// presence pins guard this region's scope (a truncated region makes every + /// absence-shaped assertion pass more readily, so it goes vacuous without failing), and the + /// absence scan guards the pin list's closed world (a pin list only knows the names + /// someone thought to write down). Neither subsumes the other. The presence half lives in + /// here, and in + /// Every_TrappedProperty_Is_Reset_In_CleanElement, + /// Every_TrappedAttachedProperty_Is_Reset_In_CleanElement and + /// Attached_Reset_Scan_Sees_Every_Owner_The_Table_Names in + /// — four detectors across two files. + /// + /// private static string ReadCleanElementCommonBlock(out string paramName) { var root = RepoRootFinder.FindRepoRoot(); @@ -339,16 +999,29 @@ private static string ReadCleanElementCommonBlock(out string paramName) Assert.True(File.Exists(file), $"ElementPool.cs not found at {file}"); var source = File.ReadAllText(file); - var signature = Regex.Match(source, @"static\s+void\s+CleanElement\s*\(\s*FrameworkElement\s+(\w+)\s*\)"); - Assert.True(signature.Success, "Could not locate CleanElement(FrameworkElement) in ElementPool.cs"); - paramName = signature.Groups[1].Value; + var method = CSharpSyntaxTree.ParseText(source).GetRoot() + .DescendantNodes() + .OfType() + .FirstOrDefault(candidate => + candidate.Identifier.ValueText == "CleanElement" + && candidate.Modifiers.Any(SyntaxKind.StaticKeyword) + && candidate.ParameterList.Parameters.Count == 1 + && candidate.ParameterList.Parameters[0].Type?.ToString() + .EndsWith("FrameworkElement", StringComparison.Ordinal) == true); + Assert.True(method is not null, "Could not locate static CleanElement(FrameworkElement) in ElementPool.cs"); + + var body = method!.Body; + Assert.True(body is not null, "CleanElement no longer has a block body — the FE-common region is undefined."); - var braceStart = source.IndexOf('{', signature.Index + signature.Length); - Assert.True(braceStart > signature.Index, "CleanElement opening brace not found"); + paramName = method.ParameterList.Parameters[0].Identifier.ValueText; + var governingName = paramName; - var switchStart = source.IndexOf($"switch ({paramName})", braceStart, StringComparison.Ordinal); - Assert.True(switchStart > braceStart, $"CleanElement layout changed — no 'switch ({paramName})' boundary found."); + var dispatch = body!.DescendantNodes() + .OfType() + .FirstOrDefault(candidate => candidate.Expression is IdentifierNameSyntax governing + && governing.Identifier.ValueText == governingName); + Assert.True(dispatch is not null, $"CleanElement layout changed — no 'switch ({governingName})' boundary found."); - return source[braceStart..switchStart]; + return source[body.OpenBraceToken.SpanStart..dispatch!.SpanStart]; } }