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(rust): stop reading a trait bound as inheritance (#2415)

Raghav Chamadiyae6112bf0fa0a
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py
index 1512ba3b7..c1a61ea78 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py
@@ -8,9 +8,6 @@ from ...models import HeritageRelation
from ...type_names import bare_type_name
from ..helpers import node_text
-# Auto-derived/auto-implemented marker traits carry no useful heritage signal.
-_SKIP_BOUNDS = ("Sized", "Send", "Sync", "Unpin")
-
def _impl_relation(def_node: Node, line: int, src: str, out: list[HeritageRelation]) -> None:
"""``impl Trait for Type`` -> ``Type`` trait_impl ``Trait``."""
@@ -34,8 +31,31 @@ def _impl_relation(def_node: Node, line: int, src: str, out: list[HeritageRelati
def _trait_supertraits(
def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
) -> None:
- """``trait Foo: Bar + Baz`` -> ``Foo`` extends ``Bar``, ``Baz``."""
- bounds = def_node.child_by_field_name("bounds")
+ """``trait Foo: Bar + Baz`` -> ``Foo`` extends ``Bar``, ``Baz``.
+
+ A supertrait may also be written ``trait Foo where Self: Bar``, which the
+ ``bounds`` field does not carry, so the where clause is read too.
+ """
+ _emit_bounds(def_node.child_by_field_name("bounds"), name, line, src, out)
+
+ for child in def_node.children:
+ if child.type != "where_clause":
+ continue
+ for predicate in child.children:
+ if predicate.type != "where_predicate":
+ continue
+ # Only `Self`. Every other subject is a type parameter, and a bound
+ # on one says nothing about the trait that declares it.
+ left = predicate.child_by_field_name("left")
+ if left is None or node_text(left, src).strip() != "Self":
+ continue
+ _emit_bounds(predicate.child_by_field_name("bounds"), name, line, src, out)
+
+
+def _emit_bounds(
+ bounds: Node | None, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Emit one ``extends`` per trait named in a bound list."""
if not bounds:
return
for child in bounds.children:
@@ -53,32 +73,11 @@ def _trait_supertraits(
)
-def _where_clause_bounds(
- def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
-) -> None:
- """``impl<T> Foo for T where T: Debug + Clone`` -> Foo trait_bound Debug, Clone."""
- for child in def_node.children:
- if child.type != "where_clause":
- continue
- for predicate in child.children:
- if predicate.type != "where_predicate":
- continue
- bounds = predicate.child_by_field_name("bounds")
- if not bounds:
- continue
- for bound_child in bounds.children:
- if bound_child.type in ("+", ":"):
- continue
- bound_name = bare_type_name(node_text(bound_child, src))
- if bound_name and bound_name not in _SKIP_BOUNDS:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=bound_name,
- kind="trait_bound",
- line=line,
- )
- )
+# A `where T: Debug` bound elsewhere constrains a type PARAMETER, and the
+# relation can only be recorded against the enclosing item, which is often a
+# function. No edge drawn from that is true in any edge type, so those bounds
+# are not extracted. Recording one needs a node for the parameter itself,
+# which the graph has no concept of.
def _derive_traits(
@@ -126,15 +125,5 @@ def _extract_rust_heritage(
elif def_node.type == "trait_item":
_trait_supertraits(def_node, name, line, src, out)
- # Trait bounds from where clauses can appear on any item type.
- if def_node.type in (
- "impl_item",
- "function_item",
- "struct_item",
- "enum_item",
- "trait_item",
- ):
- _where_clause_bounds(def_node, name, line, src, out)
-
if def_node.type in ("struct_item", "enum_item"):
_derive_traits(def_node, name, line, src, out)
diff --git a/packages/core/src/repowise/core/ingestion/heritage_resolver.py b/packages/core/src/repowise/core/ingestion/heritage_resolver.py
index 05c17bb11..dc9f59d26 100644
--- a/packages/core/src/repowise/core/ingestion/heritage_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/heritage_resolver.py
@@ -295,10 +295,17 @@ class HeritageResolver:
def _heritage_kind_to_edge_type(kind: str) -> str:
- """Map HeritageKind to graph edge_type string."""
+ """Map HeritageKind to graph edge_type string.
+
+ ``derive`` is named rather than left to the default: ``#[derive(Clone)]``
+ really does implement the trait, and falling through would call it
+ inheritance.
+ """
if kind == "implements":
return "implements"
if kind == "trait_impl":
return "implements"
+ if kind == "derive":
+ return "implements"
# extends, mixin → extends
return "extends"
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/rust.py b/packages/core/src/repowise/core/ingestion/languages/specs/rust.py
index 140499c1e..18360e67a 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/rust.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/rust.py
@@ -29,7 +29,9 @@ SPEC = LanguageSpec(
extensions=frozenset({".rs"}),
grammar_package="tree_sitter_rust",
scm_file="rust.scm",
- heritage_node_types=frozenset({"impl_item", "trait_item", "struct_item", "enum_item", "function_item"}),
+ # No `function_item`: it was here only so a function's `where` bounds could
+ # be read as heritage, which said the function inherited from the trait.
+ heritage_node_types=frozenset({"impl_item", "trait_item", "struct_item", "enum_item"}),
entry_point_patterns=("main.rs", "lib.rs"),
manifest_files=("Cargo.toml",),
lock_files=("Cargo.lock",),
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 1b7127cec..c3b5a8db3 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -301,7 +301,7 @@ class CallSite:
supplied_props: set[str] | None = None # prop names supplied in JSX element (None if unknown/spread)
-HeritageKind = Literal["extends", "implements", "trait_impl", "mixin"]
+HeritageKind = Literal["extends", "implements", "trait_impl", "mixin", "derive"]
@dataclass
diff --git a/tests/unit/ingestion/test_rust_heritage_kinds.py b/tests/unit/ingestion/test_rust_heritage_kinds.py
new file mode 100644
index 000000000..b4b279743
--- /dev/null
+++ b/tests/unit/ingestion/test_rust_heritage_kinds.py
@@ -0,0 +1,97 @@
+"""What Rust heritage extraction emits, and what edge type each kind becomes.
+
+Two kinds reached the graph as ``extends``, which is the edge type meaning
+inheritance. ``#[derive(Clone)]`` is an implementation, and a ``where`` bound
+constrains a type parameter rather than the item it is written on.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+from repowise.core.ingestion.heritage_resolver import _heritage_kind_to_edge_type
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+_PARSER = ASTParser()
+
+
+def _heritage(src: str):
+ info = FileInfo(
+ path="src/lib.rs",
+ abs_path="/repo/src/lib.rs",
+ language="rust",
+ size_bytes=len(src),
+ 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, src.encode()).heritage
+
+
+class TestDerive:
+ def test_derive_is_an_implementation(self) -> None:
+ # Not `Clone` or `Debug`: those are in the language's builtin parents
+ # and are filtered out after extraction.
+ rels = _heritage("#[derive(Serialize, Validate)]\npub struct Thing;\n")
+ got = sorted((r.child_name, r.parent_name, r.kind) for r in rels)
+ assert got == [
+ ("Thing", "Serialize", "derive"),
+ ("Thing", "Validate", "derive"),
+ ], got
+ assert _heritage_kind_to_edge_type("derive") == "implements"
+
+
+class TestWhereBounds:
+ def test_bound_on_a_function_emits_nothing(self) -> None:
+ # The bound constrains T. Recording it against `run` would say the
+ # function inherits from the trait. `Validate` is not a builtin parent,
+ # so nothing filters it out after extraction.
+ rels = _heritage("pub fn run<T>(v: T) where T: Validate {}\n")
+ assert rels == [], [(r.child_name, r.parent_name, r.kind) for r in rels]
+
+ def test_bound_on_an_impl_emits_only_the_impl(self) -> None:
+ rels = _heritage(
+ "pub trait Foo {}\npub struct Thing<T>(T);\n"
+ "impl<T> Foo for Thing<T> where T: Validate {}\n"
+ )
+ got = sorted((r.child_name, r.parent_name, r.kind) for r in rels)
+ assert got == [("Thing", "Foo", "trait_impl")], got
+
+ def test_bound_on_a_struct_emits_nothing(self) -> None:
+ rels = _heritage("pub struct Holder<T>(T) where T: Validate;\n")
+ assert rels == [], [(r.child_name, r.parent_name, r.kind) for r in rels]
+
+
+class TestSupertraitStillExtends:
+ def test_supertrait_is_preserved(self) -> None:
+ # The one Rust relation that genuinely is inheritance.
+ rels = _heritage("pub trait Base {}\npub trait Derived: Base {}\n")
+ got = sorted((r.child_name, r.parent_name, r.kind) for r in rels)
+ assert got == [("Derived", "Base", "extends")], got
+ assert _heritage_kind_to_edge_type("extends") == "extends"
+
+ def test_supertrait_written_as_a_self_bound(self) -> None:
+ # `where Self: Base` is the same fact as `: Base`, and the bounds field
+ # does not carry it.
+ rels = _heritage("pub trait Base {}\npub trait Derived where Self: Base {}\n")
+ got = sorted((r.child_name, r.parent_name, r.kind) for r in rels)
+ assert got == [("Derived", "Base", "extends")], got
+
+ def test_both_spellings_on_one_trait(self) -> None:
+ rels = _heritage(
+ "pub trait Base {}\npub trait Other {}\n"
+ "pub trait Derived: Base where Self: Other {}\n"
+ )
+ got = sorted((r.child_name, r.parent_name, r.kind) for r in rels)
+ assert got == [
+ ("Derived", "Base", "extends"),
+ ("Derived", "Other", "extends"),
+ ], got
+
+ def test_a_parameter_bound_on_a_trait_is_not_a_supertrait(self) -> None:
+ rels = _heritage("pub trait Base {}\npub trait Derived<T> where T: Base {}\n")
+ assert rels == [], [(r.child_name, r.parent_name, r.kind) for r in rels]