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.

feat(rust): bring Rust indexing to C# parity — 26 bug fixes across 8 waves (#251)

Swati Ahujaa8aeea16238a
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 9128b37a9..84da5eaf5 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -511,6 +511,12 @@ class DeadCodeAnalyzer:
continue
if sym_name in _ENTRY_POINT_SYMBOL_NAMES:
continue
+ # Rust proc-macro entry points — invoked by the compiler,
+ # not by call edges in the dependency graph.
+ if sym.get("language") == "rust":
+ decorators = sym.get("decorators") or []
+ if any(d.startswith("proc_macro") for d in decorators):
+ continue
# Explicit language-level export markers (C/C++
# ``__declspec(dllexport)``, GCC ``visibility("default")``)
# signal "called from outside this translation unit /
@@ -670,6 +676,11 @@ class DeadCodeAnalyzer:
for node, node_data in self.graph.nodes(data=True):
if node_data.get("node_type") != "symbol":
continue
+ # Rust: the graph builder does not yet emit intra-file call
+ # edges, so every private Rust function appears "uncalled".
+ # Skip the entire language until call-edge support lands.
+ if node_data.get("language") == "rust":
+ continue
if node_data.get("visibility") not in ("private", "internal"):
continue
file_path = node_data.get("file_path", "")
diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.py
index 6ef12caf6..ffd97a5dc 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -175,6 +175,43 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (
"*/stdafx.cpp",
"*ClassFactory.cpp",
"*ClassFactory.h",
+ # ---- Rust / Cargo conventions ----------------------------------------
+ # Build scripts (executed by Cargo at compile time, never imported)
+ "**/build.rs",
+ "build.rs",
+ # Examples (run via `cargo run --example <name>`)
+ "**/examples/*.rs",
+ "**/examples/**/*.rs",
+ "examples/*.rs",
+ "examples/**/*.rs",
+ # Benchmarks (run via `cargo bench`)
+ "**/benches/*.rs",
+ "**/benches/**/*.rs",
+ "benches/*.rs",
+ "benches/**/*.rs",
+ # Integration tests (run via `cargo test`)
+ # Note: fnmatch **/ requires at least one leading directory component, so
+ # we also add bare patterns for repos where tests/ sits at the root.
+ "**/tests/*.rs",
+ "**/tests/**/*.rs",
+ "tests/*.rs",
+ "tests/**/*.rs",
+ # Binary targets (separate executables in a crate)
+ "**/src/bin/*.rs",
+ "**/src/bin/**/*.rs",
+ # Fuzz targets (various layouts: fuzz/src/, fuzz_targets/, fuzz/fuzz_targets/)
+ "**/fuzz/src/**/*.rs",
+ "**/fuzz_targets/**/*.rs",
+ "**/fuzz/fuzz_targets/**/*.rs",
+ "fuzz/src/**/*.rs",
+ "fuzz_targets/**/*.rs",
+ "fuzz/fuzz_targets/**/*.rs",
+ # Derive macro crates (proc-macro, consumed at compile time)
+ "**/derive/src/*.rs",
+ # Generated code
+ "**/generated/**/*.rs",
+ # Protocol buffer generated code
+ "**/proto/**/*.rs",
)
# Decorator patterns that indicate framework usage (route handlers, fixtures, etc.)
@@ -296,6 +333,11 @@ _NEVER_PACKAGE_DIRS: frozenset[str] = frozenset({
"assets",
"static",
"public",
+ "tests",
+ "test",
+ "benches",
+ "bench",
+ "fuzz",
})
diff --git a/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
index e7bd03908..7bfb1de77 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
@@ -73,6 +73,41 @@ _DYNAMIC_IMPORT_MARKERS: dict[str, tuple[str, ...]] = {
"runtimeMirror(",
"reflect.runtime",
),
+ ".rs": (
+ # Trait object construction (runtime dispatch)
+ "Box<dyn ",
+ "Arc<dyn ",
+ "Rc<dyn ",
+ "&dyn ",
+ # FFI exports (called from C, no Rust callers)
+ '#[no_mangle]',
+ 'extern "C"',
+ # Plugin/inventory registration (resolved at link time)
+ "inventory::submit!",
+ "linkme::distributed_slice!",
+ # Dynamic dispatch through function pointers
+ "Box::new(",
+ "Arc::new(",
+ # Serde (generates field access code)
+ '#[derive(Serialize',
+ '#[derive(Deserialize',
+ '#[serde(',
+ # Conditional compilation
+ '#[cfg(target_',
+ '#[cfg(feature',
+ # Proc-macro registration (called by the compiler, not by user code)
+ '#[proc_macro]',
+ '#[proc_macro_derive',
+ '#[proc_macro_attribute',
+ # Doc-hidden items are intentionally not part of the public API surface
+ # but may still be used by downstream crates or macros via re-exports.
+ '#[doc(hidden)]',
+ # Explicitly suppressed warnings — the author knows it looks unused.
+ '#[allow(dead_code)]',
+ '#[allow(unused)]',
+ # Deprecated items are intentionally present but winding down.
+ '#[deprecated',
+ ),
".cs": (
# Reflection-driven type loading
"Type.GetType(",
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index d7d996d51..388e93232 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -126,7 +126,7 @@ _RUST = LanguageNodeMap(
function_kinds=frozenset({"function_item"}),
lambda_kinds=frozenset({"closure_expression"}),
branch_kinds=frozenset({"if_expression", "if_let_expression"}),
- loop_kinds=frozenset({"for_expression", "while_expression", "loop_expression"}),
+ loop_kinds=frozenset({"for_expression", "while_expression", "while_let_expression", "loop_expression"}),
try_kinds=frozenset(),
catch_kinds=frozenset(),
switch_kinds=frozenset({"match_expression"}),
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
index b17f3b348..63551ea24 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -196,6 +196,65 @@ def _condition_subtrees(node: Node) -> list[Node]:
return out
+def _collect_case_children(node: Node, lmap: LanguageNodeMap) -> list[Node]:
+ """Collect all case/arm nodes from a switch/match node.
+
+ In Rust, ``match_expression`` contains a ``match_block`` which in
+ turn holds the ``match_arm`` nodes. Other languages may place cases
+ directly under the switch node. This helper handles both layouts.
+ """
+ cases: list[Node] = []
+ for child in node.children:
+ if child.type in lmap.case_kinds:
+ cases.append(child)
+ else:
+ # Descend one level into intermediate wrapper nodes (e.g.
+ # ``match_block``) that are not themselves control flow.
+ for grandchild in child.children:
+ if grandchild.type in lmap.case_kinds:
+ cases.append(grandchild)
+ return cases
+
+
+def _is_flat_match(node: Node, lmap: LanguageNodeMap) -> bool:
+ """Return True if *node* is a match/switch with only simple arms.
+
+ A "flat" match has arms whose bodies are single expressions without
+ nested control flow (no ``if``, ``match``, ``for``, ``while``,
+ ``loop``, ``if_let``, ``while_let`` expressions, and no ``block``
+ with multiple statements). Flat matches contribute 1 CCN point for
+ the match keyword itself but do NOT count each arm individually.
+ """
+ complex_types = lmap.branch_kinds | lmap.loop_kinds | lmap.switch_kinds
+ cases = _collect_case_children(node, lmap)
+ if not cases:
+ return False
+ for arm in cases:
+ if _subtree_contains_complex(arm, complex_types):
+ return False
+ return True
+
+
+def _subtree_contains_complex(arm_node: Node, complex_types: frozenset[str]) -> bool:
+ """Return True if *arm_node*'s subtree contains complex control flow.
+
+ A ``block`` with more than one statement is also considered complex.
+ """
+ stack: list[Node] = list(arm_node.children)
+ while stack:
+ cur = stack.pop()
+ if cur.type in complex_types:
+ return True
+ # A block with multiple named children (statements) is complex.
+ if cur.type == "block":
+ named_children = [c for c in cur.children if c.is_named]
+ if len(named_children) > 1:
+ return True
+ for child in cur.children:
+ stack.append(child)
+ return False
+
+
def _walk_function_body(
body_node: Node,
lmap: LanguageNodeMap,
@@ -223,6 +282,10 @@ def _walk_function_body(
bumps = 0
conditions: list[ConditionComplexity] = []
+ # Track match_expression nodes identified as "flat" so their arms
+ # are not individually counted as branch points.
+ flat_match_ids: set[int] = set()
+
def _recurse(node: Node, depth: int) -> None:
nonlocal ccn, max_nesting, cognitive
@@ -235,7 +298,21 @@ def _walk_function_body(
nesting_increment = 0
ccn_increment = 0
- if (
+ # Check if this is a case/arm inside a flat match — skip it.
+ # In Rust the parent chain is match_arm → match_block → match_expression,
+ # so we check both parent and grandparent.
+ _parent = node.parent
+ is_flat_match_arm = False
+ if node.type in lmap.case_kinds and _parent is not None:
+ if _parent.id in flat_match_ids:
+ is_flat_match_arm = True
+ elif _parent.parent is not None and _parent.parent.id in flat_match_ids:
+ is_flat_match_arm = True
+
+ if is_flat_match_arm:
+ # Flat match arms: no CCN increment, no nesting increment.
+ pass
+ elif (
node.type in lmap.branch_kinds
or node.type in lmap.loop_kinds
or node.type in lmap.case_kinds
@@ -262,6 +339,12 @@ def _walk_function_body(
# TRY opens a nesting level but does not branch on its own.
nesting_increment = 1
elif node.type in lmap.switch_kinds:
+ # Detect flat match: all arms are simple single-expression arms.
+ if _is_flat_match(node, lmap):
+ flat_match_ids.add(node.id)
+ # Flat match: count 1 CCN point for the match itself,
+ # open a nesting level, but arms won't be counted.
+ ccn_increment = 1
# Switch opens nesting; each case contributes its own +1.
nesting_increment = 1
elif _is_boolean_operator(node, lmap):
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 7417168f8..b1adc8347 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -61,6 +61,8 @@ class CallResolver:
self,
parsed_files: dict[str, ParsedFile],
import_targets: dict[str, set[str]],
+ *,
+ repo_path: str | None = None,
) -> None:
# Per-file symbol index: {file_path: {symbol_name: symbol_id}}
self._file_symbols: dict[str, dict[str, str]] = {}
@@ -92,6 +94,10 @@ class CallResolver:
# Keep reference for cross-language checks in Tier 3
self._parsed_files = parsed_files
+ # Rust cross-crate resolution
+ self._repo_path = repo_path
+ self._rust_crate_src: dict[str, str] | None = None # lazy
+
self._build_indices(parsed_files)
self._follow_barrel_exports()
@@ -100,15 +106,66 @@ class CallResolver:
A barrel file imports a name and re-exports it without defining it
locally (e.g., ``__init__.py`` with ``from .calculator import Calculator``).
- When downstream code imports from the barrel, we follow one hop to
+ When downstream code imports from the barrel, we follow chains to
find the actual defining file.
"""
+ # First pass: identify direct barrel origins
for path, name_to_file in self._import_names.items():
file_syms = self._file_symbols.get(path, {})
for name, source_file in name_to_file.items():
if name not in file_syms:
self._barrel_origins[path][name] = source_file
+ # Also track Rust pub-use re-exports that use wildcard (*) bindings.
+ # When a file has `pub use foo::*`, all symbols from foo are
+ # transitively available through this file.
+ for path, parsed in self._parsed_files.items():
+ for imp in parsed.imports:
+ if not imp.is_reexport or not imp.resolved_file:
+ continue
+ if imp.resolved_file.startswith("external:"):
+ continue
+ resolved = imp.resolved_file
+ source_syms = self._file_symbols.get(resolved, {})
+ file_syms = self._file_symbols.get(path, {})
+ for sym_name in source_syms:
+ if sym_name not in file_syms:
+ self._barrel_origins[path][sym_name] = resolved
+
+ # Multi-hop: follow chains up to 5 hops
+ for _ in range(4):
+ changed = False
+ for path, origins in list(self._barrel_origins.items()):
+ for name, source in list(origins.items()):
+ deeper = self._barrel_origins.get(source, {}).get(name)
+ if deeper and deeper != source:
+ origins[name] = deeper
+ changed = True
+ if not changed:
+ break
+
+ def _get_rust_crate_src(self) -> dict[str, str]:
+ """Lazily build a mapping from normalised crate name to src/ dir."""
+ if self._rust_crate_src is not None:
+ return self._rust_crate_src
+ self._rust_crate_src = {}
+ if not self._repo_path:
+ return self._rust_crate_src
+ from .resolvers.rust_workspace import get_or_build_cargo_workspace_index
+
+ class _Ctx:
+ def __init__(self, rp, pf):
+ self.repo_path = rp
+ self.parsed_files = pf
+
+ ctx = _Ctx(self._repo_path, self._parsed_files)
+ ws = get_or_build_cargo_workspace_index(ctx)
+ if ws:
+ for crate in ws.crates:
+ normalized = crate.name.replace("-", "_")
+ self._rust_crate_src[normalized] = crate.src_dir
+ return self._rust_crate_src
+
def _build_indices(self, parsed_files: dict[str, ParsedFile]) -> None:
"""Build all lookup indices from parsed file data."""
for path, parsed in parsed_files.items():
@@ -270,6 +327,16 @@ class CallResolver:
if method_name in source_syms:
return ResolvedCall(caller_id, source_syms[method_name], 0.88, call.line)
+ # Strategy 1c: Rust crate-scoped reference (e.g. typst_html::module)
+ # The receiver is a crate name, the target is a symbol in that crate's lib.rs
+ crate_src = self._get_rust_crate_src().get(receiver_name)
+ if crate_src:
+ for root_file in ("lib.rs", "main.rs"):
+ crate_root = f"{crate_src}/{root_file}"
+ root_syms = self._file_symbols.get(crate_root, {})
+ if method_name in root_syms:
+ return ResolvedCall(caller_id, root_syms[method_name], 0.88, call.line)
+
# Strategy 2: receiver is a known class name → look for method on that class
# Check same-file classes first
file_methods = self._file_methods.get(file_path, {})
@@ -285,6 +352,15 @@ class CallResolver:
if key in imp_methods:
return ResolvedCall(caller_id, imp_methods[key], 0.88, call.line)
+ # Strategy 2b: trait method dispatch — receiver is a type that
+ # implements a trait; the method may be defined on the trait's
+ # impl block in another file.
+ for _path, methods in self._file_methods.items():
+ if _path == file_path:
+ continue
+ if key in methods:
+ return ResolvedCall(caller_id, methods[key], 0.75, call.line)
+
# Strategy 3: receiver is "self" or "this" — look in same class
if receiver_name in ("self", "this"):
# The caller is inside a class method — find its parent class
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
index e823f7c50..6b86a4348 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
@@ -25,6 +25,7 @@ from .c import CDynamicHints
from .django import DjangoDynamicHints
from .dotnet import DotNetDynamicHints
from .go import GoDynamicHints
+from .rust import RustDynamicHints
from .luau import LuauDynamicHints
from .node import NodeDynamicHints
from .php import PhpDynamicHints
@@ -66,6 +67,7 @@ class HintRegistry:
CDynamicHints(),
LuauDynamicHints(),
GoDynamicHints(),
+ RustDynamicHints(),
]
self._max_workers = max_workers or min(_DEFAULT_MAX_WORKERS, len(self._extractors))
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/rust.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/rust.py
new file mode 100644
index 000000000..1a320cf31
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/rust.py
@@ -0,0 +1,129 @@
+"""Dynamic-hint extractor for Rust attribute macros, FFI, and test patterns."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from .base import DynamicEdge, DynamicHintExtractor
+
+_SKIP_DIRS = {"target", "node_modules", ".git"}
+
+# Entry point attributes
+_ENTRY_ATTRS = (
+ "#[tokio::main]",
+ "#[actix_web::main]",
+ "#[async_std::main]",
+ "#[rocket::main]",
+ "#[tauri::command]",
+ "#[proc_macro]",
+ "#[proc_macro_derive",
+ "#[proc_macro_attribute]",
+)
+_ROUTE_RE = re.compile(
+ r"#\[(?:(?:rocket|actix_web|axum)::)?"
+ r"(?:get|post|put|delete|patch|head|options)\s*\("
+)
+
+# Test markers
+_TEST_MARKERS = ("#[test]", "#[tokio::test]", "#[cfg(test)]", "#[rstest]", "#[bench]")
+
+# FFI / dynamic dispatch markers
+_FFI_MARKERS = (
+ "#[no_mangle]",
+ 'extern "C"',
+ "#[wasm_bindgen]",
+ "#[napi]",
+ "#[pyo3::pymethods]",
+ "#[pyfunction]",
+)
+
+# Plugin registration
+_PLUGIN_MARKERS = ("inventory::submit!", "linkme::distributed_slice!")
+
+
+class RustDynamicHints(DynamicHintExtractor):
+ """Discover Rust entry points, route macros, tests, FFI, and plugin registration."""
+
+ name = "rust"
+
+ def extract(self, repo_root: Path) -> list[DynamicEdge]:
+ edges: list[DynamicEdge] = []
+ repo_resolved = repo_root.resolve()
+
+ for src in self._rglob(repo_root, "*.rs"):
+ try:
+ rel = src.resolve().relative_to(repo_resolved).as_posix()
+ except ValueError:
+ continue
+ if any(part in _SKIP_DIRS for part in Path(rel).parts):
+ continue
+ try:
+ text = src.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ continue
+
+ # Entry point attributes
+ for attr in _ENTRY_ATTRS:
+ if attr in text:
+ edges.append(
+ DynamicEdge(
+ source=rel,
+ target=rel,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:entry_point",
+ )
+ )
+ break
+
+ # Route macros
+ if _ROUTE_RE.search(text):
+ edges.append(
+ DynamicEdge(
+ source=rel,
+ target=rel,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:route_macro",
+ )
+ )
+
+ # Test markers
+ for marker in _TEST_MARKERS:
+ if marker in text:
+ edges.append(
+ DynamicEdge(
+ source=rel,
+ target=rel,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:test",
+ )
+ )
+ break
+
+ # FFI exports
+ for marker in _FFI_MARKERS:
+ if marker in text:
+ edges.append(
+ DynamicEdge(
+ source=rel,
+ target=rel,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:ffi",
+ )
+ )
+ break
+
+ # Plugin registration
+ for marker in _PLUGIN_MARKERS:
+ if marker in text:
+ edges.append(
+ DynamicEdge(
+ source=rel,
+ target=rel,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:plugin",
+ )
+ )
+ break
+
+ return edges
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 11418fa78..9f22354a8 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/rust.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/rust.py
@@ -9,7 +9,31 @@ from ..helpers import node_text
def extract_rust_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from Rust use declarations."""
+ """Extract bindings from Rust use declarations and mod items."""
+ # `mod foo;` (without body) declares a child module — treat as wildcard
+ # import because all public symbols become accessible via `foo::Name`.
+ if stmt_node.type == "mod_item":
+ return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
+
+ # `extern crate foo;` or `extern crate foo as bar;`
+ if stmt_node.type == "extern_crate_declaration":
+ alias_node = stmt_node.child_by_field_name("alias")
+ name_node = stmt_node.child_by_field_name("name")
+ if alias_node:
+ local = node_text(alias_node, src)
+ exported = node_text(name_node, src) if name_node else local
+ return [local], [NamedBinding(
+ local_name=local, exported_name=exported,
+ source_file=None, is_module_alias=True,
+ )]
+ elif name_node:
+ name = node_text(name_node, src)
+ return [name], [NamedBinding(
+ local_name=name, exported_name=name,
+ source_file=None, is_module_alias=True,
+ )]
+ 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:
diff --git a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py b/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
index a834b33fb..8fac84150 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
@@ -77,14 +77,25 @@ def extract_module_docstring(root: Node, src: str, lang: str) -> str | None:
break
return "\n".join(lines) if lines else None
elif lang == "rust":
- # //! inner doc comments or /// outer doc comments at top
+ # //! inner doc comments or /*! block inner doc comments at top
+ inner_lines: list[str] = []
for child in root.children:
- if child.type in ("line_comment", "block_comment"):
+ if child.type == "line_comment":
text = node_text(child, src).strip()
- if text.startswith("//!") or text.startswith("/*!"):
- return text.lstrip("/!* ").strip()
+ if text.startswith("//!"):
+ inner_lines.append(text[3:].strip())
+ continue
+ elif child.type == "block_comment":
+ text = node_text(child, src).strip()
+ if text.startswith("/*!"):
+ inner = text[3:]
+ if inner.endswith("*/"):
+ inner = inner[:-2]
+ return inner.strip()
else:
break
+ if inner_lines:
+ return "\n".join(inner_lines)
elif lang in ("cpp", "c"):
# Doxygen: first /** ... */ block comment before any declaration
for child in root.children:
@@ -243,7 +254,9 @@ def extract_symbol_docstring(def_node: Node, src: str, lang: str) -> str | None:
return "\n".join(lines) if lines else None
elif lang == "rust":
- # /// doc comments before the item
+ # /// doc comments or /** block doc comments before the item.
+ # Attributes (#[...]) may appear between the doc comment and the
+ # item, so we skip over attribute_item nodes when walking backward.
parent = def_node.parent
if parent is None:
return None
@@ -251,12 +264,21 @@ def extract_symbol_docstring(def_node: Node, src: str, lang: str) -> str | None:
idx = next((i for i, s in enumerate(siblings) if s.id == def_node.id), -1)
if idx <= 0:
return None
- lines: list[str] = []
+ # Walk backward, skipping attribute_item nodes
i = idx - 1
- while i >= 0 and siblings[i].type in ("line_comment", "block_comment"):
+ while i >= 0 and siblings[i].type == "attribute_item":
+ i -= 1
+ # Check for /** block doc comment first
+ if i >= 0 and siblings[i].type == "block_comment":
+ text = node_text(siblings[i], src).strip()
+ if text.startswith("/**"):
+ return clean_jsdoc(text)
+ # Collect consecutive /// line doc comments
+ lines: list[str] = []
+ while i >= 0 and siblings[i].type == "line_comment":
text = node_text(siblings[i], src).strip()
if text.startswith("///"):
- lines.insert(0, text.lstrip("/ ").strip())
+ lines.insert(0, text[3:].strip())
i -= 1
else:
break
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 58a2ecaf1..2a17f5a49 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py
@@ -17,7 +17,12 @@ def _extract_rust_heritage(
type_node = def_node.child_by_field_name("type")
if trait_node and type_node:
trait_name = node_text(trait_node, src).strip().rsplit("::", 1)[-1]
+ if "<" in trait_name:
+ trait_name = trait_name[:trait_name.index("<")]
type_name = node_text(type_node, src).strip()
+ # Strip generic parameters: "Sides<T>" → "Sides"
+ if "<" in type_name:
+ type_name = type_name[:type_name.index("<")]
if trait_name and type_name:
out.append(
HeritageRelation(
@@ -45,7 +50,32 @@ def _extract_rust_heritage(
)
)
- elif def_node.type in ("struct_item", "enum_item"):
+ # Extract trait bounds from where clauses on any item type.
+ # `impl<T> Foo for T where T: Debug + Clone` → Foo depends on Debug, Clone
+ if def_node.type in ("impl_item", "function_item", "struct_item", "enum_item", "trait_item"):
+ for child in def_node.children:
+ if child.type == "where_clause":
+ for predicate in child.children:
+ if predicate.type == "where_predicate":
+ bounds = predicate.child_by_field_name("bounds")
+ if bounds:
+ for bound_child in bounds.children:
+ if bound_child.type in ("+", ":"):
+ continue
+ bound_name = node_text(bound_child, src).strip().rsplit("::", 1)[-1]
+ if "<" in bound_name:
+ bound_name = bound_name[:bound_name.index("<")]
+ if bound_name and bound_name not in ("Sized", "Send", "Sync", "Unpin"):
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=bound_name,
+ kind="trait_bound",
+ line=line,
+ )
+ )
+
+ if def_node.type in ("struct_item", "enum_item"):
# Walk preceding siblings for #[derive(Trait1, Trait2)]
prev = def_node.prev_named_sibling
while prev is not None and prev.type == "attribute_item":
diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
index c0eac549e..92bcd863c 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
@@ -40,7 +40,16 @@ def go_visibility(name: str, _mods: list[str]) -> str:
def rust_visibility(_name: str, mods: list[str]) -> str:
- return "public" if any("pub" in m for m in mods) else "private"
+ combined = " ".join(mods).strip()
+ if not combined:
+ return "private"
+ if "pub(crate)" in combined:
+ return "internal"
+ if "pub(super)" in combined or "pub(in " in combined:
+ return "protected"
+ if "pub" in combined:
+ return "public"
+ return "private"
def java_visibility(_name: str, mods: list[str]) -> str:
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges.py b/packages/core/src/repowise/core/ingestion/framework_edges.py
index adb0cfb35..3ec2bfedc 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges.py
@@ -964,6 +964,11 @@ _RUST_AXUM_ROUTE_RE = re.compile(
_RUST_ACTIX_TO_RE = re.compile(r"web::\s*(?:get|post|put|delete|patch|head)\(\)\s*\.\s*to\s*\(\s*([\w:]+)\s*\)")
_RUST_ACTIX_SERVICE_RE = re.compile(r"\.\s*service\s*\(\s*([\w:]+)\s*\)")
_RUST_SCOPE_CONFIGURE_RE = re.compile(r"\.\s*configure\s*\(\s*([\w:]+)\s*\)")
+_RUST_NEST_RE = re.compile(r"\.\s*nest\s*\(\s*[\"'][^\"']*[\"']\s*,\s*([\w:]+)\s*\)")
+_RUST_LAYER_RE = re.compile(r"\.\s*layer\s*\(\s*(?:axum::middleware::from_fn\s*\(\s*)?([\w:]+)\s*\)")
+_RUST_FALLBACK_RE = re.compile(r"\.\s*fallback\s*\(\s*([\w:]+)\s*\)")
+_RUST_WITH_STATE_RE = re.compile(r"\.\s*with_state\s*\(\s*([\w:]+)\s*\)")
+_RUST_ROCKET_MOUNT_RE = re.compile(r"\.\s*mount\s*\(\s*[\"'][^\"']*[\"']\s*,\s*routes!\s*\[([^\]]+)\]")
def _has_rust_router_imports(parsed_files: dict[str, Any]) -> bool:
@@ -972,7 +977,7 @@ def _has_rust_router_imports(parsed_files: dict[str, Any]) -> bool:
continue
for imp in parsed.imports:
mp = imp.module_path
- if mp.startswith("axum") or mp.startswith("actix_web") or mp.startswith("actix-web"):
+ if mp.startswith(("axum", "actix_web", "actix-web", "rocket")):
return True
return False
@@ -1000,12 +1005,25 @@ def _add_rust_router_edges(
_RUST_ACTIX_TO_RE,
_RUST_ACTIX_SERVICE_RE,
_RUST_SCOPE_CONFIGURE_RE,
+ _RUST_NEST_RE,
+ _RUST_LAYER_RE,
+ _RUST_FALLBACK_RE,
+ _RUST_WITH_STATE_RE,
):
for m in regex.finditer(text):
for target in _resolve(m.group(1)):
if target != path and target in path_set and _add_edge_if_new(graph, path, target):
count += 1
+ # Rocket routes![] macro lists multiple handlers comma-separated
+ for m in _RUST_ROCKET_MOUNT_RE.finditer(text):
+ for handler in m.group(1).split(","):
+ handler = handler.strip()
+ if handler:
+ for target in _resolve(handler):
+ if target != path and target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
return count
diff --git a/packages/core/src/repowise/core/ingestion/graph/_edges.py b/packages/core/src/repowise/core/ingestion/graph/_edges.py
index f159acd98..287b797c4 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_edges.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_edges.py
@@ -91,6 +91,10 @@ class EdgesMixin:
hint_source=e.hint_source,
weight=e.weight,
)
+ # Propagate test marker: if hint_source ends with ":test", tag the
+ # source file node as is_test so downstream consumers can filter it.
+ if e.hint_source and e.hint_source.endswith(":test"):
+ self._graph.nodes[e.source]["is_test"] = True
def add_framework_edges(self, tech_stack: list[str] | None = None) -> int:
"""Add synthetic edges for framework-mediated relationships.
diff --git a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
index fafdbe80b..645e30150 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
@@ -44,6 +44,7 @@ _NODE_ATTR_KEYS = (
"end_line",
"visibility",
"signature",
+ "docstring",
"parent_symbol_id",
)
diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
index 164f86243..d33767ba1 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
@@ -101,7 +101,7 @@ class ResolveMixin:
"""Run three-tier call resolution and add CALLS edges to the graph."""
from ..call_resolver import CallResolver
- resolver = CallResolver(self._parsed_files, import_targets)
+ resolver = CallResolver(self._parsed_files, import_targets, repo_path=str(self._repo_path) if self._repo_path else None)
total_resolved = 0
files_with_calls = [
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index 653824144..abedbfc96 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -113,6 +113,7 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
has_error=bool(parsed.parse_errors),
is_test=parsed.file_info.is_test,
is_entry_point=parsed.file_info.is_entry_point,
+ docstring=parsed.docstring,
)
# --- Symbol nodes ---
@@ -133,6 +134,7 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
signature=sym.signature,
decorators=sym.decorators,
is_exported_symbol=sym.is_exported_symbol,
+ docstring=sym.docstring,
)
# DEFINES edge: file → symbol
@@ -164,6 +166,7 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
end_line=0,
visibility="private",
language=parsed.file_info.language,
+ docstring=parsed.docstring,
)
self._graph.add_edge(path, module_sym_id, edge_type="defines")
diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.py
index f50e083c8..22b8b6a9c 100644
--- a/packages/core/src/repowise/core/ingestion/language_configs.py
+++ b/packages/core/src/repowise/core/ingestion/language_configs.py
@@ -135,13 +135,17 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
"const_item": "constant",
"type_item": "type_alias",
"mod_item": "module",
- "macro_definition": "function", # macro_rules! my_macro { ... }
+ "macro_definition": "function",
+ "static_item": "constant",
+ "enum_variant": "variable",
+ "field_declaration": "property",
+ "union_item": "struct",
},
import_node_types=["use_declaration"],
export_node_types=[],
visibility_fn=rust_visibility,
parent_extraction="impl",
- parent_class_types=frozenset({"impl_item"}),
+ parent_class_types=frozenset({"impl_item", "mod_item"}),
entry_point_patterns=["main.rs", "lib.rs"],
),
"java": LanguageConfig(
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 e875f8d11..babefa175 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/rust.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/rust.py
@@ -8,10 +8,11 @@ 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"}),
+ heritage_node_types=frozenset({"impl_item", "trait_item", "struct_item", "enum_item", "function_item"}),
entry_point_patterns=("main.rs", "lib.rs"),
manifest_files=("Cargo.toml",),
lock_files=("Cargo.lock",),
+ generated_suffixes=(".generated.rs", ".pb.rs", ".flatbuffers_generated.rs"),
blocked_dirs=("target",),
builtin_calls=frozenset(
{
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 47bb95b7b..715369db1 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -187,6 +187,7 @@ class Import:
is_relative: bool
resolved_file: str | None # absolute path if successfully resolved
bindings: list[NamedBinding] = field(default_factory=list)
+ is_reexport: bool = False # True for `pub use` (Rust) or re-export patterns
@dataclass
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 2f209bc80..087305f5e 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -24,6 +24,7 @@ Capture-name conventions (shared across ALL .scm files):
from __future__ import annotations
+import re
from functools import lru_cache
from pathlib import Path
@@ -379,6 +380,22 @@ class ASTParser:
for sibling in def_node.parent.children:
if sibling.type == "decorator":
modifier_texts.append(_node_text(sibling, src))
+
+ # Rust: outer attributes (#[...]) are preceding siblings of the item
+ rust_attrs: list[str] = []
+ if file_info.language == "rust" and def_node.parent is not None:
+ siblings = def_node.parent.children
+ for j, sib in enumerate(siblings):
+ if sib.id == def_node.id:
+ k = j - 1
+ while k >= 0 and siblings[k].type == "attribute_item":
+ attr_text = _node_text(siblings[k], src).strip()
+ # Strip #[ and ] to get the inner attribute text
+ if attr_text.startswith("#[") and attr_text.endswith("]"):
+ rust_attrs.append(attr_text[2:-1])
+ k -= 1
+ break
+
visibility = config.visibility_fn(name, modifier_texts)
is_exported_symbol = False
# C/C++ visibility is dictated by AST context (access
@@ -428,7 +445,7 @@ class ASTParser:
start_line=start_line,
end_line=def_node.end_point[0] + 1,
docstring=docstring,
- decorators=[m for m in modifier_texts if m.startswith("@")],
+ decorators=[m for m in modifier_texts if m.startswith("@")] + rust_attrs,
visibility=visibility, # type: ignore[arg-type]
is_async=is_async,
language=file_info.language,
@@ -462,6 +479,16 @@ class ASTParser:
ancestor.child_by_field_name("type") # Rust impl_item
)
if name_node:
+ # For Rust impl blocks with generic types (e.g. impl<T> Foo<T>),
+ # extract only the base type name, not the full generic signature.
+ if name_node.type == "generic_type":
+ inner = name_node.child_by_field_name("type")
+ if inner and inner.type == "type_identifier":
+ name_node = inner
+ elif name_node.type == "scoped_type_identifier":
+ inner = name_node.child_by_field_name("name")
+ if inner and inner.type == "type_identifier":
+ name_node = inner
return _node_text(name_node, src)
ancestor = ancestor.parent
return None
@@ -503,9 +530,39 @@ class ASTParser:
if not module_text:
continue
+ # Rust #[path = "..."] attribute overrides module file location.
+ # In tree-sitter-rust, outer attributes are preceding siblings of
+ # the item, not children.
+ if file_info.language == "rust" and stmt_node.type == "mod_item":
+ parent = stmt_node.parent
+ if parent is not None:
+ siblings = parent.children
+ for j, sib in enumerate(siblings):
+ if sib.id == stmt_node.id:
+ # Walk backward through preceding attribute_item siblings
+ k = j - 1
+ while k >= 0 and siblings[k].type == "attribute_item":
+ attr_text = _node_text(siblings[k], src)
+ path_match = re.search(r'path\s*=\s*"([^"]+)"', attr_text)
+ if path_match:
+ module_text = path_match.group(1)
+ break
+ k -= 1
+ break
+
# Language-specific import name + binding extraction
imported_names, bindings = extract_import_bindings(stmt_node, src, file_info.language)
- is_relative = module_text.startswith(".") or module_text.startswith("./")
+ is_relative = (
+ module_text.startswith(".") or module_text.startswith("./")
+ or module_text.startswith(("self::", "super::", "crate::"))
+ )
+
+ is_reexport = False
+ if file_info.language == "rust" and stmt_node.type == "use_declaration":
+ for child in stmt_node.children:
+ if child.type == "visibility_modifier":
+ is_reexport = True
+ break
imports.append(
Import(
@@ -515,6 +572,7 @@ class ASTParser:
is_relative=is_relative,
resolved_file=None,
bindings=bindings,
+ is_reexport=is_reexport,
)
)
diff --git a/packages/core/src/repowise/core/ingestion/queries/rust.scm b/packages/core/src/repowise/core/ingestion/queries/rust.scm
index 329a770a4..9db03d7a1 100644
--- a/packages/core/src/repowise/core/ingestion/queries/rust.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/rust.scm
@@ -4,54 +4,149 @@
; =============================================================================
; ---------------------------------------------------------------------------
-; Symbols
+; Symbols — with visibility modifier (must come before without)
; ---------------------------------------------------------------------------
+; function_item WITH visibility
+(function_item
+ (visibility_modifier) @symbol.modifiers
+ name: (identifier) @symbol.name
+ parameters: (parameters) @symbol.params
+) @symbol.def
+
+; function_item WITHOUT visibility
(function_item
name: (identifier) @symbol.name
parameters: (parameters) @symbol.params
) @symbol.def
+; struct_item WITH visibility
(struct_item
+ (visibility_modifier) @symbol.modifiers
name: (type_identifier) @symbol.name
) @symbol.def
+; struct_item WITHOUT visibility
+(struct_item
+ name: (type_identifier) @symbol.name
+) @symbol.def
+
+; enum_item WITH visibility
(enum_item
+ (visibility_modifier) @symbol.modifiers
name: (type_identifier) @symbol.name
) @symbol.def
+; enum_item WITHOUT visibility
+(enum_item
+ name: (type_identifier) @symbol.name
+) @symbol.def
+
+; trait_item WITH visibility
+(trait_item
+ (visibility_modifier) @symbol.modifiers
+ name: (type_identifier) @symbol.name
+) @symbol.def
+
+; trait_item WITHOUT visibility
(trait_item
name: (type_identifier) @symbol.name
) @symbol.def
; impl block — the "type" field identifies what is being implemented
+; impl does NOT need visibility capture (inherits from type/trait)
(impl_item
type: (type_identifier) @symbol.name
) @symbol.def
+; impl with generic type target: impl<T> Foo<T> { }
+(impl_item
+ type: (generic_type
+ type: (type_identifier) @symbol.name
+ )
+) @symbol.def
+
+; impl with scoped type target: impl Trait for path::Foo
+(impl_item
+ type: (scoped_type_identifier
+ name: (type_identifier) @symbol.name
+ )
+) @symbol.def
+
+; impl with reference type target: impl Trait for &Foo
+(impl_item
+ type: (reference_type
+ type: (type_identifier) @symbol.name
+ )
+) @symbol.def
+
+; union_item WITH visibility
+(union_item
+ (visibility_modifier) @symbol.modifiers
+ name: (type_identifier) @symbol.name
+) @symbol.def
+
+; union_item WITHOUT visibility
+(union_item
+ name: (type_identifier) @symbol.name
+) @symbol.def
+
+; const_item WITH visibility
(const_item
+ (visibility_modifier) @symbol.modifiers
name: (identifier) @symbol.name
) @symbol.def
+; const_item WITHOUT visibility
+(const_item
+ name: (identifier) @symbol.name
+) @symbol.def
+
+; type_item WITH visibility
+(type_item
+ (visibility_modifier) @symbol.modifiers
+ name: (type_identifier) @symbol.name
+) @symbol.def
+
+; type_item WITHOUT visibility
(type_item
name: (type_identifier) @symbol.name
) @symbol.def
+; mod_item WITH visibility (symbol definition)
+(mod_item
+ (visibility_modifier) @symbol.modifiers
+ name: (identifier) @symbol.name
+) @symbol.def
+
+; mod_item WITHOUT visibility (symbol definition)
(mod_item
name: (identifier) @symbol.name
) @symbol.def
; macro_rules! my_macro { ... }
+; Note: macro_definition does not support visibility_modifier in tree-sitter-rust.
+; Visibility for macros is handled via #[macro_export] attribute instead.
(macro_definition
name: (identifier) @symbol.name
) @symbol.def
-; pub visibility modifier
-(function_item
+; static_item WITH visibility
+(static_item
(visibility_modifier) @symbol.modifiers
name: (identifier) @symbol.name
) @symbol.def
+; static_item WITHOUT visibility
+(static_item
+ name: (identifier) @symbol.name
+) @symbol.def
+
+; Enum variants (inherit visibility from parent enum)
+(enum_variant
+ name: (identifier) @symbol.name
+) @symbol.def
+
; ---------------------------------------------------------------------------
; Imports
; ---------------------------------------------------------------------------
@@ -60,6 +155,27 @@
argument: (_) @import.module
) @import.statement
+;; mod foo; declarations (without body block) act as imports in Rust
+(mod_item
+ name: (identifier) @import.module
+ !body
+) @import.statement
+
+;; extern crate foo; / extern crate foo as bar;
+(extern_crate_declaration
+ name: (identifier) @import.module
+) @import.statement
+
+; ---------------------------------------------------------------------------
+; Re-exports (pub use)
+; ---------------------------------------------------------------------------
+
+; pub use path::to::Item
+(use_declaration
+ (visibility_modifier) @reexport.visibility
+ argument: (_) @reexport.source
+) @reexport.statement
+
; ---------------------------------------------------------------------------
; Calls
; ---------------------------------------------------------------------------
@@ -82,6 +198,7 @@
; Scoped function call: module::function(args)
(call_expression
function: (scoped_identifier
+ path: (_) @call.receiver
name: (identifier) @call.target
)
arguments: (arguments) @call.arguments
@@ -96,7 +213,151 @@
arguments: (arguments) @call.arguments
) @call.site
+; Method call on self: self.method(args)
+(call_expression
+ function: (field_expression
+ value: (self) @call.receiver
+ field: (field_identifier) @call.target
+ )
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; Method call on field access: expr.field.method(args)
+(call_expression
+ function: (field_expression
+ value: (field_expression) @call.receiver
+ field: (field_identifier) @call.target
+ )
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; Turbofish function call: foo::<T>(args)
+(call_expression
+ function: (generic_function
+ function: (identifier) @call.target
+ )
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; Turbofish method call: obj.method::<T>(args)
+(call_expression
+ function: (generic_function
+ function: (field_expression
+ field: (field_identifier) @call.target
+ )
+ )
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; Turbofish scoped call: module::func::<T>(args)
+(call_expression
+ function: (generic_function
+ function: (scoped_identifier
+ path: (_) @call.receiver
+ name: (identifier) @call.target
+ )
+ )
+ arguments: (arguments) @call.arguments
+) @call.site
+
; Macro invocation: println!(...), vec![...]
(macro_invocation
macro: (identifier) @call.target
) @call.site
+
+; Scoped macro invocation: module::macro!(...)
+(macro_invocation
+ macro: (scoped_identifier
+ path: (_) @call.receiver
+ name: (identifier) @call.target
+ )
+) @call.site
+
+; Function pointer / callback argument: register(my_handler), vec.iter().map(process)
+; Captures top-level identifier arguments in call expressions as references
+; to prevent false-positive dead code flags on functions passed by name.
+(call_expression
+ arguments: (arguments
+ (identifier) @call.target
+ )
+) @call.site
+
+; Type argument in turbofish: func::<MyType>(...), Channel::<MyType>::new()
+; Creates a reference edge so MyType is not flagged as unused.
+(generic_function
+ type_arguments: (type_arguments
+ (type_identifier) @call.target
+ )
+) @call.site
+
+; Scoped identifier in struct field initializer: Foo { field: module::func }
+; Captures the final identifier as a reference to prevent false dead code flags.
+(field_initializer
+ value: (scoped_identifier
+ path: (_) @call.receiver
+ name: (identifier) @call.target
+ )
+) @call.site
+
+; Plain identifier in struct field initializer: Foo { field: my_func }
+(field_initializer
+ value: (identifier) @call.target
+) @call.site
+
+; ---------------------------------------------------------------------------
+; Type references — track types used in signatures to prevent false dead code
+; ---------------------------------------------------------------------------
+
+; Type reference in function parameter: fn foo(x: MyType)
+(parameter
+ type: (type_identifier) @call.target
+) @call.site
+
+; Type reference via &dyn: fn foo(x: &dyn MyTrait)
+(parameter
+ type: (reference_type
+ type: (dynamic_type
+ (type_identifier) @call.target
+ )
+ )
+) @call.site
+
+; Type reference via impl Trait: fn foo(x: impl MyTrait)
+(parameter
+ type: (abstract_type
+ (type_identifier) @call.target
+ )
+) @call.site
+
+; Trait bound in generic parameter: fn foo<T: MyTrait>()
+; Also matches where clauses: where T: MyTrait + OtherTrait
+(trait_bounds
+ (type_identifier) @call.target
+) @call.site
+
+; Return type reference: fn foo() -> MyType
+(function_item
+ return_type: (type_identifier) @call.target
+) @call.site
+
+; dyn Trait in type arguments: Box<dyn MyTrait>, Arc<dyn MyTrait>
+(type_arguments
+ (dynamic_type
+ (type_identifier) @call.target
+ )
+) @call.site
+
+; ---------------------------------------------------------------------------
+; Fields
+; ---------------------------------------------------------------------------
+
+; Struct fields (named) WITH visibility
+(field_declaration
+ (visibility_modifier) @symbol.modifiers
+ name: (field_identifier) @symbol.name
+) @symbol.def
+
+; Struct fields (named) WITHOUT visibility
+(field_declaration
+ name: (field_identifier) @symbol.name
+) @symbol.def
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/rust.py b/packages/core/src/repowise/core/ingestion/resolvers/rust.py
index 7be4b47a7..8ba1d9b46 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/rust.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/rust.py
@@ -2,49 +2,117 @@
from __future__ import annotations
+from functools import lru_cache
from pathlib import Path
from .context import ResolverContext
+def _get_frozen_path_set(ctx: ResolverContext) -> frozenset[str]:
+ """Return a cached frozenset of ctx.path_set, built once per context."""
+ cached: frozenset[str] | None = getattr(ctx, "_rust_frozen_path_set", None)
+ if cached is not None:
+ return cached
+ frozen = frozenset(ctx.path_set)
+ setattr(ctx, "_rust_frozen_path_set", frozen)
+ return frozen
+
+
+def _get_frozen_parsed_keys(ctx: ResolverContext) -> frozenset[str]:
+ """Return a cached frozenset of parsed_files keys, built once per context."""
+ cached: frozenset[str] | None = getattr(ctx, "_rust_frozen_parsed_keys", None)
+ if cached is not None:
+ return cached
+ parsed_files = ctx.parsed_files or {}
+ frozen = frozenset(parsed_files.keys())
+ setattr(ctx, "_rust_frozen_parsed_keys", frozen)
+ return frozen
+
+
def resolve_rust_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
"""Resolve a Rust ``use`` path to a repo-relative file."""
+ # Strip `as <alias>` suffix from aliased imports (e.g. "typst_syntax as syntax")
+ if " as " in module_path:
+ module_path = module_path.split(" as ")[0].strip()
+
+ # #[path = "..."] attribute — resolve relative to importer
+ if module_path.endswith(".rs"):
+ importer_dir = str(Path(importer_path).parent.as_posix())
+ candidate = f"{importer_dir}/{module_path}"
+ if candidate in ctx.path_set:
+ return candidate
+ return None
+
parts = module_path.split("::")
if not parts:
return None
+ # Strip brace-grouped imports: "crate::diag::{A, B}" → "crate::diag"
+ if parts and parts[-1].startswith("{"):
+ parts = parts[:-1]
+ if not parts:
+ return None
+
+ frozen_path_set = _get_frozen_path_set(ctx)
prefix = parts[0]
# --- crate:: — resolve from the crate root ---
if prefix == "crate":
crate_root = _find_rust_crate_root(importer_path, ctx)
- return _probe_rust_path(crate_root, parts[1:], ctx.path_set)
+ return _probe_rust_path(crate_root, parts[1:], frozen_path_set)
# --- 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:], ctx.path_set)
+ return _probe_rust_path(importer_dir, parts[1:], frozen_path_set)
- # --- super:: — resolve from the parent directory ---
+ # --- super:: — resolve from the parent directory (supports chained super::super::) ---
if prefix == "super":
- parent_dir = str(Path(importer_path).parent.parent.as_posix())
- return _probe_rust_path(parent_dir, parts[1:], ctx.path_set)
+ 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.
+ if len(parts) == 1:
+ importer_dir = str(Path(importer_path).parent.as_posix())
+ resolved = _probe_rust_path(importer_dir, parts, frozen_path_set)
+ if resolved is not None:
+ return resolved
# --- External crate (no prefix or unknown crate name) ---
# Check if it might be a local module at the crate root first
crate_root = _find_rust_crate_root(importer_path, ctx)
- resolved = _probe_rust_path(crate_root, parts, ctx.path_set)
+ resolved = _probe_rust_path(crate_root, parts, frozen_path_set)
if resolved is not None:
return resolved
- # Cargo workspace sibling crate: `use sibling_crate::...`
from .rust_workspace import get_or_build_cargo_workspace_index
ws_index = get_or_build_cargo_workspace_index(ctx)
+
+ # Try workspace-aware crate root for the importer.
+ # _find_rust_crate_root is a heuristic and may return the wrong root;
+ # if the workspace index can identify the importer's own crate, use that
+ # src_dir as a second probe base before falling through to sibling lookup.
+ if ws_index is not None:
+ importer_crate = ws_index.lookup_crate_for_file(importer_path)
+ if importer_crate and importer_crate.src_dir != crate_root:
+ resolved = _probe_rust_path(importer_crate.src_dir, parts, frozen_path_set)
+ if resolved is not None:
+ return resolved
+
+ # Cargo workspace sibling crate: `use sibling_crate::...`
if ws_index is not None:
sibling_src = ws_index.lookup(prefix)
if sibling_src is not None and sibling_src != crate_root:
- resolved = _probe_rust_path(sibling_src, parts[1:], ctx.path_set)
+ resolved = _probe_rust_path(sibling_src, parts[1:], frozen_path_set)
if resolved is None:
# Probe the crate root itself (lib.rs / main.rs) when the
# import has no further path segments.
@@ -59,46 +127,75 @@ def resolve_rust_import(module_path: str, importer_path: str, ctx: ResolverConte
return ctx.add_external_node(module_path)
-def _find_rust_crate_root(importer_path: str, ctx: ResolverContext) -> str:
- """Find the ``src/`` directory containing the importer (Rust crate root)."""
- parsed_files = ctx.parsed_files or {}
+@lru_cache(maxsize=4096)
+def _find_rust_crate_root_cached(
+ importer_path: str, parsed_file_keys: frozenset[str]
+) -> str:
+ """Cached crate-root lookup (pure function with hashable args)."""
parts = Path(importer_path).parts
for i in range(len(parts) - 1, -1, -1):
candidate_dir = Path(*parts[:i]) if i > 0 else Path(".")
for root_file in ("lib.rs", "main.rs"):
root_path = (candidate_dir / root_file).as_posix()
- if root_path in parsed_files:
+ if root_path in parsed_file_keys:
return candidate_dir.as_posix()
if parts[i] == "src" and i > 0:
return candidate_dir.as_posix()
return Path(importer_path).parent.as_posix()
-def _probe_rust_path(
+def _find_rust_crate_root(importer_path: str, ctx: ResolverContext) -> str:
+ """Find the ``src/`` directory containing the importer (Rust crate root)."""
+ return _find_rust_crate_root_cached(importer_path, _get_frozen_parsed_keys(ctx))
+
+
+@lru_cache(maxsize=8192)
+def _probe_rust_path_cached(
base_dir: str,
- path_parts: list[str],
- path_set: set[str],
+ path_parts: tuple[str, ...],
+ path_set_frozen: frozenset[str],
) -> str | None:
- """Probe for a Rust module path, trying ``.rs`` and ``mod.rs`` variants."""
+ """Cached probe (pure function with hashable args)."""
if not path_parts:
return None
-
base = Path(base_dir)
-
for depth in range(len(path_parts), 0, -1):
module_parts = path_parts[:depth]
module_dir = base
for p in module_parts[:-1]:
module_dir = module_dir / p
-
last = module_parts[-1]
- # Try <dir>/<last>.rs
candidate = (module_dir / f"{last}.rs").as_posix()
- if candidate in path_set:
+ if candidate in path_set_frozen:
return candidate
- # Try <dir>/<last>/mod.rs
candidate = (module_dir / last / "mod.rs").as_posix()
- if candidate in path_set:
+ if candidate in path_set_frozen:
return candidate
+ # Trailing-underscore fallback: #[path]-renamed modules use names like
+ # `export_` backed by `export.rs`.
+ stripped = tuple(p.rstrip("_") if p.endswith("_") else p for p in path_parts)
+ if stripped != path_parts:
+ for depth in range(len(stripped), 0, -1):
+ module_parts = stripped[:depth]
+ module_dir = base
+ for p in module_parts[:-1]:
+ module_dir = module_dir / p
+ last = module_parts[-1]
+ candidate = (module_dir / f"{last}.rs").as_posix()
+ if candidate in path_set_frozen:
+ return candidate
+ candidate = (module_dir / last / "mod.rs").as_posix()
+ if candidate in path_set_frozen:
+ return candidate
+
return None
+
+
+def _probe_rust_path(
+ base_dir: str,
+ path_parts: list[str],
+ path_set: frozenset[str],
+) -> str | None:
+ """Probe for a Rust module path, trying ``.rs`` and ``mod.rs`` variants."""
+ return _probe_rust_path_cached(base_dir, tuple(path_parts), path_set)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/rust_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/rust_workspace.py
index 47fb35e32..d0419a12d 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/rust_workspace.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/rust_workspace.py
@@ -25,12 +25,25 @@ import structlog
log = structlog.get_logger(__name__)
+@dataclass(frozen=True)
+class CargoDep:
+ """A dependency declared in Cargo.toml."""
+
+ name: str # import name (may differ from package name)
+ package: str # actual crate name on crates.io
+ is_path: bool # True if path dependency
+ path: str | None # resolved repo-relative path for path deps
+
+
@dataclass(frozen=True)
class CargoCrate:
"""A workspace member crate."""
name: str # package name as it appears in Cargo.toml (may contain "-")
src_dir: str # repo-relative POSIX path to the crate's src/ directory
+ dependencies: tuple[CargoDep, ...] = ()
+ is_proc_macro: bool = False # True if [lib] proc-macro = true
+ bin_paths: tuple[str, ...] = () # repo-relative POSIX paths to [[bin]] entry points
@dataclass(frozen=True)
@@ -38,6 +51,7 @@ class CargoWorkspaceIndex:
"""Cargo workspace member index. Map from crate-import-name → src dir."""
crates: tuple[CargoCrate, ...]
+ workspace_dependencies: tuple[CargoDep, ...] = ()
def lookup(self, import_prefix: str) -> str | None:
"""Find the src/ dir for a crate referenced as ``import_prefix::...``."""
@@ -48,6 +62,23 @@ class CargoWorkspaceIndex:
return crate.src_dir
return None
+ def lookup_crate_for_file(self, file_path: str) -> CargoCrate | None:
+ """Find the crate owning a given file path (longest prefix match)."""
+ best: CargoCrate | None = None
+ best_len = -1
+ for crate in self.crates:
+ # crate.src_dir is like "crates/foo/src"; check the parent dir
+ crate_prefix = crate.src_dir.rsplit("/src", 1)[0] + "/"
+ if file_path.startswith(crate_prefix) and len(crate_prefix) > best_len:
+ best = crate
+ best_len = len(crate_prefix)
+ return best
+
+ def is_file_in_proc_macro_crate(self, file_path: str) -> bool:
+ """Check if a file belongs to a proc-macro crate."""
+ crate = self.lookup_crate_for_file(file_path)
+ return crate is not None and crate.is_proc_macro
+
def get_or_build_cargo_workspace_index(ctx) -> CargoWorkspaceIndex | None:
"""Lazily build (and cache) the Cargo workspace index for the current repo."""
@@ -60,6 +91,70 @@ def get_or_build_cargo_workspace_index(ctx) -> CargoWorkspaceIndex | None:
return index
+def _parse_deps(
+ raw: dict,
+ crate_dir: Path,
+ repo: Path,
+ ws_deps: dict | None = None,
+) -> tuple[CargoDep, ...]:
+ """Parse a ``[dependencies]`` / ``[dev-dependencies]`` table into ``CargoDep`` tuples.
+
+ When *ws_deps* is provided (the raw ``[workspace.dependencies]`` table),
+ entries with ``workspace = true`` inherit their spec from it (Cargo 1.64+).
+ """
+ deps: list[CargoDep] = []
+ for name, spec in raw.items():
+ if isinstance(spec, str):
+ deps.append(CargoDep(name=name, package=name, is_path=False, path=None))
+ elif isinstance(spec, dict):
+ # Workspace inheritance: { workspace = true } pulls from
+ # [workspace.dependencies] in the root Cargo.toml.
+ if spec.get("workspace") and ws_deps is not None:
+ ws_spec = ws_deps.get(name, {})
+ if isinstance(ws_spec, str):
+ deps.append(CargoDep(name=name, package=name, is_path=False, path=None))
+ continue
+ elif isinstance(ws_spec, dict):
+ spec = {**ws_spec, **{k: v for k, v in spec.items() if k != "workspace"}}
+ else:
+ continue
+
+ package = spec.get("package", name)
+ path_str = spec.get("path")
+ resolved_path: str | None = None
+ if path_str:
+ abs_path = (crate_dir / path_str).resolve()
+ try:
+ resolved_path = abs_path.relative_to(repo).as_posix()
+ except ValueError:
+ resolved_path = None
+ deps.append(
+ CargoDep(
+ name=name,
+ package=package,
+ is_path=path_str is not None,
+ path=resolved_path,
+ )
+ )
+ return tuple(deps)
+
+
+def _parse_bin_targets(cargo_data: dict, member_rel: str, repo: Path) -> tuple[str, ...]:
+ """Extract ``[[bin]]`` entry-point paths from Cargo.toml data."""
+ bins = cargo_data.get("bin", [])
+ if not isinstance(bins, list):
+ return ()
+ paths: list[str] = []
+ for entry in bins:
+ if not isinstance(entry, dict):
+ continue
+ path_str = entry.get("path")
+ if path_str:
+ rel = f"{member_rel}/{path_str}" if member_rel else path_str
+ paths.append(Path(rel).as_posix())
+ return tuple(paths)
+
+
def _build_cargo_workspace_index(ctx) -> CargoWorkspaceIndex | None:
repo_path = getattr(ctx, "repo_path", None)
if not repo_path:
@@ -84,34 +179,88 @@ def _build_cargo_workspace_index(ctx) -> CargoWorkspaceIndex | None:
repo = Path(repo_path).resolve()
# Single-crate repo with a [package] at the root: still index it.
+ # Raw workspace deps table for { workspace = true } inheritance
+ ws_deps_raw = workspace.get("dependencies", {})
+
root_pkg = root_data.get("package") or {}
if root_pkg.get("name"):
- crates.append(CargoCrate(name=str(root_pkg["name"]), src_dir="src"))
+ root_deps = _parse_deps(
+ {**root_data.get("dependencies", {}),
+ **root_data.get("dev-dependencies", {}),
+ **root_data.get("build-dependencies", {})},
+ Path(repo_path),
+ repo,
+ ws_deps=ws_deps_raw,
+ )
+ root_bins = _parse_bin_targets(root_data, "", repo)
+ crates.append(CargoCrate(
+ name=str(root_pkg["name"]), src_dir="src",
+ dependencies=root_deps, bin_paths=root_bins,
+ ))
- for member in members:
- if not isinstance(member, str):
- continue
- member_path = (repo / member).resolve()
- try:
- member_rel = member_path.relative_to(repo).as_posix()
- except ValueError:
- continue
- member_toml = member_path / "Cargo.toml"
- if not member_toml.exists():
- continue
- try:
- with open(member_toml, "rb") as f:
- member_data = tomllib.load(f)
- except (OSError, tomllib.TOMLDecodeError):
- continue
- pkg = member_data.get("package") or {}
- name = pkg.get("name")
- if not name:
+ # Parse workspace-level shared dependencies
+ ws_deps = _parse_deps(ws_deps_raw, Path(repo_path), repo)
+
+ # Parse exclude patterns
+ exclude_patterns = workspace.get("exclude", [])
+ excluded_paths: set[Path] = set()
+ for pattern in exclude_patterns:
+ if isinstance(pattern, str):
+ excluded_paths.update(p.resolve() for p in repo.glob(pattern))
+
+ for member_pattern in members:
+ if not isinstance(member_pattern, str):
continue
- src_dir = f"{member_rel}/src" if member_rel else "src"
- crates.append(CargoCrate(name=str(name), src_dir=src_dir))
+ matched_paths = sorted(repo.glob(member_pattern))
+ if not matched_paths:
+ # Fallback to literal path for backward compat
+ matched_paths = [(repo / member_pattern).resolve()]
+ for member_path in matched_paths:
+ member_path = member_path.resolve()
+ if not member_path.is_dir():
+ continue
+ if member_path in excluded_paths:
+ continue
+ try:
+ member_rel = member_path.relative_to(repo).as_posix()
+ except ValueError:
+ continue
+ member_toml = member_path / "Cargo.toml"
+ if not member_toml.exists():
+ continue
+ try:
+ with open(member_toml, "rb") as f:
+ member_data = tomllib.load(f)
+ except (OSError, tomllib.TOMLDecodeError):
+ continue
+ pkg = member_data.get("package") or {}
+ name = pkg.get("name")
+ if not name:
+ continue
+ # Check if this is a proc-macro crate
+ lib_section = member_data.get("lib", {})
+ is_proc_macro = bool(
+ lib_section.get("proc-macro", False) or lib_section.get("proc_macro", False)
+ )
+ src_dir = f"{member_rel}/src" if member_rel else "src"
+ member_deps = _parse_deps(
+ {**member_data.get("dependencies", {}),
+ **member_data.get("dev-dependencies", {}),
+ **member_data.get("build-dependencies", {})},
+ member_path,
+ repo,
+ ws_deps=ws_deps_raw,
+ )
+ bin_paths = _parse_bin_targets(member_data, member_rel, repo)
+ crates.append(CargoCrate(
+ name=str(name),
+ src_dir=src_dir,
+ dependencies=member_deps,
+ is_proc_macro=is_proc_macro,
+ bin_paths=bin_paths,
+ ))
if not crates:
return None
log.debug("Built Cargo workspace index", crate_count=len(crates))
- return CargoWorkspaceIndex(crates=tuple(crates))
+ return CargoWorkspaceIndex(crates=tuple(crates), workspace_dependencies=ws_deps)
diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
index d313b4bf1..167719350 100644
--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
@@ -122,6 +122,81 @@ def _resolve_csharp_type_refs(
return emitted
+# ---------------------------------------------------------------------------
+# Strategy: Rust
+# ---------------------------------------------------------------------------
+
+_RUST_BUILTIN_TYPES = frozenset({
+ "bool", "char", "str", "u8", "u16", "u32", "u64", "u128", "usize",
+ "i8", "i16", "i32", "i64", "i128", "isize", "f32", "f64",
+ "String", "Vec", "Option", "Result", "Box", "Arc", "Rc",
+ "HashMap", "HashSet", "BTreeMap", "BTreeSet", "Cow",
+ "Pin", "Future", "Send", "Sync", "Sized", "Copy", "Clone",
+ "Debug", "Display", "Default", "Iterator", "IntoIterator",
+ "From", "Into", "TryFrom", "TryInto", "AsRef", "AsMut",
+ "Fn", "FnMut", "FnOnce", "Drop", "Deref", "DerefMut",
+ "Self", "self",
+})
+
+
+def _resolve_rust_type_refs(
+ parsed: ParsedFile,
+ ctx: "ResolverContext",
+ graph: "nx.DiGraph",
+) -> int:
+ """Resolve Rust ``@param.type`` captures via stem map + import graph."""
+ if not parsed.type_refs:
+ return 0
+
+ from_path = parsed.file_info.path
+ emitted = 0
+
+ import_targets: set[str] = set()
+ for imp in parsed.imports:
+ if imp.resolved_file and not imp.resolved_file.startswith("external:"):
+ import_targets.add(imp.resolved_file)
+
+ for ref in parsed.type_refs:
+ type_name = ref.type_name
+ if not type_name or type_name in _RUST_BUILTIN_TYPES:
+ continue
+ bare = type_name.rsplit("::", 1)[-1]
+ if bare in _RUST_BUILTIN_TYPES:
+ continue
+
+ target = _find_rust_type_file(bare, from_path, import_targets, ctx, graph)
+ if target is None:
+ continue
+ _add_or_merge_type_use_edge(graph, src=from_path, dst=target,
+ type_name=bare, origin=ref.origin)
+ emitted += 1
+ return emitted
+
+
+def _find_rust_type_file(
+ type_name: str,
+ from_path: str,
+ import_targets: set[str],
+ ctx: "ResolverContext",
+ graph: "nx.DiGraph",
+) -> str | None:
+ """Find the file defining *type_name*, preferring imported files."""
+ for imp_file in import_targets:
+ if not graph.has_node(imp_file):
+ continue
+ for succ in graph.successors(imp_file):
+ nd = graph.nodes.get(succ, {})
+ if nd.get("node_type") == "symbol" and nd.get("name") == type_name:
+ return imp_file
+
+ candidates = ctx.stem_map.get(type_name.lower(), [])
+ if len(candidates) == 1 and candidates[0] != from_path:
+ if graph.has_node(candidates[0]):
+ return candidates[0]
+
+ return None
+
+
# ---------------------------------------------------------------------------
# Strategy registry
# ---------------------------------------------------------------------------
@@ -133,6 +208,7 @@ Strategy = Callable[[ParsedFile, "ResolverContext", "nx.DiGraph"], int]
# index, never share resolver state across languages.
_STRATEGIES: dict[str, Strategy] = {
"csharp": _resolve_csharp_type_refs,
+ "rust": _resolve_rust_type_refs,
}
diff --git a/tests/fixtures/lang_samples/rust/flat_match.rs b/tests/fixtures/lang_samples/rust/flat_match.rs
new file mode 100644
index 000000000..2bed8c103
--- /dev/null
+++ b/tests/fixtures/lang_samples/rust/flat_match.rs
@@ -0,0 +1,38 @@
+// Flat match: all arms are simple single-expression arms.
+// Should count as 1 CCN point for the match keyword, NOT per-arm.
+fn flat_match(x: i32) -> &'static str {
+ match x {
+ 1 => "one",
+ 2 => "two",
+ 3 => "three",
+ _ => "other",
+ }
+}
+
+// Complex match: at least one arm has nested control flow.
+// Each arm should count as a branch point (existing behavior).
+fn complex_match(x: i32) -> i32 {
+ match x {
+ 1 => {
+ if x > 0 {
+ 42
+ } else {
+ 0
+ }
+ }
+ 2 => 100,
+ _ => 0,
+ }
+}
+
+// Mixed: one arm has a block with multiple statements.
+fn multi_stmt_match(x: i32) -> i32 {
+ match x {
+ 1 => {
+ let a = 10;
+ a + x
+ }
+ 2 => 20,
+ _ => 0,
+ }
+}
diff --git a/tests/unit/analysis/test_rust_dead_code_regression.py b/tests/unit/analysis/test_rust_dead_code_regression.py
new file mode 100644
index 000000000..edbc48320
--- /dev/null
+++ b/tests/unit/analysis/test_rust_dead_code_regression.py
@@ -0,0 +1,419 @@
+"""Regression tests for Rust dead code false positives.
+
+Each test validates that a specific pattern from the Typst audit
+does NOT produce a false positive in dead code analysis.
+"""
+from __future__ import annotations
+
+import networkx as nx
+import pytest
+from pathlib import Path
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+
+
+class TestRustNeverFlagPatterns:
+ """Validate never-flag patterns cover Rust conventions."""
+
+ def test_build_rs_never_flagged(self):
+ from repowise.core.analysis.dead_code.constants import _NEVER_FLAG_PATTERNS
+ import fnmatch
+ path = "crates/typst-pdf/build.rs"
+ assert any(fnmatch.fnmatch(path, p) for p in _NEVER_FLAG_PATTERNS)
+
+ def test_examples_never_flagged(self):
+ from repowise.core.analysis.dead_code.constants import _NEVER_FLAG_PATTERNS
+ import fnmatch
+ path = "examples/hello.rs"
+ assert any(fnmatch.fnmatch(path, p) for p in _NEVER_FLAG_PATTERNS)
+
+ def test_benches_never_flagged(self):
+ from repowise.core.analysis.dead_code.constants import _NEVER_FLAG_PATTERNS
+ import fnmatch
+ path = "crates/typst/benches/bench.rs"
+ assert any(fnmatch.fnmatch(path, p) for p in _NEVER_FLAG_PATTERNS)
+
+ def test_tests_dir_never_flagged(self):
+ from repowise.core.analysis.dead_code.constants import _NEVER_FLAG_PATTERNS
+ import fnmatch
+ path = "tests/src/run.rs"
+ assert any(fnmatch.fnmatch(path, p) for p in _NEVER_FLAG_PATTERNS)
+
+ def test_bin_target_never_flagged(self):
+ from repowise.core.analysis.dead_code.constants import _NEVER_FLAG_PATTERNS
+ import fnmatch
+ path = "crates/typst-cli/src/bin/typst.rs"
+ assert any(fnmatch.fnmatch(path, p) for p in _NEVER_FLAG_PATTERNS)
+
+ def test_fuzz_target_never_flagged(self):
+ from repowise.core.analysis.dead_code.constants import _NEVER_FLAG_PATTERNS
+ import fnmatch
+ path = "tests/fuzz/fuzz_targets/compile.rs"
+ assert any(fnmatch.fnmatch(path, p) for p in _NEVER_FLAG_PATTERNS)
+
+
+class TestRustNeverPackageDirs:
+ """Validate test/bench dirs are excluded from zombie-package detection."""
+
+ def test_tests_dir_excluded(self):
+ from repowise.core.analysis.dead_code.constants import _NEVER_PACKAGE_DIRS
+ assert "tests" in _NEVER_PACKAGE_DIRS
+
+ def test_benches_dir_excluded(self):
+ from repowise.core.analysis.dead_code.constants import _NEVER_PACKAGE_DIRS
+ assert "benches" in _NEVER_PACKAGE_DIRS
+
+ def test_fuzz_dir_excluded(self):
+ from repowise.core.analysis.dead_code.constants import _NEVER_PACKAGE_DIRS
+ assert "fuzz" in _NEVER_PACKAGE_DIRS
+
+
+class TestRustDynamicMarkers:
+ """Validate Rust dynamic markers detect proc-macro and doc(hidden) patterns."""
+
+ def test_proc_macro_detected(self):
+ from repowise.core.analysis.dead_code.dynamic_markers import _DYNAMIC_IMPORT_MARKERS
+ rs_markers = _DYNAMIC_IMPORT_MARKERS.get(".rs", ())
+ assert any("proc_macro" in m for m in rs_markers)
+
+ def test_doc_hidden_detected(self):
+ from repowise.core.analysis.dead_code.dynamic_markers import _DYNAMIC_IMPORT_MARKERS
+ rs_markers = _DYNAMIC_IMPORT_MARKERS.get(".rs", ())
+ assert '#[doc(hidden)]' in rs_markers
+
+
+class TestProcMacroCrateDetection:
+ """Validate proc-macro crate detection in workspace indexing."""
+
+ def test_proc_macro_crate_detected(self, tmp_path):
+ """A crate with [lib] proc-macro = true should be marked."""
+ from repowise.core.ingestion.resolvers.rust_workspace import (
+ CargoCrate,
+ CargoWorkspaceIndex,
+ )
+
+ crate = CargoCrate(
+ name="my-macros",
+ src_dir="crates/my-macros/src",
+ is_proc_macro=True,
+ )
+ index = CargoWorkspaceIndex(crates=(crate,))
+ assert index.is_file_in_proc_macro_crate("crates/my-macros/src/lib.rs")
+ assert not index.is_file_in_proc_macro_crate("crates/other/src/lib.rs")
+
+ def test_non_proc_macro_crate_not_detected(self, tmp_path):
+ """A regular crate should not be flagged as proc-macro."""
+ from repowise.core.ingestion.resolvers.rust_workspace import (
+ CargoCrate,
+ CargoWorkspaceIndex,
+ )
+
+ crate = CargoCrate(
+ name="regular-lib",
+ src_dir="crates/regular-lib/src",
+ is_proc_macro=False,
+ )
+ index = CargoWorkspaceIndex(crates=(crate,))
+ assert not index.is_file_in_proc_macro_crate("crates/regular-lib/src/lib.rs")
+
+ def test_proc_macro_parsed_from_toml(self, tmp_path):
+ """Workspace indexing should parse [lib] proc-macro = true from Cargo.toml."""
+ (tmp_path / "Cargo.toml").write_text(
+ '[workspace]\nmembers = ["crates/my-macros"]\n'
+ )
+ crate_dir = tmp_path / "crates" / "my-macros"
+ crate_dir.mkdir(parents=True)
+ (crate_dir / "Cargo.toml").write_text(
+ '[package]\nname = "my-macros"\nversion = "0.1.0"\n\n'
+ '[lib]\nproc-macro = true\n'
+ )
+ (crate_dir / "src").mkdir()
+ (crate_dir / "src" / "lib.rs").write_text("// proc-macro crate\n")
+
+ import networkx as nx
+ from repowise.core.ingestion.resolvers.context import ResolverContext
+ from repowise.core.ingestion.resolvers.rust_workspace import (
+ get_or_build_cargo_workspace_index,
+ )
+
+ path_set = {"crates/my-macros/src/lib.rs"}
+ stem_map = {"lib": ["crates/my-macros/src/lib.rs"]}
+ ctx = ResolverContext(
+ path_set=path_set,
+ stem_map=stem_map,
+ graph=nx.DiGraph(),
+ repo_path=tmp_path,
+ )
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ macro_crate = next((c for c in idx.crates if c.name == "my-macros"), None)
+ assert macro_crate is not None
+ assert macro_crate.is_proc_macro is True
+ assert idx.is_file_in_proc_macro_crate("crates/my-macros/src/lib.rs")
+
+
+# ---------------------------------------------------------------------------
+# Graph builder helper (mirrors tests/unit/test_dead_code.py)
+# ---------------------------------------------------------------------------
+
+def _build_graph(
+ nodes: dict[str, dict],
+ edges: list | None = None,
+) -> nx.DiGraph:
+ g = nx.DiGraph()
+ for name, attrs in nodes.items():
+ sym_list = attrs.pop("symbols", [])
+ g.add_node(name, **attrs)
+ for sym in sym_list:
+ sym_id = f"{name}::{sym['name']}"
+ g.add_node(sym_id, node_type="symbol", file_path=name, **sym)
+ g.add_edge(name, sym_id, edge_type="defines")
+ for edge in edges or []:
+ if len(edge) == 3:
+ g.add_edge(edge[0], edge[1], **(edge[2]))
+ else:
+ g.add_edge(edge[0], edge[1])
+ return g
+
+
+# ---------------------------------------------------------------------------
+# Fix 1: Rust symbols skipped in _detect_unused_internals
+# ---------------------------------------------------------------------------
+
+class TestRustUnusedInternalsSkipped:
+ """Private Rust symbols must not be flagged by unused_internals.
+
+ The graph builder does not emit intra-file call edges for Rust,
+ so every private function would appear 'uncalled'. Fix 1 skips
+ all Rust symbols in _detect_unused_internals.
+ """
+
+ def test_rust_private_function_not_flagged(self):
+ """A private Rust function with no callers should NOT appear."""
+ g = _build_graph(
+ nodes={
+ "crates/my-crate/src/helpers.rs": {
+ "language": "rust",
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "do_stuff",
+ "kind": "function",
+ "language": "rust",
+ "visibility": "private",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 10,
+ },
+ ],
+ },
+ },
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ internals = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL]
+ assert internals == [], f"Rust private function should be skipped, got: {internals}"
+
+ def test_python_private_function_still_flagged(self):
+ """Ensure the skip is Rust-only; Python private symbols still flagged."""
+ g = _build_graph(
+ nodes={
+ "pkg/utils.py": {
+ "language": "python",
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "_helper",
+ "kind": "function",
+ "language": "python",
+ "visibility": "private",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 12,
+ },
+ ],
+ },
+ },
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ internals = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL]
+ assert any(f.symbol_name == "_helper" for f in internals)
+
+
+# ---------------------------------------------------------------------------
+# Fix 7: proc_macro-decorated functions exempt from unused_exports
+# ---------------------------------------------------------------------------
+
+class TestProcMacroExemptFromUnusedExports:
+ """Proc-macro entry points are invoked by the compiler and must not
+ be flagged as unused exports.
+ """
+
+ def test_proc_macro_function_not_flagged(self):
+ """A public function with #[proc_macro] should NOT be flagged."""
+ g = _build_graph(
+ nodes={
+ "crates/my-macros/src/lib.rs": {
+ "language": "rust",
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "my_macro",
+ "kind": "function",
+ "language": "rust",
+ "visibility": "public",
+ "decorators": ["proc_macro"],
+ "start_line": 1,
+ "end_line": 20,
+ },
+ ],
+ },
+ },
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ exports = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
+ assert all(f.symbol_name != "my_macro" for f in exports), (
+ "proc_macro function should be exempt from unused_exports"
+ )
+
+ def test_proc_macro_derive_not_flagged(self):
+ """A function with #[proc_macro_derive(MyTrait)] should NOT be flagged."""
+ g = _build_graph(
+ nodes={
+ "crates/my-macros/src/lib.rs": {
+ "language": "rust",
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "derive_my_trait",
+ "kind": "function",
+ "language": "rust",
+ "visibility": "public",
+ "decorators": ["proc_macro_derive(MyTrait)"],
+ "start_line": 1,
+ "end_line": 30,
+ },
+ ],
+ },
+ },
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ exports = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
+ assert all(f.symbol_name != "derive_my_trait" for f in exports)
+
+ def test_proc_macro_attribute_not_flagged(self):
+ """A function with #[proc_macro_attribute] should NOT be flagged."""
+ g = _build_graph(
+ nodes={
+ "crates/my-macros/src/lib.rs": {
+ "language": "rust",
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "my_attr",
+ "kind": "function",
+ "language": "rust",
+ "visibility": "public",
+ "decorators": ["proc_macro_attribute"],
+ "start_line": 1,
+ "end_line": 15,
+ },
+ ],
+ },
+ },
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ exports = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
+ assert all(f.symbol_name != "my_attr" for f in exports)
+
+ def test_regular_rust_public_function_still_flagged(self):
+ """A public Rust function without proc_macro decorators IS still flagged."""
+ g = _build_graph(
+ nodes={
+ "crates/my-lib/src/lib.rs": {
+ "language": "rust",
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "unused_pub_fn",
+ "kind": "function",
+ "language": "rust",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 10,
+ },
+ ],
+ },
+ },
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ exports = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
+ assert any(f.symbol_name == "unused_pub_fn" for f in exports), (
+ "Regular public Rust function should still be flagged"
+ )
diff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.py
index 1af6bff3f..f31c328a3 100644
--- a/tests/unit/health/test_complexity_walker.py
+++ b/tests/unit/health/test_complexity_walker.py
@@ -73,6 +73,35 @@ def test_javascript_nested_depth():
assert deep.max_nesting >= 4
+def test_rust_flat_match_complexity():
+ """A flat match (all arms are simple expressions) should count as 1 CCN
+ point for the match itself; individual arms should NOT add CCN."""
+ results = _walk("rust/flat_match.rs", "rust")
+ flat = _find(results, "flat_match")
+ if flat is None:
+ pytest.skip("rust function not detected")
+ # flat_match: base CCN 1 + match 1 = 2
+ assert flat.ccn == 2, f"flat match CCN expected 2, got {flat.ccn}"
+
+ cplx = _find(results, "complex_match")
+ if cplx is None:
+ pytest.skip("rust complex_match not detected")
+ # complex_match: match has an arm with nested `if`, so arms count
+ # individually. CCN = 1 (base) + 3 arms + 1 (if in arm) = 5
+ assert cplx.ccn > flat.ccn, (
+ f"complex match CCN ({cplx.ccn}) should exceed flat match CCN ({flat.ccn})"
+ )
+
+ multi = _find(results, "multi_stmt_match")
+ if multi is None:
+ pytest.skip("rust multi_stmt_match not detected")
+ # multi_stmt_match: arm with multi-statement block → complex match
+ # CCN = 1 (base) + 3 arms = 4
+ assert multi.ccn > flat.ccn, (
+ f"multi-stmt match CCN ({multi.ccn}) should exceed flat match CCN ({flat.ccn})"
+ )
+
+
def test_unsupported_language_returns_empty():
results = walk_file_complexity("/tmp/x.unknown", "klingon", b"")
assert results == []
diff --git a/tests/unit/ingestion/test_graph.py b/tests/unit/ingestion/test_graph.py
index b5025048c..34346d0e6 100644
--- a/tests/unit/ingestion/test_graph.py
+++ b/tests/unit/ingestion/test_graph.py
@@ -7,7 +7,7 @@ from datetime import datetime
from pathlib import Path
from repowise.core.ingestion.graph import GraphBuilder
-from repowise.core.ingestion.models import FileInfo, Import, ParsedFile
+from repowise.core.ingestion.models import FileInfo, Import, ParsedFile, Symbol
# ---------------------------------------------------------------------------
# Helpers
@@ -120,6 +120,66 @@ class TestAddFile:
assert g.number_of_nodes() == 4
+# ---------------------------------------------------------------------------
+# Docstring propagation
+# ---------------------------------------------------------------------------
+
+
+def _sym(
+ path: str,
+ name: str,
+ docstring: str | None = None,
+ kind: str = "function",
+) -> Symbol:
+ return Symbol(
+ id=f"{path}::{name}",
+ name=name,
+ qualified_name=name,
+ kind=kind,
+ signature=f"def {name}()",
+ start_line=1,
+ end_line=5,
+ docstring=docstring,
+ language="python",
+ )
+
+
+class TestDocstringPropagation:
+ def test_symbol_docstring_in_graph_node(self) -> None:
+ b = GraphBuilder()
+ sym = _sym("src/calc.py", "add", docstring="Adds two numbers.")
+ parsed = _parsed("src/calc.py")
+ parsed.symbols = [sym]
+ b.add_file(parsed)
+ g = b.graph()
+ assert g.nodes[sym.id]["docstring"] == "Adds two numbers."
+
+ def test_file_docstring_in_graph_node(self) -> None:
+ b = GraphBuilder()
+ parsed = _parsed("src/calc.py")
+ parsed.docstring = "Calculator utilities."
+ b.add_file(parsed)
+ g = b.graph()
+ assert g.nodes["src/calc.py"]["docstring"] == "Calculator utilities."
+
+ def test_module_node_carries_file_docstring(self) -> None:
+ b = GraphBuilder()
+ parsed = _parsed("src/calc.py")
+ parsed.docstring = "Module doc."
+ b.add_file(parsed)
+ g = b.graph()
+ assert g.nodes["src/calc.py::__module__"]["docstring"] == "Module doc."
+
+ def test_none_docstring_preserved(self) -> None:
+ b = GraphBuilder()
+ sym = _sym("src/calc.py", "add", docstring=None)
+ parsed = _parsed("src/calc.py")
+ parsed.symbols = [sym]
+ b.add_file(parsed)
+ g = b.graph()
+ assert g.nodes[sym.id]["docstring"] is None
+
+
# ---------------------------------------------------------------------------
# Python import resolution
# ---------------------------------------------------------------------------
diff --git a/tests/unit/ingestion/test_parser.py b/tests/unit/ingestion/test_parser.py
index 50bf5efee..4182d6145 100644
--- a/tests/unit/ingestion/test_parser.py
+++ b/tests/unit/ingestion/test_parser.py
@@ -654,6 +654,24 @@ class TestRustParser:
result = parser.parse_file(fi, RUST_SOURCE)
assert len(result.imports) >= 1
+ def test_path_attribute_preceding_sibling(self, parser: ASTParser) -> None:
+ """#[path = "..."] is a preceding sibling, not a child of mod_item."""
+ src = b'#[path = "csv.rs"]\nmod csv_;\n'
+ fi = _make_file_info("rust_pkg/src/lib.rs", "rust")
+ result = parser.parse_file(fi, src)
+ mod_imports = [i for i in result.imports if i.raw_statement.startswith("mod")]
+ assert len(mod_imports) == 1
+ assert mod_imports[0].module_path == "csv.rs"
+
+ def test_path_attribute_not_applied_to_wrong_mod(self, parser: ASTParser) -> None:
+ """An attribute on one mod must not leak to an unrelated mod."""
+ src = b'#[path = "csv.rs"]\nmod csv_;\nmod normal;\n'
+ fi = _make_file_info("rust_pkg/src/lib.rs", "rust")
+ result = parser.parse_file(fi, src)
+ normal = [i for i in result.imports if "normal" in i.raw_statement]
+ assert len(normal) == 1
+ assert normal[0].module_path == "normal"
+
# ---------------------------------------------------------------------------
# Java
diff --git a/tests/unit/ingestion/test_rust_dynamic_hints.py b/tests/unit/ingestion/test_rust_dynamic_hints.py
new file mode 100644
index 000000000..6873a5e82
--- /dev/null
+++ b/tests/unit/ingestion/test_rust_dynamic_hints.py
@@ -0,0 +1,89 @@
+"""Tests for the Rust dynamic hints extractor."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion.dynamic_hints.rust import RustDynamicHints
+
+
+class TestRustDynamicHints:
+ def test_detects_tokio_main(self, tmp_path: Path) -> None:
+ (tmp_path / "main.rs").write_text('#[tokio::main]\nasync fn main() {}')
+ edges = RustDynamicHints().extract(tmp_path)
+ assert any(e.hint_source == "rust:entry_point" for e in edges)
+
+ def test_detects_test_marker(self, tmp_path: Path) -> None:
+ (tmp_path / "lib.rs").write_text(
+ '#[cfg(test)]\nmod tests {\n #[test]\n fn it_works() {}\n}'
+ )
+ edges = RustDynamicHints().extract(tmp_path)
+ assert any(e.hint_source == "rust:test" for e in edges)
+
+ def test_detects_ffi(self, tmp_path: Path) -> None:
+ (tmp_path / "ffi.rs").write_text(
+ '#[no_mangle]\npub extern "C" fn hello() {}'
+ )
+ edges = RustDynamicHints().extract(tmp_path)
+ assert any(e.hint_source == "rust:ffi" for e in edges)
+
+ def test_skips_target_dir(self, tmp_path: Path) -> None:
+ target_dir = tmp_path / "target" / "debug"
+ target_dir.mkdir(parents=True)
+ (target_dir / "main.rs").write_text('#[tokio::main]\nasync fn main() {}')
+ edges = RustDynamicHints().extract(tmp_path)
+ assert len(edges) == 0
+
+ def test_detects_route_macro(self, tmp_path: Path) -> None:
+ (tmp_path / "handler.rs").write_text(
+ '#[get("/api/health")]\nfn health() -> &str { "ok" }'
+ )
+ edges = RustDynamicHints().extract(tmp_path)
+ assert any(e.hint_source == "rust:route_macro" for e in edges)
+
+ def test_detects_plugin_registration(self, tmp_path: Path) -> None:
+ (tmp_path / "plugin.rs").write_text(
+ 'inventory::submit! { MyPlugin { name: "test" } }'
+ )
+ edges = RustDynamicHints().extract(tmp_path)
+ assert any(e.hint_source == "rust:plugin" for e in edges)
+
+ def test_detects_wasm_bindgen(self, tmp_path: Path) -> None:
+ (tmp_path / "wasm.rs").write_text(
+ '#[wasm_bindgen]\npub fn greet(name: &str) -> String { format!("Hello, {}!", name) }'
+ )
+ edges = RustDynamicHints().extract(tmp_path)
+ assert any(e.hint_source == "rust:ffi" for e in edges)
+
+ def test_no_markers_no_edges(self, tmp_path: Path) -> None:
+ (tmp_path / "plain.rs").write_text('fn add(a: i32, b: i32) -> i32 { a + b }')
+ edges = RustDynamicHints().extract(tmp_path)
+ assert len(edges) == 0
+
+ def test_detects_proc_macro(self, tmp_path: Path) -> None:
+ (tmp_path / "lib.rs").write_text(
+ '#[proc_macro]\npub fn my_macro(input: TokenStream) -> TokenStream { input }'
+ )
+ edges = RustDynamicHints().extract(tmp_path)
+ assert any(e.hint_source == "rust:entry_point" for e in edges)
+
+ def test_detects_proc_macro_derive(self, tmp_path: Path) -> None:
+ (tmp_path / "lib.rs").write_text(
+ '#[proc_macro_derive(MyDerive)]\npub fn derive_my(input: TokenStream) -> TokenStream { input }'
+ )
+ edges = RustDynamicHints().extract(tmp_path)
+ assert any(e.hint_source == "rust:entry_point" for e in edges)
+
+ def test_detects_proc_macro_attribute(self, tmp_path: Path) -> None:
+ (tmp_path / "lib.rs").write_text(
+ '#[proc_macro_attribute]\npub fn my_attr(attr: TokenStream, item: TokenStream) -> TokenStream { item }'
+ )
+ edges = RustDynamicHints().extract(tmp_path)
+ assert any(e.hint_source == "rust:entry_point" for e in edges)
+
+ def test_detects_rocket_scoped_route(self, tmp_path: Path) -> None:
+ (tmp_path / "handler.rs").write_text(
+ '#[rocket::get("/health")]\nfn health() -> &str { "ok" }'
+ )
+ edges = RustDynamicHints().extract(tmp_path)
+ assert any(e.hint_source == "rust:route_macro" for e in edges)
diff --git a/tests/unit/ingestion/test_rust_framework_edges.py b/tests/unit/ingestion/test_rust_framework_edges.py
index c5dc11c75..1d7e7a359 100644
--- a/tests/unit/ingestion/test_rust_framework_edges.py
+++ b/tests/unit/ingestion/test_rust_framework_edges.py
@@ -90,6 +90,103 @@ class TestActix:
assert graph.has_edge("main.rs", "handlers.rs")
+class TestAxumNest:
+ def test_nest_to_handler(self, tmp_path: Path) -> None:
+ (tmp_path / "api.rs").write_text(
+ "pub fn api_routes() -> Router { Router::new() }\n"
+ )
+ (tmp_path / "main.rs").write_text(
+ "use axum::Router;\n"
+ "fn app() -> Router {\n"
+ ' Router::new().nest("/api", api_routes)\n'
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["axum"])
+ assert graph.has_edge("main.rs", "api.rs")
+
+
+class TestAxumLayerAndFallback:
+ def test_layer_to_middleware(self, tmp_path: Path) -> None:
+ (tmp_path / "middleware.rs").write_text(
+ "pub async fn auth_layer() {}\n"
+ )
+ (tmp_path / "main.rs").write_text(
+ "use axum::Router;\n"
+ "fn app() -> Router {\n"
+ " Router::new().layer(auth_layer)\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["axum"])
+ assert graph.has_edge("main.rs", "middleware.rs")
+
+ def test_fallback_to_handler(self, tmp_path: Path) -> None:
+ (tmp_path / "fallback.rs").write_text(
+ "pub async fn not_found() -> &'static str { \"404\" }\n"
+ )
+ (tmp_path / "main.rs").write_text(
+ "use axum::Router;\n"
+ "fn app() -> Router {\n"
+ " Router::new().fallback(not_found)\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["axum"])
+ assert graph.has_edge("main.rs", "fallback.rs")
+
+
+class TestRocketMount:
+ def test_rocket_mount_routes(self, tmp_path: Path) -> None:
+ (tmp_path / "routes.rs").write_text(
+ '#[rocket::get("/health")]\n'
+ "pub fn health() -> &'static str { \"ok\" }\n"
+ )
+ (tmp_path / "main.rs").write_text(
+ "use rocket;\n"
+ "fn rocket() -> rocket::Rocket {\n"
+ ' rocket::build().mount("/", routes![health])\n'
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["rocket"])
+ assert graph.has_edge("main.rs", "routes.rs")
+
+ def test_rocket_mount_multiple_handlers(self, tmp_path: Path) -> None:
+ (tmp_path / "routes.rs").write_text(
+ "pub fn index() {}\npub fn about() {}\n"
+ )
+ (tmp_path / "main.rs").write_text(
+ "use rocket;\n"
+ "fn rocket() -> rocket::Rocket {\n"
+ ' rocket::build().mount("/", routes![index, about])\n'
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["rocket"])
+ assert graph.has_edge("main.rs", "routes.rs")
+
+
class TestRustGate:
def test_non_router_unaffected(self, tmp_path: Path) -> None:
(tmp_path / "main.rs").write_text("fn main() {}\n")
diff --git a/tests/unit/ingestion/test_rust_resolver.py b/tests/unit/ingestion/test_rust_resolver.py
index 2e22484f1..19d406e64 100644
--- a/tests/unit/ingestion/test_rust_resolver.py
+++ b/tests/unit/ingestion/test_rust_resolver.py
@@ -9,6 +9,9 @@ import networkx as nx
from repowise.core.ingestion.resolvers.context import ResolverContext
from repowise.core.ingestion.resolvers.rust import resolve_rust_import
from repowise.core.ingestion.resolvers.rust_workspace import (
+ CargoCrate,
+ CargoDep,
+ CargoWorkspaceIndex,
get_or_build_cargo_workspace_index,
)
@@ -67,6 +70,47 @@ class TestCargoWorkspaceIndex:
assert get_or_build_cargo_workspace_index(ctx) is None
+class TestCargoWorkspaceGlobExpansion:
+ def test_glob_member_pattern(self, tmp_path: Path) -> None:
+ """Glob pattern members = ["crates/*"] should discover all crate directories."""
+ _write_workspace(tmp_path, ["crates/*"])
+ _write_member_crate(tmp_path, "crates/foo", "foo")
+ _write_member_crate(tmp_path, "crates/bar", "bar-utils")
+ ctx = _ctx(tmp_path, [
+ "crates/foo/src/lib.rs",
+ "crates/bar/src/lib.rs",
+ ])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ assert idx.lookup("foo") == "crates/foo/src"
+ assert idx.lookup("bar_utils") == "crates/bar/src"
+
+ def test_exclude_pattern(self, tmp_path: Path) -> None:
+ """Workspace exclude patterns should skip matching crates."""
+ (tmp_path / "Cargo.toml").write_text(
+ '[workspace]\nmembers = ["crates/*"]\nexclude = ["crates/ignored"]\n'
+ )
+ _write_member_crate(tmp_path, "crates/foo", "foo")
+ _write_member_crate(tmp_path, "crates/ignored", "ignored")
+ ctx = _ctx(tmp_path, [
+ "crates/foo/src/lib.rs",
+ "crates/ignored/src/lib.rs",
+ ])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ assert idx.lookup("foo") == "crates/foo/src"
+ assert idx.lookup("ignored") is None
+
+
+def test_rust_visibility_levels():
+ from repowise.core.ingestion.extractors.visibility import rust_visibility
+ assert rust_visibility("foo", ["pub"]) == "public"
+ assert rust_visibility("foo", ["pub(crate)"]) == "internal"
+ assert rust_visibility("foo", ["pub(super)"]) == "protected"
+ assert rust_visibility("foo", ["pub(in crate::module)"]) == "protected"
+ assert rust_visibility("foo", []) == "private"
+
+
class TestRustWorkspaceResolution:
def test_use_sibling_crate_resolves_to_module_file(self, tmp_path: Path) -> None:
_write_workspace(tmp_path, ["crates/foo", "crates/bar"])
@@ -114,3 +158,409 @@ class TestRustWorkspaceResolution:
ctx.parsed_files = {p: None for p in ctx.path_set}
result = resolve_rust_import("serde::Serialize", "src/main.rs", ctx)
assert result is not None and result.startswith("external:")
+
+
+class TestAliasedAndBraceImports:
+ def test_aliased_import_strips_as_suffix(self, tmp_path: Path) -> None:
+ """``use typst_syntax as syntax`` should resolve the same as ``typst_syntax``."""
+ _write_workspace(tmp_path, ["crates/typst", "crates/typst-syntax"])
+ _write_member_crate(tmp_path, "crates/typst", "typst")
+ _write_member_crate(tmp_path, "crates/typst-syntax", "typst-syntax")
+
+ ctx = _ctx(tmp_path, [
+ "crates/typst/src/lib.rs",
+ "crates/typst-syntax/src/lib.rs",
+ ])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+
+ # Aliased form should resolve to the same target as the bare form
+ aliased = resolve_rust_import(
+ "typst_syntax as syntax", "crates/typst/src/lib.rs", ctx
+ )
+ bare = resolve_rust_import(
+ "typst_syntax", "crates/typst/src/lib.rs", ctx
+ )
+ assert aliased == bare
+ assert aliased == "crates/typst-syntax/src/lib.rs"
+
+ def test_brace_import_resolves_base_module(self, tmp_path: Path) -> None:
+ """``use crate::diag::{A, B}`` should resolve to ``diag.rs``."""
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "lib.rs").write_text("// root\n")
+ (tmp_path / "src" / "diag.rs").write_text("pub struct A; pub struct B;\n")
+
+ ctx = _ctx(tmp_path, ["src/lib.rs", "src/diag.rs"])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+
+ result = resolve_rust_import("crate::diag::{A, B}", "src/lib.rs", ctx)
+ assert result == "src/diag.rs"
+
+ def test_brace_only_import_returns_none(self, tmp_path: Path) -> None:
+ """``{A, B}`` (no base path) should return None gracefully without crashing."""
+ ctx = _ctx(tmp_path, ["src/lib.rs"])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+
+ result = resolve_rust_import("{A, B}", "src/lib.rs", ctx)
+ # After stripping the brace segment all parts are gone — None is correct.
+ assert result is None
+
+
+class TestSuperChainedResolution:
+ def test_single_super(self, tmp_path: Path) -> None:
+ (tmp_path / "a").mkdir(parents=True)
+ (tmp_path / "a/b").mkdir(parents=True)
+ (tmp_path / "a/foo.rs").write_text("pub fn hello(){}")
+ ctx = _ctx(tmp_path, ["a/foo.rs", "a/b/bar.rs"])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("super::foo", "a/b/bar.rs", ctx)
+ assert result == "a/foo.rs"
+
+ def test_double_super(self, tmp_path: Path) -> None:
+ (tmp_path / "a/b").mkdir(parents=True)
+ (tmp_path / "foo.rs").write_text("pub fn hello(){}")
+ ctx = _ctx(tmp_path, ["foo.rs", "a/b/deep.rs"])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("super::super::foo", "a/b/deep.rs", ctx)
+ assert result == "foo.rs"
+
+ def test_bare_super_returns_none(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["a/b/bar.rs"])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("super::super", "a/b/bar.rs", ctx)
+ assert result is None
+
+
+class TestCargoDependencyParsing:
+ def test_dependencies_parsed(self, tmp_path: Path) -> None:
+ (tmp_path / "Cargo.toml").write_text(
+ '[workspace]\nmembers = ["crates/foo"]\n'
+ )
+ crate_dir = tmp_path / "crates" / "foo"
+ crate_dir.mkdir(parents=True)
+ (crate_dir / "Cargo.toml").write_text(
+ '[package]\nname = "foo"\nversion = "0.1.0"\n\n'
+ '[dependencies]\nserde = "1.0"\n\n'
+ '[dependencies.bar]\npath = "../bar"\npackage = "bar-impl"\n'
+ )
+ (crate_dir / "src").mkdir()
+ (crate_dir / "src" / "lib.rs").write_text("// root\n")
+ ctx = _ctx(tmp_path, ["crates/foo/src/lib.rs"])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ # Find the "foo" crate
+ foo = next(c for c in idx.crates if c.name == "foo")
+ assert any(d.name == "serde" and not d.is_path for d in foo.dependencies)
+ assert any(
+ d.name == "bar" and d.is_path and d.package == "bar-impl"
+ for d in foo.dependencies
+ )
+
+ def test_dev_dependencies_parsed(self, tmp_path: Path) -> None:
+ (tmp_path / "Cargo.toml").write_text(
+ '[workspace]\nmembers = ["crates/foo"]\n'
+ )
+ crate_dir = tmp_path / "crates" / "foo"
+ crate_dir.mkdir(parents=True)
+ (crate_dir / "Cargo.toml").write_text(
+ '[package]\nname = "foo"\nversion = "0.1.0"\n\n'
+ '[dev-dependencies]\ntokio = "1.0"\n'
+ )
+ (crate_dir / "src").mkdir()
+ (crate_dir / "src" / "lib.rs").write_text("// root\n")
+ ctx = _ctx(tmp_path, ["crates/foo/src/lib.rs"])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ foo = next(c for c in idx.crates if c.name == "foo")
+ assert any(d.name == "tokio" for d in foo.dependencies)
+
+ def test_workspace_dependencies(self, tmp_path: Path) -> None:
+ (tmp_path / "Cargo.toml").write_text(
+ '[workspace]\nmembers = []\n\n'
+ '[workspace.dependencies]\nserde = "1.0"\n'
+ )
+ ctx = _ctx(tmp_path, [])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ # No crates means None is returned (empty workspace)
+ # We need at least one crate to get a non-None result
+ assert idx is None
+
+ def test_workspace_dependencies_with_member(self, tmp_path: Path) -> None:
+ (tmp_path / "Cargo.toml").write_text(
+ '[workspace]\nmembers = ["crates/foo"]\n\n'
+ '[workspace.dependencies]\nserde = "1.0"\n'
+ )
+ crate_dir = tmp_path / "crates" / "foo"
+ crate_dir.mkdir(parents=True)
+ (crate_dir / "Cargo.toml").write_text(
+ '[package]\nname = "foo"\nversion = "0.1.0"\n'
+ )
+ (crate_dir / "src").mkdir()
+ (crate_dir / "src" / "lib.rs").write_text("// root\n")
+ ctx = _ctx(tmp_path, ["crates/foo/src/lib.rs"])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ assert any(d.name == "serde" for d in idx.workspace_dependencies)
+
+
+class TestFileToCrateMapping:
+ def test_lookup_crate_for_file(self, tmp_path: Path) -> None:
+ _write_workspace(tmp_path, ["crates/*"])
+ _write_member_crate(tmp_path, "crates/foo", "foo")
+ _write_member_crate(tmp_path, "crates/bar", "bar")
+ ctx = _ctx(tmp_path, ["crates/foo/src/lib.rs", "crates/bar/src/lib.rs"])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ foo_crate = idx.lookup_crate_for_file("crates/foo/src/lib.rs")
+ assert foo_crate is not None
+ assert foo_crate.name == "foo"
+ bar_crate = idx.lookup_crate_for_file("crates/bar/src/lib.rs")
+ assert bar_crate is not None
+ assert bar_crate.name == "bar"
+
+ def test_lookup_nested_file(self, tmp_path: Path) -> None:
+ _write_workspace(tmp_path, ["crates/*"])
+ _write_member_crate(tmp_path, "crates/foo", "foo")
+ ctx = _ctx(tmp_path, ["crates/foo/src/lib.rs", "crates/foo/src/utils/helper.rs"])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ crate = idx.lookup_crate_for_file("crates/foo/src/utils/helper.rs")
+ assert crate is not None
+ assert crate.name == "foo"
+
+ def test_lookup_unknown_file(self, tmp_path: Path) -> None:
+ _write_workspace(tmp_path, ["crates/*"])
+ _write_member_crate(tmp_path, "crates/foo", "foo")
+ ctx = _ctx(tmp_path, ["crates/foo/src/lib.rs"])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ assert idx.lookup_crate_for_file("unknown/path/file.rs") is None
+
+
+class TestBareIdentifierProbesImporterDir:
+ """Fix 2: single-segment bare identifiers (from ``mod foo;``) should probe
+ the importer's directory before the crate root."""
+
+ def test_mod_in_subdir_resolves_locally(self, tmp_path: Path) -> None:
+ """``mod foo;`` in ``crates/typst/src/eval/mod.rs`` should find
+ ``crates/typst/src/eval/foo.rs``, not ``crates/typst/src/foo.rs``."""
+ (tmp_path / "crates/typst/src/eval").mkdir(parents=True)
+ (tmp_path / "crates/typst/src/lib.rs").write_text("// root\n")
+ (tmp_path / "crates/typst/src/eval/mod.rs").write_text("mod foo;\n")
+ (tmp_path / "crates/typst/src/eval/foo.rs").write_text("pub fn run(){}\n")
+ # Also create foo.rs at crate root so both candidates exist
+ (tmp_path / "crates/typst/src/foo.rs").write_text("pub fn other(){}\n")
+
+ ctx = _ctx(tmp_path, [
+ "crates/typst/src/lib.rs",
+ "crates/typst/src/eval/mod.rs",
+ "crates/typst/src/eval/foo.rs",
+ "crates/typst/src/foo.rs",
+ ])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("foo", "crates/typst/src/eval/mod.rs", ctx)
+ assert result == "crates/typst/src/eval/foo.rs"
+
+ def test_mod_in_crate_root_still_works(self, tmp_path: Path) -> None:
+ """``mod foo;`` in ``crates/typst/src/lib.rs`` should find
+ ``crates/typst/src/foo.rs``."""
+ (tmp_path / "crates/typst/src").mkdir(parents=True)
+ (tmp_path / "crates/typst/src/lib.rs").write_text("mod foo;\n")
+ (tmp_path / "crates/typst/src/foo.rs").write_text("pub fn hello(){}\n")
+
+ ctx = _ctx(tmp_path, [
+ "crates/typst/src/lib.rs",
+ "crates/typst/src/foo.rs",
+ ])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("foo", "crates/typst/src/lib.rs", ctx)
+ assert result == "crates/typst/src/foo.rs"
+
+ def test_mod_resolves_to_mod_rs_variant(self, tmp_path: Path) -> None:
+ """``mod foo;`` should also match ``foo/mod.rs``."""
+ (tmp_path / "src/foo").mkdir(parents=True)
+ (tmp_path / "src/lib.rs").write_text("mod foo;\n")
+ (tmp_path / "src/foo/mod.rs").write_text("pub fn hello(){}\n")
+
+ ctx = _ctx(tmp_path, [
+ "src/lib.rs",
+ "src/foo/mod.rs",
+ ])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("foo", "src/lib.rs", ctx)
+ assert result == "src/foo/mod.rs"
+
+
+class TestPathAttributeResolution:
+ """Fix 3: ``#[path = "custom.rs"] mod foo;`` should resolve the path
+ relative to the importer's directory."""
+
+ def test_rs_suffix_resolves_relative_to_importer(self, tmp_path: Path) -> None:
+ (tmp_path / "crates/foo/src").mkdir(parents=True)
+ (tmp_path / "crates/foo/src/lib.rs").write_text("// root\n")
+ (tmp_path / "crates/foo/src/custom.rs").write_text("pub fn hello(){}\n")
+
+ ctx = _ctx(tmp_path, [
+ "crates/foo/src/lib.rs",
+ "crates/foo/src/custom.rs",
+ ])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("custom.rs", "crates/foo/src/lib.rs", ctx)
+ assert result == "crates/foo/src/custom.rs"
+
+ def test_rs_suffix_nonexistent_returns_none(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["src/lib.rs"])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("nonexistent.rs", "src/lib.rs", ctx)
+ assert result is None
+
+ def test_rs_suffix_in_subdir(self, tmp_path: Path) -> None:
+ """Path attribute from a file in a subdirectory."""
+ (tmp_path / "src/sub").mkdir(parents=True)
+ (tmp_path / "src/lib.rs").write_text("// root\n")
+ (tmp_path / "src/sub/mod.rs").write_text("// mod\n")
+ (tmp_path / "src/sub/impl_file.rs").write_text("pub fn run(){}\n")
+
+ ctx = _ctx(tmp_path, [
+ "src/lib.rs",
+ "src/sub/mod.rs",
+ "src/sub/impl_file.rs",
+ ])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("impl_file.rs", "src/sub/mod.rs", ctx)
+ assert result == "src/sub/impl_file.rs"
+
+
+class TestTrailingUnderscoreFallback:
+ """#[path]-renamed modules use trailing-underscore names (e.g. ``export_``)
+ backed by files without the underscore (e.g. ``export.rs``)."""
+
+ def test_self_import_with_trailing_underscore(self, tmp_path: Path) -> None:
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "lib.rs").write_text("// root\n")
+ (tmp_path / "src" / "export.rs").write_text("pub struct BundleOptions;\n")
+
+ ctx = _ctx(tmp_path, ["src/lib.rs", "src/export.rs"])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("self::export_", "src/lib.rs", ctx)
+ assert result == "src/export.rs"
+
+ def test_crate_import_with_trailing_underscore(self, tmp_path: Path) -> None:
+ (tmp_path / "src/model").mkdir(parents=True)
+ (tmp_path / "src" / "lib.rs").write_text("// root\n")
+ (tmp_path / "src/model" / "enum.rs").write_text("pub enum MyEnum {}\n")
+
+ ctx = _ctx(tmp_path, ["src/lib.rs", "src/model/enum.rs"])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("crate::model::enum_", "src/lib.rs", ctx)
+ assert result == "src/model/enum.rs"
+
+ def test_no_false_positive_on_regular_module(self, tmp_path: Path) -> None:
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "lib.rs").write_text("// root\n")
+ (tmp_path / "src" / "my_module.rs").write_text("pub fn hello(){}\n")
+
+ ctx = _ctx(tmp_path, ["src/lib.rs", "src/my_module.rs"])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("crate::my_module", "src/lib.rs", ctx)
+ assert result == "src/my_module.rs"
+
+ def test_trailing_underscore_with_mod_rs(self, tmp_path: Path) -> None:
+ (tmp_path / "src/export").mkdir(parents=True)
+ (tmp_path / "src" / "lib.rs").write_text("// root\n")
+ (tmp_path / "src/export" / "mod.rs").write_text("pub fn run(){}\n")
+
+ ctx = _ctx(tmp_path, ["src/lib.rs", "src/export/mod.rs"])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("self::export_", "src/lib.rs", ctx)
+ assert result == "src/export/mod.rs"
+
+ def test_brace_import_with_trailing_underscore(self, tmp_path: Path) -> None:
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "lib.rs").write_text("// root\n")
+ (tmp_path / "src" / "export.rs").write_text("pub struct BundleOptions;\n")
+
+ ctx = _ctx(tmp_path, ["src/lib.rs", "src/export.rs"])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import(
+ "self::export_::{BundleOptions, export}", "src/lib.rs", ctx
+ )
+ assert result == "src/export.rs"
+
+
+class TestWorkspaceDepInheritance:
+ """Cargo 1.64+ ``{ workspace = true }`` dependency inheritance."""
+
+ def test_member_inherits_workspace_dep(self, tmp_path: Path) -> None:
+ (tmp_path / "Cargo.toml").write_text(
+ '[workspace]\nmembers = ["crates/foo"]\n\n'
+ '[workspace.dependencies]\n'
+ 'bar = { path = "../bar", package = "bar-impl" }\n'
+ )
+ crate_dir = tmp_path / "crates" / "foo"
+ crate_dir.mkdir(parents=True)
+ (crate_dir / "Cargo.toml").write_text(
+ '[package]\nname = "foo"\nversion = "0.1.0"\n\n'
+ '[dependencies]\nbar = { workspace = true }\n'
+ )
+ (crate_dir / "src").mkdir()
+ (crate_dir / "src" / "lib.rs").write_text("// root\n")
+ ctx = _ctx(tmp_path, ["crates/foo/src/lib.rs"])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ foo = next(c for c in idx.crates if c.name == "foo")
+ assert any(
+ d.name == "bar" and d.is_path and d.package == "bar-impl"
+ for d in foo.dependencies
+ )
+
+ def test_member_inherits_simple_version(self, tmp_path: Path) -> None:
+ (tmp_path / "Cargo.toml").write_text(
+ '[workspace]\nmembers = ["crates/foo"]\n\n'
+ '[workspace.dependencies]\nserde = "1.0"\n'
+ )
+ crate_dir = tmp_path / "crates" / "foo"
+ crate_dir.mkdir(parents=True)
+ (crate_dir / "Cargo.toml").write_text(
+ '[package]\nname = "foo"\nversion = "0.1.0"\n\n'
+ '[dependencies]\nserde = { workspace = true }\n'
+ )
+ (crate_dir / "src").mkdir()
+ (crate_dir / "src" / "lib.rs").write_text("// root\n")
+ ctx = _ctx(tmp_path, ["crates/foo/src/lib.rs"])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ foo = next(c for c in idx.crates if c.name == "foo")
+ assert any(d.name == "serde" and not d.is_path for d in foo.dependencies)
+
+
+class TestBinTargetDiscovery:
+ """``[[bin]]`` section parsing in Cargo.toml."""
+
+ def test_bin_paths_parsed(self, tmp_path: Path) -> None:
+ (tmp_path / "Cargo.toml").write_text(
+ '[workspace]\nmembers = ["crates/foo"]\n'
+ )
+ crate_dir = tmp_path / "crates" / "foo"
+ crate_dir.mkdir(parents=True)
+ (crate_dir / "Cargo.toml").write_text(
+ '[package]\nname = "foo"\nversion = "0.1.0"\n\n'
+ '[[bin]]\nname = "cli"\npath = "src/bin/cli.rs"\n\n'
+ '[[bin]]\nname = "server"\npath = "src/bin/server.rs"\n'
+ )
+ (crate_dir / "src").mkdir()
+ (crate_dir / "src" / "lib.rs").write_text("// root\n")
+ ctx = _ctx(tmp_path, ["crates/foo/src/lib.rs"])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ foo = next(c for c in idx.crates if c.name == "foo")
+ assert "crates/foo/src/bin/cli.rs" in foo.bin_paths
+ assert "crates/foo/src/bin/server.rs" in foo.bin_paths
+
+ def test_no_bin_section(self, tmp_path: Path) -> None:
+ _write_workspace(tmp_path, ["crates/foo"])
+ _write_member_crate(tmp_path, "crates/foo", "foo")
+ ctx = _ctx(tmp_path, ["crates/foo/src/lib.rs"])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ foo = next(c for c in idx.crates if c.name == "foo")
+ assert foo.bin_paths == ()