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(cpp): attach a call edge to the definition, not the header declaration (#1626)
Raghav Chamadiya597fe304b9c8
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 9eea7d4ed..cee432ef7 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -1129,6 +1129,15 @@ class DeadCodeAnalyzer:# binary" — never observable in the static graph.if sym.get("is_exported_symbol"):continue+ # A C/C++ forward declaration whose definition was found is not+ # independently deletable — the definition is the unit of+ # deletion, and call resolution attaches the use edge there+ # rather than to the header line, so reporting the declaration+ # too would only restate what the definition says (#1601). A+ # prototype with no definition anywhere is the opposite case:+ # nothing else can carry the finding, so it still gets one.+ if sym.get("is_declaration") and sym.get("defined_by"):+ 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/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 656e131d5..c4a467301 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -80,6 +80,11 @@ class CallResolver:# Global symbol index: {name: [symbol_ids]} — for Tier 3self._global_symbols: dict[str, list[str]] = defaultdict(list)+ # C/C++ forward declaration → the definition it declares. Populated by+ # ``_build_indices``; applied to every resolved call so the edge lands+ # on the body rather than the header line that announced it.+ self._decl_to_def: dict[str, str] = {}+# Import graph: {file_path: set of imported file paths}self._import_targets = import_targets@@ -395,13 +400,28 @@ class CallResolver:(Import-name maps are shared — see ``import_index.build_import_name_maps``.)"""+ # (parent, name) → [(file, symbol_id)] over symbols that carry a body,+ # and the bodiless declarations waiting to be paired against them.+ # Both feed ``_link_declarations`` once every file has been indexed.+ definitions: dict[tuple[str | None, str], list[tuple[str, str]]] = defaultdict(list)+ declarations: list[tuple[str, str, tuple[str | None, str]]] = []+for path, parsed in parsed_files.items():file_syms: dict[str, str] = {}file_methods: dict[tuple[str, str], str] = {}for sym in parsed.symbols:- # File-level symbol index (top-level symbols and methods)- file_syms[sym.name] = sym.id+ decl_key = (sym.parent_name, sym.name)+ if sym.is_declaration:+ declarations.append((path, sym.id, decl_key))+ # A declaration must never displace a definition already+ # indexed under this name — a .cpp that forward-declares a+ # helper above its own body holds both.+ file_syms.setdefault(sym.name, sym.id)+ else:+ definitions[decl_key].append((path, sym.id))+ # File-level symbol index (top-level symbols and methods)+ file_syms[sym.name] = sym.id# Method index: (class_name, method_name) → symbol_idif sym.parent_name:@@ -415,6 +435,72 @@ class CallResolver:self._file_symbols[path] = file_symsself._file_methods[path] = file_methods+ self._decl_to_def = self._link_declarations(declarations, definitions)++ def _link_declarations(+ self,+ declarations: list[tuple[str, str, tuple[str | None, str]]],+ definitions: dict[tuple[str | None, str], list[tuple[str, str]]],+ ) -> dict[str, str]:+ """Pair each C/C++ forward declaration with the definition it declares.++ A header declares ``double Area(double)`` and a .cpp defines it, so the+ two land as separate same-named symbols. Every tier below Tier 1 looks+ the name up in the *header's* symbol table — the header is what the+ caller includes — so the call edge attached to the declaration and left+ the definition with no inbound edge at all, which read as dead code+ (#1601). Resolving the pairing here lets ``resolve_file`` move the edge+ onto the definition, where it belongs.++ Pairing prefers a definition whose translation unit includes the+ declaring header, which is the one-definition rule C++ actually means+ and keeps same-named functions in sibling namespaces apart. Failing+ that, a repo-wide unique definition is unambiguous enough to use. An+ overload set spanning several files matches neither test, and stays+ unlinked rather than guessed at.+ """+ redirects: dict[str, str] = {}+ for decl_file, decl_id, key in declarations:+ candidates = definitions.get(key, ())+ if not candidates:+ continue+ including = [+ sym_id+ for def_file, sym_id in candidates+ if decl_file in self._import_targets.get(def_file, ())+ ]+ if len(including) == 1:+ redirects[decl_id] = including[0]+ elif len(candidates) == 1:+ redirects[decl_id] = candidates[0][1]+ return redirects++ @property+ def declaration_definitions(self) -> dict[str, str]:+ """``{declaration symbol id: definition symbol id}`` for paired decls.++ Read by the graph builder, which stamps the pairing on the declaration+ node so the dead-code pass can tell a superseded declaration from an+ orphaned prototype whose definition no longer exists.+ """+ return self._decl_to_def++ def _redirect_to_definition(self, resolved: ResolvedCall) -> ResolvedCall:+ """Move a call edge off a forward declaration onto its definition.++ No-op for every language but C/C++, and for the tiers that already+ landed on a definition.++ The self-edge guard carries a recursive function whose prototype sits+ in a header: Tier 1 declines to link the call to the body it is+ already inside, Tier 2 then finds the header declaration, and the+ redirect would point the edge straight back at the caller.+ """+ target = self._decl_to_def.get(resolved.callee_id)+ if target is None or target == resolved.caller_id:+ return resolved+ return ResolvedCall(resolved.caller_id, target, resolved.confidence, resolved.line)+def _merged_symbols_for(self, file_path: str) -> dict[str, str]:"""Merged ``{name → symbol_id}`` across every file *file_path* imports.@@ -462,7 +548,7 @@ class CallResolver:resolved = self._resolve_one(file_path, call)if resolved:- results.append(resolved)+ results.append(self._redirect_to_definition(resolved))return resultsdiff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.pyindex 1f0c639fe..9d3e442a6 100644--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py@@ -495,6 +495,15 @@ class ResolveMixin:repo_path=str(self._repo_path) if self._repo_path else None,import_maps=self._shared_import_maps(),)++ # Record which C/C++ declarations were paired with a definition. The+ # dead-code pass suppresses a declaration only when one was found: a+ # prototype whose body exists nowhere in the repo is real dead code,+ # and the header that declares it is the only place left to report it.+ for decl_id, def_id in resolver.declaration_definitions.items():+ if decl_id in self._graph:+ self._graph.nodes[decl_id]["defined_by"] = def_id+total_resolved = 0files_with_calls = [diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.pyindex 1ae456801..44435c2b1 100644--- a/packages/core/src/repowise/core/ingestion/graph/builder.py+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py@@ -242,6 +242,7 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehydsignature=sym.signature,decorators=sym.decorators,is_exported_symbol=sym.is_exported_symbol,+ is_declaration=sym.is_declaration,docstring=sym.docstring,)diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.pyindex 906b338ed..7a397fb94 100644--- a/packages/core/src/repowise/core/ingestion/language_configs.py+++ b/packages/core/src/repowise/core/ingestion/language_configs.py@@ -58,6 +58,11 @@ class LanguageConfig:# Node types that indicate a class context (used with "nesting" mode)parent_class_types: frozenset[str] = field(default_factory=frozenset)+ # Node types whose symbols are bodiless declarations. C/C++ headers declare+ # what a .cpp defines, so both sides land as same-named symbols; this is+ # what tells them apart downstream (see ``Symbol.is_declaration``).+ declaration_node_types: frozenset[str] = field(default_factory=frozenset)+LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {"python": LanguageConfig(@@ -184,6 +189,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {visibility_fn=public_by_default,parent_extraction="nesting",parent_class_types=frozenset({"class_specifier", "struct_specifier"}),+ declaration_node_types=frozenset({"declaration"}),),"c": LanguageConfig(symbol_node_types={@@ -200,6 +206,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {visibility_fn=public_by_default,parent_extraction="none",parent_class_types=frozenset(),+ declaration_node_types=frozenset({"declaration"}),),"kotlin": LanguageConfig(symbol_node_types={diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex 919cb3baf..01f24e38f 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -186,6 +186,12 @@ class Symbol:# ``__declspec(dllexport)`` / ``__attribute__((visibility("default")))``).# Used by dead-code analysis to whitelist exported entry points.is_exported_symbol: bool = False+ # True when this record is a bodiless declaration — a C/C++ forward+ # declaration in a header. The definition carrying the same name lives in+ # a .cpp and is the symbol a call should attach to; the call resolver+ # redirects onto it, and the dead-code pass never reports a declaration,+ # since a declaration is not independently deletable.+ is_declaration: bool = False@dataclassdiff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex 3fbb175a4..0c5e52219 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -755,6 +755,7 @@ class ASTParser:language=file_info.language,parent_name=parent_name,is_exported_symbol=is_exported_symbol,+ is_declaration=node_type in config.declaration_node_types,))node_types.append(node_type)diff --git a/tests/unit/dead_code/test_cpp_declarations.py b/tests/unit/dead_code/test_cpp_declarations.pynew file mode 100644index 000000000..574bb3a29--- /dev/null+++ b/tests/unit/dead_code/test_cpp_declarations.py@@ -0,0 +1,105 @@+"""A C/C++ forward declaration is never an unused export (#1601).++The definition is the unit of deletion and now carries the use edges, so+reporting the header line too would only restate what the definition says —+or, when the definition is genuinely live, report a false positive.+"""++from __future__ import annotations++from repowise.core.analysis.dead_code import DeadCodeAnalyzer++from ._helpers import _build_graph+++def _unused_export_symbols(graph) -> set[str]:+ report = DeadCodeAnalyzer(graph).analyze()+ return {f.symbol_name for f in report.findings if f.kind == "unused_export"}+++def _cpp_nodes() -> dict[str, dict]:+ return {+ "src/shapes.h": {+ "node_type": "file",+ "language": "cpp",+ "symbols": [+ {+ "name": "Area",+ "kind": "function",+ "visibility": "public",+ "language": "cpp",+ "is_declaration": True,+ "defined_by": "src/shapes.cpp::Area",+ "start_line": 2,+ "end_line": 2,+ }+ ],+ },+ "src/shapes.cpp": {+ "node_type": "file",+ "language": "cpp",+ "symbols": [+ {+ "name": "Area",+ "kind": "function",+ "visibility": "public",+ "language": "cpp",+ "is_declaration": False,+ "start_line": 2,+ "end_line": 2,+ }+ ],+ },+ }+++class TestDeclarationNeverFlagged:+ def test_declaration_skipped_when_definition_is_used(self) -> None:+ graph = _build_graph(+ _cpp_nodes(),+ edges=[+ ("src/shapes.cpp", "src/shapes.h", {"edge_type": "imports"}),+ ("src/main.cpp::main", "src/shapes.cpp::Area", {"edge_type": "calls"}),+ ],+ )+ assert _unused_export_symbols(graph) == set()++ def test_definition_still_reported_when_truly_unused(self) -> None:+ # The declaration drops out, but the finding itself must survive and+ # point at the .cpp — suppressing declarations must not suppress real+ # dead code.+ graph = _build_graph(+ _cpp_nodes(),+ edges=[("src/shapes.cpp", "src/shapes.h", {"edge_type": "imports"})],+ )+ findings = [+ f+ for f in DeadCodeAnalyzer(graph).analyze().findings+ if f.kind == "unused_export" and f.symbol_name == "Area"+ ]+ assert [f.file_path for f in findings] == ["src/shapes.cpp"]++ def test_orphaned_prototype_is_still_reported(self) -> None:+ # No definition anywhere in the repo, so nothing carries ``defined_by``+ # and nothing else can carry the finding. Suppressing this one would+ # trade a false positive for a silent false negative.+ graph = _build_graph(+ {+ "src/orphan.h": {+ "node_type": "file",+ "language": "cpp",+ "symbols": [+ {+ "name": "Vanished",+ "kind": "function",+ "visibility": "public",+ "language": "cpp",+ "is_declaration": True,+ "start_line": 2,+ "end_line": 2,+ }+ ],+ }+ }+ )+ assert _unused_export_symbols(graph) == {"Vanished"}diff --git a/tests/unit/ingestion/test_cpp_decl_def.py b/tests/unit/ingestion/test_cpp_decl_def.pynew file mode 100644index 000000000..97dc7b2c6--- /dev/null+++ b/tests/unit/ingestion/test_cpp_decl_def.py@@ -0,0 +1,112 @@+"""C/C++ forward declaration ↔ definition pairing in call resolution (#1601).++The standard C++ layout declares a function in a header and defines it in a+.cpp. Both land as same-named symbols, and every resolution tier below the+same-file one looks names up in the *header's* symbol table, because the+header is what a caller includes. The call edge therefore attached to the+declaration and the definition was left with no inbound edge at all, which+read as a ``safe_to_delete`` unused export.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+++def _build(repo: Path):+ traverser = FileTraverser(repo)+ parser = ASTParser()+ builder = GraphBuilder(repo_path=repo)+ for fi in traverser.traverse():+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))+ return builder.build()+++def _callers_of(graph, symbol_id: str) -> set[str]:+ return {+ pred+ for pred in graph.predecessors(symbol_id)+ if graph[pred][symbol_id].get("edge_type") == "calls"+ }+++class TestDeclarationFlag:+ def test_header_declaration_is_marked(self, tmp_path: Path) -> None:+ (tmp_path / "shapes.h").write_text("namespace Geo { double Area(double r); }\n")+ graph = _build(tmp_path)+ assert graph.nodes["shapes.h::Area"]["is_declaration"] is True++ def test_definition_is_not_marked(self, tmp_path: Path) -> None:+ (tmp_path / "shapes.cpp").write_text(+ "namespace Geo { double Area(double r) { return r; } }\n"+ )+ graph = _build(tmp_path)+ assert graph.nodes["shapes.cpp::Area"]["is_declaration"] is False++ def test_non_cpp_language_never_marked(self, tmp_path: Path) -> None:+ # ``declaration_node_types`` is empty for every other language, so the+ # flag stays off and the redirect below is a C/C++-only behaviour.+ (tmp_path / "mod.py").write_text("def area(r):\n return r\n")+ graph = _build(tmp_path)+ assert graph.nodes["mod.py::area"]["is_declaration"] is False+++class TestCallAttachesToDefinition:+ def test_cross_file_call_reaches_the_definition(self, tmp_path: Path) -> None:+ (tmp_path / "shapes.h").write_text("namespace Geo { double Area(double r); }\n")+ (tmp_path / "shapes.cpp").write_text(+ '#include "shapes.h"\n'+ "namespace Geo { double Area(double r) { return 3.14 * r * r; } }\n"+ )+ (tmp_path / "main.cpp").write_text(+ '#include "shapes.h"\nint main() { return (int)Geo::Area(2.0); }\n'+ )+ graph = _build(tmp_path)+ assert _callers_of(graph, "shapes.cpp::Area") == {"main.cpp::main"}+ # The declaration keeps its ``defines`` edge and nothing else.+ assert _callers_of(graph, "shapes.h::Area") == set()++ def test_c_translation_unit_pairing(self, tmp_path: Path) -> None:+ (tmp_path / "util.h").write_text("int helper(void);\n")+ (tmp_path / "util.c").write_text('#include "util.h"\nint helper(void) { return 1; }\n')+ (tmp_path / "app.c").write_text('#include "util.h"\nint run(void) { return helper(); }\n')+ graph = _build(tmp_path)+ assert _callers_of(graph, "util.c::helper") == {"app.c::run"}++ def test_same_file_forward_declaration(self, tmp_path: Path) -> None:+ # A .cpp that forward-declares a helper above its own body holds both+ # records; the declaration must not shadow the definition in the+ # file-level symbol index.+ (tmp_path / "solo.cpp").write_text(+ "static int helper(int);\n"+ "int run() { return helper(1); }\n"+ "static int helper(int v) { return v * 2; }\n"+ )+ graph = _build(tmp_path)+ assert "solo.cpp::run" in _callers_of(graph, "solo.cpp::helper")++ def test_paired_declaration_records_its_definition(self, tmp_path: Path) -> None:+ (tmp_path / "shapes.h").write_text("double Area(double r);\n")+ (tmp_path / "shapes.cpp").write_text(+ '#include "shapes.h"\ndouble Area(double r) { return r; }\n'+ )+ graph = _build(tmp_path)+ assert graph.nodes["shapes.h::Area"]["defined_by"] == "shapes.cpp::Area"++ def test_orphaned_prototype_records_no_definition(self, tmp_path: Path) -> None:+ (tmp_path / "orphan.h").write_text("double Vanished(double r);\n")+ graph = _build(tmp_path)+ assert graph.nodes["orphan.h::Vanished"].get("defined_by") is None++ def test_overload_set_across_files_is_left_alone(self, tmp_path: Path) -> None:+ # Two definitions of ``Area`` in different translation units, neither+ # including the header: the pairing is genuinely ambiguous, so no+ # redirect is invented.+ (tmp_path / "shapes.h").write_text("double Area(double r);\n")+ (tmp_path / "circle.cpp").write_text("double Area(double r) { return r; }\n")+ (tmp_path / "square.cpp").write_text("double Area(double r) { return r * r; }\n")+ graph = _build(tmp_path)+ assert _callers_of(graph, "circle.cpp::Area") == set()+ assert _callers_of(graph, "square.cpp::Area") == set()