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): inherit impl block visibility from target type/trait declaration (#2427)

Rishabh Mishra71c40e3a665c
diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
index 3ffbb4e41..8817fa075 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
@@ -380,17 +380,90 @@ def refine_csharp_visibility(def_node: Node, current_visibility: str) -> str:
# ---------------------------------------------------------------------------
+_RUST_TYPE_DECL_KINDS: frozenset[str] = frozenset(
+ {
+ "struct_item",
+ "enum_item",
+ "union_item",
+ "trait_item",
+ "type_item",
+ }
+)
+
+
+def _rust_extract_type_name(node: Node | None, src: str) -> str | None:
+ """Extract the base type identifier from a Rust type AST node."""
+ if node is None:
+ return None
+ if node.type == "type_identifier":
+ return node_text(node, src).strip() or None
+ if node.type == "scoped_type_identifier":
+ name_node = node.child_by_field_name("name")
+ if name_node is not None:
+ return _rust_extract_type_name(name_node, src)
+ if node.type in ("generic_type", "reference_type"):
+ inner = node.child_by_field_name("type")
+ if inner is not None:
+ return _rust_extract_type_name(inner, src)
+ for child in node.children:
+ if child.type == "type_identifier":
+ return node_text(child, src).strip() or None
+ nested = _rust_extract_type_name(child, src)
+ if nested:
+ return nested
+ return None
+
+
def refine_rust_visibility(def_node: Node, current_visibility: str, src: str) -> str:
- """Give a trait's items the visibility the trait itself declares.
+ """Give a trait's items or an impl block the visibility the target declares.
- Rust forbids a visibility modifier on a trait item, so ``rust_visibility``
- reads empty modifier text and calls every method of a ``pub trait``
- private. The trait's own modifier is the reachable answer: a ``pub trait``
- is downstream-callable API, and a private trait's methods are not.
+ Rust forbids a visibility modifier on trait items and impl blocks, so
+ ``rust_visibility`` reads empty modifier text and calls them private by default.
+ - For trait items: the enclosing trait's own modifier provides the visibility.
+ - For impl blocks: the target type (or trait) declaration in the same scope provides
+ the visibility.
"""
if any(c.type == "visibility_modifier" for c in def_node.children):
return current_visibility
- # Trait items sit directly in the trait's ``declaration_list``. Matching
+
+ # Case 1: An `impl_item` block inherits the visibility of its target type or trait.
+ if def_node.type == "impl_item":
+ parent = def_node.parent
+ if parent is None:
+ return current_visibility
+
+ target_names: list[str] = []
+ type_name = _rust_extract_type_name(def_node.child_by_field_name("type"), src)
+ if type_name:
+ target_names.append(type_name)
+ trait_name = _rust_extract_type_name(def_node.child_by_field_name("trait"), src)
+ if trait_name and trait_name not in target_names:
+ target_names.append(trait_name)
+
+ if not target_names:
+ return current_visibility
+
+ for target in target_names:
+ for sibling in parent.children:
+ if sibling.type in _RUST_TYPE_DECL_KINDS:
+ name_child = sibling.child_by_field_name("name")
+ if name_child is None:
+ name_child = next(
+ (c for c in sibling.children if c.type == "type_identifier"),
+ None,
+ )
+ if name_child is not None and node_text(name_child, src).strip() == target:
+ modifier = next(
+ (c for c in sibling.children if c.type == "visibility_modifier"),
+ None,
+ )
+ if modifier is not None:
+ return rust_visibility("", [node_text(modifier, src)])
+ return "private"
+
+ return current_visibility
+
+ # Case 2: Trait items sit directly in the trait's ``declaration_list``. Matching
# that exact shape rather than walking ancestors keeps an item nested
# inside a defaulted method's body out of the trait's bucket.
decls = def_node.parent
diff --git a/tests/unit/ingestion/test_rust_impl_visibility.py b/tests/unit/ingestion/test_rust_impl_visibility.py
new file mode 100644
index 000000000..516a6db5f
--- /dev/null
+++ b/tests/unit/ingestion/test_rust_impl_visibility.py
@@ -0,0 +1,148 @@
+"""A Rust impl block takes the visibility of the type or trait it implements.
+
+Rust forbids a visibility modifier on an impl block, so ``rust_visibility``
+reads empty modifier text and defaulted every impl block to private.
+``refine_rust_visibility`` reads the target type/trait's modifier instead.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+_PARSER = ASTParser()
+
+
+def _symbols_by_kind_and_name(src: str, path: str = "src/lib.rs") -> dict[tuple[str, str], str]:
+ info = FileInfo(
+ path=path,
+ abs_path=f"/repo/{path}",
+ 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,
+ )
+ parsed = _PARSER.parse_file(info, src.encode("utf-8"))
+ return {(s.kind, s.name): s.visibility for s in parsed.symbols}
+
+
+def test_pub_struct_impl_is_public() -> None:
+ src = """
+pub struct Engine;
+
+impl Engine {
+ pub fn run(&self) {}
+}
+"""
+ vis = _symbols_by_kind_and_name(src)
+ assert vis[("struct", "Engine")] == "public"
+ assert vis[("impl", "Engine")] == "public"
+
+
+def test_private_struct_impl_stays_private() -> None:
+ src = """
+struct InternalEngine;
+
+impl InternalEngine {
+ fn step(&self) {}
+}
+"""
+ vis = _symbols_by_kind_and_name(src)
+ assert vis[("struct", "InternalEngine")] == "private"
+ assert vis[("impl", "InternalEngine")] == "private"
+
+
+def test_generic_type_impl_is_public() -> None:
+ src = """
+pub struct Container<T> {
+ item: T,
+}
+
+impl<T> Container<T> {
+ pub fn get(&self) -> &T {
+ &self.item
+ }
+}
+"""
+ vis = _symbols_by_kind_and_name(src)
+ assert vis[("struct", "Container")] == "public"
+ assert vis[("impl", "Container")] == "public"
+
+
+def test_scoped_type_impl_is_public() -> None:
+ src = """
+pub struct Target;
+pub trait Worker {}
+
+impl Worker for path::Target {
+}
+"""
+ vis = _symbols_by_kind_and_name(src)
+ assert vis[("struct", "Target")] == "public"
+ assert vis[("impl", "Target")] == "public"
+
+
+def test_reference_type_impl_is_public() -> None:
+ src = """
+pub struct Target;
+pub trait AsRefWorker {}
+
+impl AsRefWorker for &Target {
+}
+"""
+ vis = _symbols_by_kind_and_name(src)
+ assert vis[("struct", "Target")] == "public"
+ assert vis[("impl", "Target")] == "public"
+
+
+def test_restricted_visibilities_on_impl() -> None:
+ src = """
+pub(crate) struct CrateStruct;
+pub(super) struct SuperStruct;
+
+impl CrateStruct {
+ pub fn hello(&self) {}
+}
+
+impl SuperStruct {
+ pub fn world(&self) {}
+}
+"""
+ vis = _symbols_by_kind_and_name(src)
+ assert vis[("struct", "CrateStruct")] == "internal"
+ assert vis[("impl", "CrateStruct")] == "internal"
+ assert vis[("struct", "SuperStruct")] == "protected"
+ assert vis[("impl", "SuperStruct")] == "protected"
+
+
+def test_enum_and_union_impl_visibility() -> None:
+ src = """
+pub enum State {
+ Init,
+ Running,
+}
+
+impl State {
+ pub fn is_init(&self) -> bool { true }
+}
+
+pub union Value {
+ i: i32,
+ f: f32,
+}
+
+impl Value {
+ pub fn to_int(&self) -> i32 { 0 }
+}
+"""
+ vis = _symbols_by_kind_and_name(src)
+ assert vis[("enum", "State")] == "public"
+ assert vis[("impl", "State")] == "public"
+ assert vis[("struct", "Value")] == "public"
+ assert vis[("impl", "Value")] == "public"