Skip to content

Commit b351ea4

Browse files
committed
audit(xaml): add XAML105 MergedDictionaryKeyShadowing (in-file)
Completes the merged-dictionary story (XAML104 = duplicate include) with the key shadowing case: the same x:Key defined in >=2 inline merged dictionaries, or in the primary dictionary AND an inline merged one. The effective value then depends on merge order (WPF: last merged wins, a primary key beats merged ones) — a silent order-dependence that breaks when includes are reordered. In-file only: dictionaries pulled in by Source="..." reference external files this single-file pass can't resolve, so their keys aren't compared (cross-file variant documented as a later slice). FP-safe — only literal same-key collisions flag; a lone key (the normal case) never does. - xaml_check.py: _rule_merged_dict_shadowing, registered in RULES; docstring updated. - taxonomy: XAML105 -> category 9 (merged-dictionary-shadowing). - selftest grows to 47: two inline merged dicts colliding flags; primary+merged collision flags; distinct keys don't; external Source= dicts are not compared. - README + design-note catalogue updated. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015zoG4YNCUf7RA5r8GAXMmb
1 parent 865d518 commit b351ea4

4 files changed

Lines changed: 84 additions & 9 deletions

File tree

‎audit/README.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -131,10 +131,10 @@ python audit/static/run_static.py --selftest # full pipeline end-to-end on fix
131131
- **XAML analyzer (Phase 1, markup-only) — done:** a build-free, stdlib-XML pass
132132
(`static/tools/xaml_check.py`) feeding the same pipeline as a second fact source —
133133
line-preserving parse, the canonical SARIF record, and rules XAML100/101/102/103/104/
134-
106/107/108/109/110/111/112/113 (resource hoisting, virtualization-off, per-keystroke
135-
binding, template complexity, Freezable/x:Shared/DynamicResource/merged-dictionary
136-
perf, image decode-at-full-size, LayoutTransform cost, TemplateBinding opportunities,
137-
and inline Freezable duplication). This makes category 8 (broken virtualization) statically
134+
105/106/107/108/109/110/111/112/113 (resource hoisting, merged-dictionary key shadowing,
135+
virtualization-off, per-keystroke binding, template complexity, Freezable/x:Shared/
136+
DynamicResource/merged-dictionary perf, image decode-at-full-size, LayoutTransform cost,
137+
TemplateBinding opportunities, and inline Freezable duplication). This makes category 8 (broken virtualization) statically
138138
covered, not NO-TOOL. Design + the full rule catalogue, phasing, and the Phase-2
139139
binding-path join: [`../docs/notes/xaml-analyzer-design.md`](../docs/notes/xaml-analyzer-design.md).
140140
- **XAML Phase-2 seam — done:** `static/tools/xaml_facts.py` emits `xaml-facts.json` (resource graph

‎audit/static/taxonomy/categories.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ rules:
6565
"XAML102": {category: 9, name: dynamic-resource-misuse} # DynamicResource for a static key
6666
"XAML103": {category: 9, name: per-instance-resource} # x:Shared=False
6767
"XAML104": {category: 9, name: merged-dictionary-waste} # duplicate merged dict
68+
"XAML105": {category: 9, name: merged-dictionary-shadowing} # order-dependent key collision
6869
"XAML110": {category: 9, name: image-decode} # full-size thumbnail decode
6970
"XAML111": {category: 8, name: layout-cost} # LayoutTransform layout pass
7071
"XAML112": {category: 9, name: template-binding-opportunity} # cheaper compiled binding

‎audit/static/tools/xaml_check.py‎

Lines changed: 78 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
XAML102 DynamicResourceLikelyStatic (cat 9) WPF-only, deferred-lookup cost
3333
XAML103 SuspiciousSharedFalse (cat 9) WPF-only, x:Shared opt-out
3434
XAML104 DuplicateMergedDictionaryInclude (cat 9) wasted load + order ambiguity
35+
XAML105 MergedDictionaryKeyShadowing (cat 9) in-file key collision, order-dependent
3536
XAML106 FreezableResourceShouldFreeze (cat 9) WPF-only, change-notify overhead
3637
XAML107 VirtualizationExplicitlyDisabled (cat 8) virtualization accidentally killed
3738
XAML108 PerKeystrokeBindingWithoutDelay (cat 6) per-keystroke source flooding
@@ -43,10 +44,11 @@
4344
4445
XAML100 covers the recurring heavy-resource case across control-local scopes — both
4546
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.
47+
covers the *in-file* merged-dictionary key collision (inline dictionaries + the
48+
primary); the same shadowing across **external** ``Source=`` dictionaries needs
49+
cross-file resolution and remains a later slice — documented so nothing on the
50+
wishlist quietly falls through. Phase 2 (Roslyn-linked XAML2xx) and Phase 3 (runtime
51+
correlation) live elsewhere per the design note.
5052
5153
WPF-only rules (XAML102/103/106) are skipped on Avalonia ``.axaml`` because the
5254
``DynamicResource`` / ``x:Shared`` / ``Freezable`` semantics differ or do not exist
@@ -401,6 +403,44 @@ def _keyed_resources(rd: Node):
401403
yield key, c
402404

403405

406+
def _rule_merged_dict_shadowing(root: Node, avalonia: bool) -> list[XamlFinding]:
407+
"""XAML105 — the same ``x:Key`` defined in more than one **inline** merged
408+
dictionary (or in the primary dictionary AND an inline merged one): the effective
409+
value then depends on merge order (WPF: last merged wins, and a primary key beats
410+
merged ones), a silent order-dependence that breaks when includes are reordered.
411+
412+
In-file only: dictionaries pulled in by ``Source="..."`` reference external files
413+
this single-file pass can't resolve, so their keys aren't compared (the cross-file
414+
variant is a documented later slice). FP-safe — only literal same-key collisions
415+
flag, and a lone key (the normal case) never does."""
416+
out: list[XamlFinding] = []
417+
for md in root.walk():
418+
if md.local() != "MergedDictionaries" or not md.is_property_element():
419+
continue
420+
host = md.parent # the owning ResourceDictionary / <X.Resources>
421+
# key -> [(where, line)] across the primary dict and each inline merged dict
422+
keymap: dict[str, list[tuple[str, int]]] = {}
423+
if host is not None:
424+
for key, c in _keyed_resources(host):
425+
keymap.setdefault(key, []).append(("primary", c.line))
426+
inline_dicts = [c for c in md.children
427+
if c.type_name() == "ResourceDictionary" and c.attr("Source") is None]
428+
for i, mdict in enumerate(inline_dicts, start=1):
429+
for key, c in _keyed_resources(mdict):
430+
keymap.setdefault(key, []).append((f"merged #{i}", c.line))
431+
432+
for key, occ in keymap.items():
433+
if len(occ) < 2:
434+
continue # the normal case: a key defined once
435+
where = ", ".join(f"{w} (line {ln})" for w, ln in occ)
436+
out.append(XamlFinding(
437+
"XAML105", occ[0][1],
438+
f"resource key '{key}' is defined in {len(occ)} merged/primary scopes "
439+
f"[{where}]; the effective value depends on merge order (last merged "
440+
"wins, primary beats merged) [resource: merged dictionary]"))
441+
return out
442+
443+
404444
def _scope_owner(rd: Node) -> str:
405445
"""The element type that owns a resource dictionary — the nearest ``<X.Resources>``
406446
ancestor (``Grid``, ``Border``, ``DataTemplate`` …), or ``root`` for the document
@@ -725,6 +765,7 @@ def _rule_layout_transform(root: Node, avalonia: bool) -> list[XamlFinding]:
725765

726766
RULES: list[Callable[[Node, bool], list[XamlFinding]]] = [
727767
_rule_resource_hoist,
768+
_rule_merged_dict_shadowing,
728769
_rule_virtualization,
729770
_rule_template_complexity,
730771
_rule_per_keystroke_binding,
@@ -941,6 +982,39 @@ def rules(text: str) -> dict[str, XamlFinding]:
941982
check(r.get("XAML104") and r["XAML104"].line == 5,
942983
"XAML104 must point at the duplicate include (line 5)")
943984

985+
# XAML105 — the same key in two inline merged dictionaries (order-dependent).
986+
shadow = (f'<ResourceDictionary {_WPF_NS}>\n'
987+
' <ResourceDictionary.MergedDictionaries>\n'
988+
' <ResourceDictionary>\n'
989+
' <SolidColorBrush x:Key="accent" Color="Red" />\n'
990+
' </ResourceDictionary>\n'
991+
' <ResourceDictionary>\n'
992+
' <SolidColorBrush x:Key="accent" Color="Blue" />\n'
993+
' </ResourceDictionary>\n'
994+
' </ResourceDictionary.MergedDictionaries>\n'
995+
'</ResourceDictionary>\n')
996+
r = rules(shadow)
997+
check("XAML105" in r, "XAML105 must flag a key defined in two inline merged dictionaries")
998+
check(r.get("XAML105") and "accent" in r["XAML105"].message, "XAML105 must name the key")
999+
# primary key + a merged-dictionary key collision is also shadowing.
1000+
primary = (f'<ResourceDictionary {_WPF_NS}>\n'
1001+
' <SolidColorBrush x:Key="accent" Color="Green" />\n'
1002+
' <ResourceDictionary.MergedDictionaries>\n'
1003+
' <ResourceDictionary>\n'
1004+
' <SolidColorBrush x:Key="accent" Color="Blue" />\n'
1005+
' </ResourceDictionary>\n'
1006+
' </ResourceDictionary.MergedDictionaries>\n'
1007+
'</ResourceDictionary>\n')
1008+
check("XAML105" in rules(primary),
1009+
"XAML105 must flag a primary key shadowed by a merged dictionary")
1010+
# distinct keys across merged dicts -> no collision, no finding.
1011+
nodup = shadow.replace('x:Key="accent" Color="Blue"', 'x:Key="other" Color="Blue"')
1012+
check("XAML105" not in rules(nodup),
1013+
"XAML105 false positive: distinct keys across merged dictionaries do not shadow")
1014+
# external Source dictionaries are not resolved -> not compared (deferred).
1015+
check("XAML105" not in rules(dup),
1016+
"XAML105 must not compare keys of external Source= dictionaries (cross-file deferred)")
1017+
9441018
# XAML101 — duplicate stateless converter across dictionaries.
9451019
conv = (f'<ResourceDictionary {_WPF_NS} xmlns:c="clr-namespace:App.Converters">\n'
9461020
' <c:BoolToVisibilityConverter x:Key="b2v" />\n'

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ offending element's stamped line; a rule that can only locate a file-level issue
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 |
117117
| **XAML104** `DuplicateMergedDictionaryInclude` | same dictionary merged more than once | wasted load + order ambiguity | ~ (Avalonia has merged dicts, diff syntax) |
118-
| **XAML105** `MergedDictionaryKeyShadowing` | key defined in multiple merged dictionaries → effective value depends on include order | "last merged wins, primary beats merged" — silent order dependence | ~ |
118+
| **XAML105** `MergedDictionaryKeyShadowing` ✅ *(in-file)* | key defined in ≥2 **inline** merged dictionaries (or primary + merged) → effective value depends on include order; external `Source=` dictionaries deferred (cross-file) | "last merged wins, primary beats merged" — silent order dependence | ~ |
119119
| **XAML106** `FreezableResourceShouldFreeze` | `Freezable` resource, no bindings/dynamic-resource/animation, missing `PresentationOptions:Freeze="True"` | freezing drops change-notification overhead + working set | ❌ **Freezable is WPF-only** |
120120
| **XAML107** `VirtualizationExplicitlyDisabled` | `IsVirtualizing="False"`, `CanContentScroll="False"` on lists, non-virtualizing `ItemsPanel`, direct/mixed containers | virtualization critical for large item controls; these accidentally kill it | ✅ `VirtualizingStackPanel`/`ItemsRepeater` |
121121
| **XAML108** `PerKeystrokeBindingWithoutDelay` | `TwoWay` + `UpdateSourceTrigger=PropertyChanged` on an editable property with no `Delay` | `Text` defaults to `LostFocus` for a reason; `Delay` exists to avoid per-keystroke flooding | ✅ |

0 commit comments

Comments
 (0)