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): resolve module paths and brace-group imports through the module tree (#2835)

Raghav Chamadiya804bae5df073
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 317c634ae..7ac9caa45 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -92,6 +92,12 @@ _INHERITED_LANGUAGES = frozenset({"kotlin", "python", "typescript", "swift", "cs
# repo-wide uniqueness is no evidence and only wildcard imports may merge names.
_LEXICAL_BARE_NAME_LANGUAGES = frozenset({"elixir", "fsharp"})
+# Languages whose imports name what they bring into scope, so only wildcard
+# imports may merge an imported file's names: ``use a::{B, C}`` binds B and C,
+# never the rest of ``a``. Rust is not lexical above: its receiver-less call
+# sites are mostly chained method calls, which repo-wide uniqueness still serves.
+_NAMED_IMPORT_SCOPE_LANGUAGES = _LEXICAL_BARE_NAME_LANGUAGES | {"rust"}
+
# The sentinel an import that binds a whole module's public names carries.
_WILDCARD_IMPORTED_NAMES = ["*"]
@@ -775,11 +781,11 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
Every language but the lexically-scoped ones can use its whole import
set: a name reaching this tier arrived through some import, and which
directive carried it is not knowable from the resolved file alone. For
- a language in ``_LEXICAL_BARE_NAME_LANGUAGES`` it is knowable and it
+ a language in ``_NAMED_IMPORT_SCOPE_LANGUAGES`` it is knowable and it
matters, so only imports that bind a whole module's public names count.
"""
targets = self._import_targets.get(file_path, set())
- if self._language_of(file_path) not in _LEXICAL_BARE_NAME_LANGUAGES:
+ if self._language_of(file_path) not in _NAMED_IMPORT_SCOPE_LANGUAGES:
return targets
parsed = self._parsed_files.get(file_path)
if parsed is None:
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/rust.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/rust.py
index 9f22354a8..30c0ea84a 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/rust.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/rust.py
@@ -34,68 +34,89 @@ def extract_rust_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[Na
)]
return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
- arg_node = stmt_node.child_by_field_name("argument")
- if arg_node is None:
- for child in stmt_node.children:
- if child.type not in ("use", ";", "pub", "visibility_modifier"):
- arg_node = child
- break
+ arg_node = rust_use_argument(stmt_node)
if arg_node is None:
return [], []
names: list[str] = []
bindings: list[NamedBinding] = []
- _parse_rust_use_tree(arg_node, src, names, bindings, depth=0)
+ for _path, local, exported in expand_rust_use_tree(arg_node, src):
+ names.append(local)
+ bindings.append(NamedBinding(local_name=local, exported_name=exported, source_file=None))
return names, bindings
-def _parse_rust_use_tree(
+def rust_use_argument(stmt_node: Node) -> Node | None:
+ """The use tree of a ``use_declaration`` (the part after ``use``)."""
+ arg_node = stmt_node.child_by_field_name("argument")
+ if arg_node is not None:
+ return arg_node
+ for child in stmt_node.children:
+ if child.type not in ("use", ";", "pub", "visibility_modifier"):
+ return child
+ return None
+
+
+def expand_rust_use_tree(node: Node, src: str) -> list[tuple[str, str, str | None]]:
+ """Flatten a Rust use tree into one ``(path, local_name, exported_name)`` per leaf.
+
+ - ``crate::a::B`` -> ``[("crate::a::B", "B", "B")]``
+ - ``crate::{a::{self, B as C}, d::*}`` -> ``crate::a`` bound as ``a``,
+ ``crate::a::B`` bound as ``C``, and ``("crate::d::*", "*", None)``
+
+ Each leaf names one path, so a brace group whose members live in
+ different modules resolves member by member instead of as one
+ unresolvable ``crate::{...}`` string.
+ """
+ leaves: list[tuple[str, str, str | None]] = []
+ _walk_use_tree(node, src, "", leaves, depth=0)
+ return leaves
+
+
+def _join(prefix: str, path: str) -> str:
+ return f"{prefix}::{path}" if prefix else path
+
+
+def _walk_use_tree(
node: Node,
src: str,
- names: list[str],
- bindings: list[NamedBinding],
+ prefix: str,
+ leaves: list[tuple[str, str, str | None]],
depth: int,
) -> None:
- """Recursively parse a Rust use-tree into named bindings."""
if depth > 10:
return
- if node.type == "use_as_clause":
- path_child = node.child_by_field_name("path") or (
- node.children[0] if node.children else None
- )
- alias_child = node.child_by_field_name("alias") or (
- node.children[-1] if len(node.children) >= 2 else None
- )
- if path_child and alias_child and path_child != alias_child:
- exported = node_text(path_child, src).rsplit("::", 1)[-1]
- local = node_text(alias_child, src)
- names.append(local)
- bindings.append(
- NamedBinding(local_name=local, exported_name=exported, source_file=None)
- )
- return
-
- if node.type == "use_wildcard":
- names.append("*")
- bindings.append(NamedBinding(local_name="*", exported_name=None, source_file=None))
+ if node.type == "scoped_use_list":
+ path_node = node.child_by_field_name("path")
+ list_node = node.child_by_field_name("list")
+ if path_node is not None:
+ prefix = _join(prefix, node_text(path_node, src))
+ if list_node is not None:
+ _walk_use_tree(list_node, src, prefix, leaves, depth + 1)
return
if node.type == "use_list":
- for child in node.children:
- if child.type in ("{", "}", ","):
- continue
- _parse_rust_use_tree(child, src, names, bindings, depth + 1)
+ for child in node.named_children:
+ _walk_use_tree(child, src, prefix, leaves, depth + 1)
return
- if node.type == "scoped_use_list":
- for child in node.children:
- if child.type == "use_list":
- _parse_rust_use_tree(child, src, names, bindings, depth + 1)
+ if node.type == "use_wildcard":
+ leaves.append((_join(prefix, node_text(node, src)), "*", None))
return
+ alias: str | None = None
+ if node.type == "use_as_clause":
+ path_node = node.child_by_field_name("path")
+ alias_node = node.child_by_field_name("alias")
+ if path_node is None or alias_node is None:
+ return
+ alias = node_text(alias_node, src)
+ node = path_node
+
text = node_text(node, src)
- bare = text.rsplit("::", 1)[-1]
- if bare and bare != "*":
- names.append(bare)
- bindings.append(NamedBinding(local_name=bare, exported_name=bare, source_file=None))
+ # ``{self}`` names the enclosing path itself: ``a::{self}`` binds ``a``.
+ path = prefix if text == "self" and prefix else _join(prefix, text)
+ exported = path.rsplit("::", 1)[-1]
+ if exported and exported != "*":
+ leaves.append((path, alias or exported, exported))
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 99f8db139..f56ecbefb 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -996,6 +996,8 @@ def _statement_imports(
return _php_imports(stmt_node, raw, src)
if language == "dart":
return [_dart_import(stmt_node, module_node, module_text, raw, src)]
+ if language == "rust" and stmt_node.type == "use_declaration":
+ return _rust_use_imports(stmt_node, module_text, raw, src)
if language in _TS_JS_LANGUAGES and _is_dynamic_esm_import(stmt_node):
# ``import('./mod')`` binds a module namespace at runtime, so it is a
# wildcard, which keeps the target's exports live.
@@ -1157,6 +1159,70 @@ def _generic_import(
)
+def _rust_use_imports(stmt_node: Node, module_text: str, raw: str, src: str) -> list[Import]:
+ """Rust: one Import per leaf of the use tree, each with its own path.
+
+ ``use crate::{a::B, c::D}`` names two modules, and the joined string
+ resolves to neither. ``super`` hops that only climb out of inline
+ ``mod`` blocks stay inside this file, so they are dropped here and the
+ resolver sees the path the file itself would write.
+ """
+ from .extractors.bindings.rust import expand_rust_use_tree, rust_use_argument
+ from .models import NamedBinding
+
+ arg_node = rust_use_argument(stmt_node)
+ leaves = expand_rust_use_tree(arg_node, src) if arg_node is not None else []
+ inline_depth = _rust_inline_mod_depth(stmt_node)
+ is_reexport = _is_reexport_import(stmt_node, raw, "rust")
+ if len(leaves) <= 1 and "{" not in module_text and not inline_depth:
+ return [_generic_import(stmt_node, module_text, raw, "rust", src)]
+ imports = []
+ for path, local, exported in leaves:
+ path = _strip_inline_super(path, inline_depth)
+ imports.append(
+ Import(
+ raw_statement=raw,
+ module_path=path,
+ imported_names=[local],
+ is_relative=path.startswith(("self::", "super::", "crate::")),
+ resolved_file=None,
+ bindings=[NamedBinding(local_name=local, exported_name=exported, source_file=None)],
+ is_reexport=is_reexport,
+ )
+ )
+ return imports
+
+
+def _rust_inline_mod_depth(node: Node) -> int:
+ """How many inline ``mod name { ... }`` blocks enclose *node* in its file."""
+ depth = 0
+ parent = node.parent
+ while parent is not None:
+ if parent.type == "mod_item":
+ depth += 1
+ parent = parent.parent
+ return depth
+
+
+def _strip_inline_super(path: str, inline_depth: int) -> str:
+ """Drop the ``super`` hops of *path* that stay inside the file.
+
+ In ``mod tests { use super::*; }`` the ``super`` is this file's own
+ module, so the path is ``self::*``, not the parent module's glob.
+ """
+ if not inline_depth:
+ return path
+ segments = path.split("::")
+ hops = 0
+ while hops < len(segments) and segments[hops] == "super":
+ hops += 1
+ if not hops:
+ return path
+ if hops <= inline_depth:
+ return "::".join(["self", *segments[hops:]])
+ return "::".join(segments[inline_depth:])
+
+
def _rust_mod_path_attribute(stmt_node: Node, src: str) -> str | None:
"""The ``#[path = "..."]`` override on a Rust ``mod`` item, if any.
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/rust.py b/packages/core/src/repowise/core/ingestion/resolvers/rust.py
index 7c9c3d50e..fb531ec1a 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/rust.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/rust.py
@@ -77,25 +77,29 @@ def resolve_rust_import(
resolved = _follow_crate_root_reexport(crate_root, parts[1:], ctx)
return resolved
- # --- self:: — resolve from the current module's directory ---
- if prefix == "self":
- importer_dir = str(Path(importer_path).parent.as_posix())
- return _probe_rust_path(importer_dir, parts[1:], frozen_path_set)
-
- # --- super:: — resolve from the parent directory (supports chained super::super::) ---
- if prefix == "super":
- parent = Path(importer_path).parent
- idx = 0
- while idx < len(parts) and parts[idx] == "super":
- parent = parent.parent
- idx += 1
- if not parts[idx:]:
- return None
- return _probe_rust_path(str(parent.as_posix()), parts[idx:], frozen_path_set)
-
- # --- Single-segment bare identifier (e.g. from `mod foo;`) ---
- # Probe the importer's directory first — `mod foo;` resolves relative
- # to the declaring file, not the crate root.
+ # --- self:: / super:: — resolve from the module tree, not the directory ---
+ if prefix in ("self", "super"):
+ hops = 0
+ while hops < len(parts) and parts[hops] == "super":
+ hops += 1
+ rest = parts[hops:] if hops else parts[1:]
+ resolved = _probe_module_relative(importer_path, hops, rest, frozen_path_set)
+ if resolved is not None or not rest:
+ return resolved
+ # Legacy base, one directory per hop above the importer's own: right
+ # for a crate root outside lib.rs/main.rs (``src/bin/x.rs``), whose
+ # children sit beside it rather than under ``x/``.
+ legacy = Path(importer_path).parent
+ for _ in range(hops):
+ legacy = legacy.parent
+ return _probe_rust_path(legacy.as_posix(), rest, frozen_path_set)
+
+ # --- Bare path: `mod foo;` or a 2018 path through a child module ---
+ # A child module of the importer comes first: `mod foo;` and
+ # `use foo::Bar` both name the declaring module's own child.
+ resolved = _probe_rust_path(_rust_module_dir(importer_path), parts, frozen_path_set)
+ if resolved is not None:
+ return resolved
if len(parts) == 1:
importer_dir = str(Path(importer_path).parent.as_posix())
resolved = _probe_rust_path(importer_dir, parts, frozen_path_set)
@@ -215,6 +219,56 @@ def _follow_crate_root_reexport(
return None
+_DIRECTORY_MODULE_FILES = ("mod.rs", "lib.rs", "main.rs")
+
+
+def _rust_module_dir(file_path: str) -> str:
+ """The directory holding the child modules of the module *file_path* defines.
+
+ ``mod.rs``, ``lib.rs`` and ``main.rs`` own their directory; any other
+ ``foo.rs`` owns ``foo/`` (the 2018 layout, ``foo.rs`` beside ``foo/bar.rs``).
+ """
+ path = Path(file_path)
+ if path.name in _DIRECTORY_MODULE_FILES:
+ return path.parent.as_posix()
+ return (path.parent / path.stem).as_posix()
+
+
+def _probe_module_relative(
+ importer_path: str, hops: int, rest: list[str], path_set: frozenset[str]
+) -> str | None:
+ """Resolve ``self::<rest>`` (no hops) or ``super::<rest>`` climbing *hops* modules.
+
+ A path that names an item of the ancestor module itself
+ (``super::Type``) lands on that module's own file.
+ """
+ base = Path(_rust_module_dir(importer_path))
+ for _ in range(hops):
+ base = base.parent
+ base_dir = base.as_posix()
+ if rest:
+ resolved = _probe_rust_path(base_dir, rest, path_set)
+ if resolved is not None:
+ return resolved
+ if not hops:
+ return None
+ for candidate in _module_files_of_dir(base_dir):
+ if candidate in path_set and candidate != importer_path:
+ return candidate
+ return None
+
+
+def _module_files_of_dir(module_dir: str) -> tuple[str, ...]:
+ """The files that can define the module whose children live in *module_dir*."""
+ roots = tuple(
+ f"{module_dir}/{name}" if module_dir not in (".", "") else name
+ for name in _DIRECTORY_MODULE_FILES
+ )
+ if module_dir in (".", ""):
+ return roots
+ return (f"{module_dir}.rs", *roots)
+
+
@lru_cache(maxsize=4096)
def _find_rust_crate_root_cached(
importer_path: str, parsed_file_keys: frozenset[str]
diff --git a/tests/unit/ingestion/test_bare_name_index_kinds.py b/tests/unit/ingestion/test_bare_name_index_kinds.py
index 3aec6d87d..b402a0e1e 100644
--- a/tests/unit/ingestion/test_bare_name_index_kinds.py
+++ b/tests/unit/ingestion/test_bare_name_index_kinds.py
@@ -229,9 +229,14 @@ class TestTheImportMergedTierRefusesTheSame:
{
"util.rs": ("rust", "pub fn render() -> u8 {\n 1\n}\n"),
"other.rs": ("rust", "pub fn render() -> u8 {\n 2\n}\n"),
- "caller.rs": ("rust", "pub fn run() -> u8 {\n render()\n}\n"),
+ "caller.rs": (
+ "rust",
+ "use crate::util::*;\npub fn run() -> u8 {\n render()\n}\n",
+ ),
},
)
+ # A Rust bare name reaches an imported file through a glob import only.
+ parsed["caller.rs"].imports[0].resolved_file = "util.rs"
edges = _edges_with_imports(
parsed, tmp_path, {"caller.rs": {"util.rs"}, "util.rs": set(), "other.rs": set()}
)
@@ -284,9 +289,13 @@ class TestTheImportMergedTierRefusesAStdName:
{
"cursor.rs": ("rust", "pub fn next() -> u8 {\n 1\n}\n"),
"other.rs": ("rust", "pub fn next() -> u8 {\n 2\n}\n"),
- "caller.rs": ("rust", "pub fn run() -> u8 {\n next()\n}\n"),
+ "caller.rs": (
+ "rust",
+ "use crate::cursor::*;\npub fn run() -> u8 {\n next()\n}\n",
+ ),
},
)
+ parsed["caller.rs"].imports[0].resolved_file = "cursor.rs"
assert "next" not in get_builtin_methods("rust")
edges = _edges_with_imports(
parsed,
diff --git a/tests/unit/ingestion/test_rust_field_type_use.py b/tests/unit/ingestion/test_rust_field_type_use.py
index fb3aec9df..d57095727 100644
--- a/tests/unit/ingestion/test_rust_field_type_use.py
+++ b/tests/unit/ingestion/test_rust_field_type_use.py
@@ -130,15 +130,15 @@ class TestRustFieldTypeCapture:
# module file via a `super::` path — no `use` statement anywhere.
_SOURCES: dict[str, str] = {
"Cargo.toml": '[package]\nname = "net"\nversion = "0.1.0"\n',
- "src/lib.rs": "pub mod transport;\n",
+ # DeadState is never referenced anywhere, a true positive that must
+ # survive the fix. It sits in the crate root because every public item of
+ # a file that a `mod` item declares counts as reachable through it.
+ "src/lib.rs": "pub mod transport;\n\npub struct DeadState { pub id: u32 }\n",
"src/transport.rs": "pub mod state;\npub mod types;\n",
"src/transport/state.rs": (
"// RecvState is used only as an enum-variant field type in\n"
"// types.rs, crossing files with no `use` statement.\n"
- "pub struct RecvState { pub id: u32 }\n\n"
- "// DeadState is never referenced anywhere — a true positive that\n"
- "// must survive the fix.\n"
- "pub struct DeadState { pub id: u32 }\n"
+ "pub struct RecvState { pub id: u32 }\n"
),
"src/transport/types.rs": (
"pub enum Event {\n"
diff --git a/tests/unit/ingestion/test_rust_module_paths.py b/tests/unit/ingestion/test_rust_module_paths.py
new file mode 100644
index 000000000..8824c2b8a
--- /dev/null
+++ b/tests/unit/ingestion/test_rust_module_paths.py
@@ -0,0 +1,221 @@
+"""Rust module paths: brace-group imports, the 2018 file layout, ``self``/``super``.
+
+A Rust module ``foo`` lives in ``foo.rs`` with its children under ``foo/``
+(or in ``foo/mod.rs``), so ``self``, ``super`` and ``mod bar;`` resolve
+against the module tree, not the importer's directory. A brace group such
+as ``use crate::{a::B, c::D}`` names several modules, each resolved alone.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from typing import ClassVar
+
+import networkx as nx
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.ingestion.graph import GraphBuilder
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.rust import resolve_rust_import
+
+_PARSER = ASTParser()
+
+
+def _file_info(path: str, abs_path: str) -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=abs_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,
+ )
+
+
+def _imports(body: str) -> list[tuple[str, list[str]]]:
+ parsed = _PARSER.parse_file(_file_info("src/c.rs", "/repo/src/c.rs"), body.encode("utf-8"))
+ return [(imp.module_path, imp.imported_names) for imp in parsed.imports]
+
+
+def _resolve(paths: list[str], module_path: str, importer: str) -> str | None:
+ ctx = ResolverContext(
+ path_set=set(paths), stem_map={}, graph=nx.DiGraph(), repo_path=Path("/repo")
+ )
+ ctx.parsed_files = {p: None for p in paths}
+ return resolve_rust_import(module_path, importer, ctx)
+
+
+def _build(repo: Path, sources: dict[str, str]) -> nx.DiGraph:
+ builder = GraphBuilder(repo_path=repo)
+ for rel, body in sources.items():
+ p = repo / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(body, encoding="utf-8")
+ for rel in sources:
+ if rel.endswith(".rs"):
+ info = _file_info(rel, str((repo / rel).resolve()))
+ builder.add_file(_PARSER.parse_file(info, (repo / rel).read_bytes()))
+ return builder.build()
+
+
+class TestUseTreeExpansion:
+ def test_nested_brace_group_is_one_import_per_leaf(self) -> None:
+ imports = _imports("use crate::{a::{B, C as D}, e::*, f::{self}};\n")
+ assert imports == [
+ ("crate::a::B", ["B"]),
+ ("crate::a::C", ["D"]),
+ ("crate::e::*", ["*"]),
+ ("crate::f", ["f"]),
+ ]
+
+ def test_plain_use_keeps_its_single_import(self) -> None:
+ assert _imports("use crate::a::B;\n") == [("crate::a::B", ["B"])]
+
+ def test_super_out_of_an_inline_module_stays_in_the_file(self) -> None:
+ body = "mod tests {\n use super::*;\n use super::super::x::Y;\n}\n"
+ assert _imports(body) == [("self::*", ["*"]), ("super::x::Y", ["Y"])]
+
+
+class TestModuleTreeResolution:
+ _PATHS: ClassVar[list[str]] = [
+ "src/lib.rs",
+ "src/transport.rs",
+ "src/transport/state.rs",
+ "src/transport/types.rs",
+ "src/a.rs",
+ "src/a/inner.rs",
+ "src/bin/tool.rs",
+ "src/bin/helper.rs",
+ ]
+
+ def test_mod_item_in_a_non_mod_file_resolves_under_its_directory(self) -> None:
+ assert _resolve(self._PATHS, "state", "src/transport.rs") == "src/transport/state.rs"
+
+ def test_bare_path_through_a_child_module(self) -> None:
+ resolved = _resolve(self._PATHS, "state::RecvState", "src/transport.rs")
+ assert resolved == "src/transport/state.rs"
+
+ def test_super_names_the_parent_module_of_a_non_mod_file(self) -> None:
+ resolved = _resolve(self._PATHS, "super::state::RecvState", "src/transport/types.rs")
+ assert resolved == "src/transport/state.rs"
+
+ def test_super_item_lands_on_the_parent_module_file(self) -> None:
+ resolved = _resolve(self._PATHS, "super::RecvState", "src/transport/types.rs")
+ assert resolved == "src/transport.rs"
+
+ def test_self_names_the_child_directory_of_a_non_mod_file(self) -> None:
+ assert _resolve(self._PATHS, "self::inner::Deep", "src/a.rs") == "src/a/inner.rs"
+
+ def test_crate_root_outside_lib_keeps_its_sibling_children(self) -> None:
+ assert _resolve(self._PATHS, "helper", "src/bin/tool.rs") == "src/bin/helper.rs"
+
+ def test_self_item_of_the_importer_resolves_to_no_file(self) -> None:
+ assert _resolve(self._PATHS, "self::Local", "src/a.rs") is None
+
+
+class TestIntraCrateDeadCode:
+ """The reported shape, in the 2018 layout: no ``use`` reaches the types."""
+
+ _SOURCES: ClassVar[dict[str, str]] = {
+ "Cargo.toml": '[package]\nname = "net"\nversion = "0.1.0"\n',
+ "src/lib.rs": "pub mod transport;\npub mod a;\n\npub struct DeadRoot;\n",
+ "src/transport.rs": "mod state;\nmod types;\npub use types::Event;\n",
+ "src/transport/state.rs": "pub struct RecvState { pub n: u32 }\n",
+ "src/transport/types.rs": (
+ "pub enum Event {\n Received { state: Option<super::state::RecvState> },\n}\n"
+ ),
+ "src/a.rs": (
+ "mod inner;\npub use self::inner::Deep;\n"
+ "mod tests {\n use super::*;\n}\n"
+ ),
+ "src/a/inner.rs": "pub struct Deep;\n",
+ }
+
+ def _unused(self, graph: nx.DiGraph) -> set[str]:
+ report = DeadCodeAnalyzer(graph, git_meta_map={}).analyze(
+ {"detect_zombie_packages": False, "detect_unused_internals": False,
+ "min_confidence": 0.0}
+ )
+ return {
+ f"{f.file_path}::{f.symbol_name}" if f.symbol_name else f.file_path
+ for f in report.findings
+ if f.kind in (DeadCodeKind.UNUSED_EXPORT, DeadCodeKind.UNREACHABLE_FILE)
+ }
+
+ def test_types_reached_through_module_paths_are_not_flagged(self, tmp_path: Path) -> None:
+ unused = self._unused(_build(tmp_path, self._SOURCES))
+ assert "src/transport/types.rs::Event" not in unused
+ assert "src/a/inner.rs::Deep" not in unused
+ assert "src/transport/state.rs" not in unused
+
+ def test_dead_struct_in_the_crate_root_is_still_flagged(self, tmp_path: Path) -> None:
+ assert "src/lib.rs::DeadRoot" in self._unused(_build(tmp_path, self._SOURCES))
+
+ def test_inline_test_glob_adds_no_edge_to_the_parent_module(self, tmp_path: Path) -> None:
+ graph = _build(tmp_path, self._SOURCES)
+ assert not graph.has_edge("src/a.rs", "src/lib.rs")
+
+
+class TestNoFalseEdges:
+ def test_missing_brace_member_resolves_to_no_repo_file(self, tmp_path: Path) -> None:
+ graph = _build(
+ tmp_path,
+ {
+ "src/lib.rs": "pub mod b;\npub mod c;\n",
+ "src/b.rs": "pub struct Present;\n",
+ "src/c.rs": "use crate::{missing::Gone, b::Present};\n",
+ },
+ )
+ assert graph["src/c.rs"]["src/b.rs"]["imported_names"] == ["Present"]
+ assert not any(
+ v.startswith("src/") and v != "src/b.rs"
+ for v in graph.successors("src/c.rs")
+ if graph.nodes[v].get("node_type") != "symbol"
+ )
+
+ def test_type_parameter_does_not_reach_a_same_named_struct(self, tmp_path: Path) -> None:
+ # ``Item`` in the field is Wrapper's type parameter, not the struct in
+ # b.rs, even though that struct is the only ``Item`` in the crate.
+ graph = _build(
+ tmp_path,
+ {
+ "src/lib.rs": "pub mod a;\npub mod b;\n",
+ "src/a.rs": "pub struct Wrapper<Item> { pub value: Item }\n",
+ "src/b.rs": "pub struct Item { pub id: u32 }\n",
+ },
+ )
+ assert not graph.has_edge("src/a.rs", "src/b.rs")
+
+
+class TestImportedNamesInScope:
+ """``use a::{B}`` brings B into scope, not the rest of ``a``."""
+
+ _LIB: ClassVar[dict[str, str]] = {
+ "src/lib.rs": "pub mod a;\npub mod b;\npub mod c;\n",
+ "src/a.rs": "pub struct B;\nimpl B { pub fn new() -> B { B } }\npub fn other() {}\n",
+ # A second ``other`` keeps the repo-wide tier out of the answer.
+ "src/b.rs": "pub fn other() {}\n",
+ }
+
+ def _callees(self, tmp_path: Path, caller: str) -> set[str]:
+ graph = _build(tmp_path, {**self._LIB, "src/c.rs": caller})
+ return {
+ v
+ for u, v, d in graph.edges(data=True)
+ if u.startswith("src/c.rs::") and d.get("edge_type") == "calls"
+ }
+
+ def test_a_name_the_import_does_not_select_stays_unresolved(self, tmp_path: Path) -> None:
+ caller = "use crate::{a::{B}};\npub fn go() { B::new().other(); }\n"
+ assert "src/a.rs::other" not in self._callees(tmp_path, caller)
+
+ def test_a_glob_import_brings_every_name_into_scope(self, tmp_path: Path) -> None:
+ caller = "use crate::a::*;\npub fn go() { other(); }\n"
+ assert "src/a.rs::other" in self._callees(tmp_path, caller)