Skip to content

Commit 865d518

Browse files
authored
Merge pull request #128 from PhysShell/claude/oun-net-html-analyzer-drff2t
audit(xaml): XAML100 — extend resource-hoist to Styles/templates (deep signature)
2 parents e2ad2dd + 57ed39f commit 865d518

2 files changed

Lines changed: 107 additions & 18 deletions

File tree

‎audit/static/tools/xaml_check.py‎

Lines changed: 106 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)
@@ -131,6 +139,7 @@ class Node:
131139
line: int
132140
children: list[Node] = field(default_factory=list)
133141
parent: Node | None = None
142+
text: str = "" # accumulated character data (used by the deep XAML100 signature)
134143

135144
def local(self) -> str:
136145
"""The unqualified element name: ``controls:DataGrid`` -> ``DataGrid``;
@@ -190,8 +199,16 @@ def end(_name: str) -> None:
190199
if stack:
191200
stack.pop()
192201

202+
def chardata(data: str) -> None:
203+
# expat may deliver a run of text in several pieces; accumulate on the open
204+
# element. Used by the deep XAML100 signature so templates that differ only
205+
# in text (<TextBlock>OK</> vs Cancel) are not treated as identical.
206+
if stack:
207+
stack[-1].text += data
208+
193209
parser.StartElementHandler = start
194210
parser.EndElementHandler = end
211+
parser.CharacterDataHandler = chardata
195212
try:
196213
parser.Parse(text, True)
197214
except xml.parsers.expat.ExpatError:
@@ -396,24 +413,47 @@ def _scope_owner(rd: Node) -> str:
396413
return "root"
397414

398415

416+
def _is_xkey(name: str) -> bool:
417+
"""The XAML resource-key directive ``x:Key`` (any prefix bound to the xaml
418+
namespace) — but NOT a CLR ``Key`` property such as ``KeyBinding.Key``, which is a
419+
real value that must stay in the signature."""
420+
return ":" in name and name.rsplit(":", 1)[-1] == "Key"
421+
422+
423+
def _deep_resource_sig(node: Node) -> tuple[Any, ...]:
424+
"""A *recursive* structural signature: the element's tag (sans namespace prefix,
425+
keeping the property-element dotted form), its attributes (excluding only the
426+
resource directive ``x:Key`` — a descendant CLR ``Key`` like ``KeyBinding Key=...``
427+
is kept), its trimmed character data, and the signatures of all its children in
428+
document order. Two resources share this only when their entire subtree —
429+
elements, attribute values AND text — is structurally identical, so a
430+
`Style`/`ControlTemplate` is matched on its actual setters/triggers/template/text,
431+
not just "has Setter children". Child order is significant (a conservative choice:
432+
only literal duplicates flag)."""
433+
head = node.tag.split(":", 1)[-1]
434+
attrs = tuple(sorted((k, v) for k, v in node.attrib.items() if not _is_xkey(k)))
435+
kids = tuple(_deep_resource_sig(c) for c in node.children)
436+
return (head, attrs, kids, node.text.strip())
437+
438+
399439
def _rule_resource_hoist(root: Node, avalonia: bool,
400440
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."""
441+
"""XAML100 — a heavy keyed resource (Freezable brush/geometry/transform/image, or a
442+
``Style``/template) declared in several **control-local** ``<X.Resources>`` scopes
443+
with the same *deep* structure: each copy is a separate object multiplying working
444+
set across siblings, when one shared resource at window/app scope would do (the
445+
"52x52 Brush collapse" of the design note). Equivalence is the full-subtree
446+
``_deep_resource_sig``, so a `Style`/template only collapses with a structurally
447+
identical twin (same setters/values), never merely a same-shaped one. Resources
448+
already at a shared (root/window/app) scope are the hoist *target*, not a finding."""
409449
by_sig: dict[tuple[Any, ...], list[Node]] = {}
410450
for rd in _resource_dictionaries(root):
411451
if _scope_owner(rd) in TOP_LEVEL_SCOPES:
412452
continue # already a shared scope — the place to hoist *to*
413453
for _key, c in _keyed_resources(rd):
414-
if c.type_name() not in FREEZABLE_TYPES:
454+
if c.type_name() not in HOISTABLE_RESOURCE_TYPES:
415455
continue
416-
sig = _inline_freezable_sig(c) # type + non-key attrs + child types
456+
sig = _deep_resource_sig(c) # full subtree: tag + non-key attrs + children
417457
if not sig[1] and not sig[2]:
418458
continue # empty/defaulted element — nothing meaningful to share
419459
by_sig.setdefault(sig, []).append(c)
@@ -1037,6 +1077,55 @@ def rules(text: str) -> dict[str, XamlFinding]:
10371077
check("XAML100" not in rules(distinct),
10381078
"XAML100 false positive: structurally distinct local resources are not duplicates")
10391079

