Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(rust): record field and type-argument types as type references (#1568)
Shaizah89917572dc77
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex 2097e61f3..27a114e90 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -108,6 +108,7 @@ from .parser_helpers import (_qualified_cpp_parent,_qualified_pascal_parent,_run_query,+ _rust_shadowed_by_type_param,)from .python_local_refs import extract_python_local_refsfrom .sfc_source import component_call_sites, prepare_source@@ -2388,6 +2389,13 @@ class ASTParser:head = head_of(type_node, src)if not head:continue+ # ``struct Wrapper<Item> { value: Item }`` binds Item as a type+ # parameter, and the capture cannot tell that from a reference+ # to a real ``struct Item``. The head extractor drops a+ # single-letter ``T`` but not a named one, so the shadow has to+ # be read off the enclosing item's ``type_parameters``.+ if lang == "rust" and _rust_shadowed_by_type_param(type_node, head, src):+ continueline = type_node.start_point[0] + 1key = (head, line)if key in seen:diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.pyindex f31d625a4..7b11f9b71 100644--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py@@ -1754,6 +1754,44 @@ def _count_arguments(arg_node: Node) -> int:)+def _rust_type_param_name(param: Node, src: str) -> str | None:+ """Return the bound name of a ``type_parameter``/``const_parameter`` node.++ Both node types put the binding name first, before any trait bound or+ default (``T: Clone``, ``D = Foo``, ``const N: usize``) — later+ ``type_identifier`` children are constraints, not the binding itself.+ """+ for child in param.children:+ if child.type in ("type_identifier", "identifier"):+ return node_text(child, src).strip()+ return None+++def _rust_shadowed_by_type_param(node: Node, target_name: str, src: str) -> bool:+ """True if *target_name* is bound as a generic type parameter by an+ ancestor item of *node* (``struct Wrapper<Item> { value: Item }``).++ Rust's field/generic-argument type captures can't distinguish a type+ parameter's own name from a real type reference — both are plain+ ``type_identifier`` nodes. Without this check, a type parameter that+ happens to share a name with a real struct/enum produces a false+ "used" edge to that struct, hiding it from dead-code detection even+ when it is genuinely unreferenced.+ """+ ancestor = node.parent+ while ancestor is not None:+ for child in ancestor.children:+ if child.type != "type_parameters":+ continue+ for param in child.children:+ if param.type not in ("type_parameter", "const_parameter"):+ continue+ if _rust_type_param_name(param, src) == target_name:+ return True+ ancestor = ancestor.parent+ return False++def _find_enclosing_symbol(line: int,symbol_ranges: list[tuple[int, int, str]],diff --git a/packages/core/src/repowise/core/ingestion/queries/rust.scm b/packages/core/src/repowise/core/ingestion/queries/rust.scmindex ebf4be42f..4b3911944 100644--- a/packages/core/src/repowise/core/ingestion/queries/rust.scm+++ b/packages/core/src/repowise/core/ingestion/queries/rust.scm@@ -387,6 +387,26 @@))+; Type argument: Option<MyType>, Vec<super::MyType>, HashMap<K, MyType>.+; One pattern for every shape: the Rust head extractor unwraps+; ``scoped_type_identifier`` / ``reference_type`` / ``generic_type`` and+; filters the builtins, so widening the capture costs nothing.+(type_arguments+ (_) @param.type+)++; Field type: struct Foo { bar: MyType }, including ``&T``, ``super::T`` and+; ``Option<T>``. ``enum_variant`` reuses ``field_declaration`` for struct-like+; variant bodies (``Received { state: MyType }``), so this covers those too.+;+; Rust intra-crate field references need no ``use`` -- path-qualified or+; same-module access is legal without importing -- so without this capture the+; reference never becomes a graph edge and the field's type reads as having no+; importers.+(field_declaration+ type: (_) @param.type+)+; ---------------------------------------------------------------------------; Fields; ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.pyindex d607895b3..00eb55fd3 100644--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py@@ -265,8 +265,16 @@ def _find_rust_type_file(if type_name in defined_names.get(imp_file, _EMPTY_NAMES):return imp_file, False+ # The stem match is Rust-only for the reason the unique-owner index below+ # states: the stem map spans every language, so a type named ``Tool``+ # matched ``Tool.tsx`` and a ``Meta`` matched a ``meta.json``.candidates = ctx.stem_map.get(type_name.lower(), [])- if len(candidates) == 1 and candidates[0] != from_path and graph.has_node(candidates[0]):+ if (+ len(candidates) == 1+ and candidates[0] != from_path+ and graph.has_node(candidates[0])+ and graph.nodes[candidates[0]].get("language") == "rust"+ ):return candidates[0], Trueowner = _rust_unique_owner_index(graph, defined_names).get(type_name)diff --git a/tests/unit/ingestion/test_rust_field_type_use.py b/tests/unit/ingestion/test_rust_field_type_use.pynew file mode 100644index 000000000..fb3aec9df--- /dev/null+++ b/tests/unit/ingestion/test_rust_field_type_use.py@@ -0,0 +1,275 @@+"""Rust struct/enum field type references — false-positive regression.++Covers the chain that turns a Rust field's type annotation into a graph+edge the dead-code analyzer can read:++* ``field_declaration``'s ``type:`` node captured as ``@param.type`` in+ ``rust.scm``, one pattern covering plain, ``&T``, scoped+ ``super::``/``crate::`` and ``Option<T>`` shapes because the Rust head+ extractor unwraps them;+* ``type_arguments`` generalised beyond the existing ``dyn Trait`` case, so+ a type nested in ``Option<T>`` / ``Vec<T>`` is also captured;+* ``_extract_type_refs`` turning those into ``TypeReference`` records and+ ``_resolve_rust_type_refs`` resolving them into a file-level ``type_use``+ edge. A type is not callable, so these positions deliberately do not mint+ ``calls`` edges (see the note above the type-reference section in+ ``rust.scm``);+* the end-to-end dead-code outcome: a struct used only as a field type,+ including across files via a path-qualified reference with no ``use``+ statement, is no longer flagged as an unused export — while a genuinely+ unreferenced struct in the same crate still is (the honesty guard).++Before this fix, ``field_declaration`` had no type capture at all, so a+struct referenced only as a struct/enum field never became a ``CallSite``+and read as having "no importers" regardless of how it was used. Since+``enum_variant``'s struct-like body reuses the ``field_declaration`` node,+this single gap covered both the plain-struct-field and enum-variant-field+false positives reported against ``get_dead_code``.++All tests drive the real parser, GraphBuilder and analyzer — no mocking of+the resolution path.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path+from typing import ClassVar++import networkx as nx++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.ingestion.graph import GraphBuilder+from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.parser import ASTParser++_PARSER = ASTParser()+++def _file_info(path: str, abs_path: str) -> FileInfo:+ return FileInfo(+ path=path,+ abs_path=abs_path,+ language="rust",+ size_bytes=100,+ git_hash="",+ last_modified=datetime.now(),+ is_test=path.endswith("_test.rs") or "/tests/" in path,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+++# ---------------------------------------------------------------------------+# Parser: field type capture+# ---------------------------------------------------------------------------+++class TestRustFieldTypeCapture:+ def _type_refs(self, body: str) -> set[str]:+ info = _file_info("p/f.rs", "/repo/p/f.rs")+ parsed = _PARSER.parse_file(info, body.encode("utf-8"))+ return {r.type_name for r in parsed.type_refs}++ def _calls(self, body: str) -> set[str]:+ info = _file_info("p/f.rs", "/repo/p/f.rs")+ parsed = _PARSER.parse_file(info, body.encode("utf-8"))+ return {c.target_name for c in parsed.calls}++ def test_plain_struct_field_type_captured(self) -> None:+ names = self._type_refs("pub struct Foo { bar: Bar }\n")+ assert "Bar" in names++ def test_field_type_is_not_captured_as_a_call(self) -> None:+ # A type is not callable. These positions mint a file-level+ # ``type_use`` edge, never ``Foo -> Bar`` in the call graph.+ assert "Bar" not in self._calls("pub struct Foo { bar: Bar }\n")++ def test_scoped_struct_field_type_captured(self) -> None:+ names = self._type_refs("pub struct Foo { bar: super::Bar }\n")+ assert "Bar" in names++ def test_enum_struct_variant_field_type_captured(self) -> None:+ # enum_variant reuses field_declaration for its struct-like body.+ names = self._type_refs(+ "pub enum Event {\n"+ " Received { state: Bar },\n"+ "}\n"+ )+ assert "Bar" in names++ def test_generic_wrapped_scoped_field_type_captured(self) -> None:+ # The reported false positive's exact shape: Option<super::Bar>.+ names = self._type_refs(+ "pub enum Event {\n"+ " Received { state: Option<super::Bar> },\n"+ "}\n"+ )+ assert "Bar" in names++ def test_reference_field_type_captured(self) -> None:+ names = self._type_refs("pub struct Foo<'a> { bar: &'a Bar }\n")+ assert "Bar" in names++ def test_generic_type_param_not_captured_as_reference(self) -> None:+ # `Item` here is the type parameter's own name, not a reference to+ # a struct named `Item` — the two are indistinguishable as bare+ # `type_identifier` nodes without checking the enclosing+ # `type_parameters` list.+ names = self._type_refs("pub struct Wrapper<Item> { pub value: Item }\n")+ assert "Item" not in names+++# ---------------------------------------------------------------------------+# Graph + dead-code outcome (end-to-end through GraphBuilder)+# ---------------------------------------------------------------------------++# A crate laid out to mirror the reported bug: a struct defined in one+# module file, referenced only as an enum-variant field type from a sibling+# module file via a `super::` path — no `use` statement anywhere.+_SOURCES: dict[str, str] = {+ "Cargo.toml": '[package]\nname = "net"\nversion = "0.1.0"\n',+ "src/lib.rs": "pub mod transport;\n",+ "src/transport.rs": "pub mod state;\npub mod types;\n",+ "src/transport/state.rs": (+ "// RecvState is used only as an enum-variant field type in\n"+ "// types.rs, crossing files with no `use` statement.\n"+ "pub struct RecvState { pub id: u32 }\n\n"+ "// DeadState is never referenced anywhere — a true positive that\n"+ "// must survive the fix.\n"+ "pub struct DeadState { pub id: u32 }\n"+ ),+ "src/transport/types.rs": (+ "pub enum Event {\n"+ " Received { state: Option<super::state::RecvState> },\n"+ "}\n"+ ),+}+++def _build_graph(repo: Path) -> nx.DiGraph:+ for rel, body in _SOURCES.items():+ p = repo / rel+ p.parent.mkdir(parents=True, exist_ok=True)+ p.write_text(body, encoding="utf-8")++ builder = GraphBuilder(repo_path=repo)+ for rel in _SOURCES:+ if not rel.endswith(".rs"):+ continue+ abs_path = str((repo / rel).resolve())+ parsed = _PARSER.parse_file(_file_info(rel, abs_path), (repo / rel).read_bytes())+ builder.add_file(parsed)+ return builder.build()+++class TestRustFieldTypeUseEdge:+ def test_cross_file_field_type_produces_type_use_edge(self, tmp_path: Path) -> None:+ graph = _build_graph(tmp_path)+ src, dst = "src/transport/types.rs", "src/transport/state.rs"+ assert graph.has_edge(src, dst)+ assert graph[src][dst].get("edge_type") == "type_use"++ def test_cross_file_field_type_produces_no_call_edge(self, tmp_path: Path) -> None:+ # The enclosing item does not call the type it holds.+ graph = _build_graph(tmp_path)+ assert not graph.has_edge(+ "src/transport/types.rs::Received",+ "src/transport/state.rs::RecvState",+ )+++class TestRustFieldTypeDeadCodeOutcome:+ def _report(self, graph: nx.DiGraph):+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={})+ return analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ "detect_unused_internals": False,+ "min_confidence": 0.0,+ }+ )++ def test_cross_file_field_referenced_struct_not_flagged(self, tmp_path: Path) -> None:+ report = self._report(_build_graph(tmp_path))+ unused_exports = {+ f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT+ }+ assert "RecvState" not in unused_exports++ def test_genuinely_dead_struct_in_same_crate_still_flagged(self, tmp_path: Path) -> None:+ # True-positive guard: the field-type capture must not turn into a+ # blanket exemption for every struct in a crate with field types.+ report = self._report(_build_graph(tmp_path))+ unused_exports = {+ f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT+ }+ assert "DeadState" in unused_exports+++class TestRustGenericTypeParamCollision:+ """A generic type parameter that shares a name with a real struct must+ not rescue that struct from dead-code detection.++ ``struct Wrapper<Item> { value: Item }`` — the field's ``Item`` is a+ reference to the type parameter, not to the ``Item`` struct defined+ elsewhere in the crate. Without the type-parameter check, that field+ produces a false ``Wrapper -> Item`` edge, so the genuinely-dead+ ``Item`` struct is no longer flagged.+ """++ _SOURCES: ClassVar[dict[str, str]] = {+ "Cargo.toml": '[package]\nname = "net"\nversion = "0.1.0"\n',+ "src/lib.rs": (+ "pub struct Item { pub id: u32 }\n\n"+ "pub struct Wrapper<Item> { pub value: Item }\n\n"+ "pub fn dead_fn() {}\n"+ ),+ }++ def _build_graph(self, repo: Path) -> nx.DiGraph:+ for rel, body in self._SOURCES.items():+ p = repo / rel+ p.parent.mkdir(parents=True, exist_ok=True)+ p.write_text(body, encoding="utf-8")++ builder = GraphBuilder(repo_path=repo)+ for rel in self._SOURCES:+ if not rel.endswith(".rs"):+ continue+ abs_path = str((repo / rel).resolve())+ parsed = _PARSER.parse_file(_file_info(rel, abs_path), (repo / rel).read_bytes())+ builder.add_file(parsed)+ return builder.build()++ def test_no_edge_from_shadowed_type_param(self, tmp_path: Path) -> None:+ graph = self._build_graph(tmp_path)+ assert not graph.has_edge("src/lib.rs::Wrapper", "src/lib.rs::Item")++ def test_shadowed_type_param_is_not_a_type_reference(self, tmp_path: Path) -> None:+ # The guard has to hold on the type-reference path, which is where+ # these captures now land. ``Item`` names the type parameter, so it+ # must not be recorded as referencing the struct of the same name.+ body = "pub struct Item { pub id: u32 }" + chr(10)+ body += "pub struct Wrapper<Item> { pub value: Item }" + chr(10)+ info = _file_info("src/lib.rs", "/repo/src/lib.rs")+ parsed = _PARSER.parse_file(info, body.encode("utf-8"))+ assert "Item" not in {r.type_name for r in parsed.type_refs}++ def test_shadowed_struct_still_flagged_unused_export(self, tmp_path: Path) -> None:+ graph = self._build_graph(tmp_path)+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={})+ report = analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ "detect_unused_internals": False,+ "min_confidence": 0.0,+ }+ )+ unused_exports = {+ f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT+ }+ assert "Item" in unused_exports