fix(rust): scope a use to the crate it names (#4699, #4712)

Applied from PR #4712 (authorship preserved); stale cache-schema bump dropped for the combined bump.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Deepjyoti-SarmahandClaude Opus 4.8 authored and safishamsi committed 2026-10-25 17:26:01 +00:00
1 parent a5ea8bbd6b
commit 3e1a423fe1
4 files changed
+405 -6

No files matched your search

+24
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import os
import re
from pathlib import Path
from typing import Any
@@ -26,6 +27,29 @@ def _load_toml(path: Path) -> dict[str, Any]:
return tomllib.load(manifest)
def package_name(manifest: Path) -> str | None:
"""A Cargo.toml's `[package] name` as Rust spells it in a path (`-` -> `_`).
Returns None when the manifest has no package name, cannot be read, or
cannot be parsed. Callers that scope a Rust import to a crate treat "no
name" as "no crate", never as an error, so this stays silent.
"""
try:
package = _load_toml(manifest).get("package")
except (OSError, ValueError):
return None
except ImportError: # Python 3.10 without tomli: recover the one key we need
try:
text = manifest.read_text(encoding="utf-8", errors="replace")
except OSError:
return None
match = re.search(r'^\[package\][^\[]*?^name\s*=\s*"([^"]+)"', text, re.M | re.S)
name = match.group(1) if match else None
else:
name = package.get("name") if isinstance(package, dict) else None
return name.replace("-", "_") if isinstance(name, str) and name else None
def _discover_root_manifest(root: Path) -> Path | None:
"""Find a Cargo.toml under *root* when none sits directly at the root.
+126 -6
View File
@@ -16,6 +16,7 @@ from pathlib import Path, PurePath
from typing import Any, Callable
from .cache import load_cached, save_cached
from .cargo_introspect import package_name
from .security import redact_secrets
from .mcp_ingest import extract_mcp_config, is_mcp_config_path
from .manifest_ingest import extract_package_manifest, is_package_manifest_path
@@ -3923,8 +3924,104 @@ def _is_top_level_function_definition(node: dict) -> bool:
)
def _rewire_unique_stub_nodes(nodes: list[dict], edges: list[dict]) -> None:
def _rewire_unique_stub_nodes(
nodes: list[dict], edges: list[dict], root: Path | None = None,
) -> None:
"""Map unresolved no-source stubs to a unique real definition with the same label."""
scan_root = Path(root).resolve() if root is not None else None
crate_by_dir: dict[Path, str | None] = {}
def crate_of(source_file: str) -> str | None:
"""The crate a Rust file belongs to: its nearest Cargo.toml with a package
name, looking no higher than the scan root. A file under none has no crate."""
if not source_file:
return None
path = Path(source_file)
if not path.is_absolute() and scan_root is not None:
path = scan_root / path
directory = path.parent
walked: list[Path] = []
crate: str | None = None
while True:
if directory in crate_by_dir:
crate = crate_by_dir[directory]
break
walked.append(directory)
manifest = directory / "Cargo.toml"
if manifest.is_file() and (crate := package_name(manifest)):
break
if directory == scan_root or directory.parent == directory:
break
directory = directory.parent
for seen in walked: # every directory below a hit shares its crate
crate_by_dir[seen] = crate
return crate
# The crates the corpus contains: a `use` naming one of these is an edge to
# follow, anything else is a dependency outside the scan (#4699).
workspace_crates: set[str] = set()
for node in nodes:
sf = str(node.get("source_file", ""))
if sf.endswith(".rs") and (crate := crate_of(sf)):
workspace_crates.add(crate)
# A crate can re-export another crate's item (`pub use core::Thing;`), so an
# import that names the re-exporting crate reaches the defining one (#4699).
# Keyed by (re-exporting crate, imported label) -> crates it re-exports from.
reexports: dict[tuple[str, str], set[str]] = {}
for edge in edges:
info = edge.get("_rust_pub_use")
owner = crate_of(str(edge.get("source_file", "")))
if not isinstance(info, dict) or owner is None:
continue
root = str(info.get("root", ""))
if root != "crate":
reexports.setdefault((owner, str(info.get("label", ""))), set()).add(root)
for _ in range(len(workspace_crates)): # follow `pub use` chains across crates
changed = False
for (crate, label), targets in tuple(reexports.items()):
more = {
deep for root in tuple(targets)
for deep in reexports.get((root, label), ())
}
if not more <= targets:
targets |= more
changed = True
if not changed:
break
def in_stub_crate(stub: dict, candidates: list[dict]) -> list[dict]:
"""Keep the candidates that live in a crate the stub's `use` names.
`_rust_use_roots` holds the first segment of every `use` binding the
stub's name, with `crate` standing for this file's own crate. A stub
with no Cargo.toml above it, or a candidate with none, keeps v8's
label-only binding: without a manifest there is no crate to scope by.
A crate the `use` names may re-export the item from another crate, so
those crates count too — but only after the named crate itself, which
always wins when it has the definition.
"""
origin = str(stub.get("origin_file", ""))
own = crate_of(origin) if origin.endswith(".rs") else None
if own is None:
return candidates
roots = stub.get("_rust_use_roots") or ["crate"]
label = str(stub.get("label", ""))
named = {own if root == "crate" else root for root in roots} & workspace_crates
allowed = set(named)
for root in named:
allowed |= reexports.get((root, label), set())
def keep(crates: set[str]) -> list[dict]:
return [
candidate for candidate in candidates
if not str(candidate.get("source_file", "")).endswith(".rs")
or crate_of(str(candidate.get("source_file", ""))) in (crates | {None})
]
scoped_named = keep(named)
return scoped_named if len(scoped_named) == 1 else keep(allowed)
real_by_label: dict[str, list[dict]] = {} # exact-case type-like (all languages)
real_by_label_ci: dict[str, list[dict]] = {} # case-INSENSITIVE-language reals only
func_by_label: dict[str, list[dict]] = {} # top-level function defs (#1781)
@@ -3976,7 +4073,7 @@ def _rewire_unique_stub_nodes(nodes: list[dict], edges: list[dict]) -> None:
stub_id = str(stub.get("id", ""))
if not stub_id:
continue
candidates = real_by_label.get(_node_label_key(stub), [])
candidates = in_stub_crate(stub, real_by_label.get(_node_label_key(stub), []))
if len(candidates) > 1 and all(
_lang_family(c.get("source_file")) == "rust" for c in candidates
):
@@ -3995,12 +4092,13 @@ def _rewire_unique_stub_nodes(nodes: list[dict], edges: list[dict]) -> None:
# No unique exact type match — fall back to a case-insensitive match, but
# only against case-insensitive-language definitions (so a case-sensitive
# `PATH` can never absorb a `Path` reference).
candidates = real_by_label_ci.get(_node_label_key(stub, fold=True), [])
candidates = in_stub_crate(
stub, real_by_label_ci.get(_node_label_key(stub, fold=True), []))
if len(candidates) != 1:
# #1781: no unique type — try a unique top-level FUNCTION definition,
# gated by (a) the stub not being used as a supertype and (b) a
# language-family match with the stub's referrers.
fcands = func_by_label.get(_node_label_key(stub), [])
fcands = in_stub_crate(stub, func_by_label.get(_node_label_key(stub), []))
if len(fcands) == 1 and stub_id not in supertype_stub_ids:
fams = stub_families.get(stub_id, set())
cand_fam = _lang_family(fcands[0].get("source_file"))
@@ -4081,6 +4179,19 @@ def _rewire_unique_stub_nodes(nodes: list[dict], edges: list[dict]) -> None:
and edge_fam != cand_fam
)
def _scoped_by_a_use(stub: dict) -> bool:
"""A `use` that names this crate or a scanned crate vouches for the stub."""
roots = stub.get("_rust_use_roots") or []
return "crate" in roots or bool(set(roots) & workspace_crates)
# A Rust stub bound by its label alone is a guess: no `use` that names a corpus
# crate vouches for it (#4699).
rust_by_name_only = {
stub_id for stub_id in remap
if str(by_id.get(stub_id, {}).get("origin_file", "")).endswith(".rs")
and not _scoped_by_a_use(by_id.get(stub_id, {}))
} - {edge.get("target") for edge in edges if edge.get("_rust_use_name")}
for edge in edges:
is_csharp_scoped_edge = (
_is_dotnet_source_file(str(edge.get("source_file", "")))
@@ -4104,6 +4215,8 @@ def _rewire_unique_stub_nodes(nodes: list[dict], edges: list[dict]) -> None:
edge, str(target), remapped_target
) and not _cross_language_candidate(edge, remapped_target):
edge["target"] = remapped_target
if target in rust_by_name_only:
edge["confidence"] = "INFERRED"
referenced = {x for e in edges for x in (e.get("source"), e.get("target"))}
drop_ids = {stub_id for stub_id in remap if stub_id not in referenced}
@@ -10408,13 +10521,17 @@ def extract(
# a sourceless node under the same id. Lend the rewire one for each imported name
# that has none; they are not kept, so an unresolved import dangles as before.
_use_stubs = {
e["target"]: {"id": e["target"], "label": e["_rust_use_name"], "file_type": "code", "source_file": ""}
e["target"]: {
"id": e["target"], "label": e["_rust_use_name"], "file_type": "code",
"source_file": "", "origin_file": e.get("source_file"),
"_rust_use_roots": ["crate"],
}
for e in all_edges
if e.get("_rust_use_name", "").isidentifier() and e["target"] not in _fresh_ids
}
_rewire_view = all_nodes + list(_use_stubs.values()) + [
n for n in resolution_context_nodes or [] if n.get("id") not in _fresh_ids]
_rewire_unique_stub_nodes(_rewire_view, all_edges)
_rewire_unique_stub_nodes(_rewire_view, all_edges, root)
_kept = {id(n) for n in _rewire_view} - {id(n) for n in _use_stubs.values()}
all_nodes[:] = [n for n in all_nodes if id(n) in _kept]
@@ -11064,6 +11181,9 @@ def extract(
for e in all_edges:
e.pop("_rust_use_binding", None)
e.pop("_rust_use_name", None)
e.pop("_rust_pub_use", None)
for n in all_nodes:
n.pop("_rust_use_roots", None)
# Relativize source_file fields so paths are portable across machines (#555).
# When the node's id was itself minted from the absolute path, remap it to a
+26
View File
@@ -274,6 +274,11 @@ def extract_rust(path: Path) -> dict:
_scan_local_types(root)
local_type_names = frozenset(local_types)
# Where each imported name comes from: `crate` for this crate's own paths, otherwise
# the first path segment (`serde_json`, or a workspace crate's name). A sourceless
# stub under such a name carries it, so the corpus rewire can scope the binding.
use_roots: dict[str, set[str]] = {}
# `macro_rules!` macros defined in this file, keyed by bare name. A macro and a
# function can share a name in Rust (`vec!` vs `vec`), and a macro is invoked
# as `name!(...)` (a `macro_invocation`, never a `call_expression`), so macros
@@ -768,6 +773,17 @@ def extract_rust(path: Path) -> dict:
and (name_node := sibling.child_by_field_name("name")) is not None
}
# A plain `pub use` re-exports the named item from the crate its path
# starts with, so a later `use this_crate::Item` may reach a definition
# that lives in that crate (#4699). `pub(crate)` and `pub(super)` stay
# inside the re-exporting crate, so only a bare `pub` counts.
visibility = next(
(child for child in node.children if child.type == "visibility_modifier"),
None,
)
reexport = visibility is not None and _read_text(
visibility, source).strip() == "pub"
def name_use(written: str, path: str) -> None:
# The name as written, for the corpus rewire (#4439): the id folds its
# case. Only for a path rooted in this crate: `serde::Serialize` or
@@ -776,6 +792,7 @@ def extract_rust(path: Path) -> dict:
# too (`mod item; pub use item::Invoice;`), unless the path starts with
# `::`, which always names a crate (#4564).
first = path.lstrip(": ").split("::")[0].strip()
bound = written.split(" as ")[-1].strip()
ident = re.match(r"[A-Za-z_][A-Za-z0-9_]*", first) # `item as items` -> `item`
if first in ("crate", "self", "super") or (
ident is not None
@@ -783,6 +800,11 @@ def extract_rust(path: Path) -> dict:
and not path.lstrip().startswith("::")
):
edges[-1]["_rust_use_name"] = written.split(" as ")[0].strip()
use_roots.setdefault(bound, set()).add("crate")
else:
use_roots.setdefault(bound, set()).add(first)
if reexport and bound.isidentifier():
edges[-1]["_rust_pub_use"] = {"label": bound, "root": first}
module_name = _rust_use_module(_read_text(arg, source))
grouped = arg.type in ("use_list", "scoped_use_list")
if module_name:
@@ -952,6 +974,10 @@ def extract_rust(path: Path) -> dict:
for caller_nid, body_node, impl_type, impl_key in function_bodies:
walk_calls(body_node, caller_nid, impl_type, impl_key)
for node in nodes:
if not node["source_file"] and node["label"] in use_roots:
node["_rust_use_roots"] = sorted(use_roots[node["label"]])
valid_ids = seen_ids
clean_edges = []
for edge in edges:
+229
View File
@@ -0,0 +1,229 @@
"""A Rust `use` from another crate does not land on a same-named local definition.
A reference to `Value` is a sourceless stub, and the corpus rewire bound it to the
only `Value` in the corpus — even when the file said `use serde_json::Value` and
the local `Value` was a struct field. The rewire now reads the crate a stub's
`use` names: `serde_json` is outside the scanned crates, so the stub stays
unbound; `a::Value` in a workspace where `a` is scanned reaches `a`'s definition
and not a namesake elsewhere. A stub is only scoped when its file is under a
Cargo.toml, so each fixture writes one per crate; a manifest-less `.rs` scan
keeps the old label-only binding, which the rewire flags as INFERRED instead of
silently presenting it as EXTRACTED (#4699).
"""
from __future__ import annotations
from pathlib import Path
import pytest
from graphify.extract import extract
ENUM_A = "pub enum Field {\n Value(String),\n}\n"
STRUCT_VALUE = "pub struct Value;\n"
USE_VALUE = 'pub fn get(v: &Value) -> Option<&Value> {\n v.get("x")\n}\n'
def _write(root: Path, files: dict[str, str], manifests: bool = True) -> None:
for rel, text in files.items():
path = root / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
if not manifests:
return
for crate in {rel.split("/")[0] for rel in files if rel.endswith(".rs")}:
manifest = root / crate / "Cargo.toml"
if not manifest.exists():
manifest.write_text(f'[package]\nname = "{crate}"\n', encoding="utf-8")
def _run(tmp_path: Path, files: dict[str, str], manifests: bool = True) -> dict:
_write(tmp_path, files, manifests)
paths = sorted(tmp_path.rglob("*.rs"))
return extract(paths, root=tmp_path, cache_root=tmp_path / "cache", parallel=False)
def _crate(root: Path, source_file: str | None) -> str | None:
if not source_file:
return None
path = Path(source_file)
rel = path.relative_to(root) if path.is_absolute() else path
return rel.parts[0]
def _edges_between(result: dict, root: Path, src_crate: str, dst_crate: str) -> list[dict]:
"""Non-structural edges from a node in `src_crate` to a node in `dst_crate`."""
nodes = {n["id"]: n for n in result["nodes"]}
return [
edge
for edge in result["edges"]
if edge["relation"] not in ("contains", "case_of", "method")
and _crate(root, nodes.get(edge["source"], {}).get("source_file")) == src_crate
and _crate(root, nodes.get(edge["target"], {}).get("source_file")) == dst_crate
]
@pytest.mark.parametrize("decl", [ENUM_A, STRUCT_VALUE], ids=["variant", "struct"])
def test_external_crate_use_and_annotation_do_not_reach_a_local_crate(tmp_path, decl):
result = _run(tmp_path, {
"a/src/lib.rs": decl,
"b/src/lib.rs": "use serde_json::Value;\n\n" + USE_VALUE,
})
assert _edges_between(result, tmp_path, "b", "a") == []
def test_external_crate_use_alone_does_not_reach_a_local_crate(tmp_path):
result = _run(tmp_path, {
"a/src/lib.rs": ENUM_A,
"b/src/lib.rs": "use serde_json::Value;\n\npub fn f() {}\n",
})
assert _edges_between(result, tmp_path, "b", "a") == []
def test_annotation_without_any_use_does_not_reach_a_local_crate(tmp_path):
result = _run(tmp_path, {"a/src/lib.rs": ENUM_A, "b/src/lib.rs": USE_VALUE})
assert _edges_between(result, tmp_path, "b", "a") == []
def test_std_use_does_not_reach_a_same_named_local_struct(tmp_path):
result = _run(tmp_path, {
"a/src/lib.rs": "pub struct HashMap;\n",
"b/src/lib.rs": "use std::collections::HashMap;\n\npub fn f(m: &HashMap<u8, u8>) {}\n",
})
assert _edges_between(result, tmp_path, "b", "a") == []
def test_grouped_external_use_does_not_reach_a_local_crate(tmp_path):
result = _run(tmp_path, {
"a/src/lib.rs": ENUM_A + "pub struct Map;\n",
"b/src/lib.rs": "use serde_json::{Map, Value};\n\npub fn f(m: &Map<String, Value>) {}\n",
})
assert _edges_between(result, tmp_path, "b", "a") == []
def test_workspace_crate_use_reaches_that_crate(tmp_path):
result = _run(tmp_path, {
"a/src/lib.rs": STRUCT_VALUE,
"b/src/lib.rs": "use a::Value;\n\n" + USE_VALUE,
"b/Cargo.toml": '[package]\nname = "b"\n\n[dependencies]\na = { path = "../a" }\n',
})
assert _edges_between(result, tmp_path, "b", "a") != []
def test_workspace_crate_use_reaches_the_named_crate_not_a_namesake(tmp_path):
result = _run(tmp_path, {
"a/src/lib.rs": STRUCT_VALUE,
"c/src/lib.rs": STRUCT_VALUE,
"b/src/lib.rs": "use a::Value;\n\n" + USE_VALUE,
})
assert _edges_between(result, tmp_path, "b", "a") != []
assert _edges_between(result, tmp_path, "b", "c") == []
def test_workspace_crate_use_does_not_reach_another_crates_namesake(tmp_path):
# `osiris_types` (package `osiris-types`) has no `Config`; `server` has one.
result = _run(tmp_path, {
"osiris-types/src/lib.rs": "pub struct Other;\n",
"server/src/lib.rs": "pub struct Config;\n",
"plugin/src/lib.rs": "use osiris_types::Config;\n\npub fn f(c: &Config) {}\n",
})
assert _edges_between(result, tmp_path, "plugin", "server") == []
def test_workspace_crate_use_reaches_its_own_crate_when_two_crates_share_a_name(tmp_path):
result = _run(tmp_path, {
"osiris-types/src/lib.rs": "pub struct Config;\n",
"server/src/lib.rs": "pub struct Config;\n",
"plugin/src/lib.rs": "use osiris_types::Config;\n\npub fn f(c: &Config) {}\n",
})
assert _edges_between(result, tmp_path, "plugin", "osiris-types") != []
assert _edges_between(result, tmp_path, "plugin", "server") == []
def test_crate_relative_use_reaches_its_own_module(tmp_path):
result = _run(tmp_path, {
"b/src/lib.rs": "mod model;\nuse crate::model::Value;\n\n" + USE_VALUE,
"b/src/model.rs": STRUCT_VALUE,
})
assert _edges_between(result, tmp_path, "b", "b") != []
def test_same_named_types_in_two_crates_have_no_edge_without_a_use(tmp_path):
result = _run(tmp_path, {"a/src/lib.rs": STRUCT_VALUE, "b/src/lib.rs": STRUCT_VALUE})
assert _edges_between(result, tmp_path, "a", "b") == []
assert _edges_between(result, tmp_path, "b", "a") == []
def test_a_crate_less_binding_is_flagged_inferred_not_extracted(tmp_path):
# No Cargo.toml anywhere: there is no crate to scope the external `use` by, so
# the rewire still binds by label and must say it is guessing.
result = _run(
tmp_path,
{"a/src/lib.rs": STRUCT_VALUE, "b/src/lib.rs": "use serde_json::Value;\n\n" + USE_VALUE},
manifests=False,
)
edges = _edges_between(result, tmp_path, "b", "a")
assert edges
assert {edge["confidence"] for edge in edges} == {"INFERRED"}
def test_a_use_of_this_crate_keeps_the_binding_extracted(tmp_path):
result = _run(tmp_path, {
"b/src/lib.rs": "mod model;\nuse crate::model::Value;\n\n" + USE_VALUE,
"b/src/model.rs": STRUCT_VALUE,
})
edges = _edges_between(result, tmp_path, "b", "b")
assert {edge["confidence"] for edge in edges} == {"EXTRACTED"}
def test_a_use_of_a_reexporting_crate_reaches_the_defining_crate(tmp_path):
# `api` re-exports `corelib`'s type, as axum re-exports axum-core's.
result = _run(tmp_path, {
"corelib/src/lib.rs": "pub struct FromRequestParts;\n",
"api/src/lib.rs": "pub use corelib::FromRequestParts;\n",
"plugin/src/lib.rs": "use api::FromRequestParts;\n\npub fn f(x: &FromRequestParts) {}\n",
})
assert _edges_between(result, tmp_path, "plugin", "corelib") != []
def test_a_reexport_does_not_reach_an_unrelated_namesake(tmp_path):
result = _run(tmp_path, {
"corelib/src/lib.rs": "pub struct FromRequestParts;\n",
"other/src/lib.rs": "pub struct FromRequestParts;\n",
"api/src/lib.rs": "pub use corelib::FromRequestParts;\n",
"plugin/src/lib.rs": "use api::FromRequestParts;\n\npub fn f(x: &FromRequestParts) {}\n",
})
assert _edges_between(result, tmp_path, "plugin", "corelib") != []
assert _edges_between(result, tmp_path, "plugin", "other") == []
def test_a_super_use_of_a_reexported_type_reaches_the_defining_crate(tmp_path):
# axum/src/extract/connect_info.rs: `use super::{.., FromRequestParts}` where the
# parent module re-exports an axum-core type.
result = _run(tmp_path, {
"corelib/src/lib.rs": "pub struct FromRequestParts;\n",
"api/src/lib.rs": "pub mod sub;\npub use corelib::FromRequestParts;\n",
"api/src/sub.rs": "use super::FromRequestParts;\n\npub fn f(x: &FromRequestParts) {}\n",
})
assert _edges_between(result, tmp_path, "api", "corelib") != []
def test_a_crate_restricted_reexport_does_not_leak_out_of_its_crate(tmp_path):
# `pub(crate) use` is not visible to another crate, so the name stays unbound.
result = _run(tmp_path, {
"corelib/src/lib.rs": "pub struct FromRequestParts;\n",
"api/src/lib.rs": "pub(crate) use corelib::FromRequestParts;\n",
"plugin/src/lib.rs": "use api::FromRequestParts;\n\npub fn f(x: &FromRequestParts) {}\n",
})
assert _edges_between(result, tmp_path, "plugin", "corelib") == []
def test_a_use_of_a_scanned_crate_keeps_the_binding_extracted(tmp_path):
result = _run(tmp_path, {
"corelib/src/lib.rs": "pub struct FromRequestParts;\n",
"plugin/src/lib.rs": (
"use corelib::FromRequestParts;\n\npub fn f(x: &FromRequestParts) {}\n"
),
})
edges = _edges_between(result, tmp_path, "plugin", "corelib")
assert edges
assert {edge["confidence"] for edge in edges} == {"EXTRACTED"}