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): recognise .inl / .ipp / .tpp as C++ source (#1625)
Raghav Chamadiya2383e96f7255
diff --git a/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.pyindex 3bdf318d2..7c3733df6 100644--- a/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py+++ b/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py@@ -38,12 +38,16 @@ from __future__ import annotationsfrom pathlib import PurePosixPathfrom typing import Any+from ...ingestion.languages.specs.cpp import INCLUDE_FRAGMENT_EXTENSIONSfrom ...ingestion.models import REACHABILITY_USE_EDGE_TYPES# File extensions this module rescues. The C/C++ tree-sitter grammar-# tag covers all of these; the resolver shares them too.+# tag covers all of these; the resolver shares them too. Include fragments+# count as headers here: like a header, a fragment has no importer of its+# own beyond the translation unit that pastes it in._CPP_HEADER_EXTS: tuple[str, ...] = (".h", ".hpp", ".hxx", ".hh", ".h++", ".inc",+ *sorted(INCLUDE_FRAGMENT_EXTENSIONS),)_CPP_SOURCE_EXTS: tuple[str, ...] = (".c", ".cc", ".cpp", ".cxx", ".c++", ".C",diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/cpp.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/cpp.pyindex c046970ad..9f3361f00 100644--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/cpp.py+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/cpp.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport refrom pathlib import Path+from ..languages.specs.cpp import INCLUDE_FRAGMENT_EXTENSIONSfrom .base import DynamicEdge, DynamicHintExtractor_SKIP_DIRS = {@@ -19,7 +20,13 @@ _SKIP_DIRS = {"node_modules", ".git", "third_party", "vendor", "_deps",}-_CPP_EXTS: tuple[str, ...] = (".cc", ".cpp", ".cxx", ".c++", ".hpp", ".hxx", ".h")+# Include fragments are scanned too: a generated binding table pasted into a+# .inl is exactly where function-pointer and designated-initialiser wiring+# tends to live, which is the wiring this extractor exists to find.+_CPP_EXTS: tuple[str, ...] = (+ ".cc", ".cpp", ".cxx", ".c++", ".hpp", ".hxx", ".h",+ *sorted(INCLUDE_FRAGMENT_EXTENSIONS),+)# fp = some_function; (function-pointer wiring — RHS must be a known# function name to count as a function-pointer assignment).diff --git a/packages/core/src/repowise/core/ingestion/external_systems/cmake.py b/packages/core/src/repowise/core/ingestion/external_systems/cmake.pyindex 7d9706d24..bcabdd00f 100644--- a/packages/core/src/repowise/core/ingestion/external_systems/cmake.py+++ b/packages/core/src/repowise/core/ingestion/external_systems/cmake.py@@ -31,6 +31,7 @@ from pathlib import Path, PurePosixPathimport structlog+from ..languages.specs.cpp import INCLUDE_FRAGMENT_EXTENSIONSfrom .base import ExternalSystemRecordlog = structlog.get_logger(__name__)@@ -109,7 +110,12 @@ _SET_RHS_TERMINATORS: frozenset[str] = frozenset({_VAR_REF_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")-_HEADER_EXTS: tuple[str, ...] = (".h", ".hpp", ".hxx", ".hh", ".h++", ".inc")+# Include fragments bucket with the headers: a target that lists one is+# shipping it as part of its interface, not compiling it on its own.+_HEADER_EXTS: tuple[str, ...] = (+ ".h", ".hpp", ".hxx", ".hh", ".h++", ".inc",+ *sorted(INCLUDE_FRAGMENT_EXTENSIONS),+)_SOURCE_EXTS: tuple[str, ...] = (".c", ".cc", ".cpp", ".cxx", ".c++", ".cppm", ".ixx", ".mxx")diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.pyindex 5f8804b5e..1f0c639fe 100644--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py@@ -10,6 +10,8 @@ from typing import Anyimport structlog+from ..languages.specs.cpp import INCLUDE_FRAGMENT_EXTENSIONS+log = structlog.get_logger(__name__)@@ -251,7 +253,19 @@ class ResolveMixin:The pairing edge makes BFS transit headers into implementations."""header_exts = (".h", ".hpp", ".hxx", ".hh", ".h++")- source_exts = (".c", ".cc", ".cpp", ".cxx", ".c++")+ # An include fragment pairs as the implementation side: ``vector.inl``+ # holds what ``vector.h`` declares, which is the relationship this edge+ # exists to carry. The reachability pass groups fragments with headers+ # instead, because the question there is "who imports this", and a+ # fragment has no importer of its own either. Different questions.+ source_exts = (+ ".c",+ ".cc",+ ".cpp",+ ".cxx",+ ".c++",+ *sorted(INCLUDE_FRAGMENT_EXTENSIONS),+ )cpp_files = [pdiff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.pyindex 13ffea481..089d76a38 100644--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py@@ -24,6 +24,8 @@ import contextlibfrom collections.abc import Callablefrom typing import TYPE_CHECKING, Any+from .languages.specs.cpp import INCLUDE_FRAGMENT_EXTENSIONS+if TYPE_CHECKING:from .models import ParsedFilefrom .resolvers import ResolverContext@@ -34,6 +36,16 @@ if TYPE_CHECKING:# attribute cache); the dispatcher does not inspect the return value.Warmup = Callable[["ResolverContext"], None]+# Paths the export-macro rescan reads. Include fragments belong here: a+# template implementation in a .inl carries the same project export macro as+# the header that declares it, and missing it leaves the symbol marked+# non-exported, which is what the dead-code pass then acts on.+_CPP_MACRO_SCAN_EXTS: tuple[str, ...] = (+ ".h", ".hpp", ".hxx", ".hh", ".h++", ".inc",+ ".c", ".cc", ".cpp", ".cxx", ".c++",+ *sorted(INCLUDE_FRAGMENT_EXTENSIONS),+)+def _warmup_jvm(ctx: ResolverContext) -> None:from .resolvers.jvm_workspace import get_or_build_jvm_index@@ -134,8 +146,7 @@ def _warmup_cpp(ctx: ResolverContext) -> None:if macros:for path, parsed in parsed_files.items():- if not path.endswith((".h", ".hpp", ".hxx", ".hh", ".h++", ".inc",- ".c", ".cc", ".cpp", ".cxx", ".c++")):+ if not path.endswith(_CPP_MACRO_SCAN_EXTS):continuefor sym in parsed.symbols:sig = sym.signature or ""diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/cpp.py b/packages/core/src/repowise/core/ingestion/languages/specs/cpp.pyindex c2cd225d4..fae625c47 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/cpp.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/cpp.py@@ -2,6 +2,16 @@from ..spec import LanguageSpec+#: Include fragments: C++ source that is ``#include``d into a translation unit+#: rather than compiled as one of its own. The convention carries inline and+#: template implementations, and generated binding tables pasted mid-file.+#:+#: Exported because three questions elsewhere need the same answer and used to+#: each keep their own list: which extensions are C++ at all, which behave like+#: a header for include resolution and reachability, and which are a fragment+#: rather than a module. See ``traverser`` for the last of those.+INCLUDE_FRAGMENT_EXTENSIONS: frozenset[str] = frozenset({".inl", ".ipp", ".tpp"})+SPEC = LanguageSpec(tag="cpp",display_name="C++",@@ -13,7 +23,8 @@ SPEC = LanguageSpec(# its API surface (fmt, leveldb, boost layouts). Root-anchored: a# vendored include/ deep in another tree must not mint the layer.layer_dir_hints=(("/include", "API"),),- extensions=frozenset({".cpp", ".cc", ".cxx", ".h", ".hpp", ".hxx"}),+ extensions=frozenset({".cpp", ".cc", ".cxx", ".h", ".hpp", ".hxx"})+ | INCLUDE_FRAGMENT_EXTENSIONS,grammar_package="tree_sitter_cpp",scm_file="cpp.scm",heritage_node_types=frozenset({"class_specifier", "struct_specifier"}),diff --git a/packages/core/src/repowise/core/ingestion/resolvers/cpp.py b/packages/core/src/repowise/core/ingestion/resolvers/cpp.pyindex 75e934527..8a52f87af 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/cpp.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/cpp.py@@ -31,10 +31,21 @@ from __future__ import annotationsimport posixpathfrom pathlib import Path+from ..languages.specs.cpp import INCLUDE_FRAGMENT_EXTENSIONSfrom .context import ResolverContext_SOURCE_TU_EXTS: tuple[str, ...] = (".c", ".cc", ".cpp", ".cxx", ".c++", ".cppm", ".ixx", ".mxx")-_HEADER_EXTS: tuple[str, ...] = (".h", ".hpp", ".hxx", ".hh", ".h++", ".inc")+# Include fragments sit with the headers: ``#include "math_impl.inl"`` resolves+# by the same rules, and a fragment is never a translation unit of its own.+_HEADER_EXTS: tuple[str, ...] = (+ ".h",+ ".hpp",+ ".hxx",+ ".hh",+ ".h++",+ ".inc",+ *sorted(INCLUDE_FRAGMENT_EXTENSIONS),+)def _is_system_include(module_path: str, system_form: bool) -> bool:diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.pyindex d9fcf386c..e29348ff6 100644--- a/packages/core/src/repowise/core/ingestion/traverser.py+++ b/packages/core/src/repowise/core/ingestion/traverser.py@@ -31,6 +31,7 @@ from pathspec.patterns.gitwildmatch import GitWildMatchPattern, GitWildMatchPattfrom ..entry_candidacy import conventional_entry_stems, not_an_execution_startfrom ..test_paths import is_test_related_pathfrom .languages.registry import REGISTRY as _LANG_REGISTRY+from .languages.specs.cpp import INCLUDE_FRAGMENT_EXTENSIONSfrom .models import (EXTENSION_TO_LANGUAGE,SPECIAL_FILENAMES,@@ -662,7 +663,20 @@ class FileTraverser:# Generated file detection: only meaningful for code files. Skipping# for data/markup files avoids a 512-byte read per file with no benefit.- if language not in _SKIP_GENERATED_CHECK and _is_generated(abs_path):+ #+ # An include fragment is exempt even when generated. This skip exists to+ # keep machine-written *modules* out of the index, and a .inl is not a+ # module: it is text pasted into a hand-written translation unit, so+ # dropping it deletes edges from code nobody generated. A generated+ # binding table is often the only reason the macros it invokes have call+ # sites at all, and skipping it reported those macros as unused (#1600).+ # Parsing generated modules without documenting them is a wider question+ # than this exemption, and is left alone.+ if (+ language not in _SKIP_GENERATED_CHECK+ and abs_path.suffix.lower() not in INCLUDE_FRAGMENT_EXTENSIONS+ and _is_generated(abs_path)+ ):with self._count_lock:self.stats.skipped_generated += 1log.debug("Skipping generated file", path=rel_str)diff --git a/tests/unit/ingestion/test_cpp_include_fragments.py b/tests/unit/ingestion/test_cpp_include_fragments.pynew file mode 100644index 000000000..e50cbdf5c--- /dev/null+++ b/tests/unit/ingestion/test_cpp_include_fragments.py@@ -0,0 +1,172 @@+"""``.inl`` / ``.ipp`` / ``.tpp`` are C++ (#1600).++The convention carries inline and template implementations, and generated+binding tables pasted mid-file. None of those extensions was in the C++ spec,+so the files were excluded as "unknown type" before anything read them: the+symbols they define were absent from the index, and — the more damaging half —+so was every reference *made from inside* them, which left the macros a+generated table invokes looking unused.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+from repowise.core.ingestion.languages.registry import REGISTRY+++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 _traversed(repo: Path) -> set[str]:+ return {fi.path for fi in FileTraverser(repo).traverse()}+++def _callers_of(graph, symbol_id: str) -> set[str]:+ if not graph.has_node(symbol_id):+ return set()+ return {+ pred+ for pred in graph.predecessors(symbol_id)+ if graph[pred][symbol_id].get("edge_type") == "calls"+ }+++class TestExtensionRegistration:+ def test_fragment_extensions_map_to_cpp(self) -> None:+ for ext in (".inl", ".ipp", ".tpp"):+ assert REGISTRY.from_extension(ext) == "cpp"++ def test_existing_cpp_extensions_not_regressed(self) -> None:+ for ext in (".cpp", ".cc", ".cxx", ".h", ".hpp", ".hxx"):+ assert REGISTRY.from_extension(ext) == "cpp"+++class TestFragmentIsIndexed:+ def test_symbol_defined_in_a_fragment_is_indexed(self, tmp_path: Path) -> None:+ (tmp_path / "math_impl.inl").write_text("inline int TripleValue(int v) { return v * 3; }\n")+ graph = _build(tmp_path)+ assert graph.has_node("math_impl.inl::TripleValue")++ def test_call_into_a_fragment_resolves(self, tmp_path: Path) -> None:+ (tmp_path / "math_impl.inl").write_text("inline int TripleValue(int v) { return v * 3; }\n")+ (tmp_path / "uses.cpp").write_text(+ '#include "math_impl.inl"\nint Show() { return TripleValue(3); }\n'+ )+ graph = _build(tmp_path)+ assert _callers_of(graph, "math_impl.inl::TripleValue") == {"uses.cpp::Show"}++ def test_include_of_a_fragment_is_an_import_edge(self, tmp_path: Path) -> None:+ (tmp_path / "math_impl.inl").write_text("inline int TripleValue(int v) { return v * 3; }\n")+ (tmp_path / "uses.cpp").write_text('#include "math_impl.inl"\nint Show() { return 0; }\n')+ graph = _build(tmp_path)+ assert graph.has_edge("uses.cpp", "math_impl.inl")++ def test_ipp_and_tpp_are_traversed(self, tmp_path: Path) -> None:+ (tmp_path / "a.ipp").write_text("inline int A() { return 1; }\n")+ (tmp_path / "b.tpp").write_text("template <class T> T B(T v) { return v; }\n")+ assert {"a.ipp", "b.tpp"} <= _traversed(tmp_path)+++class TestGeneratedFragment:+ def test_generated_fragment_is_still_parsed(self, tmp_path: Path) -> None:+ # A .inl is not a module: it is text pasted into a hand-written TU, so+ # skipping it deletes edges from code nobody generated.+ (tmp_path / "table.inl").write_text(+ "// DO NOT EDIT - generated by tools/gen.py\nSAVE_COMPONENT(Transform)\n"+ )+ assert "table.inl" in _traversed(tmp_path)++ def test_macro_invoked_only_from_a_generated_table_has_call_sites(+ self, tmp_path: Path+ ) -> None:+ (tmp_path / "table.inl").write_text(+ "// DO NOT EDIT - generated by tools/gen.py\nSAVE_COMPONENT(Transform)\n"+ )+ (tmp_path / "save.cpp").write_text(+ "#define SAVE_COMPONENT(T) RegisterSave(#T)\n"+ "void RegisterSave(const char* n);\n"+ "void InstallAll() {\n#include \"table.inl\"\n}\n"+ )+ graph = _build(tmp_path)+ assert _callers_of(graph, "save.cpp::SAVE_COMPONENT")++ def test_generated_fragment_exemption_is_case_insensitive(self, tmp_path: Path) -> None:+ # Language detection lowercases the extension, so a ``.INL`` is C++ and+ # reaches the generated check. If the exemption compared raw suffixes+ # it would drop the file again, reproducing the bug for this spelling.+ (tmp_path / "Table.INL").write_text(+ "// DO NOT EDIT - generated by tools/gen.py\nSAVE_COMPONENT(Transform)\n"+ )+ assert "Table.INL" in _traversed(tmp_path)++ def test_generated_module_is_still_skipped(self, tmp_path: Path) -> None:+ # The exemption is for fragments only. A generated .cpp is a+ # translation unit of its own and stays out, as before.+ (tmp_path / "gen.cpp").write_text(+ "// DO NOT EDIT - generated by protoc\nint Gen() { return 1; }\n"+ )+ assert "gen.cpp" not in _traversed(tmp_path)+++class TestReachabilityTreatsFragmentsAsHeaders:+ def test_fragment_counts_as_a_header(self) -> None:+ from repowise.core.analysis.dead_code.cpp_reachability import (+ _is_header,+ is_cpp_path,+ )++ for ext in (".inl", ".ipp", ".tpp"):+ assert is_cpp_path(f"src/x{ext}")+ assert _is_header(f"src/x{ext}")+++class TestSharedExtensionSet:+ """The lists that had drifted now read the one exported set.++ The issue called this out directly: ``.inc`` was in the reachability pass+ and absent from the spec. Pinning each consumer keeps the next extension+ from having to be added in six places.+ """++ def test_every_consumer_covers_the_fragment_extensions(self) -> None:+ from repowise.core.analysis.dead_code.cpp_reachability import _CPP_HEADER_EXTS+ from repowise.core.ingestion.dynamic_hints.cpp import _CPP_EXTS+ from repowise.core.ingestion.external_systems.cmake import (+ _HEADER_EXTS as CMAKE_HEADER_EXTS,+ )+ from repowise.core.ingestion.graph_warmups import _CPP_MACRO_SCAN_EXTS+ from repowise.core.ingestion.languages.specs.cpp import (+ INCLUDE_FRAGMENT_EXTENSIONS,+ SPEC,+ )+ from repowise.core.ingestion.resolvers.cpp import _HEADER_EXTS++ for consumer in (+ SPEC.extensions,+ _CPP_HEADER_EXTS,+ _HEADER_EXTS,+ CMAKE_HEADER_EXTS,+ _CPP_EXTS,+ _CPP_MACRO_SCAN_EXTS,+ ):+ assert set(consumer) >= INCLUDE_FRAGMENT_EXTENSIONS++ def test_header_pairing_treats_a_fragment_as_the_implementation(+ self, tmp_path: Path+ ) -> None:+ # ``vector.inl`` holds what ``vector.h`` declares, so a consumer of the+ # header can transit into the fragment.+ (tmp_path / "vector.h").write_text("template <class T> T Get(T v);\n")+ (tmp_path / "vector.inl").write_text("template <class T> T Get(T v) { return v; }\n")+ graph = _build(tmp_path)+ pair = graph.get_edge_data("vector.h", "vector.inl")+ assert pair is not None+ assert pair.get("hint_source") == "header_source_pair"