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: cut dead-code false positives across C++, C#, XAML, tests (#190)

Raghav Chamadiya44223d86c4fa
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 2c3ffbee5..ef5e411fe 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -372,14 +372,17 @@ class DeadCodeAnalyzer:
if self._should_never_flag(str(node), whitelist):
continue
- symbols = [
- self.graph.nodes[succ]
+ # Pair each symbol's data with its node id so we can check
+ # incoming ``calls`` edges on the symbol itself further down.
+ symbol_pairs = [
+ (succ, self.graph.nodes[succ])
for succ in self.graph.successors(node)
if self.graph.nodes[succ].get("node_type") == "symbol"
and self.graph.get_edge_data(node, succ, {}).get("edge_type") == "defines"
]
- if not symbols:
+ if not symbol_pairs:
continue
+ symbols = [sym for _, sym in symbol_pairs]
file_has_importers = self.graph.in_degree(node) > 0
@@ -408,7 +411,7 @@ class DeadCodeAnalyzer:
and sym.get("end_line", 0) > sym.get("start_line", 0)
]
- for sym in symbols:
+ for sym_id, sym in symbol_pairs:
if sym.get("visibility") != "public":
continue
sym_name = sym.get("name", "")
@@ -476,6 +479,20 @@ class DeadCodeAnalyzer:
if has_importers:
continue
+ # Symbol-level usage signal: any incoming ``calls`` /
+ # ``method_implements`` / ``reads`` edge means somewhere
+ # in the codebase actually uses this symbol — even if
+ # the file-level ``imported_names`` machinery missed it
+ # (intra-file C++ helpers, ``Foo::method`` qualified
+ # definitions linked by call resolution but never named
+ # in a header, Razor/XAML code-behind dispatches).
+ if self.graph.has_node(sym_id) and any(
+ self.graph[pred][sym_id].get("edge_type")
+ in ("calls", "method_implements", "reads")
+ for pred in self.graph.predecessors(sym_id)
+ ):
+ continue
+
if is_deprecated:
confidence = 0.3
elif file_has_importers:
diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.py
index a18da68cf..b6fa30708 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -120,6 +120,28 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (
"*/Themes/*.xaml",
"*/Styles/*.xaml",
"*/Resources/*.xaml",
+ # ---- Test infrastructure conventions -----------------------------
+ # Test classes are loaded by the test runner via reflection on
+ # ``[Test]`` / ``[TestMethod]`` / ``[Fact]`` attributes — they
+ # never appear in a `using` import that names the class. Match
+ # both the file location *and* the standard suffix patterns so we
+ # catch tests dropped at arbitrary paths.
+ "*Tests/*.cs",
+ "*.Tests/*.cs",
+ "*UnitTests/*.cs",
+ "*.UnitTests/*.cs",
+ "*IntegrationTests/*.cs",
+ "*.IntegrationTests/*.cs",
+ "*FuzzTests/*.cs",
+ "*.FuzzTests/*.cs",
+ "*UITests/*.cs",
+ "*.UITests/*.cs",
+ "*UITest/*.cs",
+ "*UITestAutomation/*.cs",
+ "*/unittests/*.cpp",
+ "*/unittests/*.h",
+ "*Tests.cs",
+ "*UnitTests.cs",
)
# Decorator patterns that indicate framework usage (route handlers, fixtures, etc.)
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py
index 0268884e3..8f892d947 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py
@@ -77,6 +77,12 @@ _INTERNALS_VISIBLE_RE = re.compile(
# resolves: ``_files_for`` strips the namespace.
_NAMEOF_TYPE_RE = re.compile(r"\bnameof\s*\(\s*([A-Z][\w.]*)\s*\)")
+# ``typeof(TypeName)`` — used heavily in ``[JsonConverter(typeof(X))]``,
+# ``[TypeConverter(typeof(X))]``, ``DataTemplate.DataType = typeof(X)``,
+# ``services.AddSingleton(typeof(IFoo), typeof(FooImpl))``, route
+# constraints, etc. Same shape and PascalCase guard as ``nameof``.
+_TYPEOF_TYPE_RE = re.compile(r"\btypeof\s*\(\s*([A-Z][\w.]*)\s*\)")
+
class DotNetDynamicHints(DynamicHintExtractor):
"""Discover DI registrations, reflection, and assembly-level hints in .NET."""
@@ -273,6 +279,20 @@ class DotNetDynamicHints(DynamicHintExtractor):
)
)
+ # ---- typeof(TypeName) — JsonConverter/TypeConverter attrs,
+ # DataTemplate.DataType, manual DI registration, etc. ----
+ for match in _TYPEOF_TYPE_RE.finditer(text):
+ for target in _files_for(match.group(1)):
+ if target != rel:
+ edges.append(
+ DynamicEdge(
+ source=rel,
+ target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:typeof",
+ )
+ )
+
# ---- [assembly: InternalsVisibleTo("Other.Tests")] ----
for match in _INTERNALS_VISIBLE_RE.finditer(text):
friend = match.group(1)
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 37621370d..4f09ecedb 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,17 @@ _XTYPE_RE = re.compile(
re.IGNORECASE,
)
+# ``<prefix:TypeName ...>`` element-tag references. WPF / WinUI / MAUI
+# instantiate controls, converters and templates by writing them as
+# XAML elements; the consumer code never says ``using`` for those
+# types. We require the namespace prefix to avoid over-matching XAML's
+# built-in elements (``<Grid>``, ``<TextBlock>``…), and to keep noise
+# out we skip property-element syntax (``<Grid.Resources>``) by
+# rejecting tags whose name contains a dot.
+_ELEMENT_TAG_RE = re.compile(
+ r"""<(\w+):([A-Z][\w]*)(?=[\s/>])""",
+)
+
# <ResourceDictionary Source="..."/> — both standalone and inside a
# <ResourceDictionary.MergedDictionaries> block. Match attribute order
# agnostically; only the Source value is needed.
@@ -200,6 +211,14 @@ def _extract_type_references(text: str, prefix_to_ns: dict[str, str]) -> set[str
type_name = match.group(2)
if type_name and type_name[0].isupper():
names.add(type_name)
+ # Element-tag references like ``<converters:BoolToVisibilityConverter ...>``.
+ # The leading-uppercase guard is in the regex; we additionally skip
+ # the ``ResourceDictionary`` tag because that's handled separately
+ # and binding it to the C# type map would just produce noise.
+ for match in _ELEMENT_TAG_RE.finditer(text):
+ type_name = match.group(2)
+ if type_name and type_name != "ResourceDictionary":
+ names.add(type_name)
# The xmlns prefixes themselves never name a type, but their target
# namespaces are a useful signal — left here as a hook for future
# enhancement that resolves "every type in that namespace" when no
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index d6d9f0a79..79112251e 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -670,6 +670,18 @@ class ASTParser:
# Parent class detection
parent_name = self._find_parent(def_node, config, receiver_nodes, src)
+ # C/C++ qualified definitions: ``void Foo::method() { … }``
+ # carries the class as the scope of a ``qualified_identifier``
+ # parent of the name node. Without this resolution, every
+ # ``Class::method`` lands as a free function and bloats the
+ # unused_export pass with thousands of method symbols.
+ if (
+ parent_name is None
+ and file_info.language in ("cpp", "c")
+ and name_nodes
+ ):
+ parent_name = _qualified_cpp_parent(name_nodes[0], src)
+
# Upgrade function → method when a parent class is detected
if parent_name and kind == "function":
kind = "method"
@@ -990,6 +1002,33 @@ def _is_async_node(node: Node, src: str) -> bool:
return node.type == "async_function_definition" or any(c.type == "async" for c in node.children)
+def _qualified_cpp_parent(name_node: Node, src: str) -> str | None:
+ """Return the parent class for a C/C++ ``Class::method`` definition.
+
+ The captured ``@symbol.name`` for a qualified function definition
+ is the bare ``method`` identifier whose parent is a
+ ``qualified_identifier`` carrying the class / namespace as its
+ ``scope`` field. For multi-level qualifications (``NS::Foo::method``)
+ the relevant parent is still the innermost qualifier — namespaces
+ above it are not the symbol's containing type. Tree-sitter-cpp
+ represents this by nesting ``qualified_identifier`` left-recursively,
+ so the immediate parent's ``scope`` is always the right answer.
+
+ Returns ``None`` when the name node is not inside a qualified
+ identifier (i.e. plain free function).
+ """
+ parent = name_node.parent
+ if parent is None or parent.type != "qualified_identifier":
+ return None
+ scope = parent.child_by_field_name("scope")
+ if scope is None:
+ return None
+ text = src[scope.start_byte : scope.end_byte].strip()
+ # ``scope`` may itself be a qualified path (``NS::Foo``); take the
+ # last component — that's the immediate enclosing type.
+ return text.rsplit("::", 1)[-1] or None
+
+
def _build_qualified_name(file_path: str, parent_name: str | None, name: str) -> str:
module = Path(file_path).with_suffix("").as_posix().replace("/", ".")
if parent_name:
diff --git a/packages/core/src/repowise/core/ingestion/queries/cpp.scm b/packages/core/src/repowise/core/ingestion/queries/cpp.scm
index d063d7e05..3c7f26779 100644
--- a/packages/core/src/repowise/core/ingestion/queries/cpp.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/cpp.scm
@@ -36,6 +36,22 @@
)
) @symbol.def
+; Two-level qualified function: ReturnType NS::ClassName::method(params) { }
+; The grammar nests the qualified_identifier left-recursively, so we
+; need a separate pattern for each depth. Parser walks the captured
+; name's qualified-identifier parent to extract the class name, so the
+; deeper namespace prefix doesn't need to be captured here.
+(function_definition
+ declarator: (function_declarator
+ declarator: (qualified_identifier
+ name: (qualified_identifier
+ name: (identifier) @symbol.name
+ )
+ )
+ parameters: (parameter_list) @symbol.params
+ )
+) @symbol.def
+
; Class
(class_specifier
name: (type_identifier) @symbol.name
diff --git a/tests/unit/ingestion/test_cpp_extractors.py b/tests/unit/ingestion/test_cpp_extractors.py
index d26616c62..b32a11037 100644
--- a/tests/unit/ingestion/test_cpp_extractors.py
+++ b/tests/unit/ingestion/test_cpp_extractors.py
@@ -103,6 +103,24 @@ private:
assert by_name["Visible"].visibility == "public"
assert by_name["Hidden"].visibility == "private"
+ def test_qualified_definition_binds_to_class(self, parser: ASTParser) -> None:
+ """``void Foo::method() { … }`` extracts as a method with parent=Foo."""
+ src = b"""\
+void Foo::DoOne(int x) { }
+void NS::Bar::DoTwo(int y) { }
+void Free() { }
+"""
+ result = parser.parse_file(_file(), src)
+ by_name = {s.name: s for s in result.symbols}
+ assert by_name["DoOne"].kind == "method"
+ assert by_name["DoOne"].parent_name == "Foo"
+ assert by_name["DoTwo"].kind == "method"
+ # Two-level NS::Bar::DoTwo → parent is the innermost qualifier, Bar.
+ assert by_name["DoTwo"].parent_name == "Bar"
+ # Free function unaffected.
+ assert by_name["Free"].kind == "function"
+ assert by_name["Free"].parent_name is None
+
def test_dllexport_marks_exported_symbol(self, parser: ASTParser) -> None:
src = b"""\
extern "C" __declspec(dllexport) HRESULT DllRegisterServer(void) { return 0; }
diff --git a/tests/unit/ingestion/test_csharp_framework_edges.py b/tests/unit/ingestion/test_csharp_framework_edges.py
index a13c0cbbd..9d9208b7c 100644
--- a/tests/unit/ingestion/test_csharp_framework_edges.py
+++ b/tests/unit/ingestion/test_csharp_framework_edges.py
@@ -306,6 +306,40 @@ public class Bootstrap {
for e in edges
)
+ def test_typeof_type_emits_dynamic_uses(self, tmp_path: Path) -> None:
+ """``typeof(MyConverter)`` references must surface as dynamic edges.
+
+ Critical for ``[JsonConverter(typeof(X))]``,
+ ``[TypeConverter(typeof(X))]``, ``DataTemplate.DataType =
+ typeof(X)`` and manual DI registration.
+ """
+ (tmp_path / "BoolConverter.cs").write_text(
+ "namespace Acme;\npublic class BoolConverter { }\n"
+ )
+ (tmp_path / "Settings.cs").write_text(
+ """namespace Acme;
+public class Settings {
+ [JsonConverter(typeof(BoolConverter))]
+ public bool Flag { get; set; }
+}
+"""
+ )
+ edges = DotNetDynamicHints().extract(tmp_path)
+ assert any(
+ e.source == "Settings.cs"
+ and e.target == "BoolConverter.cs"
+ and e.hint_source.endswith(":typeof")
+ for e in edges
+ )
+
+ def test_typeof_lowercase_local_ignored(self, tmp_path: Path) -> None:
+ """``typeof(int)`` and lowercase identifiers must not bind."""
+ (tmp_path / "Foo.cs").write_text(
+ "namespace Acme;\npublic class Foo { void Go() { var t = typeof(int); } }\n"
+ )
+ edges = DotNetDynamicHints().extract(tmp_path)
+ assert not any(e.hint_source.endswith(":typeof") for e in edges)
+
def test_nameof_lowercase_member_ignored(self, tmp_path: Path) -> None:
"""``nameof(someLocal)`` must NOT bind — only type-looking
identifiers are scanned to keep noise out.
diff --git a/tests/unit/ingestion/test_parser.py b/tests/unit/ingestion/test_parser.py
index 6457337de..8c02051f6 100644
--- a/tests/unit/ingestion/test_parser.py
+++ b/tests/unit/ingestion/test_parser.py
@@ -582,9 +582,11 @@ class TestCppParser:
def test_finds_functions_in_source(self, parser: ASTParser) -> None:
fi = _make_file_info("cpp_pkg/calculator.cpp", "cpp")
result = parser.parse_file(fi, CPP_SOURCE)
- fns = [s for s in result.symbols if s.kind == "function"]
- # Qualified definitions like Calculator::add should be caught
- assert len(fns) >= 1
+ # ``Calculator::add`` style qualified definitions now resolve to
+ # ``kind=method`` with ``parent_name=Calculator``; free functions
+ # stay ``kind=function``. Either way we expect symbols to land.
+ callable_symbols = [s for s in result.symbols if s.kind in ("function", "method")]
+ assert len(callable_symbols) >= 1
def test_parses_includes(self, parser: ASTParser) -> None:
fi = _make_file_info("cpp_pkg/calculator.cpp", "cpp")
diff --git a/tests/unit/ingestion/test_xaml_dynamic_hints.py b/tests/unit/ingestion/test_xaml_dynamic_hints.py
index d837d52ae..ab51f3903 100644
--- a/tests/unit/ingestion/test_xaml_dynamic_hints.py
+++ b/tests/unit/ingestion/test_xaml_dynamic_hints.py
@@ -59,6 +59,25 @@ class TestTypeReferenceExtraction:
refs = _extract_type_references(text, {"vm": "Acme.ViewModels"})
assert "SettingsViewModel" in refs
+ def test_element_tag_with_prefix_extracted(self) -> None:
+ """``<converters:BoolToVisibilityConverter />`` registers ``BoolToVisibilityConverter``."""
+ text = '<Page><converters:BoolToVisibilityConverter x:Key="b2v"/></Page>'
+ refs = _extract_type_references(text, {"converters": "Acme.Converters"})
+ assert "BoolToVisibilityConverter" in refs
+
+ def test_element_tag_property_syntax_skipped(self) -> None:
+ """``<Grid.Resources>`` is property-element syntax, not a type reference."""
+ text = '<Grid><Grid.Resources/></Grid>'
+ refs = _extract_type_references(text, {})
+ assert "Resources" not in refs
+
+ def test_bare_xaml_element_not_a_type_reference(self) -> None:
+ """Built-in XAML elements (``<Grid>``, ``<TextBlock>``) must not bind."""
+ text = '<Page><Grid><TextBlock/></Grid></Page>'
+ refs = _extract_type_references(text, {})
+ assert "Grid" not in refs
+ assert "TextBlock" not in refs
+
def test_lowercase_attribute_value_skipped(self) -> None:
# Attribute values that don't start with an uppercase letter
# (e.g. property names accidentally captured) are skipped.
diff --git a/tests/unit/test_dead_code.py b/tests/unit/test_dead_code.py
index c4a261dc5..a3d57895f 100644
--- a/tests/unit/test_dead_code.py
+++ b/tests/unit/test_dead_code.py
@@ -199,6 +199,59 @@ def test_unused_export_detected():
assert "helper_func" in sym_names
+def test_unused_export_skipped_when_symbol_has_incoming_calls():
+ """A public symbol with no file-level importers but at least one
+ incoming ``calls`` edge on the symbol itself is still in use —
+ typical for C++ intra-file helpers and ``Foo::method`` qualified
+ definitions reached via call resolution rather than headers."""
+ g = _build_graph(
+ nodes={
+ "pkg/utils.cpp": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "language": "cpp",
+ "symbols": [
+ {
+ "name": "helper",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 10,
+ "complexity_estimate": 1,
+ },
+ {
+ "name": "caller",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 12,
+ "end_line": 20,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ edges=[
+ ("pkg/utils.cpp::caller", "pkg/utils.cpp::helper", {"edge_type": "calls"}),
+ ],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ }
+ )
+ sym_names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
+ # ``helper`` is called by ``caller`` — must not be flagged.
+ assert "helper" not in sym_names
+ # ``caller`` has no callers — still flagged.
+ assert "caller" in sym_names
+
+
def test_interface_without_implementor_demoted_below_safe_threshold():
"""Public interfaces with no incoming ``implements`` edges have
their unused-export confidence clamped below 0.7 so the demo