1080+
# XAML100 for Styles — the deep signature: an IDENTICAL style in two local scopes
1081+
# is a duplicate, but two styles with different Setter values are NOT.
1082+
def _two_styles(setter1: str, setter2: str) -> str:
1083+
def blk(owner: str, setter: str) -> str:
1084+
return (f' <{owner}><{owner}.Resources>\n'
1085+
' <Style x:Key="s" TargetType="Button">\n'
1086+
f' <Setter Property="Background" Value="{setter}" />\n'
1087+
' </Style>\n'
1088+
f' </{owner}.Resources></{owner}>\n')
1089+
return (f'<UserControl {_WPF_NS}>\n <Grid>\n'
1090+
+ blk("Border", setter1) + blk("StackPanel", setter2)
1091+
+ ' </Grid>\n</UserControl>\n')
1092+
check("XAML100" in rules(_two_styles("Red", "Red")),
1093+
"XAML100 must flag an identical Style duplicated across control-local scopes")
1094+
check("XAML100" not in rules(_two_styles("Red", "Blue")),
1095+
"XAML100 false positive: Styles with different Setter values are not duplicates "
1096+
"(deep structural signature)")
1097+
1098+
# Deep signature must include character data: two DataTemplates that differ ONLY in
1099+
# text are not duplicates; identical text still collapses (recall preserved).
1100+
def _two_templates(text1: str, text2: str) -> str:
1101+
def blk(owner: str, txt: str) -> str:
1102+
return (f' <{owner}><{owner}.Resources>\n'
1103+
f' <DataTemplate x:Key="t"><TextBlock Text="x">{txt}</TextBlock>'
1104+
'</DataTemplate>\n'
1105+
f' </{owner}.Resources></{owner}>\n')
1106+
return (f'<UserControl {_WPF_NS}>\n <Grid>\n'
1107+
+ blk("Border", text1) + blk("StackPanel", text2)
1108+
+ ' </Grid>\n</UserControl>\n')
1109+
check("XAML100" not in rules(_two_templates("OK", "Cancel")),
1110+
"XAML100 false positive: templates differing only in text are not duplicates")
1111+
check("XAML100" in rules(_two_templates("OK", "OK")),
1112+
"XAML100 must still flag templates that are identical incl. text")
1113+
1114+
# The x:Key exclusion must be prefix-aware: a CLR `Key` (e.g. KeyBinding.Key) is a
1115+
# real value, so templates differing only by it are NOT duplicates.
1116+
kb = ('<UserControl ' + _WPF_NS + '>\n <Grid>\n'
1117+
' <Border><Border.Resources><Style x:Key="s" TargetType="Window">\n'
1118+
' <Setter Property="InputBindings"><Setter.Value>\n'
1119+
' <KeyBinding Key="Enter" /></Setter.Value></Setter>\n'
1120+
' </Style></Border.Resources></Border>\n'
1121+
' <StackPanel><StackPanel.Resources><Style x:Key="s2" TargetType="Window">\n'
1122+
' <Setter Property="InputBindings"><Setter.Value>\n'
1123+
' <KeyBinding Key="Escape" /></Setter.Value></Setter>\n'
1124+
' </Style></StackPanel.Resources></StackPanel>\n'
1125+
' </Grid>\n</UserControl>\n')
1126+
check("XAML100" not in rules(kb),
1127+
"XAML100 false positive: descendant CLR Key (KeyBinding Key=) must stay in the signature")
1128+
10401129
# Implicit <X.Resources> dictionary (the common WPF syntax, no <ResourceDictionary>
10411130
# wrapper) must feed the keyed-resource rules — else XAML101/102/106 miss most files.
10421131
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)