Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

quality: C++ COM heritage + visibility, MVVM synthesis, XAML resource dicts (#186)

Raghav Chamadiya484966257b55
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index 906e9952c..ddb8ac706 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -52,7 +52,9 @@ All eight languages support:
- Docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc, Doxygen, XML doc)
- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection; ASP.NET controllers / minimal API / EF Core DbContext for C#; Spring Boot DI + `@Bean` factories for Java/Kotlin; Rails routes + ActiveRecord relationships; Laravel routes + service providers + Eloquent; TYPO3 convention files (`ext_localconf.php`, `Configuration/TCA/*`, `JavaScriptModules.php` registrations) for PHP; Express `app.use(router)` + NestJS `@Module` arrays; Gin/Echo/Chi router → handler files for Go; Axum/Actix `.route` → handler files for Rust)
- Per-language dynamic-hint extractors (Django/Pytest/Node for Python+JS/TS; .NET DI/Activator/InternalsVisibleTo for C#; Spring `getBean`/`@Bean` factories for Java/Kotlin; Ruby `send`/`const_get`/`define_method`/`delegate`; PHP `call_user_func`/`ReflectionClass`/container `get`; Scala `Class.forName`/`given`/`implicit val`; Swift `NSClassFromString`/`Selector`/`#selector`/KVC; C function-pointer assignment + `dlopen`/`dlsym`; Luau `game:GetService`/`setmetatable __index`; Go `reflect.TypeOf`/`plugin.Open`/`plugin.Lookup`)
-- For C# only: MSBuild project graph (`<ProjectReference>` / `<PackageReference>`), namespace → file mapping across projects, `global using` / `using static` / `using alias` propagation, ASP.NET HTTP and gRPC-dotnet contract extraction in workspace mode, cross-repo `<ProjectReference>` and internal-NuGet detection, host-builder extension method resolution (`app.MapCatalogApi()` / `services.AddCatalogServices()` on any C# repo, not just ASP.NET), `nameof(Type)` references resolved as dynamic uses, and local `var x = new T()` property reads bound to the defining file
+- For C# only: MSBuild project graph (`<ProjectReference>` / `<PackageReference>`), namespace → file mapping across projects, `global using` / `using static` / `using alias` propagation, ASP.NET HTTP and gRPC-dotnet contract extraction in workspace mode, cross-repo `<ProjectReference>` and internal-NuGet detection, host-builder extension method resolution (`app.MapCatalogApi()` / `services.AddCatalogServices()` on any C# repo, not just ASP.NET), `nameof(Type)` references resolved as dynamic uses, local `var x = new T()` property reads bound to the defining file, and CommunityToolkit MVVM source-generator synthesis (`[ObservableProperty]` fields → PascalCase property, `[RelayCommand]` methods → `<Name>Command`)
+- For C/C++ only: visibility tracked from access specifiers (`public:` / `private:` / `protected:`), `static` file-scope storage class, and export attributes (`__declspec(dllexport)`, `__attribute__((visibility("default")))`); COM / I-prefixed bases emit `implements` edges (rest are `extends`); Windows DLL entry points (`DllMain`, `DllGetClassObject`, `DllCanUnloadNow`, `DllRegisterServer`, `DllUnregisterServer`, `DllGetActivationFactory`) are never flagged as dead
+- For XAML only: `<ResourceDictionary Source="..."/>` and `MergedDictionaries` entries resolve across `pack://application:,,,/`, `ms-appx:///`, repo-rooted and relative URIs, emitting xaml→xaml `dynamic_uses` edges
### Good
@@ -293,6 +295,15 @@ without touching the shared pipeline files:
- `languages/<lang>_member_reads.py` --- emit `reads` edges for
property / member access. Used today for C# `var x = new T()`
locals; the same shape applies to any statically-typed language.
+- `extractors/synthetic_symbols.py` --- recognise source-generator
+ attributes and emit the symbols the generator would produce
+ at compile time. Used today for CommunityToolkit MVVM
+ (`[ObservableProperty]`, `[RelayCommand]`); the same shape fits
+ Java Lombok, Kotlin `@Parcelize`, etc.
+- `extractors/visibility.py::refine_<lang>_visibility` --- node-aware
+ visibility refinement for languages where access is dictated by AST
+ context (C/C++ access specifiers, storage class, export attributes)
+ rather than modifier text alone.
---
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 66fe29104..2c3ffbee5 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -93,6 +93,15 @@ _ENTRY_POINT_SYMBOL_NAMES: frozenset[str] = frozenset({
"Startup", # ASP.NET Core legacy
"__module__", # synthetic per-file module anchor
"_start", # C runtime
+ # ---- Windows DLL / COM entry points -----------------------------
+ # Invoked by the Windows loader or COM runtime; never referenced
+ # statically from user code.
+ "DllMain",
+ "DllGetClassObject",
+ "DllCanUnloadNow",
+ "DllRegisterServer",
+ "DllUnregisterServer",
+ "DllGetActivationFactory",
})
from .dynamic_markers import find_dynamic_edge_files, find_dynamic_import_files
from .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport
@@ -416,6 +425,12 @@ class DeadCodeAnalyzer:
continue
if sym_name in _ENTRY_POINT_SYMBOL_NAMES:
continue
+ # Explicit language-level export markers (C/C++
+ # ``__declspec(dllexport)``, GCC ``visibility("default")``)
+ # signal "called from outside this translation unit /
+ # binary" — never observable in the static graph.
+ if sym.get("is_exported_symbol"):
+ continue
# Names that contain a dot are namespace path fragments
# (e.g. ``eShop.ClientApp``), not user-visible exports.
if "." in sym_name:
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/xaml.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/xaml.py
index 21318d4a5..37621370d 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/xaml.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/xaml.py
@@ -68,6 +68,14 @@ _XTYPE_RE = re.compile(
re.IGNORECASE,
)
+# <ResourceDictionary Source="..."/> — both standalone and inside a
+# <ResourceDictionary.MergedDictionaries> block. Match attribute order
+# agnostically; only the Source value is needed.
+_RESOURCE_DICT_SOURCE_RE = re.compile(
+ r"""<ResourceDictionary\b[^>]*?\bSource\s*=\s*["']([^"']+)["']""",
+ re.IGNORECASE,
+)
+
class XamlDynamicHints(DynamicHintExtractor):
"""Emit ``dynamic_uses`` edges from XAML files to the C# types they bind to."""
@@ -85,12 +93,19 @@ class XamlDynamicHints(DynamicHintExtractor):
# here keeps XAML resolution cross-project / cross-repo
# consistent with how `using` directives resolve.
type_map = _load_type_map(repo_root)
- if not type_map:
- return []
+ # Even without a .NET project we can still resolve xaml→xaml
+ # ResourceDictionary references, so don't early-exit on an empty
+ # type_map — only the C# binding pass is gated on it.
edges: list[DynamicEdge] = []
repo_root_resolved = repo_root.resolve()
+ # Build a {basename → [rel_paths]} index of every XAML in the
+ # repo for absolute-source / pack-URI lookups. The relative-source
+ # path resolves against the parent of the consuming XAML, so it
+ # doesn't need the index.
+ xaml_by_basename = _index_xaml_by_basename(xaml_files, repo_root_resolved)
+
for xaml_path in xaml_files:
try:
rel = xaml_path.resolve().relative_to(repo_root_resolved).as_posix()
@@ -101,28 +116,43 @@ class XamlDynamicHints(DynamicHintExtractor):
except OSError:
continue
- prefix_to_namespace = _collect_prefix_namespaces(text)
- type_refs = _extract_type_references(text, prefix_to_namespace)
-
- for type_name in type_refs:
- targets = type_map.get(type_name)
- if not targets:
- continue
- for target_abs in targets:
- try:
- target_rel = target_abs.resolve().relative_to(repo_root_resolved).as_posix()
- except ValueError:
- continue
- if target_rel == rel:
+ if type_map:
+ prefix_to_namespace = _collect_prefix_namespaces(text)
+ type_refs = _extract_type_references(text, prefix_to_namespace)
+ for type_name in type_refs:
+ targets = type_map.get(type_name)
+ if not targets:
continue
- edges.append(
- DynamicEdge(
- source=rel,
- target=target_rel,
- edge_type="dynamic_uses",
- hint_source=f"{self.name}:binding",
+ for target_abs in targets:
+ try:
+ target_rel = target_abs.resolve().relative_to(repo_root_resolved).as_posix()
+ except ValueError:
+ continue
+ if target_rel == rel:
+ continue
+ edges.append(
+ DynamicEdge(
+ source=rel,
+ target=target_rel,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:binding",
+ )
)
+
+ # ResourceDictionary cross-references — pure xaml→xaml.
+ for target_rel in _resolve_resource_dictionary_sources(
+ text, rel, xaml_by_basename
+ ):
+ if target_rel == rel:
+ continue
+ edges.append(
+ DynamicEdge(
+ source=rel,
+ target=target_rel,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:resource_dictionary",
)
+ )
return edges
@@ -178,6 +208,106 @@ def _extract_type_references(text: str, prefix_to_ns: dict[str, str]) -> set[str
return names
+def _index_xaml_by_basename(
+ xaml_files: list[Path], repo_root_resolved: Path
+) -> dict[str, list[str]]:
+ """Return a ``{basename.lower(): [repo-relative paths]}`` index."""
+ out: dict[str, list[str]] = {}
+ for path in xaml_files:
+ try:
+ rel = path.resolve().relative_to(repo_root_resolved).as_posix()
+ except ValueError:
+ continue
+ out.setdefault(path.name.lower(), []).append(rel)
+ return out
+
+
+# Strip leading pack URI / WinUI prefixes from a Source attribute value.
+# Returns a path that's either repo-relative (leading "/") or
+# source-file-relative. Returns ``None`` if the URI is opaque
+# (HTTP/HTTPS or unrecognised scheme).
+_PACK_URI_PREFIX_RE = re.compile(
+ r"""^pack://application:,,,/(?:[^/]+;component/)?""", re.IGNORECASE
+)
+_MS_APPX_PREFIX_RE = re.compile(r"""^ms-appx:///?""", re.IGNORECASE)
+
+
+def _normalise_source_uri(raw: str) -> str | None:
+ """Reduce a XAML ``Source`` URI to a plain path.
+
+ Recognised forms (case-insensitive):
+
+ * ``pack://application:,,,/Assembly;component/Themes/Light.xaml`` → ``Themes/Light.xaml``
+ * ``pack://application:,,,/Themes/Light.xaml`` → ``Themes/Light.xaml``
+ * ``ms-appx:///Themes/Light.xaml`` → ``Themes/Light.xaml``
+ * ``/Themes/Light.xaml`` → ``Themes/Light.xaml`` (treated as repo-rooted)
+ * ``Themes/Light.xaml`` → ``Themes/Light.xaml`` (relative to caller)
+
+ Returns ``None`` for HTTP-style absolute URIs.
+ """
+ raw = raw.strip()
+ if not raw:
+ return None
+ lower = raw.lower()
+ if lower.startswith(("http://", "https://")):
+ return None
+ raw = _PACK_URI_PREFIX_RE.sub("", raw)
+ raw = _MS_APPX_PREFIX_RE.sub("", raw)
+ return raw.lstrip("/")
+
+
+def _resolve_resource_dictionary_sources(
+ text: str, source_rel: str, xaml_by_basename: dict[str, list[str]]
+) -> list[str]:
+ """Return the list of XAML files referenced from *source_rel*.
+
+ Resolution order, per source:
+ 1. Treat as a path relative to the parent directory of *source_rel*.
+ If a XAML file exists there, use it.
+ 2. Fall back to basename matching across the repo's XAML index.
+ When multiple files share a basename we emit edges to all of
+ them — over-emit beats under-emit for the dead-code use case.
+ """
+ if "<ResourceDictionary" not in text and "<ResourceDictionary" not in text.lower():
+ return []
+ results: list[str] = []
+ seen: set[str] = set()
+ parent_dir = source_rel.rsplit("/", 1)[0] if "/" in source_rel else ""
+ for match in _RESOURCE_DICT_SOURCE_RE.finditer(text):
+ raw = match.group(1)
+ normalised = _normalise_source_uri(raw)
+ if not normalised:
+ continue
+ candidate_rel = (
+ f"{parent_dir}/{normalised}" if parent_dir and not raw.startswith("/") else normalised
+ )
+ candidate_rel = _normpath(candidate_rel)
+ basename = candidate_rel.rsplit("/", 1)[-1].lower()
+ # Repo-wide basename index — accept any match. When the relative
+ # path happens to land on an actual file the index will contain
+ # it; otherwise we still attach to same-named files elsewhere.
+ for hit in xaml_by_basename.get(basename, ()):
+ if hit not in seen:
+ seen.add(hit)
+ results.append(hit)
+ return results
+
+
+def _normpath(path: str) -> str:
+ """Collapse ``..`` segments without touching the filesystem."""
+ parts: list[str] = []
+ for part in path.split("/"):
+ if part in ("", "."):
+ continue
+ if part == ".." and parts:
+ parts.pop()
+ continue
+ if part == "..":
+ continue
+ parts.append(part)
+ return "/".join(parts)
+
+
def _load_type_map(repo_root: Path) -> dict[str, list[Path]]:
"""Return the unqualified-type-name → defining-files map for *repo_root*.
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py
index f5d6aafca..4bdefce05 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py
@@ -1,32 +1,59 @@
-"""C++ heritage extraction."""
+"""C++ heritage extraction.
+
+C++ has no language-level concept of an ``interface`` — every parent
+class lands in the same ``base_class_clause`` node regardless of role.
+For semantic edge fidelity we treat a base as an ``implements``
+relationship when its bare name follows the Microsoft / COM
+``I[A-Z]…`` convention (``IUnknown``, ``IShellExtInit``, etc.). All
+other bases stay ``extends``. This is purely heuristic — the
+downstream interface confidence cap accepts both edge types, so
+mis-classification can't produce false negatives.
+"""
from __future__ import annotations
+import re
+
from tree_sitter import Node
from ...models import HeritageRelation
from ..helpers import node_text
+# ``IFoo`` / ``IShellExtInit`` — COM / Microsoft interface naming
+# convention. Two-letter prefixes like ``IO`` are intentionally
+# excluded by requiring at least one lowercase letter after the
+# second character.
+_INTERFACE_NAME_RE = re.compile(r"^I[A-Z][A-Za-z0-9_]*[a-z][A-Za-z0-9_]*$")
+
+
+def _classify_parent(bare_name: str) -> str:
+ """Return ``"implements"`` for I-prefixed interface-style names, else ``"extends"``."""
+ if _INTERFACE_NAME_RE.match(bare_name):
+ return "implements"
+ return "extends"
+
def _extract_cpp_heritage(
def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
) -> None:
- """C++: class Foo : public Bar, protected Baz."""
+ """C++: class Foo : public Bar, protected IBaz."""
for child in def_node.children:
- if child.type == "base_class_clause":
- for base in child.children:
- if base.type in (":", ","):
- continue
- text = node_text(base, src).strip()
- for prefix in ("public", "protected", "private", "virtual"):
- text = text.removeprefix(prefix).strip()
- bare = text.split("::")[-1].strip()
- if bare:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=bare,
- kind="extends",
- line=line,
- )
- )
+ if child.type != "base_class_clause":
+ continue
+ for base in child.children:
+ if base.type in (":", ","):
+ continue
+ text = node_text(base, src).strip()
+ for prefix in ("public", "protected", "private", "virtual"):
+ text = text.removeprefix(prefix).strip()
+ bare = text.split("::")[-1].strip()
+ if not bare:
+ continue
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=bare,
+ kind=_classify_parent(bare), # type: ignore[arg-type]
+ line=line,
+ )
+ )
diff --git a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols.py
new file mode 100644
index 000000000..8b79b3564
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols.py
@@ -0,0 +1,249 @@
+"""Per-language synthetic-symbol passes.
+
+Some frameworks rely on source generators that emit symbols at compile
+time. Those generated symbols don't appear in the AST of the user's
+source file, but they ARE referenced by name from other code (XAML
+bindings, code-behind, etc.). Without representing them in the symbol
+table, every binding to such a name looks like an unresolved reference
+and the user-visible symbol that "backs" it looks orphaned.
+
+This module synthesises those names directly from the user-authored
+attributes. No filesystem coupling to ``obj/Generated/*.g.cs``.
+
+Supported today (CommunityToolkit.Mvvm):
+ - ``[ObservableProperty] private string _name;`` → property ``Name``
+ - ``[RelayCommand] private void Save() { … }`` → method ``SaveCommand``
+
+The dispatcher is keyed by language and returns extra ``Symbol``
+instances that the parser appends to its main symbol list. Adding a
+new framework's generator support is one function plus one entry in
+``_SYNTHETIC_EXTRACTORS``.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Callable
+from typing import TYPE_CHECKING
+
+from ..models import FileInfo, Symbol
+from .helpers import node_text
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+
+# Match the *bare* attribute name inside ``[Name]`` or ``[Name(args)]``.
+# The grammar nests attributes under ``attribute_list`` / ``attribute``
+# nodes; we look for the bare name text rather than relying on field
+# names so the pass is robust across grammar versions.
+_OBSERVABLE_PROPERTY = "ObservableProperty"
+_RELAY_COMMAND = "RelayCommand"
+
+_FIELD_NAME_TO_PROP_RE = re.compile(r"^_?([A-Za-z])(.*)$")
+
+
+def _pascal_from_field(field_name: str) -> str | None:
+ """Convert ``_name`` / ``m_name`` / ``name`` → ``Name``.
+
+ Returns ``None`` when the result would be empty or non-identifier.
+ """
+ stripped = field_name.lstrip("_")
+ if stripped.startswith("m_"):
+ stripped = stripped[2:]
+ match = _FIELD_NAME_TO_PROP_RE.match(stripped)
+ if not match:
+ return None
+ first, rest = match.groups()
+ return first.upper() + rest
+
+
+def _attribute_names(attr_list_node: Node, src: str) -> set[str]:
+ """Return the set of bare attribute names declared in an ``attribute_list``.
+
+ ``[ObservableProperty]`` → ``{"ObservableProperty"}``.
+ ``[RelayCommand(CanExecute=nameof(CanSave))]`` → ``{"RelayCommand"}``.
+ """
+ names: set[str] = set()
+ for child in attr_list_node.children:
+ if child.type != "attribute":
+ continue
+ # The first ``identifier`` / ``qualified_name`` child is the
+ # attribute's name. Strip any namespace prefix.
+ for sub in child.children:
+ if sub.type in ("identifier", "qualified_name"):
+ text = node_text(sub, src).strip()
+ names.add(text.split(".")[-1])
+ break
+ return names
+
+
+def _csharp_synthetic_symbols(
+ root: Node, src: str, file_info: FileInfo
+) -> list[Symbol]:
+ """Emit synthetic symbols for CommunityToolkit MVVM attributes.
+
+ Walks the file once looking for ``field_declaration`` and
+ ``method_declaration`` nodes; for each, scans preceding
+ ``attribute_list`` children for the trigger attribute.
+ """
+ out: list[Symbol] = []
+ stack: list[Node] = [root]
+ while stack:
+ node = stack.pop()
+ if node.type == "field_declaration":
+ sym = _maybe_observable_property(node, src, file_info)
+ if sym is not None:
+ out.append(sym)
+ elif node.type == "method_declaration":
+ sym = _maybe_relay_command(node, src, file_info)
+ if sym is not None:
+ out.append(sym)
+ stack.extend(node.children)
+ return out
+
+
+def _maybe_observable_property(
+ field_node: Node, src: str, file_info: FileInfo
+) -> Symbol | None:
+ """If *field_node* is ``[ObservableProperty] private T _name;``, synthesise ``Name``."""
+ if not _has_attribute(field_node, _OBSERVABLE_PROPERTY, src):
+ return None
+ # Locate the variable_declarator → identifier for the field name.
+ field_name = _first_field_name(field_node, src)
+ if not field_name:
+ return None
+ prop_name = _pascal_from_field(field_name)
+ if not prop_name or prop_name == field_name:
+ return None
+ parent = _enclosing_type_name(field_node, src)
+ start_line = field_node.start_point[0] + 1
+ end_line = field_node.end_point[0] + 1
+ return _build_synthetic_symbol(
+ name=prop_name,
+ kind="variable", # auto-properties surface as ``variable`` everywhere else
+ signature=f"public T {prop_name} {{ get; set; }}",
+ start_line=start_line,
+ end_line=end_line,
+ file_info=file_info,
+ parent_name=parent,
+ )
+
+
+def _maybe_relay_command(
+ method_node: Node, src: str, file_info: FileInfo
+) -> Symbol | None:
+ """If *method_node* is ``[RelayCommand] void Save() { … }``, synthesise ``SaveCommand``."""
+ if not _has_attribute(method_node, _RELAY_COMMAND, src):
+ return None
+ method_name = _first_method_name(method_node, src)
+ if not method_name:
+ return None
+ command_name = f"{method_name}Command"
+ parent = _enclosing_type_name(method_node, src)
+ start_line = method_node.start_point[0] + 1
+ end_line = method_node.end_point[0] + 1
+ return _build_synthetic_symbol(
+ name=command_name,
+ kind="variable",
+ signature=f"public IRelayCommand {command_name} {{ get; }}",
+ start_line=start_line,
+ end_line=end_line,
+ file_info=file_info,
+ parent_name=parent,
+ )
+
+
+def _has_attribute(node: Node, attr_name: str, src: str) -> bool:
+ for child in node.children:
+ if child.type == "attribute_list" and attr_name in _attribute_names(child, src):
+ return True
+ return False
+
+
+def _first_field_name(field_node: Node, src: str) -> str | None:
+ for child in field_node.children:
+ if child.type == "variable_declaration":
+ for sub in child.children:
+ if sub.type == "variable_declarator":
+ for leaf in sub.children:
+ if leaf.type == "identifier":
+ return node_text(leaf, src).strip()
+ return None
+
+
+def _first_method_name(method_node: Node, src: str) -> str | None:
+ for child in method_node.children:
+ if child.type == "identifier":
+ return node_text(child, src).strip()
+ return None
+
+
+def _enclosing_type_name(node: Node, src: str) -> str | None:
+ ancestor = node.parent
+ while ancestor is not None:
+ if ancestor.type in (
+ "class_declaration",
+ "struct_declaration",
+ "record_declaration",
+ ):
+ name_node = ancestor.child_by_field_name("name")
+ if name_node is not None:
+ return node_text(name_node, src).strip()
+ ancestor = ancestor.parent
+ return None
+
+
+def _build_synthetic_symbol(
+ *,
+ name: str,
+ kind: str,
+ signature: str,
+ start_line: int,
+ end_line: int,
+ file_info: FileInfo,
+ parent_name: str | None,
+) -> Symbol:
+ sym_id = (
+ f"{file_info.path}::{parent_name}::{name}"
+ if parent_name
+ else f"{file_info.path}::{name}"
+ )
+ qualified = (
+ f"{file_info.path}.{parent_name}.{name}"
+ if parent_name
+ else f"{file_info.path}.{name}"
+ )
+ return Symbol(
+ id=sym_id,
+ name=name,
+ qualified_name=qualified,
+ kind=kind, # type: ignore[arg-type]
+ signature=signature,
+ start_line=start_line,
+ end_line=end_line,
+ docstring=None,
+ decorators=[],
+ visibility="public",
+ is_async=False,
+ language=file_info.language,
+ parent_name=parent_name,
+ )
+
+
+_SYNTHETIC_EXTRACTORS: dict[str, Callable[[Node, str, FileInfo], list[Symbol]]] = {
+ "csharp": _csharp_synthetic_symbols,
+}
+
+
+def extract_synthetic_symbols(
+ root: Node, src: str, file_info: FileInfo
+) -> list[Symbol]:
+ """Dispatch to the language-appropriate synthetic-symbol extractor.
+
+ Returns an empty list for languages with no registered extractor.
+ """
+ fn = _SYNTHETIC_EXTRACTORS.get(file_info.language)
+ if fn is None:
+ return []
+ return fn(root, src, file_info)
diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
index 661835af6..c0eac549e 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
@@ -1,8 +1,21 @@
-"""Per-language visibility determination functions."""
+"""Per-language visibility determination functions.
+
+Most languages can determine visibility from a symbol's name + modifier
+text alone (the ``visibility_fn`` shape). C/C++ is the exception: its
+visibility comes from surrounding AST context — ``public:`` / ``private:``
+access specifier siblings inside a class body, ``static`` storage class
+at file scope, or ``__declspec(dllexport)`` / GCC visibility attributes.
+``refine_cpp_visibility`` handles that node-aware refinement; the
+parser calls it after the generic ``visibility_fn`` for C/C++ files.
+"""
from __future__ import annotations
from collections.abc import Callable
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
def py_visibility(name: str, _mods: list[str]) -> str:
@@ -98,6 +111,128 @@ def php_visibility(_name: str, modifier_texts: list[str]) -> str:
return "public"
+# ---------------------------------------------------------------------------
+# C / C++ node-aware visibility refinement
+# ---------------------------------------------------------------------------
+
+_CPP_EXPORT_MARKERS: tuple[str, ...] = (
+ "__declspec(dllexport)",
+ "__declspec( dllexport )",
+ 'visibility("default")',
+ "visibility(\"default\")",
+)
+
+
+def _preceding_access_specifier(def_node: Node) -> str | None:
+ """Walk back through siblings to find the most recent ``access_specifier``.
+
+ Inside a ``field_declaration_list`` (class / struct body), C++ groups
+ members under ``public:`` / ``private:`` / ``protected:`` access
+ specifiers that appear as ordinary siblings. The visibility of a
+ given member is dictated by the most recent specifier before it.
+ """
+ sibling = def_node.prev_sibling
+ while sibling is not None:
+ if sibling.type == "access_specifier":
+ # The specifier's text is "public" / "private" / "protected".
+ children = [c for c in sibling.children if c.is_named or c.type in ("public", "private", "protected")]
+ for c in children:
+ if c.type in ("public", "private", "protected"):
+ return c.type
+ # Fall back to raw text for grammars that don't name the child.
+ return None
+ sibling = sibling.prev_sibling
+ return None
+
+
+def _enclosing_class_default_access(def_node: Node) -> str:
+ """Default access in the enclosing aggregate: ``private`` for class, ``public`` for struct."""
+ ancestor = def_node.parent
+ while ancestor is not None:
+ if ancestor.type == "class_specifier":
+ return "private"
+ if ancestor.type == "struct_specifier":
+ return "public"
+ ancestor = ancestor.parent
+ return "public"
+
+
+def _has_export_marker(def_node: Node, src: str) -> bool:
+ """Return True if any ``__declspec(dllexport)`` / ``visibility("default")`` precedes the def."""
+ # Walk back through siblings and check for attribute / declspec nodes
+ # whose text contains an export marker. The tree-sitter-cpp grammar
+ # exposes these as ``ms_declspec_modifier`` or ``attribute_specifier``
+ # nodes — but textual matching is robust across grammar versions.
+ sibling = def_node.prev_sibling
+ seen = 0
+ while sibling is not None and seen < 4:
+ text = src[sibling.start_byte : sibling.end_byte]
+ if any(marker in text for marker in _CPP_EXPORT_MARKERS):
+ return True
+ sibling = sibling.prev_sibling
+ seen += 1
+ # Also check the def_node's own leading children — some grammars
+ # nest the declspec inside the function_definition.
+ for child in def_node.children[:3]:
+ text = src[child.start_byte : child.end_byte]
+ if any(marker in text for marker in _CPP_EXPORT_MARKERS):
+ return True
+ return False
+
+
+def _has_file_scope_static(def_node: Node, src: str) -> bool:
+ """Return True if a ``static`` storage-class specifier appears in the leading declarators."""
+ for child in def_node.children[:4]:
+ if child.type == "storage_class_specifier":
+ text = src[child.start_byte : child.end_byte]
+ if "static" in text:
+ return True
+ return False
+
+
+def refine_cpp_visibility(
+ def_node: Node, current_visibility: str, src: str
+) -> tuple[str, bool]:
+ """Return ``(visibility, is_exported)`` for a C/C++ symbol.
+
+ Inputs:
+ * *def_node* — the captured ``@symbol.def`` node.
+ * *current_visibility* — what ``public_by_default`` returned; used
+ as the fallback when no specifier / marker applies.
+ * *src* — full file source text.
+
+ Behaviour:
+ * Inside a ``class_specifier`` body, look back for the nearest
+ ``access_specifier`` sibling. Absent one, fall back to
+ ``private`` (the C++ class default) — ``struct`` defaults to
+ ``public``.
+ * Free function at namespace / file scope with ``static`` storage
+ class → ``private`` (translation-unit local; not importable).
+ * ``__declspec(dllexport)`` or ``__attribute__((visibility("default")))``
+ → forces ``public`` and sets ``is_exported = True`` so a future
+ "exported entry point" check can whitelist it.
+ * Otherwise keep *current_visibility*.
+ """
+ # 1. Export markers always win.
+ if _has_export_marker(def_node, src):
+ return "public", True
+
+ # 2. Class / struct member visibility comes from access specifiers.
+ parent = def_node.parent
+ if parent is not None and parent.type == "field_declaration_list":
+ access = _preceding_access_specifier(def_node)
+ if access is not None:
+ return access, False
+ # No access specifier — use the enclosing aggregate's default.
+ return _enclosing_class_default_access(def_node), False
+
+ # 3. File-scope ``static`` is translation-unit local.
+ if _has_file_scope_static(def_node, src):
+ return "private", False
+
+ return current_visibility, False
+
+
VISIBILITY_FNS: dict[str, Callable[[str, list[str]], str]] = {
"python": py_visibility,
"typescript": ts_visibility,
diff --git a/packages/core/src/repowise/core/ingestion/graph.py b/packages/core/src/repowise/core/ingestion/graph.py
index eb5070b4f..26b246b3a 100644
--- a/packages/core/src/repowise/core/ingestion/graph.py
+++ b/packages/core/src/repowise/core/ingestion/graph.py
@@ -154,6 +154,7 @@ class GraphBuilder:
parent_name=sym.parent_name,
signature=sym.signature,
decorators=sym.decorators,
+ is_exported_symbol=sym.is_exported_symbol,
)
# DEFINES edge: file → symbol
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 34c470118..47bb95b7b 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -155,6 +155,10 @@ class Symbol:
complexity_estimate: int = 1 # cyclomatic complexity
language: str = ""
parent_name: str | None = None # for methods: the containing class name
+ # True when a language-level export marker is present (e.g. C/C++
+ # ``__declspec(dllexport)`` / ``__attribute__((visibility("default")))``).
+ # Used by dead-code analysis to whitelist exported entry points.
+ is_exported_symbol: bool = False
@dataclass
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index cd926bcdb..d6d9f0a79 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -43,6 +43,7 @@ from .extractors import (
refine_go_type_kind,
refine_kotlin_class_kind,
)
+from .extractors.synthetic_symbols import extract_synthetic_symbols
from .extractors.visibility import (
csharp_visibility,
go_visibility,
@@ -51,6 +52,7 @@ from .extractors.visibility import (
php_visibility,
public_by_default,
py_visibility,
+ refine_cpp_visibility,
rust_visibility,
scala_visibility,
swift_visibility,
@@ -68,6 +70,13 @@ from .models import (
log = structlog.get_logger(__name__)
+# Any single file emitting more than this many symbols is almost
+# certainly machine-generated (large gRPC service contracts, OpenAPI
+# bindings, SQL schema bindings). Warn rather than truncate — operators
+# can decide whether to add the file to ``_NEVER_FLAG_PATTERNS`` or to
+# exclude it via traversal.
+_SYMBOL_COUNT_WARN_THRESHOLD = 500
+
QUERIES_DIR = Path(__file__).parent / "queries"
@@ -542,6 +551,14 @@ class ASTParser:
query = self._get_query(lang, language)
symbols = self._extract_symbols(tree, query, config, file_info, src)
+ # Per-language synthetic-symbol pass — recognises source-generator
+ # attributes (e.g. CommunityToolkit.Mvvm) and adds the symbols the
+ # generator would emit at compile time. No-op for languages
+ # without a registered extractor.
+ synthetic = extract_synthetic_symbols(root, src, file_info)
+ if synthetic:
+ existing_ids = {s.id for s in symbols}
+ symbols.extend(s for s in synthetic if s.id not in existing_ids)
imports = self._extract_imports(tree, query, config, file_info, src)
calls = self._extract_calls(tree, query, config, file_info, src, symbols)
heritage = extract_heritage(tree, query, config, file_info, src, run_query=_run_query)
@@ -549,6 +566,15 @@ class ASTParser:
docstring = extract_module_docstring(root, src, lang)
type_refs = self._extract_type_refs(tree, query, src)
+ if len(symbols) > _SYMBOL_COUNT_WARN_THRESHOLD:
+ log.warning(
+ "parser.symbol_bloat",
+ path=file_info.path,
+ language=lang,
+ symbol_count=len(symbols),
+ threshold=_SYMBOL_COUNT_WARN_THRESHOLD,
+ )
+
return ParsedFile(
file_info=file_info,
symbols=symbols,
@@ -632,6 +658,14 @@ class ASTParser:
if sibling.type == "decorator":
modifier_texts.append(_node_text(sibling, src))
visibility = config.visibility_fn(name, modifier_texts)
+ is_exported_symbol = False
+ # C/C++ visibility is dictated by AST context (access
+ # specifiers / storage class / export attributes), not by
+ # modifier text. Refine after the generic fn ran.
+ if file_info.language in ("cpp", "c"):
+ visibility, is_exported_symbol = refine_cpp_visibility(
+ def_node, visibility, src
+ )
# Parent class detection
parent_name = self._find_parent(def_node, config, receiver_nodes, src)
@@ -671,6 +705,7 @@ class ASTParser:
is_async=is_async,
language=file_info.language,
parent_name=parent_name,
+ is_exported_symbol=is_exported_symbol,
)
)
diff --git a/packages/core/src/repowise/core/ingestion/queries/cpp.scm b/packages/core/src/repowise/core/ingestion/queries/cpp.scm
index 9a6f7e97e..d063d7e05 100644
--- a/packages/core/src/repowise/core/ingestion/queries/cpp.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/cpp.scm
@@ -17,6 +17,15 @@
)
) @symbol.def
+; Inline method definition inside a class body: void method(args) { ... }
+; The name is a ``field_identifier`` in this case, not a plain identifier.
+(function_definition
+ declarator: (function_declarator
+ declarator: (field_identifier) @symbol.name
+ parameters: (parameter_list) @symbol.params
+ )
+) @symbol.def
+
; Qualified function definition: ReturnType ClassName::method(params) { }
(function_definition
declarator: (function_declarator
diff --git a/tests/unit/ingestion/test_cpp_extractors.py b/tests/unit/ingestion/test_cpp_extractors.py
new file mode 100644
index 000000000..d26616c62
--- /dev/null
+++ b/tests/unit/ingestion/test_cpp_extractors.py
@@ -0,0 +1,124 @@
+"""Unit tests for C++ heritage extraction.
+
+Exercises the parser path end-to-end so we cover the same code paths as
+production. Other C++ extractors (bindings, docstrings) follow the
+``public_by_default`` shape and don't need parallel coverage here.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+
+def _file(path: str = "Foo.cpp") -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/tmp/{path}",
+ language="cpp",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
[email protected](scope="module")
+def parser() -> ASTParser:
+ return ASTParser()
+
+
+class TestCppHeritage:
+ def test_com_interface_classified_as_implements(self, parser: ASTParser) -> None:
+ """``class X : public IFoo, public CBase`` → IFoo implements, CBase extends."""
+ src = b"""\
+class CShellExt : public IShellExtInit, public IContextMenu, public CBase {
+};
+"""
+ result = parser.parse_file(_file(), src)
+ rels = {(r.parent_name, r.kind) for r in result.heritage}
+ assert ("IShellExtInit", "implements") in rels
+ assert ("IContextMenu", "implements") in rels
+ assert ("CBase", "extends") in rels
+
+ def test_qualified_base_stripped_to_bare_name(self, parser: ASTParser) -> None:
+ """``public ns::IFoo`` is classified by the bare name."""
+ src = b"""\
+class CFoo : public ns::IFooService {
+};
+"""
+ result = parser.parse_file(_file(), src)
+ rels = {(r.parent_name, r.kind) for r in result.heritage}
+ assert ("IFooService", "implements") in rels
+
+ def test_namespace_scope_function_is_public(self, parser: ASTParser) -> None:
+ src = b"""\
+namespace ns {
+ void Helper(int x) { }
+}
+"""
+ result = parser.parse_file(_file(), src)
+ sym = next(s for s in result.symbols if s.name == "Helper")
+ assert sym.visibility == "public"
+ assert sym.is_exported_symbol is False
+
+ def test_file_scope_static_function_is_private(self, parser: ASTParser) -> None:
+ src = b"""\
+static int Helper(int x) { return x; }
+"""
+ result = parser.parse_file(_file(), src)
+ sym = next(s for s in result.symbols if s.name == "Helper")
+ assert sym.visibility == "private"
+
+ def test_class_method_private_by_default(self, parser: ASTParser) -> None:
+ src = b"""\
+class Foo {
+ void Hidden(int x) { }
+public:
+ void Visible(int x) { }
+};
+"""
+ result = parser.parse_file(_file(), src)
+ by_name = {s.name: s for s in result.symbols}
+ assert by_name["Hidden"].visibility == "private"
+ assert by_name["Visible"].visibility == "public"
+
+ def test_struct_method_public_by_default(self, parser: ASTParser) -> None:
+ src = b"""\
+struct Foo {
+ void Visible(int x) { }
+private:
+ void Hidden(int x) { }
+};
+"""
+ result = parser.parse_file(_file(), src)
+ by_name = {s.name: s for s in result.symbols}
+ assert by_name["Visible"].visibility == "public"
+ assert by_name["Hidden"].visibility == "private"
+
+ def test_dllexport_marks_exported_symbol(self, parser: ASTParser) -> None:
+ src = b"""\
+extern "C" __declspec(dllexport) HRESULT DllRegisterServer(void) { return 0; }
+"""
+ result = parser.parse_file(_file(), src)
+ sym = next(s for s in result.symbols if s.name == "DllRegisterServer")
+ assert sym.visibility == "public"
+ assert sym.is_exported_symbol is True
+
+ def test_two_letter_i_prefix_not_misclassified(self, parser: ASTParser) -> None:
+ """``IO`` / ``ID`` etc. aren't COM interfaces — must stay extends."""
+ src = b"""\
+class StreamWrapper : public IO {
+};
+"""
+ result = parser.parse_file(_file(), src)
+ rels = {(r.parent_name, r.kind) for r in result.heritage}
+ assert ("IO", "extends") in rels
+ assert ("IO", "implements") not in rels
diff --git a/tests/unit/ingestion/test_csharp_synthetic_symbols.py b/tests/unit/ingestion/test_csharp_synthetic_symbols.py
new file mode 100644
index 000000000..5b584ae86
--- /dev/null
+++ b/tests/unit/ingestion/test_csharp_synthetic_symbols.py
@@ -0,0 +1,114 @@
+"""Unit tests for CommunityToolkit MVVM synthetic-symbol extraction."""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+
+def _file(path: str = "Vm.cs") -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/tmp/{path}",
+ language="csharp",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
[email protected](scope="module")
+def parser() -> ASTParser:
+ return ASTParser()
+
+
+class TestMvvmObservableProperty:
+ def test_observable_property_synthesises_pascal_property(self, parser: ASTParser) -> None:
+ src = b"""\
+public partial class Vm {
+ [ObservableProperty]
+ private string _userName;
+}
+"""
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "UserName" in names
+ prop = next(s for s in result.symbols if s.name == "UserName")
+ assert prop.parent_name == "Vm"
+ assert prop.visibility == "public"
+
+ def test_field_without_underscore_strips_correctly(self, parser: ASTParser) -> None:
+ src = b"""\
+public partial class Vm {
+ [ObservableProperty]
+ private string name;
+}
+"""
+ result = parser.parse_file(_file(), src)
+ # When the field is already PascalCase-equivalent the synthetic
+ # name would collide with the field — skipped, not duplicated.
+ # ``name`` → ``Name`` is a real change; both symbols should exist.
+ names = {s.name for s in result.symbols}
+ assert "Name" in names
+
+ def test_no_attribute_no_synthesis(self, parser: ASTParser) -> None:
+ src = b"""\
+public class Vm {
+ private string _userName;
+}
+"""
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "UserName" not in names
+
+
+class TestMvvmRelayCommand:
+ def test_relay_command_synthesises_command_method(self, parser: ASTParser) -> None:
+ src = b"""\
+public partial class Vm {
+ [RelayCommand]
+ private void Save() { }
+}
+"""
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "SaveCommand" in names
+ cmd = next(s for s in result.symbols if s.name == "SaveCommand")
+ assert cmd.parent_name == "Vm"
+
+ def test_relay_command_with_arguments(self, parser: ASTParser) -> None:
+ src = b"""\
+public partial class Vm {
+ [RelayCommand(CanExecute = nameof(CanReset))]
+ private void Reset() { }
+}
+"""
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "ResetCommand" in names
+
+ def test_non_csharp_returns_no_synthetics(self, parser: ASTParser) -> None:
+ """The synthetic pass dispatches by language tag — other languages no-op."""
+ fi = FileInfo(
+ path="vm.py",
+ abs_path="/tmp/vm.py",
+ language="python",
+ size_bytes=10,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ result = parser.parse_file(fi, b"def Save(): pass\n")
+ # Nothing should have been added beyond the real ``Save``.
+ assert [s.name for s in result.symbols] == ["Save"]
diff --git a/tests/unit/ingestion/test_xaml_dynamic_hints.py b/tests/unit/ingestion/test_xaml_dynamic_hints.py
index 770c7e8ff..d837d52ae 100644
--- a/tests/unit/ingestion/test_xaml_dynamic_hints.py
+++ b/tests/unit/ingestion/test_xaml_dynamic_hints.py
@@ -88,14 +88,76 @@ class TestEndToEnd:
"App/ViewModels/GeneralViewModel.cs",
) in sources
- def test_no_csproj_emits_nothing(self, tmp_path: Path) -> None:
+ def test_no_csproj_emits_no_type_binding_edges(self, tmp_path: Path) -> None:
# A repo with XAML but no .csproj has no .NET type index to
- # bind against; the extractor should silently produce nothing
- # rather than spuriously create external edges.
+ # bind against; type-binding edges silently produce nothing.
+ # ResourceDictionary edges remain xaml→xaml and don't need the
+ # type map — they're tested separately.
(tmp_path / "View.xaml").write_text(
'<Page xmlns:vm="using:Foo" x:DataType="vm:Bar"/>'
)
- assert XamlDynamicHints().extract(tmp_path) == []
+ edges = XamlDynamicHints().extract(tmp_path)
+ # No binding edges should fire — and with no other xaml in the
+ # tree the list is empty.
+ assert edges == []
+
+
+class TestResourceDictionaryEdges:
+ """``<ResourceDictionary Source="..."/>`` cross-references between XAML files."""
+
+ def test_relative_source_resolves_to_sibling_xaml(self, tmp_path: Path) -> None:
+ (tmp_path / "Themes").mkdir()
+ (tmp_path / "Themes" / "Light.xaml").write_text(
+ '<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"/>'
+ )
+ (tmp_path / "Themes" / "App.xaml").write_text(
+ '<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">\n'
+ ' <ResourceDictionary.MergedDictionaries>\n'
+ ' <ResourceDictionary Source="Light.xaml"/>\n'
+ ' </ResourceDictionary.MergedDictionaries>\n'
+ '</ResourceDictionary>\n'
+ )
+ edges = {(e.source, e.target) for e in XamlDynamicHints().extract(tmp_path)}
+ assert ("Themes/App.xaml", "Themes/Light.xaml") in edges
+
+ def test_pack_uri_strips_assembly_prefix(self, tmp_path: Path) -> None:
+ (tmp_path / "Themes").mkdir()
+ (tmp_path / "Themes" / "Dark.xaml").write_text(
+ '<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"/>'
+ )
+ (tmp_path / "Themes" / "Generic.xaml").write_text(
+ '<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"\n'
+ ' Source="pack://application:,,,/Acme.UI;component/Themes/Dark.xaml"/>\n'
+ )
+ edges = {(e.source, e.target) for e in XamlDynamicHints().extract(tmp_path)}
+ assert ("Themes/Generic.xaml", "Themes/Dark.xaml") in edges
+
+ def test_ms_appx_uri_resolves(self, tmp_path: Path) -> None:
+ (tmp_path / "Styles").mkdir()
+ (tmp_path / "Styles" / "Buttons.xaml").write_text("<ResourceDictionary/>")
+ (tmp_path / "App.xaml").write_text(
+ '<ResourceDictionary>\n'
+ ' <ResourceDictionary Source="ms-appx:///Styles/Buttons.xaml"/>\n'
+ '</ResourceDictionary>'
+ )
+ edges = {(e.source, e.target) for e in XamlDynamicHints().extract(tmp_path)}
+ assert ("App.xaml", "Styles/Buttons.xaml") in edges
+
+ def test_self_reference_dropped(self, tmp_path: Path) -> None:
+ (tmp_path / "Self.xaml").write_text(
+ '<ResourceDictionary>\n'
+ ' <ResourceDictionary Source="Self.xaml"/>\n'
+ '</ResourceDictionary>'
+ )
+ edges = XamlDynamicHints().extract(tmp_path)
+ assert edges == []
+
+ def test_no_resource_dictionary_no_edges(self, tmp_path: Path) -> None:
+ (tmp_path / "Plain.xaml").write_text(
+ '<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"/>'
+ )
+ edges = XamlDynamicHints().extract(tmp_path)
+ assert edges == []
class TestLanguageRegistration: