|
27 | 27 | perf/lifetime axis that WpfAnalyzers / PropertyChangedAnalyzers do **not** cover — |
28 | 28 | we deliberately do not re-implement their correctness rules: |
29 | 29 |
|
30 | | - XAML100 ResourceShouldBeHoisted (cat 9) Freezable keyed in N local scopes |
| 30 | + XAML100 ResourceShouldBeHoisted (cat 9) Freezable/Style/template dup'd per-scope |
31 | 31 | XAML101 DuplicateStatelessConverterResource (cat 9) per-instance resource churn |
32 | 32 | XAML102 DynamicResourceLikelyStatic (cat 9) WPF-only, deferred-lookup cost |
33 | 33 | XAML103 SuspiciousSharedFalse (cat 9) WPF-only, x:Shared opt-out |
|
41 | 41 | XAML112 TemplateBindingOpportunity (cat 9) cheaper compiled binding available |
42 | 42 | XAML113 InlineFreezableDuplication (cat 9) identical inline brush/geometry |
43 | 43 |
|
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. |
50 | 50 |
|
51 | 51 | WPF-only rules (XAML102/103/106) are skipped on Avalonia ``.axaml`` because the |
52 | 52 | ``DynamicResource`` / ``x:Shared`` / ``Freezable`` semantics differ or do not exist |
|
95 | 95 | # the document root and the window/app/page-level dictionaries (XAML100). |
96 | 96 | TOP_LEVEL_SCOPES = {"root", "Window", "UserControl", "Application", "Page", |
97 | 97 | "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 | +} |
98 | 106 |
|
99 | 107 | # Binding markers for XAML108 (per-keystroke source updates). |
100 | 108 | _TWOWAY_RE = re.compile(r"Mode\s*=\s*TwoWay", re.IGNORECASE) |
@@ -131,6 +139,7 @@ class Node: |
131 | 139 | line: int |
132 | 140 | children: list[Node] = field(default_factory=list) |
133 | 141 | parent: Node | None = None |
| 142 | + text: str = "" # accumulated character data (used by the deep XAML100 signature) |
134 | 143 |
|
135 | 144 | def local(self) -> str: |
136 | 145 | """The unqualified element name: ``controls:DataGrid`` -> ``DataGrid``; |
@@ -190,8 +199,16 @@ def end(_name: str) -> None: |
190 | 199 | if stack: |
191 | 200 | stack.pop() |
192 | 201 |
|
| 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 | + |
193 | 209 | parser.StartElementHandler = start |
194 | 210 | parser.EndElementHandler = end |
| 211 | + parser.CharacterDataHandler = chardata |
195 | 212 | try: |
196 | 213 | parser.Parse(text, True) |
197 | 214 | except xml.parsers.expat.ExpatError: |
@@ -396,24 +413,47 @@ def _scope_owner(rd: Node) -> str: |
396 | 413 | return "root" |
397 | 414 |
|
398 | 415 |
|
| 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 | + |
399 | 439 | def _rule_resource_hoist(root: Node, avalonia: bool, |
400 | 440 | 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.""" |
409 | 449 | by_sig: dict[tuple[Any, ...], list[Node]] = {} |
410 | 450 | for rd in _resource_dictionaries(root): |
411 | 451 | if _scope_owner(rd) in TOP_LEVEL_SCOPES: |
412 | 452 | continue # already a shared scope — the place to hoist *to* |
413 | 453 | 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: |
415 | 455 | 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 |
417 | 457 | if not sig[1] and not sig[2]: |
418 | 458 | continue # empty/defaulted element — nothing meaningful to share |
419 | 459 | by_sig.setdefault(sig, []).append(c) |
@@ -1037,6 +1077,55 @@ def rules(text: str) -> dict[str, XamlFinding]: |
1037 | 1077 | check("XAML100" not in rules(distinct), |
1038 | 1078 | "XAML100 false positive: structurally distinct local resources are not duplicates") |
1039 | 1079 |
|
| 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 | + |
1040 | 1129 | # Implicit <X.Resources> dictionary (the common WPF syntax, no <ResourceDictionary> |
1041 | 1130 | # wrapper) must feed the keyed-resource rules — else XAML101/102/106 miss most files. |
1042 | 1131 | implicit = (f'<Window {_WPF_NS}>\n' |
|
0 commit comments