Skip to content

Commit 371116b

Browse files
committed
audit(xaml): XAML100 — extend resource-hoist to Styles/templates (deep signature)
Follows #124 (XAML100 for Freezables). Styles/templates couldn't use the shallow signature — two unrelated Styles both have `Setter` children, so a shallow type-only sig would collapse them and mis-flag distinct styles as duplicates. - _deep_resource_sig: a recursive full-subtree signature (tag + non-x:Key attrs + ordered child signatures), so a Style/ControlTemplate/DataTemplate only collapses with a structurally identical twin (same setters/values/template), never a merely same-shaped one. Child order is significant (conservative: only literal duplicates flag). - HOISTABLE_RESOURCE_TYPES = Freezables + Style/ControlTemplate/DataTemplate/ HierarchicalDataTemplate/ItemsPanelTemplate; _rule_resource_hoist now uses the deep sig for all of them (Freezable behavior unchanged — a leaf brush's deep sig equals its old shallow sig). - selftest grows to 39: an identical Style duplicated across control-local scopes flags; two Styles with different Setter values do NOT (proves deep equivalence). - docstring + design-note catalogue updated (Style/template no longer deferred). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015zoG4YNCUf7RA5r8GAXMmb
1 parent e2ad2dd commit 371116b

2 files changed

Lines changed: 58 additions & 18 deletions

File tree

‎audit/static/tools/xaml_check.py‎

Lines changed: 57 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
perf/lifetime axis that WpfAnalyzers / PropertyChangedAnalyzers do **not** cover —
2828
we deliberately do not re-implement their correctness rules:
2929
30-
XAML100 ResourceShouldBeHoisted (cat 9) Freezable keyed in N local scopes
30+
XAML100 ResourceShouldBeHoisted (cat 9) Freezable/Style/template dup'd per-scope
3131
XAML101 DuplicateStatelessConverterResource (cat 9) per-instance resource churn
3232
XAML102 DynamicResourceLikelyStatic (cat 9) WPF-only, deferred-lookup cost
3333
XAML103 SuspiciousSharedFalse (cat 9) WPF-only, x:Shared opt-out
@@ -41,12 +41,12 @@
4141
XAML112 TemplateBindingOpportunity (cat 9) cheaper compiled binding available
4242
XAML113 InlineFreezableDuplication (cat 9) identical inline brush/geometry
4343
44-
XAML100 covers the recurring-Freezable case (the same keyed brush/geometry/transform
45-
declared in several control-local scopes); the Style/template variant (deep
46-
structural equivalence) and XAML105 MergedDictionaryKeyShadowing across *external*
47-
dictionaries (cross-file resolution) remain a later slice — documented so nothing on
48-
the wishlist quietly falls through. Phase 2 (Roslyn-linked XAML2xx) and Phase 3
49-
(runtime correlation) live elsewhere per the design note.
44+
XAML100 covers the recurring heavy-resource case across control-local scopes — both
45+
Freezables and Styles/templates (the latter on a full-subtree signature). XAML105
46+
MergedDictionaryKeyShadowing across *external* dictionaries (cross-file resolution)
47+
remains a later slice — documented so nothing on the wishlist quietly falls through.
48+
Phase 2 (Roslyn-linked XAML2xx) and Phase 3 (runtime correlation) live elsewhere per
49+
the design note.
5050
5151
WPF-only rules (XAML102/103/106) are skipped on Avalonia ``.axaml`` because the
5252
``DynamicResource`` / ``x:Shared`` / ``Freezable`` semantics differ or do not exist
@@ -95,6 +95,14 @@
9595
# the document root and the window/app/page-level dictionaries (XAML100).
9696
TOP_LEVEL_SCOPES = {"root", "Window", "UserControl", "Application", "Page",
9797
"NavigationWindow", "ResourceDictionary"}
98+
# Heavy keyed resources worth hoisting when duplicated across control-local scopes
99+
# (XAML100): Freezables (a shallow sig would do) plus Styles/templates (which need the
100+
# DEEP structural signature, since their direct-child types alone — all `Setter` — say
101+
# nothing about the values).
102+
HOISTABLE_RESOURCE_TYPES = FREEZABLE_TYPES | {
103+
"Style", "ControlTemplate", "DataTemplate", "HierarchicalDataTemplate",
104+
"ItemsPanelTemplate",
105+
}
98106

99107
# Binding markers for XAML108 (per-keystroke source updates).
100108
_TWOWAY_RE = re.compile(r"Mode\s*=\s*TwoWay", re.IGNORECASE)
@@ -396,24 +404,38 @@ def _scope_owner(rd: Node) -> str:
396404
return "root"
397405

398406

