fix(rust): keep module-path calls inside the caller's crate and out of local names
Review follow-ups on the rebased #2135.
- `crate::util::f()` stopped matching at `crate` without checking which
crate the candidate is in, so in a workspace it bound to another crate's
util.rs. A candidate must now share the caller's crate root (nearest
Cargo.toml, else the directory above `src`).
- `crate::b::helper()` in a.rs went through the in-file bare-name lookup
first and bound to a.rs's own helper. A module-path call binds in-file only
for `self::f()` or an inline `mod m { .. }` declared in that file.
- Module names starting with `_` were rejected (`'_'.islower()` is False);
only an UpperCamelCase segment means a type.
- Methods are skipped as candidates: a module path names a free function.
(cherry picked from commit ef748fd9f0)
This commit is contained in:
1 parent
07f61e1bdd
commit
afb177911f
4 files changed
+126
-2
No files matched your search
@@ -10982,6 +10982,7 @@ def extract(
|
||||
# nid -> raw source_file string, for the ambiguous-name tie-breakers below
|
||||
# (test/non-test classification + path proximity). Kept separate from the
|
||||
# file-node-id map because tie-breaking compares the actual file paths.
|
||||
_rust_nid_to_label: "dict[str, str] | None" = None
|
||||
nid_to_source_file: dict[str, str] = {}
|
||||
for n in resolution_nodes:
|
||||
sf = n.get("source_file")
|
||||
@@ -11099,10 +11100,16 @@ def extract(
|
||||
# EXTRACTED because the module is named explicitly in source — same
|
||||
# reasoning as the qualified-class-method passes (#1446/#1533).
|
||||
if rc.get("is_scoped_call"):
|
||||
if _rust_nid_to_label is None:
|
||||
_rust_nid_to_label = {
|
||||
str(n.get("id")): str(n.get("label", "")) for n in resolution_nodes
|
||||
}
|
||||
_survivors = rust_scoped_call_survivors(
|
||||
str(rc.get("scope_qualifier", "")).strip(),
|
||||
global_label_to_nids.get(callee, []),
|
||||
nid_to_source_file,
|
||||
caller_file=str(rc.get("source_file", "")),
|
||||
nid_to_label=_rust_nid_to_label,
|
||||
)
|
||||
if len(_survivors) != 1:
|
||||
continue
|
||||
|
||||
@@ -286,6 +286,17 @@ def extract_rust(path: Path) -> dict:
|
||||
# are resolved through their own registry rather than the function/type
|
||||
# label_to_nid to avoid cross-binding.
|
||||
macro_nids_by_name: dict[str, str] = {}
|
||||
# `mod m { .. }` blocks declared in this file, so a `m::f()` call can bind
|
||||
# in-file; `mod m;` declares a module that lives in another file.
|
||||
inline_mods: set[str] = set()
|
||||
_mod_stack = [root]
|
||||
while _mod_stack:
|
||||
_n = _mod_stack.pop()
|
||||
if _n.type == "mod_item" and _n.child_by_field_name("body") is not None:
|
||||
_name = _n.child_by_field_name("name")
|
||||
if _name is not None:
|
||||
inline_mods.add(_read_text(_name, source))
|
||||
_mod_stack.extend(_n.children)
|
||||
|
||||
# (bare impl type, method name) -> the method nodes this file's `impl` blocks
|
||||
# define, so an in-file `Type::f()` / `self.f()` binds to a method of that type.
|
||||
@@ -938,6 +949,16 @@ def extract_rust(path: Path) -> dict:
|
||||
tgt_nid = named if named in type_nids else None
|
||||
elif is_member_call:
|
||||
tgt_nid = method_label_to_nid.get(callee_name)
|
||||
elif is_scoped_call:
|
||||
# `m::f()` names module m. It is in this file only for
|
||||
# `self::f()` or an inline `mod m { .. }` declared here; any
|
||||
# other module lives in another file, so the bare-name match
|
||||
# would bind `crate::b::helper()` to this file's own helper.
|
||||
path_node = func_node.child_by_field_name("path") if func_node else None
|
||||
qual = _read_text(path_node, source) if path_node is not None else ""
|
||||
head = qual.split("::")[-1].strip()
|
||||
tgt_nid = label_to_nid.get(callee_name) if (
|
||||
qual == "self" or head in inline_mods) else None
|
||||
else:
|
||||
tgt_nid = label_to_nid.get(callee_name)
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
|
||||
@@ -6,6 +6,7 @@ import ast
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
@@ -325,10 +326,31 @@ def resolve_python_import_guided_calls(
|
||||
return resolved_edges
|
||||
|
||||
|
||||
@lru_cache(maxsize=4096)
|
||||
def _rust_crate_root(source_file: str) -> str | None:
|
||||
"""The crate a Rust file belongs to: the nearest directory holding a
|
||||
``Cargo.toml``, else the directory above the nearest ``src``. None when
|
||||
neither is found (a flat layout this pass cannot place)."""
|
||||
path = Path(source_file)
|
||||
for parent in path.parents:
|
||||
try:
|
||||
if (parent / "Cargo.toml").is_file():
|
||||
return str(parent)
|
||||
except OSError:
|
||||
break
|
||||
parts = path.parts
|
||||
if "src" in parts[:-1]:
|
||||
idx = len(parts) - 1 - parts[::-1].index("src")
|
||||
return str(Path(*parts[:idx])) if idx else ""
|
||||
return None
|
||||
|
||||
|
||||
def rust_scoped_call_survivors(
|
||||
qualifier: str,
|
||||
candidates: Sequence[str],
|
||||
nid_to_source_file: dict[str, str],
|
||||
caller_file: str = "",
|
||||
nid_to_label: "dict[str, str] | None" = None,
|
||||
) -> list[str]:
|
||||
"""Return the candidates a Rust ``module::function()`` qualifier verifies.
|
||||
|
||||
@@ -344,6 +366,10 @@ def rust_scoped_call_survivors(
|
||||
Candidates not defined in a ``.rs`` file are skipped — a bare stem match
|
||||
let a Rust ``b::helper()`` bind to a Python ``b.py``.
|
||||
|
||||
A candidate must live in the caller's crate (see ``_rust_crate_root``):
|
||||
``crate::util::f()`` in crate_a never means crate_b's ``util.rs``. Methods
|
||||
are skipped, since a module path names a free function, never an impl's.
|
||||
|
||||
Returns [] outright when the qualifier disqualifies resolution: a bare
|
||||
``crate``/``super``/``self`` names no module file, and an UpperCamelCase
|
||||
segment is a type (``Type::method()`` / ``Enum::Variant`` — rustc enforces
|
||||
@@ -354,13 +380,18 @@ def rust_scoped_call_survivors(
|
||||
if not segments:
|
||||
return []
|
||||
last = segments[-1]
|
||||
if last in ("crate", "super", "self") or not last[:1].islower():
|
||||
if last in ("crate", "super", "self") or last[:1].isupper():
|
||||
return []
|
||||
caller_crate = _rust_crate_root(caller_file) if caller_file else None
|
||||
survivors: list[str] = []
|
||||
for cand in candidates:
|
||||
cand_file = str(nid_to_source_file.get(cand, ""))
|
||||
if not cand_file.endswith(".rs"):
|
||||
continue
|
||||
if nid_to_label is not None and nid_to_label.get(cand, "").startswith("."):
|
||||
continue
|
||||
if caller_file and _rust_crate_root(cand_file) != caller_crate:
|
||||
continue
|
||||
path = Path(cand_file)
|
||||
if path.stem == last:
|
||||
cursor = path.parent
|
||||
@@ -404,6 +435,7 @@ def resolve_cross_file_raw_calls(
|
||||
for n in all_nodes
|
||||
if n.get("id")
|
||||
}
|
||||
nid_to_label = {str(n.get("id")): str(n.get("label", "")) for n in all_nodes if n.get("id")}
|
||||
resolved: list[dict[str, Any]] = []
|
||||
|
||||
for raw_call in iter_raw_calls(per_file):
|
||||
@@ -425,7 +457,9 @@ def resolve_cross_file_raw_calls(
|
||||
# as the Python qualified-class-method pass (#1446/#1533).
|
||||
qualifier = str(raw_call.get("scope_qualifier", "")).strip()
|
||||
survivors = rust_scoped_call_survivors(
|
||||
qualifier, label_index.get(callee.lower(), []), nid_to_source_file
|
||||
qualifier, label_index.get(callee.lower(), []), nid_to_source_file,
|
||||
caller_file=str(raw_call.get("source_file", "")),
|
||||
nid_to_label=nid_to_label,
|
||||
)
|
||||
if len(survivors) != 1:
|
||||
continue
|
||||
|
||||
@@ -160,3 +160,65 @@ def test_bare_name_calls_keep_their_existing_resolution(tmp_path: Path) -> None:
|
||||
"pub fn helper() {}\n")
|
||||
calls = _calls(sorted(tmp_path.rglob("*.rs")), tmp_path)
|
||||
assert any(s == "run" and t == "helper" for s, t, _ in calls), calls
|
||||
|
||||
|
||||
def _scoped_calls(tmp_path, files: dict[str, str]) -> set[tuple[str, str]]:
|
||||
paths = []
|
||||
for name, text in files.items():
|
||||
path = tmp_path / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
paths.append(path)
|
||||
result = extract(paths, root=tmp_path, cache_root=tmp_path / "cache")
|
||||
node = {n["id"]: n for n in result["nodes"]}
|
||||
|
||||
def where(nid: str) -> str:
|
||||
n = node.get(nid, {})
|
||||
sf = Path(n.get("source_file", ""))
|
||||
rel = (sf.relative_to(tmp_path) if sf.is_absolute() else sf).as_posix()
|
||||
return f'{rel}:{n.get("label")}'
|
||||
|
||||
return {
|
||||
(where(e["source"]), where(e["target"]))
|
||||
for e in result["edges"]
|
||||
if e["relation"] == "calls" and e["target"] in node and e["source"] in node
|
||||
}
|
||||
|
||||
|
||||
def test_crate_path_does_not_cross_into_another_workspace_crate(tmp_path):
|
||||
calls = _scoped_calls(tmp_path, {
|
||||
"crate_a/Cargo.toml": "[package]\nname = \"a\"\n",
|
||||
"crate_a/src/main.rs": "mod util;\nfn run() { crate::util::f(); }\n",
|
||||
"crate_a/src/util.rs": "pub fn g() {}\n",
|
||||
"crate_b/Cargo.toml": "[package]\nname = \"b\"\n",
|
||||
"crate_b/src/util.rs": "pub fn f() {}\n",
|
||||
})
|
||||
assert not any(tgt.startswith("crate_b/") for _, tgt in calls)
|
||||
|
||||
|
||||
def test_module_path_never_names_an_impl_method(tmp_path):
|
||||
calls = _scoped_calls(tmp_path, {
|
||||
"Cargo.toml": "[package]\nname = \"s\"\n",
|
||||
"src/store.rs": "pub struct Db;\nimpl Db { pub fn open(&self) {} }\n",
|
||||
"src/main.rs": "mod store;\nfn run() { store::open(); }\n",
|
||||
})
|
||||
assert not any(src.endswith("run()") for src, _ in calls)
|
||||
|
||||
|
||||
def test_underscore_module_resolves(tmp_path):
|
||||
calls = _scoped_calls(tmp_path, {
|
||||
"Cargo.toml": "[package]\nname = \"u\"\n",
|
||||
"src/_internal.rs": "pub fn helper() {}\n",
|
||||
"src/main.rs": "mod _internal;\nfn run() { crate::_internal::helper(); }\n",
|
||||
})
|
||||
assert ("src/main.rs:run()", "src/_internal.rs:helper()") in calls
|
||||
|
||||
|
||||
def test_path_call_does_not_bind_to_a_same_named_local_function(tmp_path):
|
||||
calls = _scoped_calls(tmp_path, {
|
||||
"Cargo.toml": "[package]\nname = \"p\"\n",
|
||||
"src/a.rs": "fn helper() {}\nfn run() { crate::b::helper(); }\n",
|
||||
"src/b.rs": "pub fn helper() {}\n",
|
||||
})
|
||||
assert ("src/a.rs:run()", "src/b.rs:helper()") in calls
|
||||
assert ("src/a.rs:run()", "src/a.rs:helper()") not in calls
|
||||
Reference in new issue
Block a user