Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(rust): give a trait's items the visibility the trait declares (#2376)
Raghav Chamadiyaeb86debbb67c
diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.pyindex 319832302..3ffbb4e41 100644--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py@@ -5,7 +5,8 @@ text alone (the ``visibility_fn`` shape). Some cannot, because the answerdepends on surrounding AST context — C/C++ ``public:`` / ``private:``access specifier siblings, ``static`` storage class at file scope and``__declspec(dllexport)`` attributes; C#'s no-modifier default, which-differs by enclosing declaration; TS/JS export position. Each has a+differs by enclosing declaration; TS/JS export position; Rust's+trait items, which may not write a modifier of their own. Each has a``refine_*_visibility`` the parser calls after the generic``visibility_fn``."""@@ -374,6 +375,36 @@ def refine_csharp_visibility(def_node: Node, current_visibility: str) -> str:return current_visibility+# ---------------------------------------------------------------------------+# Rust node-aware visibility refinement+# ---------------------------------------------------------------------------+++def refine_rust_visibility(def_node: Node, current_visibility: str, src: str) -> str:+ """Give a trait's items the visibility the trait itself 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.+ """+ 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+ # 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+ if decls is None or decls.type != "declaration_list":+ return current_visibility+ trait = decls.parent+ if trait is None or trait.type != "trait_item":+ return current_visibility+ modifier = next((c for c in trait.children if c.type == "visibility_modifier"), None)+ if modifier is None:+ return current_visibility+ return rust_visibility("", [node_text(modifier, src)])++# ---------------------------------------------------------------------------# C / C++ node-aware visibility refinement# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex d08810e22..2097e61f3 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -61,6 +61,7 @@ from .extractors.synthetic_symbols import extract_synthetic_symbolsfrom .extractors.visibility import (refine_cpp_visibility,refine_csharp_visibility,+ refine_rust_visibility,refine_ts_visibility,ts_deferred_export_names,ts_export_aliases,@@ -1571,6 +1572,10 @@ class ASTParser:# inline, via ``export { x }`` lists, or ``export default x``.elif file_info.language in _TS_JS_LANGUAGES:visibility = refine_ts_visibility(def_node, visibility, name, ts_deferred_exports)+ # Rust: a trait's items may not write ``pub`` of their own, so the+ # trait's modifier is the only place their visibility is stated.+ elif file_info.language == "rust":+ visibility = refine_rust_visibility(def_node, visibility, src)# Parent class detectionparent_name = self._find_parent(def_node, config, receiver_nodes, src)diff --git a/tests/unit/ingestion/test_rust_trait_visibility.py b/tests/unit/ingestion/test_rust_trait_visibility.pynew file mode 100644index 000000000..58b183aa4--- /dev/null+++ b/tests/unit/ingestion/test_rust_trait_visibility.py@@ -0,0 +1,116 @@+"""A Rust trait's items take the visibility the trait itself 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.+That put downstream-callable API into the narrow dead-code pool.+``refine_rust_visibility`` reads the enclosing ``trait_item``'s own+``visibility_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 _visibility(src: str, path: str = "src/lib.rs") -> dict[str, str]:+ info = FileInfo(+ path=path,+ abs_path=f"/repo/{path}",+ language="rust",+ size_bytes=100,+ 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.name: s.visibility for s in parsed.symbols}+++def _by_parent(src: str) -> dict[tuple[str | None, str], str]:+ """Visibility keyed by (parent, name), for sources where a name repeats."""+ info = FileInfo(+ path="src/lib.rs",+ abs_path="/repo/src/lib.rs",+ language="rust",+ size_bytes=100,+ 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.parent_name, s.name): s.visibility for s in parsed.symbols}+++def test_pub_trait_methods_are_public() -> None:+ src = """+pub trait Matcher {+ fn is_match(&self, hay: &str) -> bool { hay.is_empty() }+ fn describe(&self) -> String { String::new() }+}+"""+ vis = _visibility(src)+ assert vis["Matcher"] == "public"+ assert vis["is_match"] == "public"+ assert vis["describe"] == "public"+++def test_private_trait_methods_stay_private() -> None:+ src = """+trait Hidden {+ fn helper(&self) -> u8 { 1 }+}+"""+ vis = _visibility(src)+ assert vis["Hidden"] == "private"+ assert vis["helper"] == "private"+++def test_restricted_trait_methods_take_the_trait_restriction() -> None:+ src = """+pub(crate) trait Crated {+ fn inner(&self) {}+}+pub(super) trait Supered {+ fn up(&self) {}+}+"""+ vis = _visibility(src)+ assert vis["inner"] == "internal"+ assert vis["up"] == "protected"+++def test_impl_methods_are_unchanged() -> None:+ src = """+pub struct Engine;++impl Engine {+ pub fn run(&self) {}+ fn step(&self) {}+}++pub trait Matcher {+ fn is_match(&self) -> bool { true }+}++impl Matcher for Engine {+ fn is_match(&self) -> bool { false }+}+"""+ vis = _by_parent(src)+ assert vis[("Engine", "run")] == "public"+ assert vis[("Engine", "step")] == "private"+ # The trait declares it public; the impl writes no ``pub`` and is a+ # plain inherent-position method, so it must not be promoted with it.+ assert vis[("Matcher", "is_match")] == "public"+ assert vis[("Engine", "is_match")] == "private"