Skip to content

Commit 57ed39f

Browse files
committed
audit(xaml): XAML100 deep signature — capture text + precise x:Key exclusion (review)
Two false-positive fixes from the Codex/CodeRabbit review on PR #128's deep template signature: - Capture character data. Node never stored text, so the deep signature treated <DataTemplate><TextBlock>OK</> and ...Cancel... as identical and XAML100 would flag text-different templates as duplicates. Added Node.text + an expat CharacterDataHandler (accumulates across split runs), and the trimmed text is now part of _deep_resource_sig. - Make the x:Key exclusion prefix-aware. The signature dropped every attribute whose local name is "Key", not just the resource directive x:Key — so a descendant CLR `KeyBinding Key="Enter"` vs "Escape" was erased, collapsing non-identical templates. _is_xkey now excludes only a prefixed `x:Key`; a bare CLR `Key` stays in the signature. Attribute names are kept raw (prefix included) for fidelity. Selftest grows to 42: templates differing only in text are not duplicates (identical text still collapses); a descendant KeyBinding Key keeps templates distinct. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015zoG4YNCUf7RA5r8GAXMmb
1 parent 371116b commit 57ed39f

1 file changed

Lines changed: 57 additions & 8 deletions

File tree

‎audit/static/tools/xaml_check.py‎

Lines changed: 57 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ class Node:
139139
line: int
140140
children: list[Node] = field(default_factory=list)
141141
parent: Node | None = None
142+
text: str = "" # accumulated character data (used by the deep XAML100 signature)
142143

143144
def local(self) -> str:
144145
"""The unqualified element name: ``controls:DataGrid`` -> ``DataGrid``;
@@ -198,8 +199,16 @@ def end(_name: str) -> None:
198199
if stack:
199200
stack.pop()
200201

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+
201209
parser.StartElementHandler = start
202210
parser.EndElementHandler = end
211+
parser.CharacterDataHandler = chardata
203212
try:
204213
parser.Parse(text, True)
205214
except xml.parsers.expat.ExpatError:
@@ -404,18 +413,27 @@ def _scope_owner(rd: Node) -> str:
404413
return "root"
405414

406415

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+
407423
def _deep_resource_sig(node: Node) -> tuple[Any, ...]:
408424
"""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)."""
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)."""
414433
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"))
434+
attrs = tuple(sorted((k, v) for k, v in node.attrib.items() if not _is_xkey(k)))
417435
kids = tuple(_deep_resource_sig(c) for c in node.children)
418-
return (head, attrs, kids)
436+
return (head, attrs, kids, node.text.strip())
419437

420438

421439
def _rule_resource_hoist(root: Node, avalonia: bool,
@@ -1077,6 +1095,37 @@ def blk(owner: str, setter: str) -> str:
10771095
"XAML100 false positive: Styles with different Setter values are not duplicates "
10781096
"(deep structural signature)")
10791097

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+
10801129
# Implicit <X.Resources> dictionary (the common WPF syntax, no <ResourceDictionary>
10811130
# wrapper) must feed the keyed-resource rules — else XAML101/102/106 miss most files.
10821131
implicit = (f'<Window {_WPF_NS}>\n'

0 commit comments

Comments
 (0)