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(graph): a C++ forward-declared type is not an unused export (#1700)
Raghav Chamadiyaa8109c9759d2
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex f5bf7675a..87f4c8488 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -358,6 +358,18 @@ _UNCALLABLE_TYPE_KINDS: frozenset[str] = frozenset(})++#: C/C++ symbol kinds a bare ``class Env;`` / ``struct Options;`` can carry.+#: Paired with ``is_declaration`` this identifies a type forward declaration,+#: which is never a deletable unit — see the guard in ``_detect_unused_exports``.+_CPP_TYPE_DECLARATION_KINDS: frozenset[str] = frozenset(+ {+ "class",+ "struct",+ "enum",+ }+)+# Symbol names that are language-runtime entry points or compiler-implicit# anchors — never invoked by user-authored callers, never dead._ENTRY_POINT_SYMBOL_NAMES: frozenset[str] = frozenset(@@ -1239,6 +1251,22 @@ class DeadCodeAnalyzer:# nothing else can carry the finding, so it still gets one.if sym.get("is_declaration") and sym.get("defined_by"):continue+ # A C/C++ *type* forward declaration is not a deletable unit at+ # all, paired or not, so it is not held to the clause above.+ # A prototype promises a body, and a body that exists nowhere+ # makes the prototype itself the dead thing. ``class Env;``+ # promises nothing: it exists so the declaring file can name+ # the type without including its header, which makes that file+ # the declaration's user. Deleting the line breaks it whether+ # the definition lives in this repo or in a dependency — and+ # when it is in the repo, the definition already carries the+ # finding.+ if (+ sym.get("is_declaration")+ and sym.get("language") in ("cpp", "c")+ and sym.get("kind") in _CPP_TYPE_DECLARATION_KINDS+ ):+ 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/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.pyindex 8fd1d5d25..a8b8e55dd 100644--- a/packages/core/src/repowise/core/ingestion/graph/builder.py+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py@@ -226,6 +226,22 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd# --- Symbol nodes ---for sym in parsed.symbols:+ # A declaration must never displace a definition already indexed+ # under this id — the same rule ``call_resolver._build_indices``+ # applies to its own symbol table, and it belongs here too because+ # the id is ``<path>::<name>``, so a C++ header that defines a+ # class and re-declares it later (a second namespace block, a+ # template primary declaration beside its specializations) collapses+ # both into one node and the *last* emission wins. Left unguarded,+ # the one-line declaration overwrites a definition's span, kind and+ # ``is_declaration``, and every consumer that tells the two apart+ # then reads the header line as the whole symbol.+ if sym.is_declaration:+ existing = self._graph.nodes.get(sym.id)+ if existing is not None and existing.get("is_declaration") is False:+ self._graph.add_edge(path, sym.id, edge_type="defines")+ continue+self._graph.add_node(sym.id,node_type="symbol",diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex 9a85e62bd..c835fcf4b 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -114,6 +114,45 @@ _TS_JS_LANGUAGES = ("typescript", "javascript", "svelte", "vue")_REFERENCE_LANGUAGES = ("cpp", "c", "go", "rust", "kotlin")+# C/C++ node types that spell a type. Each one covers both the definition and+# the forward declaration of that type; only the ``body`` field tells them+# apart. See ``_is_bodiless_cpp_type``.+# ``union_specifier`` is absent because neither grammar's query captures one+# as a symbol today. If a union capture is ever added, add it here too, or a+# bodiless ``union U;`` goes back to reading as a definition.+_CPP_TYPE_SPECIFIER_NODES = frozenset(+ {"class_specifier", "struct_specifier", "enum_specifier"}+)+++def _is_bodiless_cpp_type(language: str, node_type: str, def_node: Node) -> bool:+ """True for a C/C++ type forward declaration such as ``class Env;``.++ ``declaration_node_types`` already catches a *function* prototype, whose+ tree-sitter node genuinely is a ``declaration``. A type forward declaration+ is not: it arrives as the very same ``class_specifier`` a definition uses,+ minus the ``body`` field. Left unmarked it reads as a whole class defined+ on one line, so every consumer that distinguishes a declaration from a+ definition — call resolution's declaration/definition pairing and the+ dead-code passes — silently treats the header line as the real thing.+ """+ if language not in ("cpp", "c"):+ return False+ if node_type not in _CPP_TYPE_SPECIFIER_NODES:+ return False+ if def_node.child_by_field_name("body") is not None:+ return False+ # ``typedef struct CBMAutomaton CBMAutomaton;`` — C's opaque-handle idiom.+ # The tag and the typedef name are the same identifier, so both patterns+ # match at one position and dedup keeps a single symbol. That symbol is the+ # typedef name, which *is* a deletable API artifact and must stay+ # reportable. Erring toward under-marking: a forward-declared tag under a+ # differently-named typedef (``typedef struct Impl_s Handle;``) is left+ # unmarked too, which only costs a suppression we never had.+ parent = def_node.parent+ return parent is None or parent.type != "type_definition"++@cachedef _load_compiled_query(lang: str, grammar_tag: str | None = None) -> object | None:"""Process-wide cache of compiled tree-sitter Query objects.@@ -786,7 +825,10 @@ 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,+ is_declaration=(+ node_type in config.declaration_node_types+ or _is_bodiless_cpp_type(file_info.language, node_type, def_node)+ ),))node_types.append(node_type)diff --git a/tests/unit/dead_code/test_cpp_declarations.py b/tests/unit/dead_code/test_cpp_declarations.pyindex 574bb3a29..6028d5b33 100644--- a/tests/unit/dead_code/test_cpp_declarations.py+++ b/tests/unit/dead_code/test_cpp_declarations.py@@ -103,3 +103,90 @@ class TestDeclarationNeverFlagged:})assert _unused_export_symbols(graph) == {"Vanished"}+++class TestTypeDeclarationNeverFlagged:+ """A *type* forward declaration is not held to the ``defined_by`` clause.++ The asymmetry with a prototype is argued at the guard in ``analyzer.py``.+ """++ @staticmethod+ def _header_with(kind: str, *, defined_by: str | None = None) -> dict:+ symbol = {+ "name": "Env",+ "kind": kind,+ "visibility": "public",+ "language": "cpp",+ "is_declaration": True,+ "start_line": 4,+ "end_line": 4,+ }+ if defined_by:+ symbol["defined_by"] = defined_by+ return {+ "src/builder.h": {+ "node_type": "file",+ "language": "cpp",+ "symbols": [symbol],+ }+ }++ def test_unpaired_type_declaration_is_skipped(self) -> None:+ # The orphaned-prototype rule must not extend to types: `class Env;`+ # with the definition in a dependency is the normal case, not dead code.+ for kind in ("class", "struct", "enum"):+ graph = _build_graph(self._header_with(kind))+ assert _unused_export_symbols(graph) == set(), kind++ def test_paired_type_declaration_is_skipped(self) -> None:+ graph = _build_graph(self._header_with("class", defined_by="src/env.cc::Env"))+ assert _unused_export_symbols(graph) == set()++ def test_type_definition_is_still_reported(self) -> None:+ # Only the declaration is exempt. An unused definition of the same name+ # must still be reported, or the guard has bought a false negative.+ graph = _build_graph(+ {+ "src/env.h": {+ "node_type": "file",+ "language": "cpp",+ "symbols": [+ {+ "name": "Env",+ "kind": "class",+ "visibility": "public",+ "language": "cpp",+ "is_declaration": False,+ "start_line": 4,+ "end_line": 40,+ }+ ],+ }+ }+ )+ assert _unused_export_symbols(graph) == {"Env"}++ def test_other_languages_are_untouched(self) -> None:+ # The guard is C/C++ only. Nothing else marks a bodiless type as a+ # declaration, and a stray flag must not silence another language.+ graph = _build_graph(+ {+ "src/model.ts": {+ "node_type": "file",+ "language": "typescript",+ "symbols": [+ {+ "name": "Env",+ "kind": "class",+ "visibility": "public",+ "language": "typescript",+ "is_declaration": True,+ "start_line": 4,+ "end_line": 4,+ }+ ],+ }+ }+ )+ assert _unused_export_symbols(graph) == {"Env"}diff --git a/tests/unit/ingestion/test_cpp_decl_def.py b/tests/unit/ingestion/test_cpp_decl_def.pyindex 97dc7b2c6..ac42a2b5f 100644--- a/tests/unit/ingestion/test_cpp_decl_def.py+++ b/tests/unit/ingestion/test_cpp_decl_def.py@@ -110,3 +110,70 @@ class TestCallAttachesToDefinition:graph = _build(tmp_path)assert _callers_of(graph, "circle.cpp::Area") == set()assert _callers_of(graph, "square.cpp::Area") == set()+++class TestTypeDeclarationFlag:+ """``class Env;`` is a declaration too, and only the ``body`` field says so.++ Mechanics in ``parser._is_bodiless_cpp_type``.+ """++ def test_bodiless_type_is_marked(self, tmp_path: Path) -> None:+ (tmp_path / "builder.h").write_text(+ "namespace leveldb {\nclass Env;\nstruct Options;\nenum Level;\n}\n"+ )+ graph = _build(tmp_path)+ for name in ("Env", "Options", "Level"):+ assert graph.nodes[f"builder.h::{name}"]["is_declaration"] is True, name++ def test_type_with_a_body_is_not_marked(self, tmp_path: Path) -> None:+ (tmp_path / "env.h").write_text(+ "namespace leveldb {\nclass Env {\n public:\n int Now();\n};\n}\n"+ )+ graph = _build(tmp_path)+ assert graph.nodes["env.h::Env"]["is_declaration"] is False++ def test_c_opaque_handle_typedef_stays_reportable(self, tmp_path: Path) -> None:+ # ``typedef struct Foo Foo;`` is C's opaque-handle idiom. Tag and+ # typedef name are one identifier, so the two query patterns match at+ # one position and a single symbol survives — the typedef name, which+ # is real API and must not be exempted as a forward declaration.+ (tmp_path / "ac.h").write_text(+ "typedef struct CBMAutomaton CBMAutomaton;\n"+ "typedef struct Impl_s Handle;\n"+ "struct Plain;\n"+ )+ graph = _build(tmp_path)+ assert graph.nodes["ac.h::CBMAutomaton"]["is_declaration"] is False+ assert graph.nodes["ac.h::Handle"]["is_declaration"] is False+ # Not a typedef, so still a plain forward declaration.+ assert graph.nodes["ac.h::Plain"]["is_declaration"] is True++ def test_definition_wins_whichever_order_they_appear_in(self, tmp_path: Path) -> None:+ # Declaration and definition share a symbol id, so the graph holds one+ # node and the last emission would otherwise win. Definition-*after*-+ # declaration passes either way; the reverse is the real case (seastar's+ # smp.hh defines smp_message_queue at 177 and re-declares it at 301) and+ # it silently reduced a 120-line class to a one-line declaration.+ decl, defn = "class Shape;", "class Shape {\n public:\n int Area();\n};"+ for name, body in (+ ("decl_first.h", f"namespace geo {{\n{decl}\n{defn}\n}}\n"),+ ("def_first.h", f"namespace geo {{\n{defn}\n{decl}\n}}\n"),+ ):+ (tmp_path / name).write_text(body)+ graph = _build(tmp_path)+ for name in ("decl_first.h", "def_first.h"):+ node = graph.nodes[f"{name}::Shape"]+ assert node["is_declaration"] is False, name+ assert node["end_line"] > node["start_line"], name++ def test_the_definition_keeps_its_defines_edge(self, tmp_path: Path) -> None:+ # Skipping the declaration's ``add_node`` must not skip its file edge,+ # or the file stops defining a symbol it does define.+ (tmp_path / "def_first.h").write_text(+ "namespace geo {\nclass Shape {\n public:\n int Area();\n};\nclass Shape;\n}\n"+ )+ graph = _build(tmp_path)+ assert graph.get_edge_data("def_first.h", "def_first.h::Shape") == {+ "edge_type": "defines"+ }