407+
def _deep_resource_sig(node: Node) -> tuple[Any, ...]:
408+
"""A *recursive* structural signature: the element's tag (sans namespace prefix,
409+
keeping the property-element dotted form), its non-``x:Key`` attributes, and the
410+
signatures of all its children in document order. Two resources share this only
411+
when their entire subtree is structurally identical — so a `Style`/`ControlTemplate`
412+
is matched on its actual setters/triggers/template, not just "has Setter children".
413+
Child order is significant (a conservative choice: only literal duplicates flag)."""
414+
head = node.tag.split(":", 1)[-1]
415+
attrs = tuple(sorted((k.split(":", 1)[-1], v) for k, v in node.attrib.items()
416+
if k.split(":", 1)[-1] != "Key"))
417+
kids = tuple(_deep_resource_sig(c) for c in node.children)
418+
return (head, attrs, kids)
419+
420+
399421
def _rule_resource_hoist(root: Node, avalonia: bool,
400422
min_copies: int = 2) -> list[XamlFinding]:
401-
"""XAML100 — a heavy Freezable resource (brush/geometry/transform/image) declared
402-
with ``x:Key`` in several **control-local** ``<X.Resources>`` scopes with the same
403-
structure: each copy is a separate object multiplying working set across siblings,
404-
when one shared resource at window/app scope would do (the "52x52 Brush collapse"
405-
of the design note). Restricted to Freezables, where the shallow structural
406-
signature is reliable; Styles/templates (deep structural equivalence) are a later
407-
refinement. Resources already at a shared (root/window/app) scope are the hoist
408-
*target*, not a finding."""
423+
"""XAML100 — a heavy keyed resource (Freezable brush/geometry/transform/image, or a
424+
``Style``/template) declared in several **control-local** ``<X.Resources>`` scopes
425+
with the same *deep* structure: each copy is a separate object multiplying working
426+
set across siblings, when one shared resource at window/app scope would do (the
427+
"52x52 Brush collapse" of the design note). Equivalence is the full-subtree
428+
``_deep_resource_sig``, so a `Style`/template only collapses with a structurally
429+
identical twin (same setters/values), never merely a same-shaped one. Resources
430+
already at a shared (root/window/app) scope are the hoist *target*, not a finding."""
409431
by_sig: dict[tuple[Any, ...], list[Node]] = {}
410432
for rd in _resource_dictionaries(root):
411433
if _scope_owner(rd) in TOP_LEVEL_SCOPES:
412434
continue # already a shared scope — the place to hoist *to*
413435
for _key, c in _keyed_resources(rd):
414-
if c.type_name() not in FREEZABLE_TYPES:
436+
if c.type_name() not in HOISTABLE_RESOURCE_TYPES:
415437
continue
416-
sig = _inline_freezable_sig(c) # type + non-key attrs + child types
438+
sig = _deep_resource_sig(c) # full subtree: tag + non-key attrs + children
417439
if not sig[1] and not sig[2]:
418440
continue # empty/defaulted element — nothing meaningful to share
419441
by_sig.setdefault(sig, []).append(c)
@@ -1037,6 +1059,24 @@ def rules(text: str) -> dict[str, XamlFinding]:
10371059
check("XAML100" not in rules(distinct),
10381060
"XAML100 false positive: structurally distinct local resources are not duplicates")
10391061

1062+
# XAML100 for Styles — the deep signature: an IDENTICAL style in two local scopes
1063+
# is a duplicate, but two styles with different Setter values are NOT.
1064+
def _two_styles(setter1: str, setter2: str) -> str:
1065+
def blk(owner: str, setter: str) -> str:
1066+
return (f' <{owner}><{owner}.Resources>\n'
1067+
' <Style x:Key="s" TargetType="Button">\n'
1068+
f' <Setter Property="Background" Value="{setter}" />\n'
1069+
' </Style>\n'
1070+
f' </{owner}.Resources></{owner}>\n')
1071+
return (f'<UserControl {_WPF_NS}>\n <Grid>\n'
1072+
+ blk("Border", setter1) + blk("StackPanel", setter2)
1073+
+ ' </Grid>\n</UserControl>\n')
1074+
check("XAML100" in rules(_two_styles("Red", "Red")),
1075+
"XAML100 must flag an identical Style duplicated across control-local scopes")
1076+
check("XAML100" not in rules(_two_styles("Red", "Blue")),
1077+
"XAML100 false positive: Styles with different Setter values are not duplicates "
1078+
"(deep structural signature)")
1079+
10401080
# Implicit <X.Resources> dictionary (the common WPF syntax, no <ResourceDictionary>
10411081
# wrapper) must feed the keyed-resource rules — else XAML101/102/106 miss most files.
10421082
implicit = (f'<Window {_WPF_NS}>\n'

‎docs/notes/xaml-analyzer-design.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ offending element's stamped line; a rule that can only locate a file-level issue
110110

111111
| Rule | What it flags | Doc rationale | Avalonia |
112112
|---|---|---|---|
113-
| **XAML100** `ResourceShouldBeHoisted` ✅ *(Freezables)* | heavy shared resource (Brush/Geometry/Transform/Image — Style/template deferred) keyed identically in ≥2 control-local `.Resources` scopes | per-instance control resources multiply working set; app/window scope shares (the 52×52 Brush collapse) | ✅ scope model maps |
113+
| **XAML100** `ResourceShouldBeHoisted` ✅ | heavy shared resource (Brush/Geometry/Transform/Image, or Style/template via a full-subtree signature) keyed identically in ≥2 control-local `.Resources` scopes | per-instance control resources multiply working set; app/window scope shares (the 52×52 Brush collapse) | ✅ scope model maps |
114114
| **XAML101** `DuplicateStatelessConverterResource` | identical stateless converter declared in many local dictionaries | converters are normally one shared instance; duplication is churn | ✅ |
115115
| **XAML102** `DynamicResourceLikelyStatic` | `DynamicResource` for an app-local, lexically-stable, non-theme/system key | StaticResource recommended unless runtime-mutated; dynamic carries deferred lookup cost | ❌ Avalonia DynamicResource semantics differ |
116116
| **XAML103** `SuspiciousSharedFalse` | `x:Shared="False"` on converters/styles/brushes outside documented exceptions | resources shared by default; `x:Shared=false` is the deliberate opt-out | ❌ WPF-only attribute |

0 commit comments

Comments
 (0)