Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(cpp): workspace-aware include resolution and public-header rescue (#282)

Raghav Chamadiya2f5dff8e89c3
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 19a676b71..8d3577d94 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -109,6 +109,10 @@ class CallResolver:
self._jvm_index: Any = None
self._jvm_index_built = False
+ # C/C++ same-target resolution (lazy CppWorkspaceIndex)
+ self._cpp_index: Any = None
+ self._cpp_index_built = False
+
self._build_indices(parsed_files)
self._follow_barrel_exports()
@@ -213,6 +217,54 @@ class CallResolver:
parsed = self._parsed_files.get(file_path)
return bool(parsed and parsed.file_info.language in ("java", "kotlin"))
+ def _is_cpp_family(self, file_path: str) -> bool:
+ parsed = self._parsed_files.get(file_path)
+ return bool(parsed and parsed.file_info.language in ("cpp", "c"))
+
+ def _get_cpp_index(self) -> Any:
+ """Lazily build a CppWorkspaceIndex via a minimal stand-in context."""
+ if self._cpp_index_built:
+ return self._cpp_index
+ self._cpp_index_built = True
+ if not self._repo_path:
+ return None
+ from pathlib import Path
+
+ from .resolvers.cpp_workspace import build_cpp_workspace_index
+
+ class _Ctx:
+ def __init__(self, rp: str, pf: dict[str, ParsedFile]) -> None:
+ self.repo_path = Path(rp)
+ self.path_set = set(pf.keys())
+ self.parsed_files = pf
+ self.stem_map: dict[str, list[str]] = {}
+
+ self._cpp_index = build_cpp_workspace_index(_Ctx(self._repo_path, self._parsed_files))
+ return self._cpp_index
+
+ def _resolve_cpp_same_target(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ ) -> ResolvedCall | None:
+ """Resolve a bare call against the workspace target's source list.
+
+ C++ files in the same CMake/Bazel target share a build unit — an
+ unqualified ``Helper(...)`` may be defined in any sibling
+ ``.cc``/``.cpp`` in the same target with no ``#include`` line.
+ """
+ index = self._get_cpp_index()
+ if index is None:
+ return None
+ siblings = index.siblings_in_targets(file_path)
+ for sibling in siblings:
+ syms = self._file_symbols.get(sibling, {})
+ sym_id = syms.get(call.target_name)
+ if sym_id is not None and sym_id != caller_id:
+ return ResolvedCall(caller_id, sym_id, 0.85, call.line)
+ return None
+
def _get_jvm_index(self) -> Any:
"""Lazily build the JvmWorkspaceIndex (or None if unavailable)."""
if self._jvm_index_built:
@@ -419,6 +471,14 @@ class CallResolver:
if jvm_same_pkg is not None:
return jvm_same_pkg
+ # C/C++: same-target unqualified access — a bare call may target a
+ # function declared in a header consumed by the importer's CMake/
+ # Bazel target and defined in any sibling TU of that target.
+ if self._is_cpp_family(file_path):
+ cpp_same_target = self._resolve_cpp_same_target(file_path, call, caller_id)
+ if cpp_same_target is not None:
+ return cpp_same_target
+
# Tier 2: import-scoped
# 2a: Check specific imported name → source file (binding-aware)
binding = self._import_bindings.get(file_path, {}).get(target_name)
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/__init__.py b/packages/core/src/repowise/core/ingestion/external_systems/__init__.py
index de918a7c0..bec436987 100644
--- a/packages/core/src/repowise/core/ingestion/external_systems/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/external_systems/__init__.py
@@ -18,7 +18,7 @@ from collections.abc import Iterable
from pathlib import Path
from types import ModuleType
-from . import cargo, go, maven, npm, nuget, pypi
+from . import bazel, cargo, cmake, go, maven, npm, nuget, pypi
from .base import ExternalSystemRecord, ManifestParser
__all__ = [
@@ -27,7 +27,7 @@ __all__ = [
"extract_external_systems",
]
-_PARSERS: tuple[ModuleType, ...] = (npm, pypi, cargo, go, nuget, maven)
+_PARSERS: tuple[ModuleType, ...] = (npm, pypi, cargo, go, nuget, maven, cmake, bazel)
# Map exact filename → parser module
_FILENAME_PARSERS: dict[str, ModuleType] = {
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/bazel.py b/packages/core/src/repowise/core/ingestion/external_systems/bazel.py
new file mode 100644
index 000000000..1db86de34
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/external_systems/bazel.py
@@ -0,0 +1,323 @@
+"""Bazel BUILD reader — narrow ``cc_*`` rule extraction.
+
+Like :mod:`.cmake`, serves two roles:
+
+1. Build-graph extraction (``cc_binary`` / ``cc_library`` / ``cc_test`` /
+ ``cc_proto_library`` / ``cc_grpc_library``) consumed by
+ :mod:`repowise.core.ingestion.resolvers.cpp_workspace`.
+
+2. ``ManifestParser`` shape — emits no external records today (Bazel
+ external deps live in ``WORKSPACE`` / ``MODULE.bazel`` and require
+ their own grammar). Registered so the manifest discovery walk picks
+ up BUILD files cheaply.
+
+The reader recognises Starlark function-call literals at the top level —
+``cc_binary(name = "x", srcs = ["a.cc"], hdrs = ["a.h"], deps = [":b"])``.
+List values, kwarg syntax, and string literals are tokenised with a
+small dedicated scanner. Anything more complex (Starlark loops, list
+comprehensions, ``select(...)``, ``glob(...)``) falls back to "list of
+literal strings collected from the call".
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterable
+from dataclasses import dataclass, field
+from pathlib import Path, PurePosixPath
+
+import structlog
+
+from .base import ExternalSystemRecord
+
+log = structlog.get_logger(__name__)
+
+filenames: tuple[str, ...] = ("BUILD", "BUILD.bazel")
+ecosystem: str = "bazel"
+
+
+@dataclass
+class BazelTarget:
+ name: str
+ kind: str # cc_binary | cc_library | cc_test | cc_proto_library | cc_grpc_library | cc_fuzz_test
+ build_file: str # repo-relative POSIX path
+ package: str # repo-relative dir owning the BUILD
+ srcs: list[str] = field(default_factory=list)
+ hdrs: list[str] = field(default_factory=list)
+ deps: list[str] = field(default_factory=list)
+ includes: list[str] = field(default_factory=list)
+ testonly: bool = False
+
+
+@dataclass
+class BazelFile:
+ path: str # repo-relative POSIX path to BUILD/BUILD.bazel
+ package: str # repo-relative dir
+ targets: list[BazelTarget] = field(default_factory=list)
+
+
+_CC_RULE_NAMES: frozenset[str] = frozenset({
+ "cc_binary",
+ "cc_library",
+ "cc_test",
+ "cc_proto_library",
+ "cc_grpc_library",
+ "cc_fuzz_test",
+ "cc_shared_library",
+})
+
+# Matches ``rule_name(`` at start of line (or after whitespace) — enough
+# for top-level rule discovery. Nested rule calls inside macros are
+# missed; that's acceptable for the first pass.
+_RULE_CALL_RE = re.compile(
+ r"(?:^|\n)\s*(" + "|".join(re.escape(r) for r in _CC_RULE_NAMES) + r")\s*\(",
+ re.MULTILINE,
+)
+
+_STRING_LIT_RE = re.compile(r'"((?:\\.|[^"\\])*)"')
+
+
+def _slice_call_body(text: str, open_paren_pos: int) -> str:
+ """Return the substring between the matching ``(`` and ``)`` (exclusive)."""
+ depth = 1
+ i = open_paren_pos + 1
+ n = len(text)
+ while i < n and depth > 0:
+ ch = text[i]
+ if ch == '"':
+ i += 1
+ while i < n and text[i] != '"':
+ if text[i] == "\\" and i + 1 < n:
+ i += 2
+ continue
+ i += 1
+ i += 1
+ continue
+ if ch == "'":
+ i += 1
+ while i < n and text[i] != "'":
+ if text[i] == "\\" and i + 1 < n:
+ i += 2
+ continue
+ i += 1
+ i += 1
+ continue
+ if ch == "(" or ch == "[" or ch == "{":
+ depth += 1
+ elif ch == ")" or ch == "]" or ch == "}":
+ depth -= 1
+ if depth == 0:
+ break
+ i += 1
+ return text[open_paren_pos + 1 : i]
+
+
+_KWARG_RE = re.compile(
+ r"\s*,?\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*",
+)
+
+
+def _extract_kwargs(call_body: str) -> dict[str, str]:
+ """Split a call body into ``kwarg → raw RHS``.
+
+ The RHS is everything up to the next top-level comma (paren-aware).
+ No further parsing is done here — list / boolean recognition is done
+ by the callers via ``_collect_strings`` / ``_truthy``.
+ """
+ out: dict[str, str] = {}
+ i = 0
+ n = len(call_body)
+ while i < n:
+ m = _KWARG_RE.search(call_body, i)
+ if not m:
+ break
+ key = m.group(1)
+ rhs_start = m.end()
+ depth = 0
+ j = rhs_start
+ while j < n:
+ ch = call_body[j]
+ if ch == '"':
+ j += 1
+ while j < n and call_body[j] != '"':
+ if call_body[j] == "\\" and j + 1 < n:
+ j += 2
+ continue
+ j += 1
+ j += 1
+ continue
+ if ch == "'":
+ j += 1
+ while j < n and call_body[j] != "'":
+ if call_body[j] == "\\" and j + 1 < n:
+ j += 2
+ continue
+ j += 1
+ j += 1
+ continue
+ if ch in "([{":
+ depth += 1
+ elif ch in ")]}":
+ if depth == 0:
+ break
+ depth -= 1
+ elif ch == "," and depth == 0:
+ break
+ j += 1
+ out[key] = call_body[rhs_start:j].strip()
+ i = j + 1
+ return out
+
+
+def _collect_strings(rhs: str) -> list[str]:
+ """Return every string literal in *rhs* in source order."""
+ return [m.group(1) for m in _STRING_LIT_RE.finditer(rhs)]
+
+
+def _truthy(rhs: str) -> bool:
+ s = rhs.strip().rstrip(",").strip()
+ return s.lower() in ("true", "1")
+
+
+def parse_bazel_build(
+ build_path: Path,
+ *,
+ repo_root: Path | None = None,
+) -> BazelFile:
+ """Parse one ``BUILD`` / ``BUILD.bazel`` file into a :class:`BazelFile`."""
+ try:
+ text = build_path.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ text = ""
+
+ if repo_root is not None:
+ try:
+ rel_self = build_path.resolve().relative_to(repo_root.resolve()).as_posix()
+ except ValueError:
+ rel_self = build_path.as_posix()
+ else:
+ rel_self = build_path.as_posix()
+ package = PurePosixPath(rel_self).parent.as_posix() if "/" in rel_self else ""
+ if package == ".":
+ package = ""
+
+ bf = BazelFile(path=rel_self, package=package)
+
+ for match in _RULE_CALL_RE.finditer(text):
+ kind = match.group(1)
+ open_paren = match.end() - 1
+ body = _slice_call_body(text, open_paren)
+ kwargs = _extract_kwargs(body)
+
+ name = ""
+ for s in _collect_strings(kwargs.get("name", "")):
+ name = s
+ break
+ if not name:
+ continue
+
+ srcs = _collect_strings(kwargs.get("srcs", ""))
+ hdrs = _collect_strings(kwargs.get("hdrs", ""))
+ deps = _collect_strings(kwargs.get("deps", ""))
+ includes = _collect_strings(kwargs.get("includes", ""))
+ textual_hdrs = _collect_strings(kwargs.get("textual_hdrs", ""))
+ testonly = _truthy(kwargs.get("testonly", "False"))
+
+ hdrs.extend(textual_hdrs)
+
+ # Resolve each src/hdr to a repo-relative path. Bazel labels in
+ # ``srcs``/``hdrs`` are usually plain filenames relative to the
+ # package; ``//pkg:foo.cc`` and ``:foo.cc`` forms are also valid.
+ resolved_srcs = [_resolve_label(s, package) for s in srcs]
+ resolved_srcs = [s for s in resolved_srcs if s]
+ resolved_hdrs = [_resolve_label(s, package) for s in hdrs]
+ resolved_hdrs = [s for s in resolved_hdrs if s]
+
+ bf.targets.append(
+ BazelTarget(
+ name=name,
+ kind=kind,
+ build_file=rel_self,
+ package=package,
+ srcs=resolved_srcs,
+ hdrs=resolved_hdrs,
+ deps=deps,
+ includes=includes,
+ testonly=testonly or kind == "cc_test" or kind == "cc_fuzz_test",
+ )
+ )
+
+ return bf
+
+
+def _resolve_label(label: str, package: str) -> str:
+ """Turn a Bazel label / filename into a repo-relative POSIX path.
+
+ Handles:
+ * Plain filenames (``foo.cc``) → joined with the package dir.
+ * Local labels (``:foo.cc``) → joined with the package dir.
+ * Absolute labels (``//pkg/sub:foo.cc``) → ``pkg/sub/foo.cc``.
+ * External (``@repo//pkg:foo.cc``) → discarded.
+ """
+ if not label or label.startswith("@"):
+ return ""
+ if label.startswith("//"):
+ rest = label[2:]
+ if ":" in rest:
+ pkg, _, fname = rest.partition(":")
+ return f"{pkg}/{fname}" if pkg else fname
+ return rest
+ if label.startswith(":"):
+ label = label[1:]
+ if package:
+ return f"{package}/{label}"
+ return label
+
+
+def discover_bazel_packages(repo_root: Path, *, max_files: int = 5000) -> list[BazelFile]:
+ """Walk the repo for every ``BUILD`` / ``BUILD.bazel`` file."""
+ repo_root = repo_root.resolve()
+ out: list[BazelFile] = []
+ skip_dirs = {".git", "node_modules", "bazel-bin", "bazel-out", "bazel-testlogs",
+ "bazel-" + repo_root.name, ".venv", "venv", "build"}
+ for candidate in ("BUILD", "BUILD.bazel"):
+ for p in repo_root.rglob(candidate):
+ try:
+ rel = p.resolve().relative_to(repo_root).as_posix()
+ except ValueError:
+ continue
+ parts = PurePosixPath(rel).parts
+ if any(part in skip_dirs for part in parts):
+ continue
+ if len(out) >= max_files:
+ break
+ out.append(parse_bazel_build(p, repo_root=repo_root))
+ return out
+
+
+def is_bazel_repo(repo_root: Path) -> bool:
+ for marker in ("WORKSPACE", "WORKSPACE.bazel", "MODULE.bazel"):
+ if (repo_root / marker).exists():
+ return True
+ return False
+
+
+# ---------------------------------------------------------------------------
+# ManifestParser shape — empty list (Bazel external deps live elsewhere)
+# ---------------------------------------------------------------------------
+
+
+def parse(manifest_path: Path, repo_root: Path) -> list[ExternalSystemRecord]:
+ return []
+
+
+__all__ = [
+ "BazelTarget",
+ "BazelFile",
+ "parse_bazel_build",
+ "discover_bazel_packages",
+ "is_bazel_repo",
+ "parse",
+ "filenames",
+ "ecosystem",
+]
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/cmake.py b/packages/core/src/repowise/core/ingestion/external_systems/cmake.py
new file mode 100644
index 000000000..fef1c20e8
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/external_systems/cmake.py
@@ -0,0 +1,785 @@
+"""CMake build-system reader.
+
+Serves two purposes:
+
+1. **Build-graph extraction** for the C/C++ workspace index — ``add_executable``,
+ ``add_library``, ``target_sources``, ``target_include_directories``,
+ ``target_compile_definitions``, ``add_subdirectory``, ``option``, ``if/endif``
+ conditional source membership. Consumed by
+ :mod:`repowise.core.ingestion.resolvers.cpp_workspace`.
+
+2. **External dependency extraction** (``ManifestParser`` shape) — ``find_package``
+ calls land as ``cmake`` ecosystem records so the manifest classifier can list
+ them alongside ``package.json`` / ``Cargo.toml`` deps.
+
+The reader is **regex-tokenised**, not a full CMake evaluator. Best-effort
+variable expansion supports ``${VAR}`` against literal ``set(VAR …)``
+definitions seen earlier in the same file. Unknown variables are left as-is
+and any downstream consumer falls back to stem matching.
+
+If a ``build/.cmake/api/v1/reply/`` directory exists, callers should prefer
+:func:`parse_cmake_file_api_reply` — it gives the authoritative target graph.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from collections.abc import Iterable, Sequence
+from dataclasses import dataclass, field
+from pathlib import Path, PurePosixPath
+
+import structlog
+
+from .base import ExternalSystemRecord
+
+log = structlog.get_logger(__name__)
+
+filenames: tuple[str, ...] = ("CMakeLists.txt",)
+ecosystem: str = "cmake"
+
+
+# ---------------------------------------------------------------------------
+# Build-graph types
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class CMakeTarget:
+ """A single CMake target (``add_executable`` / ``add_library`` / test)."""
+
+ name: str
+ kind: str # executable | library_static | library_shared | library_interface | library_object | library_module | test | unknown
+ cmakelists: str # repo-relative POSIX path to defining CMakeLists.txt
+ sources: list[str] = field(default_factory=list)
+ public_headers: list[str] = field(default_factory=list)
+ private_headers: list[str] = field(default_factory=list)
+ include_dirs: list[str] = field(default_factory=list) # PUBLIC + INTERFACE
+ private_include_dirs: list[str] = field(default_factory=list)
+ compile_defines: list[str] = field(default_factory=list)
+ link_deps: list[str] = field(default_factory=list)
+ conditional_sources: list[str] = field(default_factory=list)
+ """Sources added inside an ``if(...)`` block — used by dead-code
+ analysis to pair mutually-exclusive alternatives (e.g.,
+ ``env_posix.cc`` vs ``env_windows.cc``)."""
+
+
+@dataclass
+class CMakeFile:
+ """Parsed CMakeLists.txt — targets, subdirectories, variables."""
+
+ path: str # repo-relative POSIX path to CMakeLists.txt
+ targets: list[CMakeTarget] = field(default_factory=list)
+ subdirectories: list[str] = field(default_factory=list)
+ """Repo-relative subdirectories from ``add_subdirectory(...)``."""
+
+ variables: dict[str, str] = field(default_factory=dict)
+ """Best-effort ``set(VAR literal)`` map."""
+
+ options: list[str] = field(default_factory=list)
+ """``option(NAME …)`` flags (used to detect conditional blocks)."""
+
+ find_packages: list[tuple[str, str | None]] = field(default_factory=list)
+ """``find_package(NAME [VERSION])`` calls."""
+
+
+# ---------------------------------------------------------------------------
+# Tokenising / command extraction
+# ---------------------------------------------------------------------------
+
+# Strip CMake comments (``# ...`` to end-of-line, NOT inside strings) and
+# bracket comments ``#[[ ... ]]``. The bracket form is rare; handle the
+# simple ``#[[…]]`` pattern only.
+_BRACKET_COMMENT_RE = re.compile(r"#\[\[.*?]]", re.DOTALL)
+_LINE_COMMENT_RE = re.compile(r"#[^\n]*")
+
+# Command extractor: NAME ( ARGS ) — CMake commands are case-insensitive.
+_COMMAND_RE = re.compile(r"([A-Za-z_][A-Za-z0-9_]*)\s*\(", re.MULTILINE)
+
+# Argument splitter — splits on whitespace but keeps double-quoted strings
+# (with backslash escapes) intact.
+_ARG_RE = re.compile(r'"((?:\\.|[^"\\])*)"|(\S+)')
+
+# ``set(VAR <literal>)`` capture — only the literal-RHS form. Anything with
+# ``CACHE``, generator expressions, or list expansion falls back to whatever
+# the variable map already had (typically nothing).
+_SET_RHS_TERMINATORS: frozenset[str] = frozenset({
+ "CACHE", "PARENT_SCOPE", "FORCE",
+})
+
+_VAR_REF_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
+
+_HEADER_EXTS: tuple[str, ...] = (".h", ".hpp", ".hxx", ".hh", ".h++", ".inc")
+_SOURCE_EXTS: tuple[str, ...] = (".c", ".cc", ".cpp", ".cxx", ".c++", ".cppm", ".ixx", ".mxx")
+
+
+def _strip_comments(text: str) -> str:
+ text = _BRACKET_COMMENT_RE.sub("", text)
+ return _LINE_COMMENT_RE.sub("", text)
+
+
+def _split_args(args_text: str) -> list[str]:
+ """Split a CMake command's argument string into individual tokens."""
+ out: list[str] = []
+ for match in _ARG_RE.finditer(args_text):
+ quoted, bare = match.groups()
+ if quoted is not None:
+ out.append(quoted)
+ elif bare:
+ out.append(bare)
+ return out
+
+
+def _expand_vars(token: str, variables: dict[str, str]) -> str:
+ """Expand ``${VAR}`` references in *token* using *variables*."""
+ def repl(m: re.Match[str]) -> str:
+ name = m.group(1)
+ return variables.get(name, m.group(0))
+
+ # Up to 3 expansion passes for nested refs
+ prev = token
+ for _ in range(3):
+ nxt = _VAR_REF_RE.sub(repl, prev)
+ if nxt == prev:
+ break
+ prev = nxt
+ return prev
+
+
+@dataclass
+class _Command:
+ name: str # lowercased
+ args: list[str]
+ in_conditional: bool
+
+
+def _scan_commands(text: str) -> list[_Command]:
+ """Scan stripped CMake text and yield commands with ``if``-depth tracking.
+
+ ``if(...)/endif()`` nesting is approximate — we don't evaluate the
+ condition; we just flag any command that appears inside any ``if`` block
+ so the caller can mark its source list as conditional.
+ """
+ cmds: list[_Command] = []
+ if_depth = 0
+ pos = 0
+ n = len(text)
+ while pos < n:
+ m = _COMMAND_RE.search(text, pos)
+ if not m:
+ break
+ cmd_name = m.group(1).lower()
+ # Walk the parenthesised argument list, respecting nested parens
+ # (variable references like ``$<...>`` are not parens so safe).
+ args_start = m.end()
+ depth = 1
+ i = args_start
+ while i < n and depth > 0:
+ ch = text[i]
+ if ch == "(":
+ depth += 1
+ elif ch == ")":
+ depth -= 1
+ if depth == 0:
+ break
+ elif ch == '"':
+ # Skip past quoted string respecting backslash escapes
+ i += 1
+ while i < n and text[i] != '"':
+ if text[i] == "\\" and i + 1 < n:
+ i += 2
+ continue
+ i += 1
+ i += 1
+ args_text = text[args_start:i]
+ pos = i + 1
+
+ args = _split_args(args_text)
+ cmds.append(_Command(name=cmd_name, args=args, in_conditional=if_depth > 0))
+
+ if cmd_name == "if":
+ if_depth += 1
+ elif cmd_name == "endif":
+ if_depth = max(0, if_depth - 1)
+
+ return cmds
+
+
+# ---------------------------------------------------------------------------
+# Per-file parse
+# ---------------------------------------------------------------------------
+
+
+def _classify_target_kind(library_type: str) -> str:
+ t = library_type.upper()
+ if t == "STATIC":
+ return "library_static"
+ if t == "SHARED" or t == "MODULE":
+ return "library_shared"
+ if t == "INTERFACE":
+ return "library_interface"
+ if t == "OBJECT":
+ return "library_object"
+ return "library_static" # default per CMake
+
+
+def _classify_path(rel_posix: str) -> str:
+ """Return ``"header"``, ``"source"`` or ``"other"`` from extension."""
+ lower = rel_posix.lower()
+ for ext in _HEADER_EXTS:
+ if lower.endswith(ext):
+ return "header"
+ for ext in _SOURCE_EXTS:
+ if lower.endswith(ext):
+ return "source"
+ return "other"
+
+
+def _resolve_repo_rel(
+ cmakelists_dir: str,
+ raw_path: str,
+ *,
+ repo_root_posix: str | None = None,
+) -> str:
+ """Resolve a CMake-relative path to a repo-relative POSIX path.
+
+ *cmakelists_dir* is the dir containing the CMakeLists, repo-relative.
+ *raw_path* may be absolute (``${CMAKE_CURRENT_SOURCE_DIR}/x`` expanded),
+ relative to the CMakeLists, or contain unexpanded ``${VAR}`` refs (which
+ we leave verbatim so the caller can stem-match).
+ """
+ if not raw_path or "${" in raw_path:
+ return raw_path # unexpanded — let caller stem-match
+ if raw_path.startswith("/") and repo_root_posix and raw_path.startswith(repo_root_posix + "/"):
+ return raw_path[len(repo_root_posix) + 1:]
+ if raw_path.startswith("/"):
+ return raw_path # outside repo — caller will discard
+ joined = (PurePosixPath(cmakelists_dir) / raw_path).as_posix() if cmakelists_dir else raw_path
+ # Collapse ../ and ./ segments
+ parts: list[str] = []
+ for seg in joined.split("/"):
+ if seg in ("", "."):
+ continue
+ if seg == "..":
+ if parts:
+ parts.pop()
+ continue
+ parts.append(seg)
+ return "/".join(parts)
+
+
+def parse_cmake_lists(
+ cmakelists_path: Path,
+ *,
+ repo_root: Path | None = None,
+) -> CMakeFile:
+ """Parse one CMakeLists.txt into a :class:`CMakeFile`.
+
+ *cmakelists_path* should be an absolute path on disk; *repo_root* is
+ used to derive the repo-relative POSIX path stored in ``CMakeFile.path``.
+ """
+ try:
+ text = cmakelists_path.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ text = ""
+ text = _strip_comments(text)
+ commands = _scan_commands(text)
+
+ if repo_root is not None:
+ try:
+ rel_self = cmakelists_path.resolve().relative_to(repo_root.resolve()).as_posix()
+ except ValueError:
+ rel_self = cmakelists_path.as_posix()
+ else:
+ rel_self = cmakelists_path.as_posix()
+ cmakelists_dir = PurePosixPath(rel_self).parent.as_posix() if "/" in rel_self else ""
+ if cmakelists_dir == ".":
+ cmakelists_dir = ""
+ repo_root_posix = repo_root.resolve().as_posix() if repo_root else None
+
+ cm = CMakeFile(path=rel_self)
+
+ # Pre-seed implicit variables so common patterns expand.
+ cm.variables["CMAKE_CURRENT_SOURCE_DIR"] = cmakelists_dir or "."
+ cm.variables["CMAKE_CURRENT_LIST_DIR"] = cmakelists_dir or "."
+ if repo_root_posix:
+ cm.variables["PROJECT_SOURCE_DIR"] = repo_root_posix
+ cm.variables["CMAKE_SOURCE_DIR"] = repo_root_posix
+
+ for cmd in commands:
+ name = cmd.name
+ # Expand variables in arguments lazily for commands that need it
+ if name == "set" and cmd.args:
+ var = cmd.args[0]
+ rhs_tokens: list[str] = []
+ for tok in cmd.args[1:]:
+ if tok.upper() in _SET_RHS_TERMINATORS:
+ break
+ rhs_tokens.append(_expand_vars(tok, cm.variables))
+ if rhs_tokens:
+ cm.variables[var] = " ".join(rhs_tokens) if len(rhs_tokens) > 1 else rhs_tokens[0]
+
+ elif name == "option" and cmd.args:
+ cm.options.append(cmd.args[0])
+
+ elif name == "find_package" and cmd.args:
+ pkg = cmd.args[0]
+ version: str | None = None
+ for tok in cmd.args[1:]:
+ if re.match(r"^\d", tok):
+ version = tok
+ break
+ cm.find_packages.append((pkg, version))
+
+ elif name == "add_subdirectory" and cmd.args:
+ sub = _expand_vars(cmd.args[0], cm.variables)
+ rel = _resolve_repo_rel(cmakelists_dir, sub, repo_root_posix=repo_root_posix)
+ if rel:
+ cm.subdirectories.append(rel)
+
+ elif name == "add_executable" and cmd.args:
+ target = _parse_add_target(
+ cmd, kind="executable", cmakelists=rel_self,
+ cmakelists_dir=cmakelists_dir, cm=cm,
+ repo_root_posix=repo_root_posix,
+ )
+ if target:
+ cm.targets.append(target)
+
+ elif name == "add_library" and cmd.args:
+ # add_library(name [STATIC|SHARED|MODULE|OBJECT|INTERFACE] ...)
+ target_name = cmd.args[0]
+ kind = "library_static"
+ sources_start = 1
+ if len(cmd.args) >= 2 and cmd.args[1].upper() in (
+ "STATIC", "SHARED", "MODULE", "OBJECT", "INTERFACE", "IMPORTED",
+ ):
+ kind = _classify_target_kind(cmd.args[1])
+ sources_start = 2
+ t = CMakeTarget(name=target_name, kind=kind, cmakelists=rel_self)
+ _ingest_sources(
+ t, cmd.args[sources_start:], cmakelists_dir, cm,
+ conditional=cmd.in_conditional, repo_root_posix=repo_root_posix,
+ )
+ cm.targets.append(t)
+
+ elif name == "target_sources" and cmd.args:
+ _apply_target_sources(
+ cmd, cm, cmakelists_dir, repo_root_posix=repo_root_posix,
+ )
+
+ elif name == "target_include_directories" and cmd.args:
+ _apply_target_include_dirs(
+ cmd, cm, cmakelists_dir, repo_root_posix=repo_root_posix,
+ )
+
+ elif name == "target_compile_definitions" and cmd.args:
+ _apply_target_compile_defs(cmd, cm)
+
+ elif name == "target_link_libraries" and cmd.args:
+ _apply_target_link_libs(cmd, cm)
+
+ elif name == "add_test" and cmd.args:
+ # add_test(NAME tname COMMAND target ...) or
+ # add_test(tname target args...)
+ # We use this primarily to flag library targets that drive tests;
+ # the second positional after NAME/keyword is the executable.
+ args = cmd.args
+ if args[0].upper() == "NAME" and len(args) >= 4 and args[2].upper() == "COMMAND":
+ ref_target = args[3]
+ elif len(args) >= 2:
+ ref_target = args[1]
+ else:
+ ref_target = None
+ if ref_target:
+ for t in cm.targets:
+ if t.name == ref_target and t.kind == "executable":
+ t.kind = "test"
+
+ return cm
+
+
+def _parse_add_target(
+ cmd: _Command,
+ *,
+ kind: str,
+ cmakelists: str,
+ cmakelists_dir: str,
+ cm: CMakeFile,
+ repo_root_posix: str | None,
+) -> CMakeTarget | None:
+ name = cmd.args[0]
+ # ``add_executable(name)`` with no sources is valid — sources arrive via
+ # ``target_sources(...)``. Build the target with whatever inline sources
+ # there are; ``_apply_target_sources`` fills in the rest.
+ t = CMakeTarget(name=name, kind=kind, cmakelists=cmakelists)
+ _ingest_sources(
+ t, cmd.args[1:], cmakelists_dir, cm,
+ conditional=cmd.in_conditional, repo_root_posix=repo_root_posix,
+ )
+ return t
+
+
+def _ingest_sources(
+ target: CMakeTarget,
+ raw_args: Sequence[str],
+ cmakelists_dir: str,
+ cm: CMakeFile,
+ *,
+ conditional: bool,
+ repo_root_posix: str | None,
+) -> None:
+ """Append each path-like argument to the target's source/header lists."""
+ for raw in raw_args:
+ if raw.upper() in ("WIN32", "MACOSX_BUNDLE", "EXCLUDE_FROM_ALL"):
+ continue
+ expanded = _expand_vars(raw, cm.variables)
+ # ``set(SRC a.cc b.cc)`` was stored as a space-joined string; split.
+ for tok in expanded.split():
+ tok = tok.strip()
+ if not tok or tok.startswith("$<"):
+ continue
+ rel = _resolve_repo_rel(
+ cmakelists_dir, tok, repo_root_posix=repo_root_posix,
+ )
+ if not rel or rel.startswith("/"):
+ continue
+ cls = _classify_path(rel)
+ if cls == "header":
+ target.private_headers.append(rel)
+ elif cls == "source":
+ target.sources.append(rel)
+ if conditional:
+ target.conditional_sources.append(rel)
+
+
+_SCOPE_KEYWORDS: frozenset[str] = frozenset({"PUBLIC", "PRIVATE", "INTERFACE"})
+
+
+def _apply_target_sources(
+ cmd: _Command,
+ cm: CMakeFile,
+ cmakelists_dir: str,
+ *,
+ repo_root_posix: str | None,
+) -> None:
+ args = cmd.args
+ if not args:
+ return
+ target_name = args[0]
+ target = next((t for t in cm.targets if t.name == target_name), None)
+ # If the target was declared in a parent file, create a stub so the
+ # source list survives — the reactor merges these later.
+ if target is None:
+ target = CMakeTarget(name=target_name, kind="unknown", cmakelists=cm.path)
+ cm.targets.append(target)
+
+ scope = "PRIVATE"
+ for tok in args[1:]:
+ upper = tok.upper()
+ if upper in _SCOPE_KEYWORDS or upper in ("FILE_SET", "BASE_DIRS", "FILES", "TYPE"):
+ if upper in _SCOPE_KEYWORDS:
+ scope = upper
+ continue
+ expanded = _expand_vars(tok, cm.variables)
+ for part in expanded.split():
+ part = part.strip()
+ if not part or part.startswith("$<"):
+ continue
+ rel = _resolve_repo_rel(cmakelists_dir, part, repo_root_posix=repo_root_posix)
+ if not rel or rel.startswith("/"):
+ continue
+ cls = _classify_path(rel)
+ if cls == "header":
+ if scope == "PUBLIC" or scope == "INTERFACE":
+ target.public_headers.append(rel)
+ else:
+ target.private_headers.append(rel)
+ elif cls == "source":
+ target.sources.append(rel)
+ if cmd.in_conditional:
+ target.conditional_sources.append(rel)
+
+
+def _apply_target_include_dirs(
+ cmd: _Command,
+ cm: CMakeFile,
+ cmakelists_dir: str,
+ *,
+ repo_root_posix: str | None,
+) -> None:
+ args = cmd.args
+ if not args:
+ return
+ target_name = args[0]
+ target = next((t for t in cm.targets if t.name == target_name), None)
+ if target is None:
+ target = CMakeTarget(name=target_name, kind="unknown", cmakelists=cm.path)
+ cm.targets.append(target)
+
+ scope = "PRIVATE"
+ for tok in args[1:]:
+ upper = tok.upper()
+ if upper in _SCOPE_KEYWORDS or upper in ("SYSTEM", "AFTER", "BEFORE"):
+ if upper in _SCOPE_KEYWORDS:
+ scope = upper
+ continue
+ expanded = _expand_vars(tok, cm.variables)
+ for part in expanded.split():
+ part = part.strip()
+ if not part or part.startswith("$<"):
+ continue
+ # Strip generator-expression wrappers like
+ # ``$<BUILD_INTERFACE:include>`` — keep just the inner path.
+ if ":" in part and part.startswith("$<") and ">" in part:
+ inner = part[part.find(":") + 1 : part.rfind(">")]
+ part = inner
+ rel = _resolve_repo_rel(cmakelists_dir, part, repo_root_posix=repo_root_posix)
+ if not rel:
+ continue
+ if scope in ("PUBLIC", "INTERFACE"):
+ target.include_dirs.append(rel)
+ else:
+ target.private_include_dirs.append(rel)
+
+
+def _apply_target_compile_defs(cmd: _Command, cm: CMakeFile) -> None:
+ args = cmd.args
+ if not args:
+ return
+ target_name = args[0]
+ target = next((t for t in cm.targets if t.name == target_name), None)
+ if target is None:
+ target = CMakeTarget(name=target_name, kind="unknown", cmakelists=cm.path)
+ cm.targets.append(target)
+ for tok in args[1:]:
+ upper = tok.upper()
+ if upper in _SCOPE_KEYWORDS:
+ continue
+ # ``-DFOO=1`` and bare ``FOO`` both land
+ if tok.startswith("-D"):
+ tok = tok[2:]
+ # Strip ``=value`` for the macro-name set
+ macro = tok.split("=", 1)[0]
+ if macro:
+ target.compile_defines.append(macro)
+
+
+def _apply_target_link_libs(cmd: _Command, cm: CMakeFile) -> None:
+ args = cmd.args
+ if not args:
+ return
+ target_name = args[0]
+ target = next((t for t in cm.targets if t.name == target_name), None)
+ if target is None:
+ target = CMakeTarget(name=target_name, kind="unknown", cmakelists=cm.path)
+ cm.targets.append(target)
+ for tok in args[1:]:
+ if tok.upper() in _SCOPE_KEYWORDS:
+ continue
+ target.link_deps.append(tok)
+
+
+# ---------------------------------------------------------------------------
+# Reactor discovery
+# ---------------------------------------------------------------------------
+
+
+def discover_cmake_reactor(
+ repo_root: Path,
+ *,
+ max_files: int = 2000,
+) -> list[CMakeFile]:
+ """Walk the repo from ``repo_root`` following ``add_subdirectory`` links.
+
+ Starts at ``<repo_root>/CMakeLists.txt`` (if present) and recurses into
+ every subdirectory it references. If the root file is missing, falls
+ back to any top-level subdirectory that owns a CMakeLists.txt — this
+ catches projects that nest their build under ``src/`` or similar.
+ Caps at ``max_files`` to avoid runaway walks on monorepos.
+ """
+ repo_root = repo_root.resolve()
+ out: list[CMakeFile] = []
+ seen: set[str] = set()
+
+ def visit(rel_dir: str) -> None:
+ if len(out) >= max_files:
+ return
+ target = (repo_root / rel_dir / "CMakeLists.txt").resolve() if rel_dir else (repo_root / "CMakeLists.txt").resolve()
+ try:
+ target_rel = target.relative_to(repo_root).as_posix()
+ except ValueError:
+ return
+ if target_rel in seen or not target.exists():
+ return
+ seen.add(target_rel)
+ cm = parse_cmake_lists(target, repo_root=repo_root)
+ out.append(cm)
+ for sub in cm.subdirectories:
+ visit(sub)
+
+ if (repo_root / "CMakeLists.txt").exists():
+ visit("")
+ else:
+ # Best-effort: scan top-level dirs
+ for child in repo_root.iterdir():
+ if child.is_dir() and (child / "CMakeLists.txt").exists():
+ visit(child.name)
+
+ # Catch any orphan CMakeLists not referenced via add_subdirectory.
+ # Cap the rglob to a reasonable depth to avoid pathological monorepos.
+ skip_dirs = {".git", "build", "_build", "out", "_deps", "cmake-build-debug",
+ "cmake-build-release", "node_modules", ".venv", "venv"}
+ if len(out) < max_files:
+ for cml in repo_root.rglob("CMakeLists.txt"):
+ try:
+ rel = cml.resolve().relative_to(repo_root).as_posix()
+ except ValueError:
+ continue
+ if rel in seen:
+ continue
+ parts = PurePosixPath(rel).parts
+ if any(p in skip_dirs for p in parts):
+ continue
+ if len(out) >= max_files:
+ break
+ seen.add(rel)
+ out.append(parse_cmake_lists(cml, repo_root=repo_root))
+
+ return out
+
+
+# ---------------------------------------------------------------------------
+# CMake File API reply parsing
+# ---------------------------------------------------------------------------
+
+
+def parse_cmake_file_api_reply(repo_root: Path) -> list[CMakeTarget] | None:
+ """Parse ``build/.cmake/api/v1/reply/`` JSON if present.
+
+ Returns ``None`` if no reply directory is found. The reply gives the
+ authoritative target/source graph (no regex approximation), so callers
+ that find it should prefer this output over the text-regex reader.
+ """
+ reply_root = None
+ for candidate in (
+ repo_root / "build" / ".cmake" / "api" / "v1" / "reply",
+ repo_root / ".cmake" / "api" / "v1" / "reply",
+ ):
+ if candidate.is_dir():
+ reply_root = candidate
+ break
+ if reply_root is None:
+ return None
+
+ targets: list[CMakeTarget] = []
+ repo_root_resolved = repo_root.resolve()
+ for entry in reply_root.glob("target-*.json"):
+ try:
+ data = json.loads(entry.read_text(encoding="utf-8", errors="ignore"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ name = data.get("name", "")
+ type_str = str(data.get("type", "")).upper()
+ kind_map = {
+ "EXECUTABLE": "executable",
+ "STATIC_LIBRARY": "library_static",
+ "SHARED_LIBRARY": "library_shared",
+ "MODULE_LIBRARY": "library_shared",
+ "INTERFACE_LIBRARY": "library_interface",
+ "OBJECT_LIBRARY": "library_object",
+ }
+ kind = kind_map.get(type_str, "unknown")
+
+ backtrace = data.get("backtraceGraph", {}).get("files", [])
+ cmakelists_rel = ""
+ if backtrace:
+ try:
+ cmakelists_rel = (
+ Path(backtrace[0]).resolve().relative_to(repo_root_resolved).as_posix()
+ )
+ except (ValueError, OSError):
+ cmakelists_rel = ""
+
+ t = CMakeTarget(name=name, kind=kind, cmakelists=cmakelists_rel)
+ for src in data.get("sources", []):
+ path = src.get("path", "")
+ if not path:
+ continue
+ try:
+ abs_path = (repo_root_resolved / path).resolve()
+ rel = abs_path.relative_to(repo_root_resolved).as_posix()
+ except (ValueError, OSError):
+ rel = path
+ cls = _classify_path(rel)
+ if cls == "header":
+ t.private_headers.append(rel)
+ elif cls == "source":
+ t.sources.append(rel)
+ for inc in data.get("compileGroups", []):
+ for ig in inc.get("includes", []):
+ path = ig.get("path", "")
+ if not path:
+ continue
+ try:
+ rel = Path(path).resolve().relative_to(repo_root_resolved).as_posix()
+ except (ValueError, OSError):
+ rel = path
+ t.include_dirs.append(rel)
+ for d in inc.get("defines", []):
+ define = d.get("define", "")
+ macro = define.split("=", 1)[0].strip()
+ if macro:
+ t.compile_defines.append(macro)
+ for dep in data.get("dependencies", []):
+ dep_id = dep.get("id", "")
+ if "::@" in dep_id:
+ t.link_deps.append(dep_id.split("::@", 1)[0])
+
+ targets.append(t)
+
+ return targets
+
+
+# ---------------------------------------------------------------------------
+# ManifestParser shape — external system records from ``find_package``
+# ---------------------------------------------------------------------------
+
+
+def parse(manifest_path: Path, repo_root: Path) -> list[ExternalSystemRecord]:
+ """Extract ``find_package(...)`` calls as external-dependency records."""
+ cm = parse_cmake_lists(manifest_path, repo_root=repo_root)
+ try:
+ declared_in = manifest_path.resolve().relative_to(repo_root.resolve()).as_posix()
+ except ValueError:
+ declared_in = manifest_path.as_posix()
+ out: list[ExternalSystemRecord] = []
+ seen: set[str] = set()
+ for pkg, version in cm.find_packages:
+ if not pkg or pkg in seen:
+ continue
+ seen.add(pkg)
+ out.append(
+ ExternalSystemRecord(
+ name=pkg,
+ ecosystem=ecosystem,
+ declared_in=declared_in,
+ version=version,
+ display_name=pkg,
+ category="library",
+ is_dev_dep=False,
+ )
+ )
+ return out
+
+
+__all__ = [
+ "CMakeTarget",
+ "CMakeFile",
+ "parse_cmake_lists",
+ "discover_cmake_reactor",
+ "parse_cmake_file_api_reply",
+ "parse",
+ "filenames",
+ "ecosystem",
+]
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index a98da77d4..b89895e44 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -247,6 +247,16 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
from ..resolvers.kotlin import resolve_kotlin_import_all
targets = resolve_kotlin_import_all(imp.module_path, path, ctx)
+ elif _lang in ("cpp", "c"):
+ # Fan-out across sibling TUs in the same CMake/Bazel
+ # target so a public header reached by one ``.cc`` is
+ # also marked imported by the other ``.cc`` files in
+ # the library — rescues every public-header symbol
+ # whose only declared import lives in one sibling
+ # without the workspace edge.
+ from ..resolvers.cpp import resolve_cpp_import_all
+
+ targets = resolve_cpp_import_all(imp.module_path, path, ctx)
else:
single = resolve_import(imp.module_path, path, _lang, ctx)
targets = (single,) if single else ()
diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.py
index a4068bbfd..c60cbfe20 100644
--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py
+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py
@@ -99,6 +99,54 @@ def _warmup_jvm(ctx: "ResolverContext") -> None:
nd["is_never_flag"] = True
+def _warmup_cpp(ctx: "ResolverContext") -> None:
+ """Build the C/C++ workspace index and propagate workspace-discovered
+ export macros back into the graph.
+
+ The parser runs before the warmup, so symbols on public headers that
+ are tagged with a project-defined export macro (``LEVELDB_EXPORT``,
+ ``SEASTAR_API``, …) land as ``is_exported_symbol=False``. We re-mark
+ them here by reading each symbol's signature text and checking it
+ against the workspace's discovered macro set. This keeps the parser
+ stateless w.r.t. the workspace while still surfacing the right
+ visibility on the graph nodes the dead-code analyzer reads.
+ """
+ from .resolvers.cpp_workspace import get_or_build_cpp_index
+
+ index = get_or_build_cpp_index(ctx)
+ graph = getattr(ctx, "graph", None)
+ if graph is None or not index.project_export_macros:
+ return
+
+ macros = index.project_export_macros
+ parsed_files = getattr(ctx, "parsed_files", None) or {}
+ for path, parsed in parsed_files.items():
+ if not path.endswith((".h", ".hpp", ".hxx", ".hh", ".h++", ".inc",
+ ".c", ".cc", ".cpp", ".cxx", ".c++")):
+ continue
+ for sym in parsed.symbols:
+ sig = sym.signature or ""
+ if not sig:
+ continue
+ # Check macro presence as a token — cheap substring with a
+ # word-boundary check to avoid false matches inside other
+ # identifiers.
+ for macro in macros:
+ idx = sig.find(macro)
+ if idx == -1:
+ continue
+ before_ok = idx == 0 or not (sig[idx - 1].isalnum() or sig[idx - 1] == "_")
+ end = idx + len(macro)
+ after_ok = end >= len(sig) or not (sig[end].isalnum() or sig[end] == "_")
+ if before_ok and after_ok:
+ node = graph.nodes.get(sym.id)
+ if node is not None:
+ node["is_exported_symbol"] = True
+ if node.get("visibility") == "private":
+ node["visibility"] = "public"
+ break
+
+
def _warmup_dotnet(ctx: "ResolverContext") -> None:
from .resolvers.dotnet import get_or_build_index
@@ -169,6 +217,8 @@ _WARMUPS: dict[str, tuple[str, Warmup]] = {
"go": ("graph.go_index", _warmup_go),
"typescript": ("graph.ts_index", _warmup_typescript),
"javascript": ("graph.ts_index", _warmup_typescript),
+ "cpp": ("graph.cpp_index", _warmup_cpp),
+ "c": ("graph.cpp_index", _warmup_cpp),
}
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/cpp.py b/packages/core/src/repowise/core/ingestion/resolvers/cpp.py
index 9cd63b69c..bf16fdb6f 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/cpp.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/cpp.py
@@ -1,4 +1,30 @@
-"""C / C++ import resolution."""
+"""C / C++ import resolution.
+
+Resolves a ``#include "x/y.h"`` or ``#include <x/y.h>`` directive to a
+repo-relative file path. Order, highest-fidelity first:
+
+1. **compile_commands.json include dirs** for the *importer* TU.
+2. **Workspace public-header map** (``CppWorkspaceIndex.public_header_includes``)
+ so ``#include "leveldb/cache.h"`` lands on
+ ``include/leveldb/cache.h`` even without ``compile_commands``.
+3. **Per-target include-search-roots** for every target that owns the
+ importer.
+4. **Importer-directory relative** join (``db_impl.cc`` includes
+ ``"db/builder.h"`` → ``db/builder.h``).
+5. **Stdlib filter** — angle-bracket system includes like ``<vector>``
+ / ``<stdio.h>`` resolve to ``None`` (no edge emitted) so the graph
+ isn't polluted with one external node per stdlib import.
+6. **Stem fallback** — last-ditch lookup against the global stem map.
+
+:func:`resolve_cpp_import_all` performs sibling fan-out: when the
+importer is a translation unit (``.cc`` / ``.cpp`` / ``.c``) and the
+include resolves to a header that belongs to one or more targets in
+the workspace index, the resolver also emits import targets for every
+other TU sharing those targets. That mirrors the JVM / Go same-package
+fan-out and rescues the leveldb-shape false positives where every
+public header reads as ``unreachable_file`` because the only ``.cc``
+that includes it is one file out of many in the same library target.
+"""
from __future__ import annotations
@@ -8,15 +34,22 @@ from pathlib import Path
from .context import ResolverContext
-def resolve_cpp_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
- """Resolve a C/C++ ``#include`` to a repo-relative file path."""
- repo_root = ctx.repo_path.resolve() if ctx.repo_path else None
+_SOURCE_TU_EXTS: tuple[str, ...] = (".c", ".cc", ".cpp", ".cxx", ".c++", ".cppm", ".ixx", ".mxx")
+_HEADER_EXTS: tuple[str, ...] = (".h", ".hpp", ".hxx", ".hh", ".h++", ".inc")
+
+
+def _is_system_include(module_path: str, system_form: bool) -> bool:
+ """Best-effort check for a stdlib-style angle-bracket include."""
+ if not system_form:
+ return False
+ from .cpp_workspace import is_stdlib_include
- # The graph builder passes ``importer_path`` as a *repo-relative* POSIX
- # path. Reduce it to its repo-relative directory; if a caller ever passes
- # an absolute path, fold it back under the repo root first so the
- # importer-relative join below stays repo-relative (and never resolves
- # against the process CWD).
+ return is_stdlib_include(module_path)
+
+
+def _normalise_importer(importer_path: str, ctx: ResolverContext) -> tuple[str, str]:
+ """Return ``(importer_repo_relative, importer_dir)``."""
+ repo_root = ctx.repo_path.resolve() if ctx.repo_path else None
importer_rel = importer_path
if repo_root and Path(importer_path).is_absolute():
try:
@@ -24,8 +57,25 @@ def resolve_cpp_import(module_path: str, importer_path: str, ctx: ResolverContex
except ValueError:
importer_rel = Path(importer_path).as_posix()
importer_dir = posixpath.dirname(Path(importer_rel).as_posix())
+ return importer_rel, importer_dir
+
- # 1. Try compile_commands.json include paths (absolute on-disk dirs)
+def _resolve_single(
+ module_path: str,
+ importer_path: str,
+ ctx: ResolverContext,
+ *,
+ system_form: bool,
+) -> str | None:
+ """Resolve a single include path; returns the resolved repo file or None."""
+ repo_root = ctx.repo_path.resolve() if ctx.repo_path else None
+ importer_rel, importer_dir = _normalise_importer(importer_path, ctx)
+
+ # Drop stdlib system includes outright — no node, no edge.
+ if _is_system_include(module_path, system_form):
+ return None
+
+ # 1. compile_commands include dirs (absolute on-disk paths)
for inc_dir in ctx.extract_include_dirs(importer_path):
candidate = (Path(inc_dir) / module_path).resolve()
if repo_root:
@@ -36,14 +86,115 @@ def resolve_cpp_import(module_path: str, importer_path: str, ctx: ResolverContex
except ValueError:
pass
- # 2. Relative to the importer's directory. ``importer_dir`` and the
- # ``#include`` target are both repo-relative, so normalise the join as a
- # plain POSIX path (collapsing ``..``/``.``) and test membership directly —
- # never touch the filesystem, which would resolve against the CWD.
+ # Lazy import to avoid pulling the workspace index on every C file
+ # parse if it isn't relevant (the warmup builds it eagerly when any
+ # C/C++ files are present).
+ cpp_index = None
+ try:
+ from .cpp_workspace import get_or_build_cpp_index
+
+ cpp_index = get_or_build_cpp_index(ctx)
+ except Exception:
+ cpp_index = None
+
+ # 2. Workspace public-header map
+ if cpp_index is not None:
+ target = cpp_index.public_header_includes.get(module_path)
+ if target and target in ctx.path_set:
+ return target
+
+ # 3. Per-target include-search-roots for the importer's owning targets
+ if cpp_index is not None:
+ owning = cpp_index.file_to_targets.get(importer_rel, ())
+ for tid in owning:
+ search_roots = cpp_index.target_include_search_dirs.get(tid, ())
+ for root in search_roots:
+ joined = posixpath.normpath(posixpath.join(root, module_path)) if root else module_path
+ if joined in ctx.path_set:
+ return joined
+
+ # 4. Importer-directory relative
candidate_rel = posixpath.normpath(posixpath.join(importer_dir, module_path))
if candidate_rel in ctx.path_set:
return candidate_rel
- # 3. Stem-matching fallback
+ # 6. Stem fallback (5 was system-include filter above)
stem = Path(module_path).stem.lower()
return ctx.stem_lookup(stem)
+
+
+def resolve_cpp_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
+ """Resolve a C/C++ ``#include`` to a repo-relative file path."""
+ # The parser strips ``< >`` / ``" "`` wrappers before passing
+ # ``module_path``; we treat any path that lacks an absolute prefix as
+ # a quoted include and let the importer-relative join catch it. The
+ # stdlib filter is conservative — bare names like ``vector`` resolve
+ # to None which is what we want.
+ # Heuristic: if the raw text never collides with a repo file in
+ # ``ctx.path_set`` AND it matches a stdlib name, treat as system.
+ system_form = False
+ if module_path:
+ from .cpp_workspace import is_stdlib_include
+
+ # Only treat as system when the path looks unambiguous (bare
+ # stem like ``vector`` or canonical ``stdio.h``) — quoted-form
+ # ``"vector"`` could in theory be a repo file, but in practice
+ # repos don't ship ``./vector`` next to a C++ TU.
+ if is_stdlib_include(module_path):
+ system_form = True
+ return _resolve_single(module_path, importer_path, ctx, system_form=system_form)
+
+
+def resolve_cpp_import_all(
+ module_path: str,
+ importer_path: str,
+ ctx: ResolverContext,
+) -> tuple[str, ...]:
+ """Resolve a ``#include`` and fan out across sibling TUs in shared targets.
+
+ Returns a tuple of resolved repo paths. The primary resolved file is
+ always first; sibling TUs follow. Used by :mod:`..graph.builder` so
+ the IMPORTS edges from a header propagate to every implementation
+ file in the same target — rescuing public-header-only entry points
+ from ``unreachable_file`` flags.
+ """
+ primary = resolve_cpp_import(module_path, importer_path, ctx)
+ if primary is None:
+ return ()
+
+ # Fan-out only makes sense when the import RESOLVES to a header and
+ # the importer is a TU — otherwise we'd be linking ``.cc`` → ``.cc``
+ # files that have no source-level relationship.
+ if not primary.lower().endswith(_HEADER_EXTS):
+ return (primary,)
+ importer_rel, _ = _normalise_importer(importer_path, ctx)
+ if not importer_rel.lower().endswith(_SOURCE_TU_EXTS):
+ return (primary,)
+
+ try:
+ from .cpp_workspace import get_or_build_cpp_index
+
+ cpp_index = get_or_build_cpp_index(ctx)
+ except Exception:
+ return (primary,)
+
+ owning_targets = cpp_index.file_to_targets.get(primary, ())
+ if not owning_targets:
+ return (primary,)
+
+ out: list[str] = [primary]
+ seen: set[str] = {primary, importer_rel}
+ for tid in owning_targets:
+ t = cpp_index.targets.get(tid)
+ if t is None:
+ continue
+ # Limit fan-out scope: only target a small set of siblings — a
+ # single-header library can otherwise pull in dozens of TUs and
+ # blow up the import-edge count. Cap at the target's first 32
+ # sources (stable order) which is enough for the rescue effect.
+ for src in t.sources[:32]:
+ if src in seen:
+ continue
+ seen.add(src)
+ out.append(src)
+ return tuple(out)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/cpp_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/cpp_workspace.py
new file mode 100644
index 000000000..29d53b168
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/cpp_workspace.py
@@ -0,0 +1,451 @@
+"""C/C++ workspace index — unified build-graph view across CMake + Bazel.
+
+Built once per resolver run via :func:`get_or_build_cpp_index` and cached
+on the :class:`ResolverContext`. Mirrors the role that
+:class:`JvmWorkspaceIndex`, :class:`GoPackageIndex`, and
+:class:`DotNetProjectIndex` play for their languages.
+
+What the index gives downstream consumers:
+
+* ``targets`` — every CMake / Bazel ``cc_*`` target with its source list,
+ public/private header list, include dirs, link deps, and a flag for
+ conditionally-compiled sources (CMake ``if(option)`` blocks).
+* ``file_to_targets`` — which targets own a given source/header file
+ (drives sibling fan-out in :func:`resolve_cpp_import`).
+* ``public_header_includes`` — every ``#include "x/y.h"`` shape supported
+ by the workspace's public-header layout. Without this, ``leveldb``-shape
+ repos (where every ``include/leveldb/*.h`` is the library's public API
+ surface) read the entire public API as ``unreachable_file``.
+* ``project_export_macros`` — the project's own visibility macros
+ (``LEVELDB_EXPORT``, ``SEASTAR_API``, …) discovered by scanning header
+ files for ``#define X __declspec(dllexport)`` /
+ ``__attribute__((visibility("default")))`` patterns and from CMake
+ ``target_compile_definitions`` ending in ``_EXPORT`` / ``_API``.
+
+The index is **best-effort**. CMake parsing is regex-based and may miss
+sources hidden behind generator expressions, ``foreach`` loops, or
+``include()`` of helper modules. Callers must always combine the
+workspace data with the lazy stem-fallback path so unparsable repos
+degrade gracefully.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterable
+from dataclasses import dataclass, field
+from functools import lru_cache
+from pathlib import Path, PurePosixPath
+from typing import TYPE_CHECKING
+
+import structlog
+
+from ..external_systems.bazel import (
+ BazelTarget,
+ discover_bazel_packages,
+ is_bazel_repo,
+)
+from ..external_systems.cmake import (
+ CMakeTarget,
+ discover_cmake_reactor,
+ parse_cmake_file_api_reply,
+)
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+log = structlog.get_logger(__name__)
+
+
+# ---------------------------------------------------------------------------
+# Stdlib filter — system includes we should never even emit as external nodes
+# ---------------------------------------------------------------------------
+
+
+_CPP_STDLIB_HEADERS: frozenset[str] = frozenset({
+ # C++ standard library — bare names without extension
+ "algorithm", "any", "array", "atomic", "barrier", "bit", "bitset",
+ "cassert", "ccomplex", "cctype", "cerrno", "cfenv", "cfloat",
+ "charconv", "chrono", "cinttypes", "ciso646", "climits", "clocale",
+ "cmath", "codecvt", "compare", "complex", "concepts", "condition_variable",
+ "coroutine", "csetjmp", "csignal", "cstdalign", "cstdarg", "cstdbool",
+ "cstddef", "cstdint", "cstdio", "cstdlib", "cstring", "ctgmath",
+ "ctime", "cuchar", "cwchar", "cwctype",
+ "deque", "exception", "execution", "expected", "filesystem",
+ "format", "forward_list", "fstream", "functional", "future",
+ "initializer_list", "iomanip", "ios", "iosfwd", "iostream",
+ "istream", "iterator", "latch", "limits", "list", "locale",
+ "map", "memory", "memory_resource", "mutex", "new", "numbers",
+ "numeric", "optional", "ostream", "queue", "random", "ranges",
+ "ratio", "regex", "scoped_allocator", "semaphore", "set", "shared_mutex",
+ "source_location", "span", "sstream", "stack", "stacktrace",
+ "stdexcept", "stop_token", "streambuf", "string", "string_view",
+ "syncstream", "system_error", "thread", "tuple", "typeindex",
+ "typeinfo", "type_traits", "unordered_map", "unordered_set",
+ "utility", "valarray", "variant", "vector", "version", "print",
+ # std experimental
+ "experimental/optional", "experimental/string_view",
+})
+
+
+_C_STDLIB_HEADERS: frozenset[str] = frozenset({
+ "assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", "float.h",
+ "inttypes.h", "iso646.h", "limits.h", "locale.h", "math.h", "setjmp.h",
+ "signal.h", "stdalign.h", "stdarg.h", "stdatomic.h", "stdbool.h",
+ "stddef.h", "stdint.h", "stdio.h", "stdlib.h", "stdnoreturn.h",
+ "string.h", "tgmath.h", "threads.h", "time.h", "uchar.h", "wchar.h",
+ "wctype.h",
+ # POSIX / commonly-bundled
+ "unistd.h", "fcntl.h", "sys/types.h", "sys/stat.h", "sys/mman.h",
+ "sys/socket.h", "sys/wait.h", "sys/ioctl.h", "sys/select.h", "sys/time.h",
+ "sys/uio.h", "sys/un.h", "sys/file.h", "sys/syscall.h", "sys/resource.h",
+ "sys/utsname.h", "sys/epoll.h", "sys/eventfd.h", "sys/timerfd.h",
+ "sys/inotify.h", "sys/sysinfo.h", "sys/random.h", "sys/prctl.h",
+ "netdb.h", "netinet/in.h", "netinet/tcp.h", "netinet/udp.h",
+ "arpa/inet.h", "poll.h", "pthread.h", "sched.h", "semaphore.h",
+ "syslog.h", "termios.h", "dirent.h", "dlfcn.h", "ftw.h", "glob.h",
+ "grp.h", "pwd.h", "regex.h", "spawn.h", "strings.h", "tar.h",
+ "ulimit.h", "utime.h", "wordexp.h", "libgen.h",
+ # Windows SDK common
+ "windows.h", "winsock2.h", "ws2tcpip.h", "io.h", "process.h", "direct.h",
+ "intrin.h", "mmintrin.h", "xmmintrin.h", "emmintrin.h", "immintrin.h",
+})
+
+
+def is_stdlib_include(raw_include: str) -> bool:
+ """Return True if *raw_include* names a C/C++ standard-library header.
+
+ *raw_include* is the path inside ``<>`` (e.g., ``"vector"`` or
+ ``"stdio.h"``).
+ """
+ if raw_include in _C_STDLIB_HEADERS or raw_include in _CPP_STDLIB_HEADERS:
+ return True
+ # Headers like ``sys/types.h`` — already covered. The bare-stem ``c*``
+ # form (cstdio, cstdlib, …) — also covered. Anything starting with
+ # ``__`` or ``bits/`` is libstdc++/libc internals.
+ return raw_include.startswith(("bits/", "ext/", "tr1/", "tr2/", "__"))
+
+
+# ---------------------------------------------------------------------------
+# Index types
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class CppTarget:
+ """Unified build target (CMake or Bazel)."""
+
+ id: str
+ """Stable identifier — ``<source>:<name>`` (e.g., ``cmake:leveldb``,
+ ``bazel://absl/strings:strings``)."""
+
+ name: str
+ kind: str
+ root_dir: str # repo-relative dir owning the build file
+ sources: tuple[str, ...]
+ public_headers: tuple[str, ...]
+ private_headers: tuple[str, ...]
+ include_dirs: tuple[str, ...]
+ compile_defines: tuple[str, ...]
+ link_deps: tuple[str, ...]
+ conditional_sources: tuple[str, ...]
+ is_test: bool
+ is_benchmark: bool
+ is_app: bool
+ is_demo: bool
+ is_example: bool
+
+ @property
+ def is_library(self) -> bool:
+ return self.kind.startswith("library")
+
+
+@dataclass
+class CppWorkspaceIndex:
+ """Repo-scoped view of every local C/C++ build target."""
+
+ targets: dict[str, CppTarget] = field(default_factory=dict)
+
+ file_to_targets: dict[str, tuple[str, ...]] = field(default_factory=dict)
+ """Maps repo-relative file path → target IDs that own it as src/hdr."""
+
+ public_header_includes: dict[str, str] = field(default_factory=dict)
+ """Maps ``#include "x/y.h"`` style key → resolved repo file path.
+
+ Keys come from ``target_include_directories(PUBLIC|INTERFACE …)`` —
+ for every include-dir + every public header, the relative path from
+ the include dir is registered. Also pre-seeded with the as-written
+ path so ``#include "include/leveldb/cache.h"`` keeps working.
+ """
+
+ project_export_macros: frozenset[str] = field(default_factory=frozenset)
+ """``LEVELDB_EXPORT``, ``SEASTAR_API``, ``ABSL_DLL`` — discovered from
+ headers and target_compile_definitions."""
+
+ target_include_search_dirs: dict[str, tuple[str, ...]] = field(default_factory=dict)
+ """Per-target list of include-search-roots (repo-relative). Used as
+ fallback when ``public_header_includes`` misses."""
+
+ main_files: frozenset[str] = field(default_factory=frozenset)
+ """Source files defining ``int main`` / ``WinMain`` / fuzzer entry.
+
+ Populated lazily by Phase 3 when reachability analysis kicks in."""
+
+ def targets_owning(self, file_path: str) -> tuple[str, ...]:
+ return self.file_to_targets.get(file_path, ())
+
+ def siblings_in_targets(self, file_path: str) -> tuple[str, ...]:
+ """All source files sharing at least one target with *file_path*."""
+ owners = self.file_to_targets.get(file_path, ())
+ if not owners:
+ return ()
+ out: list[str] = []
+ seen: set[str] = set()
+ for tid in owners:
+ t = self.targets.get(tid)
+ if not t:
+ continue
+ for src in t.sources:
+ if src == file_path or src in seen:
+ continue
+ seen.add(src)
+ out.append(src)
+ return tuple(out)
+
+ def is_public_header(self, file_path: str) -> bool:
+ for tid in self.file_to_targets.get(file_path, ()):
+ t = self.targets.get(tid)
+ if t and file_path in t.public_headers:
+ return True
+ return False
+
+ def is_conditional(self, file_path: str) -> bool:
+ for tid in self.file_to_targets.get(file_path, ()):
+ t = self.targets.get(tid)
+ if t and file_path in t.conditional_sources:
+ return True
+ return False
+
+
+# ---------------------------------------------------------------------------
+# Build pipeline
+# ---------------------------------------------------------------------------
+
+
+_PROJECT_EXPORT_MACRO_RE = re.compile(
+ r"^\s*#\s*define\s+([A-Z][A-Z0-9_]{2,})\s+(?:__declspec\(\s*dllexport|__attribute__\(\(\s*(?:visibility\(\s*\"default\"|used)|EMSCRIPTEN_KEEPALIVE)",
+ re.MULTILINE,
+)
+_EXPORT_LIKE_NAME_RE = re.compile(r"^[A-Z][A-Z0-9_]{2,}_(?:EXPORT|API|PUBLIC|DLL|VISIBLE)$")
+
+
+@lru_cache(maxsize=8192)
+def _scan_header_for_export_macros(abs_path: str) -> tuple[str, ...]:
+ try:
+ text = Path(abs_path).read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ return ()
+ # Limit to the first ~8KB — export macros are nearly always near the top.
+ head = text[:8192]
+ return tuple({m.group(1) for m in _PROJECT_EXPORT_MACRO_RE.finditer(head)})
+
+
+def _classify_dir(root_dir: str) -> dict[str, bool]:
+ """Classify a target's root dir into ``apps`` / ``demos`` / etc.
+
+ Heuristic on common path segments. Used to drive Phase 3 never-flag
+ decisions without hard-coding repo-specific paths.
+ """
+ parts = [p.lower() for p in PurePosixPath(root_dir).parts]
+ return {
+ "is_app": any(p in ("apps", "app", "bin", "cmd") for p in parts),
+ "is_demo": any(p in ("demos", "demo") for p in parts),
+ "is_example": any(p in ("examples", "example", "samples", "sample") for p in parts),
+ "is_benchmark": any(p in ("benchmarks", "benchmark", "bench") for p in parts)
+ or any("perf" in p for p in parts),
+ "is_test_dir": any(p in ("tests", "test", "testing") for p in parts),
+ }
+
+
+def _cmake_target_to_cpp(t: CMakeTarget, *, path_set: set[str]) -> CppTarget:
+ classification = _classify_dir(PurePosixPath(t.cmakelists).parent.as_posix() if "/" in t.cmakelists else "")
+ is_test = (t.kind == "test") or classification["is_test_dir"]
+ # Filter sources / headers to those actually present in the path_set
+ # so downstream lookups never resolve to phantom files.
+ sources = tuple(s for s in t.sources if s in path_set)
+ public_headers = tuple(s for s in t.public_headers if s in path_set)
+ private_headers = tuple(s for s in t.private_headers if s in path_set)
+ root_dir = PurePosixPath(t.cmakelists).parent.as_posix() if "/" in t.cmakelists else ""
+ if root_dir == ".":
+ root_dir = ""
+ return CppTarget(
+ id=f"cmake:{t.name}@{t.cmakelists}",
+ name=t.name,
+ kind=t.kind,
+ root_dir=root_dir,
+ sources=sources,
+ public_headers=public_headers,
+ private_headers=private_headers,
+ include_dirs=tuple(dict.fromkeys(t.include_dirs)),
+ compile_defines=tuple(dict.fromkeys(t.compile_defines)),
+ link_deps=tuple(dict.fromkeys(t.link_deps)),
+ conditional_sources=tuple(s for s in t.conditional_sources if s in path_set),
+ is_test=is_test,
+ is_benchmark=classification["is_benchmark"],
+ is_app=classification["is_app"] and t.kind == "executable",
+ is_demo=classification["is_demo"],
+ is_example=classification["is_example"],
+ )
+
+
+def _bazel_target_to_cpp(t: BazelTarget, *, path_set: set[str]) -> CppTarget:
+ classification = _classify_dir(t.package)
+ sources = tuple(s for s in t.srcs if s in path_set)
+ public_headers = tuple(s for s in t.hdrs if s in path_set)
+ return CppTarget(
+ id=f"bazel://{t.package}:{t.name}",
+ name=t.name,
+ kind=t.kind,
+ root_dir=t.package,
+ sources=sources,
+ public_headers=public_headers,
+ private_headers=(),
+ include_dirs=tuple(dict.fromkeys(t.includes)),
+ compile_defines=(),
+ link_deps=tuple(dict.fromkeys(t.deps)),
+ conditional_sources=(),
+ is_test=t.testonly or t.kind in ("cc_test", "cc_fuzz_test"),
+ is_benchmark=classification["is_benchmark"],
+ is_app=classification["is_app"] and t.kind == "cc_binary",
+ is_demo=classification["is_demo"],
+ is_example=classification["is_example"],
+ )
+
+
+def _register_target(index: CppWorkspaceIndex, t: CppTarget) -> None:
+ index.targets[t.id] = t
+ for f in (*t.sources, *t.public_headers, *t.private_headers):
+ existing = index.file_to_targets.get(f, ())
+ if t.id not in existing:
+ index.file_to_targets[f] = (*existing, t.id)
+
+ # Populate include-search-roots and public-header path keys.
+ search_roots: list[str] = []
+ if t.include_dirs:
+ search_roots.extend(t.include_dirs)
+ # Heuristic: if the target's root_dir contains an ``include/`` subdir,
+ # treat that as an implicit public include root even without an
+ # explicit ``target_include_directories`` call (catches the leveldb
+ # layout where ``include/leveldb/*.h`` lives under the project root
+ # with no explicit declaration).
+ if t.root_dir:
+ impl_inc = (PurePosixPath(t.root_dir) / "include").as_posix()
+ else:
+ impl_inc = "include"
+ if not any(d == impl_inc for d in search_roots):
+ search_roots.append(impl_inc)
+ index.target_include_search_dirs[t.id] = tuple(dict.fromkeys(search_roots))
+
+ for hdr in t.public_headers:
+ # Map ``include/leveldb/cache.h`` → itself (literal include path)
+ index.public_header_includes.setdefault(hdr, hdr)
+ # Also strip each candidate include-search root prefix so
+ # ``#include "leveldb/cache.h"`` works.
+ for root in search_roots:
+ prefix = root.rstrip("/") + "/"
+ if hdr.startswith(prefix):
+ rel = hdr[len(prefix):]
+ # Always prefer the most-specific include-key first match.
+ index.public_header_includes.setdefault(rel, hdr)
+
+
+def build_cpp_workspace_index(ctx: "ResolverContext") -> CppWorkspaceIndex:
+ index = CppWorkspaceIndex()
+ if ctx.repo_path is None:
+ return index
+
+ repo_path = ctx.repo_path.resolve()
+ path_set = set(ctx.path_set)
+
+ cmake_files = discover_cmake_reactor(repo_path)
+ file_api_targets = parse_cmake_file_api_reply(repo_path)
+ bazel_files = discover_bazel_packages(repo_path) if is_bazel_repo(repo_path) else []
+
+ # Prefer File API output if present — it's authoritative.
+ if file_api_targets:
+ for ct in file_api_targets:
+ _register_target(index, _cmake_target_to_cpp(ct, path_set=path_set))
+ else:
+ for cf in cmake_files:
+ for ct in cf.targets:
+ # Skip stub targets that ``target_sources`` created without
+ # a corresponding ``add_*`` (we have no source list nor a
+ # known kind).
+ if ct.kind == "unknown" and not ct.sources and not ct.public_headers:
+ continue
+ _register_target(index, _cmake_target_to_cpp(ct, path_set=path_set))
+
+ for bf in bazel_files:
+ for bt in bf.targets:
+ _register_target(index, _bazel_target_to_cpp(bt, path_set=path_set))
+
+ # Project export macros — scan every header in any target's public list
+ # plus ``include/**/*.h`` as a fallback (covers projects with no public
+ # header declared in CMake).
+ macros: set[str] = set()
+ scanned: set[str] = set()
+ header_candidates: list[str] = []
+ for t in index.targets.values():
+ for h in t.public_headers:
+ if h not in scanned:
+ scanned.add(h)
+ header_candidates.append(h)
+ # ``target_compile_definitions`` ending in ``_EXPORT`` etc.
+ for define in t.compile_defines:
+ base = define.split("=", 1)[0].strip()
+ if _EXPORT_LIKE_NAME_RE.match(base):
+ macros.add(base)
+ if not header_candidates:
+ for p in path_set:
+ if p.startswith(("include/", "include\\")) and p.lower().endswith((".h", ".hpp", ".hxx")):
+ header_candidates.append(p)
+ if len(header_candidates) > 200:
+ break
+ for rel in header_candidates:
+ abs_p = str((repo_path / rel).resolve())
+ macros.update(_scan_header_for_export_macros(abs_p))
+ _scan_header_for_export_macros.cache_clear()
+
+ # Filter out anything that doesn't look like an export marker name.
+ cleaned = {m for m in macros if _EXPORT_LIKE_NAME_RE.match(m) or m.endswith(("_EXPORT", "_API", "_DLL", "_PUBLIC", "_VISIBLE"))}
+ index.project_export_macros = frozenset(cleaned)
+
+ log.debug(
+ "cpp_workspace_index_built",
+ targets=len(index.targets),
+ files=len(index.file_to_targets),
+ public_keys=len(index.public_header_includes),
+ export_macros=len(index.project_export_macros),
+ )
+ return index
+
+
+_INDEX_KEY = "_cpp_workspace_index"
+
+
+def get_or_build_cpp_index(ctx: "ResolverContext") -> CppWorkspaceIndex:
+ cached = getattr(ctx, _INDEX_KEY, None)
+ if cached is not None:
+ return cached
+ index = build_cpp_workspace_index(ctx)
+ setattr(ctx, _INDEX_KEY, index)
+ return index
+
+
+__all__ = [
+ "CppTarget",
+ "CppWorkspaceIndex",
+ "build_cpp_workspace_index",
+ "get_or_build_cpp_index",
+ "is_stdlib_include",
+]
diff --git a/tests/unit/ingestion/external_systems/test_bazel.py b/tests/unit/ingestion/external_systems/test_bazel.py
new file mode 100644
index 000000000..a3aecb87d
--- /dev/null
+++ b/tests/unit/ingestion/external_systems/test_bazel.py
@@ -0,0 +1,74 @@
+"""Tests for the Bazel BUILD reader."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion.external_systems import bazel
+
+
+def _write(tmp_path: Path, rel: str, text: str) -> Path:
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(text, encoding="utf-8")
+ return p
+
+
+def test_cc_library_with_srcs_and_hdrs(tmp_path):
+ _write(tmp_path, "lib/BUILD.bazel", """
+cc_library(
+ name = "strings",
+ srcs = ["str.cc", "str_util.cc"],
+ hdrs = ["str.h"],
+ deps = ["//base:logging"],
+ includes = ["."],
+)
+""")
+ bf = bazel.parse_bazel_build(tmp_path / "lib/BUILD.bazel", repo_root=tmp_path)
+ assert bf.package == "lib"
+ assert len(bf.targets) == 1
+ t = bf.targets[0]
+ assert t.name == "strings"
+ assert t.kind == "cc_library"
+ assert "lib/str.cc" in t.srcs
+ assert "lib/str.h" in t.hdrs
+ assert "//base:logging" in t.deps
+
+
+def test_cc_test_is_testonly(tmp_path):
+ _write(tmp_path, "BUILD", """
+cc_test(
+ name = "str_test",
+ srcs = ["str_test.cc"],
+ deps = [":strings", "@gtest//:gtest_main"],
+)
+""")
+ bf = bazel.parse_bazel_build(tmp_path / "BUILD", repo_root=tmp_path)
+ assert bf.targets[0].testonly is True
+ assert bf.targets[0].kind == "cc_test"
+
+
+def test_label_resolution(tmp_path):
+ _write(tmp_path, "src/foo/BUILD.bazel", """
+cc_binary(
+ name = "tool",
+ srcs = ["main.cc", "//src/foo:helper.cc", ":local.cc"],
+)
+""")
+ bf = bazel.parse_bazel_build(tmp_path / "src/foo/BUILD.bazel", repo_root=tmp_path)
+ srcs = bf.targets[0].srcs
+ assert "src/foo/main.cc" in srcs
+ assert "src/foo/helper.cc" in srcs
+ assert "src/foo/local.cc" in srcs
+
+
+def test_is_bazel_repo(tmp_path):
+ assert bazel.is_bazel_repo(tmp_path) is False
+ (tmp_path / "MODULE.bazel").write_text("module(name='x')", encoding="utf-8")
+ assert bazel.is_bazel_repo(tmp_path) is True
+
+
+def test_malformed_does_not_raise(tmp_path):
+ p = _write(tmp_path, "BUILD", "cc_library(name = ")
+ bf = bazel.parse_bazel_build(p, repo_root=tmp_path)
+ assert bf.targets == []
diff --git a/tests/unit/ingestion/external_systems/test_cmake.py b/tests/unit/ingestion/external_systems/test_cmake.py
new file mode 100644
index 000000000..4671b7c8c
--- /dev/null
+++ b/tests/unit/ingestion/external_systems/test_cmake.py
@@ -0,0 +1,123 @@
+"""Tests for the CMake reader."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion.external_systems import cmake
+
+
+def _write(tmp_path: Path, rel: str, text: str) -> Path:
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(text, encoding="utf-8")
+ return p
+
+
+def test_add_executable_with_inline_sources(tmp_path):
+ cml = _write(tmp_path, "CMakeLists.txt", """
+ cmake_minimum_required(VERSION 3.10)
+ project(demo)
+ add_executable(demo_app main.cc helper.cc helper.h)
+ """)
+ cm = cmake.parse_cmake_lists(cml, repo_root=tmp_path)
+ assert cm.path == "CMakeLists.txt"
+ assert len(cm.targets) == 1
+ t = cm.targets[0]
+ assert t.name == "demo_app"
+ assert t.kind == "executable"
+ assert "main.cc" in t.sources and "helper.cc" in t.sources
+ assert "helper.h" in t.private_headers
+
+
+def test_add_library_with_target_sources_public(tmp_path):
+ _write(tmp_path, "lib/CMakeLists.txt", """
+ add_library(libfoo STATIC)
+ target_sources(libfoo PRIVATE foo.cc)
+ target_sources(libfoo PUBLIC include/foo/foo.h)
+ target_include_directories(libfoo PUBLIC include)
+ """)
+ cm = cmake.parse_cmake_lists(tmp_path / "lib/CMakeLists.txt", repo_root=tmp_path)
+ t = cm.targets[0]
+ assert t.kind == "library_static"
+ assert "lib/foo.cc" in t.sources
+ assert "lib/include/foo/foo.h" in t.public_headers
+ assert "lib/include" in t.include_dirs
+
+
+def test_add_subdirectory_reactor(tmp_path):
+ _write(tmp_path, "CMakeLists.txt", """
+ add_subdirectory(libfoo)
+ add_subdirectory(app)
+ """)
+ _write(tmp_path, "libfoo/CMakeLists.txt", "add_library(foo SHARED foo.cc)")
+ _write(tmp_path, "app/CMakeLists.txt", "add_executable(my_app main.cc)")
+ files = cmake.discover_cmake_reactor(tmp_path)
+ by_path = {f.path: f for f in files}
+ assert "CMakeLists.txt" in by_path
+ assert "libfoo/CMakeLists.txt" in by_path
+ assert "app/CMakeLists.txt" in by_path
+ libfoo = by_path["libfoo/CMakeLists.txt"]
+ assert libfoo.targets[0].kind == "library_shared"
+ app = by_path["app/CMakeLists.txt"]
+ assert app.targets[0].kind == "executable"
+
+
+def test_if_block_marks_conditional_sources(tmp_path):
+ _write(tmp_path, "CMakeLists.txt", """
+ add_library(plat STATIC stub.cc)
+ if(WIN32)
+ target_sources(plat PRIVATE env_windows.cc)
+ endif()
+ if(UNIX)
+ target_sources(plat PRIVATE env_posix.cc)
+ endif()
+ """)
+ cm = cmake.parse_cmake_lists(tmp_path / "CMakeLists.txt", repo_root=tmp_path)
+ t = cm.targets[0]
+ assert "env_windows.cc" in t.conditional_sources
+ assert "env_posix.cc" in t.conditional_sources
+ assert "stub.cc" not in t.conditional_sources
+
+
+def test_find_package_emits_external_record(tmp_path):
+ cml = _write(tmp_path, "CMakeLists.txt", """
+ find_package(Boost 1.74 REQUIRED)
+ find_package(OpenSSL REQUIRED)
+ """)
+ records = cmake.parse(cml, tmp_path)
+ names = {r.name for r in records}
+ assert names == {"Boost", "OpenSSL"}
+ boost = next(r for r in records if r.name == "Boost")
+ assert boost.version == "1.74"
+ assert boost.ecosystem == "cmake"
+
+
+def test_set_expansion(tmp_path):
+ _write(tmp_path, "CMakeLists.txt", """
+ set(LIB_SRC a.cc b.cc)
+ add_library(thing STATIC ${LIB_SRC})
+ """)
+ cm = cmake.parse_cmake_lists(tmp_path / "CMakeLists.txt", repo_root=tmp_path)
+ t = cm.targets[0]
+ assert "a.cc" in t.sources and "b.cc" in t.sources
+
+
+def test_target_compile_definitions(tmp_path):
+ _write(tmp_path, "CMakeLists.txt", """
+ add_library(thing STATIC a.cc)
+ target_compile_definitions(thing PRIVATE -DTHING_EXPORT_BUILD THING_API)
+ """)
+ cm = cmake.parse_cmake_lists(tmp_path / "CMakeLists.txt", repo_root=tmp_path)
+ t = cm.targets[0]
+ assert "THING_EXPORT_BUILD" in t.compile_defines
+ assert "THING_API" in t.compile_defines
+
+
+def test_malformed_does_not_raise(tmp_path):
+ p = tmp_path / "CMakeLists.txt"
+ p.write_text("add_executable(", encoding="utf-8")
+ cm = cmake.parse_cmake_lists(p, repo_root=tmp_path)
+ # Trailing-open paren is tolerated; either zero targets or the args are
+ # captured but we don't crash.
+ assert isinstance(cm.targets, list)
diff --git a/tests/unit/ingestion/test_cpp_workspace.py b/tests/unit/ingestion/test_cpp_workspace.py
new file mode 100644
index 000000000..868847fec
--- /dev/null
+++ b/tests/unit/ingestion/test_cpp_workspace.py
@@ -0,0 +1,151 @@
+"""Tests for the C/C++ workspace index + include resolver."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.cpp import (
+ resolve_cpp_import,
+ resolve_cpp_import_all,
+)
+from repowise.core.ingestion.resolvers.cpp_workspace import (
+ build_cpp_workspace_index,
+ is_stdlib_include,
+)
+
+
+def _write(tmp_path: Path, rel: str, text: str) -> Path:
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(text, encoding="utf-8")
+ return p
+
+
+def _make_ctx(tmp_path: Path, paths: list[str]) -> ResolverContext:
+ return ResolverContext(
+ path_set=set(paths),
+ stem_map={Path(p).stem.lower(): [p] for p in paths},
+ graph=nx.DiGraph(),
+ repo_path=tmp_path,
+ )
+
+
+def test_public_header_layout_includes_lib_dir(tmp_path):
+ _write(tmp_path, "CMakeLists.txt", """
+ add_library(coffee STATIC src/brew.cc)
+ target_sources(coffee PUBLIC include/coffee/brew.h)
+ target_include_directories(coffee PUBLIC include)
+ """)
+ _write(tmp_path, "include/coffee/brew.h", "// header\n")
+ _write(tmp_path, "src/brew.cc", "// impl\n")
+ paths = ["include/coffee/brew.h", "src/brew.cc", "CMakeLists.txt"]
+
+ ctx = _make_ctx(tmp_path, paths)
+ index = build_cpp_workspace_index(ctx)
+ assert "include/coffee/brew.h" in index.public_header_includes.values()
+ # Both literal and include-dir-stripped keys map to the file
+ assert index.public_header_includes.get("coffee/brew.h") == "include/coffee/brew.h"
+
+
+def test_resolve_public_header_via_workspace(tmp_path):
+ _write(tmp_path, "CMakeLists.txt", """
+ add_library(coffee STATIC src/brew.cc)
+ target_sources(coffee PUBLIC include/coffee/brew.h)
+ target_include_directories(coffee PUBLIC include)
+ """)
+ _write(tmp_path, "include/coffee/brew.h", "// header\n")
+ _write(tmp_path, "src/brew.cc", '#include "coffee/brew.h"\n')
+ paths = ["include/coffee/brew.h", "src/brew.cc", "CMakeLists.txt"]
+ ctx = _make_ctx(tmp_path, paths)
+
+ target = resolve_cpp_import("coffee/brew.h", "src/brew.cc", ctx)
+ assert target == "include/coffee/brew.h"
+
+
+def test_resolve_importer_relative_still_works(tmp_path):
+ _write(tmp_path, "src/util.h", "")
+ _write(tmp_path, "src/util.cc", '#include "util.h"\n')
+ paths = ["src/util.h", "src/util.cc"]
+ ctx = _make_ctx(tmp_path, paths)
+ target = resolve_cpp_import("util.h", "src/util.cc", ctx)
+ assert target == "src/util.h"
+
+
+def test_stdlib_includes_are_dropped(tmp_path):
+ paths = ["main.cc"]
+ ctx = _make_ctx(tmp_path, paths)
+ assert is_stdlib_include("vector")
+ assert is_stdlib_include("stdio.h")
+ assert resolve_cpp_import("vector", "main.cc", ctx) is None
+ assert resolve_cpp_import("stdio.h", "main.cc", ctx) is None
+
+
+def test_resolve_all_fans_out_to_target_siblings(tmp_path):
+ """A ``#include`` of a public header fans out to every TU sharing
+ the owning target so the header's defining files aren't orphaned."""
+ _write(tmp_path, "CMakeLists.txt", """
+ add_library(coffee STATIC src/brew.cc src/grind.cc)
+ target_sources(coffee PUBLIC include/coffee/brew.h)
+ target_include_directories(coffee PUBLIC include)
+ """)
+ _write(tmp_path, "include/coffee/brew.h", "")
+ _write(tmp_path, "src/brew.cc", '#include "coffee/brew.h"\n')
+ _write(tmp_path, "src/grind.cc", "")
+ paths = [
+ "include/coffee/brew.h", "src/brew.cc", "src/grind.cc", "CMakeLists.txt",
+ ]
+ ctx = _make_ctx(tmp_path, paths)
+
+ targets = resolve_cpp_import_all("coffee/brew.h", "src/brew.cc", ctx)
+ assert targets[0] == "include/coffee/brew.h"
+ # Sibling TU should be included in the fan-out
+ assert "src/grind.cc" in targets
+
+
+def test_project_export_macro_discovery(tmp_path):
+ _write(tmp_path, "CMakeLists.txt", """
+ add_library(coffee STATIC src/brew.cc)
+ target_sources(coffee PUBLIC include/coffee/api.h)
+ target_include_directories(coffee PUBLIC include)
+ """)
+ _write(tmp_path, "include/coffee/api.h", """
+#if defined(_WIN32)
+#define COFFEE_EXPORT __declspec(dllexport)
+#else
+#define COFFEE_EXPORT __attribute__((visibility("default")))
+#endif
+
+class COFFEE_EXPORT Brewer { };
+""")
+ _write(tmp_path, "src/brew.cc", "")
+ paths = ["include/coffee/api.h", "src/brew.cc", "CMakeLists.txt"]
+ ctx = _make_ctx(tmp_path, paths)
+
+ index = build_cpp_workspace_index(ctx)
+ assert "COFFEE_EXPORT" in index.project_export_macros
+
+
+def test_no_workspace_falls_back_to_stem(tmp_path):
+ _write(tmp_path, "src/util.h", "")
+ paths = ["src/util.h", "src/main.cc"]
+ ctx = _make_ctx(tmp_path, paths)
+ # No CMakeLists, no compile_commands — must still find util.h via stem
+ target = resolve_cpp_import("util.h", "src/main.cc", ctx)
+ assert target == "src/util.h"
+
+
+def test_siblings_in_targets(tmp_path):
+ _write(tmp_path, "CMakeLists.txt", """
+ add_library(thing STATIC a.cc b.cc c.cc)
+ target_sources(thing PUBLIC a.h)
+ """)
+ for f in ("a.cc", "b.cc", "c.cc", "a.h"):
+ _write(tmp_path, f, "")
+ paths = ["a.cc", "b.cc", "c.cc", "a.h", "CMakeLists.txt"]
+ ctx = _make_ctx(tmp_path, paths)
+ index = build_cpp_workspace_index(ctx)
+ siblings = set(index.siblings_in_targets("a.cc"))
+ assert siblings == {"b.cc", "c.cc"}