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(ingestion): rescue C++ types used only within their own TU (#1787)
Sloe7cd722c01d08
diff --git a/packages/core/src/repowise/core/ingestion/queries/cpp.scm b/packages/core/src/repowise/core/ingestion/queries/cpp.scmindex 8457c454c..f057f80f5 100644--- a/packages/core/src/repowise/core/ingestion/queries/cpp.scm+++ b/packages/core/src/repowise/core/ingestion/queries/cpp.scm@@ -229,6 +229,16 @@(field_declarationtype: (_) @param.type)+; Local / global variable declarations: Row scratch{ ... }; or Widget *w;+; A type used as the declared type of a variable in the same TU is a genuine+; reference, but the captures above only see parameters, fields, return+; types and template arguments — a ``Row scratch`` local reads as dead+; without this. ``type_identifier`` matches only the bare-name form, so a+; ``struct Row { ... }`` definition (wrapped in ``struct_specifier``) is not+; caught here; it has no cross-file edge anyway.+(declaration+ type: (type_identifier) @param.type)+; Function return type: Widget * make(...)(function_definitiontype: (_) @param.type)diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.pyindex 9275d3501..d607895b3 100644--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py@@ -468,6 +468,7 @@ def _resolve_c_type_refs(emitted = 0seen_targets: set[tuple[str, str]] = set()+ same_file_refs: set[str] = set()for ref in parsed.type_refs:name = ref.type_nameif not name or name in c_builtin_types:@@ -478,7 +479,17 @@ def _resolve_c_type_refs(name, from_path, sorted_imports, sorted_siblings, ctx, graph,defined_names,)- if target is None or target == from_path:+ # A type defined in this very translation unit has no cross-file edge+ # to mint — ``_find_c_type_file`` returns ``None`` for it (the stem+ # map excludes ``from_path``). It is still genuinely referenced, so+ # stamp it onto ``local_type_uses`` so the dead-code analyzer rescues+ # it, exactly as the Go and TS resolvers do for intra-module type+ # refs. Otherwise a struct/class used only inside its own .cpp reads+ # as an unused_export with ``safe_to_delete: ✓``, yet deleting it+ # breaks the build.+ if target is None:+ if name in defined_names.get(from_path, _EMPTY_NAMES):+ same_file_refs.add(name)continueif (name, target) in seen_targets:continue@@ -486,6 +497,14 @@ def _resolve_c_type_refs(_add_or_merge_type_use_edge(graph, src=from_path, dst=target,type_name=name, origin=ref.origin)emitted += 1++ if same_file_refs and graph.has_node(from_path):+ existing = graph.nodes[from_path].get("local_type_uses")+ if existing is None:+ graph.nodes[from_path]["local_type_uses"] = same_file_refs+ else:+ existing.update(same_file_refs)+return emitteddiff --git a/tests/unit/ingestion/test_c_type_use.py b/tests/unit/ingestion/test_c_type_use.pyindex a3166c583..3aea20c41 100644--- a/tests/unit/ingestion/test_c_type_use.py+++ b/tests/unit/ingestion/test_c_type_use.py@@ -18,6 +18,7 @@ from __future__ import annotationsfrom datetime import datetimefrom pathlib import Path+from typing import ClassVarimport networkx as nx@@ -163,3 +164,92 @@ class TestHonestyGuard:findings = DeadCodeAnalyzer(graph).analyze().findingsflagged = {f.symbol_name for f in findings}assert "avif_encode" not in flagged+++# ---------------------------------------------------------------------------+# C++ same-TU type use (#1656) — a struct used only inside its own .cpp+# ---------------------------------------------------------------------------+++class TestCppSameTranslationUnitTypeUse:+ """Issue #1656: a ``struct``/``class`` defined in a .cpp and used only+ within that same translation unit must NOT read as an unused export.++ The C++ resolver mints a cross-file ``type_use`` edge for a header type+ used across an ``#include``, but a type defined and used in the *same* file+ has no cross-file edge to mint. It is still genuinely referenced, so it+ must be rescued via ``local_type_uses`` — exactly as the Go and TS+ resolvers already do for intra-module type refs.+ """++ _SOURCES: ClassVar[dict[str, str]] = {+ "sky.h": (+ "#pragma once\n\n"+ "namespace demo\n"+ "{\n"+ " class Sky\n"+ " {\n"+ " public:\n"+ " float Compute(float t) const;\n"+ " };\n"+ "}\n"+ ),+ "sky.cpp": (+ '#include "sky.h"\n\n'+ "namespace demo\n"+ "{\n"+ " struct Row\n"+ " {\n"+ " float a;\n"+ " float b;\n"+ " };\n\n"+ " float Sky::Compute(float t) const\n"+ " {\n"+ " Row scratch{ 1.0f, 2.0f }; // Row is used right here\n"+ " return scratch.a * t + scratch.b;\n"+ " }\n"+ "}\n"+ ),+ "main.cpp": (+ '#include "sky.h"\n\n'+ "int main()\n"+ "{\n"+ " demo::Sky sky;\n"+ " return static_cast<int>(sky.Compute(2.0f));\n"+ "}\n"+ ),+ }++ def _build(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")+ # FileTraverser infers language from the extension (.cpp → cpp), which+ # is what routes the C++ type-ref strategy.+ from repowise.core.ingestion import FileTraverser++ parser = ASTParser()+ builder = GraphBuilder(repo_path=repo)+ for fi in FileTraverser(repo).traverse():+ builder.add_file(+ parser.parse_file(fi, Path(fi.abs_path).read_bytes())+ )+ return builder.build()++ def test_same_file_type_use_stamped_local(self, tmp_path: Path) -> None:+ graph = self._build(tmp_path)+ # Row is defined and used only inside sky.cpp — no cross-file edge, but+ # the type-ref resolver must stamp it as a local use.+ node = graph.nodes.get("sky.cpp")+ assert node is not None+ assert "Row" in node.get("local_type_uses", ())++ def test_same_file_type_not_flagged_as_dead(self, tmp_path: Path) -> None:+ graph = self._build(tmp_path)+ findings = DeadCodeAnalyzer(graph).analyze().findings+ flagged = {f.symbol_name for f in findings}+ assert "Row" not in flagged, (+ "Row is used in the same TU; it must not read as an unused_export"+ )+