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.

fix(ingestion): give Rust cfg build variants their own ids (#3020)

Amanea4160bf6f8c
diff --git a/packages/core/src/repowise/core/ingestion/call_overload_selection.py b/packages/core/src/repowise/core/ingestion/call_overload_selection.py
index 6a7919817..421051e52 100644
--- a/packages/core/src/repowise/core/ingestion/call_overload_selection.py
+++ b/packages/core/src/repowise/core/ingestion/call_overload_selection.py
@@ -236,31 +236,47 @@ class OverloadSelectionMixin:
"""Overload-set indexing and member selection."""
def _index_overload_sets(self, parsed: ParsedFile) -> dict[str, str]:
- """Record *parsed*'s overload sets; ``{member id: representative}``.
-
- Only parameter-count members are narrowed: a build-variant member
- (``#cfg(...)``) is not chosen by its arguments. Kotlin extensions of
- different receivers are separate sets: the receiver chooses among them.
- """
+ """Record overload sets and Rust build variants for one parsed file."""
members: dict[tuple[str, str | None], list[Symbol]] = defaultdict(list)
+ variants: dict[str, list[Symbol]] = defaultdict(list)
+
for sym in parsed.symbols:
base, payload = split_symbol_id(sym.id)
- if payload is not None and payload[0].isdigit():
+ if payload is None:
+ continue
+ if payload[0].isdigit():
members[(base, sym.extension_receiver)].append(sym)
+ else:
+ variants[base].append(sym)
+
representatives: dict[str, str] = {}
+
for overloads in members.values():
overloads.sort(key=lambda sym: sym.start_line)
rep = overloads[0].id
ranges: dict[str, tuple[int, int | None]] = {}
+
for sym in overloads:
representatives[sym.id] = rep
- admitted = signature_parameter_range(sym.signature or "", sym.language)
+ admitted = signature_parameter_range(
+ sym.signature or "", sym.language
+ )
if admitted is None:
self._unranged_overload_sets.add(rep)
else:
ranges.setdefault(sym.id, admitted)
+
self._overload_members[rep] = tuple(ranges.items())
+
self._overload_rep.update(representatives)
+
+ for group in variants.values():
+ group.sort(key=lambda sym: sym.start_line)
+ ids = tuple(sym.id for sym in group)
+ for sym_id in ids:
+ representatives[sym_id] = ids[0]
+ self._variant_siblings[sym_id] = ids
+
return representatives
def _pair_overload_members(self) -> None:
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 35e7e8da7..0d8aa599c 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -355,9 +355,14 @@ class CallResolver(
# {representative: ((member id, (fewest, most) arguments), ...)}.
self._overload_rep: dict[str, str] = {}
self._overload_members: dict[str, tuple[tuple[str, tuple[int, int | None]], ...]] = {}
+
# Representatives of sets with a member whose range is unknown; a count
# cannot choose there, since that member may admit it too.
self._unranged_overload_sets: set[str] = set()
+
+ # Build variants (``f#cfg(unix)``, ``f#cfg(not(unix))``) are not chosen by
+ # arguments: a call means every one, so an edge fans out to each.
+ self._variant_siblings: dict[str, tuple[str, ...]] = {}
self._symbols_by_id = {
symbol.id: symbol for parsed in parsed_files.values() for symbol in parsed.symbols
}
@@ -794,9 +799,16 @@ class CallResolver(
# tier that answered, so it is stamped once here.
if call.edge_type != "calls":
resolved = replace(resolved, edge_type=call.edge_type)
+
if call.spawned:
resolved = replace(resolved, spawned=True)
- results.append(resolved)
+
+ for variant in self._variant_siblings.get(
+ resolved.callee_id, (resolved.callee_id,)
+ ):
+ if variant != resolved.caller_id:
+ results.append(replace(resolved, callee_id=variant))
+
return results
diff --git a/packages/core/src/repowise/core/ingestion/symbol_identity.py b/packages/core/src/repowise/core/ingestion/symbol_identity.py
index d2110ecf5..663e94da5 100644
--- a/packages/core/src/repowise/core/ingestion/symbol_identity.py
+++ b/packages/core/src/repowise/core/ingestion/symbol_identity.py
@@ -264,6 +264,39 @@ def _parameter_types(symbol: Symbol) -> str:
return "(" + ",".join(receiver + erased_parameter_types(symbol)) + ")"
+def _normalize_cfg_whitespace(predicate: str) -> str:
+ """Remove whitespace outside quoted strings in a Rust cfg predicate."""
+ result: list[str] = []
+ quote: str | None = None
+ escaped = False
+
+ for char in predicate:
+ if quote is not None:
+ result.append(char)
+ if escaped:
+ escaped = False
+ elif char == "\\":
+ escaped = True
+ elif char == quote:
+ quote = None
+ elif char in ('"', "'"):
+ quote = char
+ result.append(char)
+ elif not char.isspace():
+ result.append(char)
+
+ return "".join(result)
+
+
+def _rust_cfg_predicate(symbol: Symbol) -> str | None:
+ """A Rust item's ``cfg(...)`` predicate with whitespace stripped, or None."""
+ for decorator in symbol.decorators:
+ predicate = _normalize_cfg_whitespace(decorator)
+ if predicate.startswith("cfg(") and predicate.endswith(")"):
+ return predicate
+ return None
+
+
# Which discriminator tells colliding members apart, per language. A build
# variant (C ``#if`` branches, Rust ``cfg``) registers here as its own function.
_DISCRIMINATORS: dict[str, Callable[[Symbol], str | None]] = {
@@ -271,6 +304,7 @@ _DISCRIMINATORS: dict[str, Callable[[Symbol], str | None]] = {
"csharp": _parameter_count,
"cpp": _parameter_count,
"kotlin": _parameter_count,
+ "rust": _rust_cfg_predicate,
}
# Languages where a type may share its name with a sibling of another arity.
diff --git a/tests/unit/ingestion/test_rust_cfg_variants.py b/tests/unit/ingestion/test_rust_cfg_variants.py
new file mode 100644
index 000000000..a24422350
--- /dev/null
+++ b/tests/unit/ingestion/test_rust_cfg_variants.py
@@ -0,0 +1,145 @@
+"""A Rust item declared once per ``cfg`` predicate gets one id per variant.
+
+``#[cfg(unix)] fn f`` and ``#[cfg(not(unix))] fn f`` compile in one each, so
+they used to share the id ``f`` and the graph kept one node for both. Each now
+carries its predicate, ``f#cfg(unix)``, and a call means every variant, so the
+edge fans out to each. Variants are never narrowed by arguments.
+
+The controls: a name declared once keeps its plain id, two items with the same
+predicate stay one id, and an unpredicated item beside a variant keeps the
+plain id.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+from repowise.core.ingestion.call_resolver import CallResolver
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.symbol_identity import _normalize_cfg_whitespace
+
+_PARSER = ASTParser()
+
+PLATFORM = """#[cfg(unix)]
+fn f() -> u32 { 1 }
+
+#[cfg(not(unix))]
+fn f() -> u32 { 2 }
+
+pub fn run() -> u32 { f() }
+"""
+
+
+def _parse(rel: str, text: str, root: Path | None = None) -> ParsedFile:
+ abs_path = rel
+ if root is not None:
+ path = root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ abs_path = str(path)
+ info = FileInfo(
+ path=rel,
+ abs_path=abs_path,
+ language="rust",
+ size_bytes=len(text),
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ return _PARSER.parse_file(info, text.encode("utf-8"))
+
+
+def _ids(parsed: ParsedFile) -> list[str]:
+ return [s.id for s in parsed.symbols]
+
+
+def _edges(root: Path, files: dict[str, str]) -> set[tuple[str, str]]:
+ parsed = {rel: _parse(rel, text, root) for rel, text in files.items()}
+ resolver = CallResolver(
+ parsed, {rel: set(parsed) - {rel} for rel in parsed}, repo_path=str(root)
+ )
+ return {
+ (rc.caller_id, rc.callee_id)
+ for rel, pf in parsed.items()
+ for rc in resolver.resolve_file(rel, pf.calls)
+ }
+
+
+class TestBuildVariants:
+ def test_each_variant_carries_its_predicate(self) -> None:
+ ids = _ids(_parse("lib.rs", PLATFORM))
+ assert "lib.rs::f#cfg(unix)" in ids
+ assert "lib.rs::f#cfg(not(unix))" in ids
+ assert "lib.rs::f" not in ids
+
+ def test_a_call_fans_out_to_every_variant(self, tmp_path: Path) -> None:
+ edges = _edges(tmp_path, {"lib.rs": PLATFORM})
+ assert {callee for caller, callee in edges if caller == "lib.rs::run"} == {
+ "lib.rs::f#cfg(unix)",
+ "lib.rs::f#cfg(not(unix))",
+ }
+
+ def test_predicates_compare_without_whitespace(self) -> None:
+ text = (
+ '#[cfg(feature = "x")]\nfn g() -> u32 { 1 }\n'
+ '#[cfg(feature="y")]\nfn g() -> u32 { 2 }\n'
+ )
+ ids = _ids(_parse("lib.rs", text))
+ assert 'lib.rs::g#cfg(feature="x")' in ids
+ assert 'lib.rs::g#cfg(feature="y")' in ids
+
+ def test_variants_are_not_narrowed_by_argument_count(self, tmp_path: Path) -> None:
+ text = (
+ "#[cfg(unix)]\nfn h(a: u32) -> u32 { a }\n"
+ "#[cfg(not(unix))]\nfn h(a: u32, b: u32) -> u32 { a + b }\n"
+ "pub fn run() -> u32 { h(1) }\n"
+ )
+ edges = _edges(tmp_path, {"lib.rs": text})
+ assert {callee for caller, callee in edges if caller == "lib.rs::run"} == {
+ "lib.rs::h#cfg(unix)",
+ "lib.rs::h#cfg(not(unix))",
+ }
+
+
+class TestControls:
+ def test_a_name_declared_once_keeps_its_plain_id(self) -> None:
+ ids = _ids(_parse("lib.rs", "#[cfg(unix)]\nfn only() -> u32 { 1 }\n"))
+ assert ids == ["lib.rs::only"]
+
+ def test_two_items_with_the_same_predicate_stay_one_id(self) -> None:
+ text = "#[cfg(unix)]\nfn s() -> u32 { 1 }\n#[cfg(unix)]\nfn s() -> u32 { 2 }\n"
+ ids = _ids(_parse("lib.rs", text))
+ assert ids.count("lib.rs::s") == 2
+ assert not any("#" in i for i in ids)
+
+ def test_an_unpredicated_item_beside_a_variant_keeps_the_plain_id(self) -> None:
+ text = (
+ "fn k() -> u32 { 0 }\n"
+ "#[cfg(unix)]\nfn k() -> u32 { 1 }\n"
+ "#[cfg(not(unix))]\nfn k() -> u32 { 2 }\n"
+ )
+ ids = _ids(_parse("lib.rs", text))
+ assert "lib.rs::k" in ids
+ assert "lib.rs::k#cfg(unix)" in ids
+ assert "lib.rs::k#cfg(not(unix))" in ids
+
+ def test_a_variant_calling_itself_draws_no_edge(self, tmp_path: Path) -> None:
+ text = (
+ "#[cfg(unix)]\nfn r() -> u32 { r() }\n"
+ "#[cfg(not(unix))]\nfn r() -> u32 { 2 }\n"
+ )
+ edges = _edges(tmp_path, {"lib.rs": text})
+ assert not any(caller == callee for caller, callee in edges)
+
+def test_rust_cfg_normalization_preserves_string_whitespace() -> None:
+ spaced = _normalize_cfg_whitespace('cfg(feature = "foo bar")')
+ compact = _normalize_cfg_whitespace('cfg(feature="foobar")')
+
+ assert spaced == 'cfg(feature="foo bar")'
+ assert compact == 'cfg(feature="foobar")'
+ assert spaced != compact