Skip to content

Commit ef1d256

Browse files
bercedevsafishamsi
authored andcommitted
fix(rust): land a use on the declaration it imports (#4439)
A Rust `use` targets the bare, case-folded name it imports. That reached the declaration only when a type annotation in the corpus had left a sourceless node under the same id for the stub rewire to remap. Otherwise the edge dangled, and since 0.9.63 build mints the target as an external stub that ties with the real declaration in `affected` and `explain`. The `use` edge now carries the name as written, and the rewire is lent a sourceless node for each imported name that has none. The lent nodes are not kept, so an import with no unique declaration dangles exactly as before. Standard-library paths are left out. An incremental build re-extracts only the changed files, so the rewire also takes the unchanged ones as candidates; without that it resolved less than a full build. Bumps the AST cache schema: cached edges lack the name. (cherry picked from commit 672a2b6)
1 parent 1af5104 commit ef1d256

4 files changed

Lines changed: 63 additions & 6 deletions

File tree

‎graphify/cache.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
_EXTRACTOR_VERSION = "unknown"
3838

3939
# Bump when AST cache-key semantics change independently of the package version.
40-
_AST_CACHE_SCHEMA = 15 # Go generic receiver types normalized (`Box[T]` -> `Box`) so methods attach to the type node; prior (14): C# receiver resolution for nameless/`new X()`/`foreach` receivers (defer + receiver-chain markers) and `_`/case-distinct node ids (underscore-salted); prior (13): Kotlin/Scala/C++/Swift generic & template type params no longer mint sourceless stubs; Objective-C NS_ENUM/NS_OPTIONS extraction and `_callable`/`_callable_class` markers; Go and PHP receiver-typed member calls park cross-repo (`go_type_table`/`php_type_table`, receiver fields); prior (12): Java inherited-supertype (`receiver_unbound`) and chained/new/cast receiver typing (`java_receiver_chain`, `_java_ret`); C/C++ quoted cross-directory include provenance (`include_kind`); JS external imports anchored to the package, not the path leaf; prior (11): Python property-accessor decorators / `Self`, Swift `Self`, Go generic type params, Python forward type-hint file node, PowerShell dot-source, C# verbatim-interpolated string recovery; (10): C# partial types carry `type_path`; (9): Python property-read raw calls and `_py_property` nodes; (8): Rust `use`-group per-binding edges; (7): Python opaque-base/super(args) markers + nested-class enclosing ids.
40+
_AST_CACHE_SCHEMA = 16 # Rust `use` edges carry the imported name as written (`_rust_use_name`, #4439); prior (15): Go generic receiver types normalized (`Box[T]` -> `Box`) so methods attach to the type node; prior (14): C# receiver resolution for nameless/`new X()`/`foreach` receivers (defer + receiver-chain markers) and `_`/case-distinct node ids (underscore-salted); prior (13): Kotlin/Scala/C++/Swift generic & template type params no longer mint sourceless stubs; Objective-C NS_ENUM/NS_OPTIONS extraction and `_callable`/`_callable_class` markers; Go and PHP receiver-typed member calls park cross-repo (`go_type_table`/`php_type_table`, receiver fields); prior (12): Java inherited-supertype (`receiver_unbound`) and chained/new/cast receiver typing (`java_receiver_chain`, `_java_ret`); C/C++ quoted cross-directory include provenance (`include_kind`); JS external imports anchored to the package, not the path leaf; prior (11): Python property-accessor decorators / `Self`, Swift `Self`, Go generic type params, Python forward type-hint file node, PowerShell dot-source, C# verbatim-interpolated string recovery; (10): C# partial types carry `type_path`; (9): Python property-read raw calls and `_py_property` nodes; (8): Rust `use`-group per-binding edges; (7): Python opaque-base/super(args) markers + nested-class enclosing ids.
4141

4242

4343
# Per-process memo: distributions() scans site-packages metadata, which is

‎graphify/extract.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9933,7 +9933,22 @@ def _learn(e: dict) -> None:
99339933
except Exception as exc:
99349934
import logging
99359935
logging.getLogger(__name__).warning("Cross-file import resolution failed, skipping: %s", exc)
9936-
_rewire_unique_stub_nodes(all_nodes, all_edges)
9936+
# An incremental build re-extracts only the changed files, so the rewire also
9937+
# needs the unchanged ones as candidates, or it resolves less than a full build.
9938+
_fresh_ids = {n.get("id") for n in all_nodes}
9939+
# #4439: a Rust `use` reached its declaration only when a type annotation had left
9940+
# a sourceless node under the same id. Lend the rewire one for each imported name
9941+
# that has none; they are not kept, so an unresolved import dangles as before.
9942+
_use_stubs = {
9943+
e["target"]: {"id": e["target"], "label": e["_rust_use_name"], "file_type": "code", "source_file": ""}
9944+
for e in all_edges
9945+
if e.get("_rust_use_name", "").isidentifier() and e["target"] not in _fresh_ids
9946+
}
9947+
_rewire_view = all_nodes + list(_use_stubs.values()) + [
9948+
n for n in resolution_context_nodes or [] if n.get("id") not in _fresh_ids]
9949+
_rewire_unique_stub_nodes(_rewire_view, all_edges)
9950+
_kept = {id(n) for n in _rewire_view} - {id(n) for n in _use_stubs.values()}
9951+
all_nodes[:] = [n for n in all_nodes if id(n) in _kept]
99379952

99389953
# Cross-file Java import resolution
99399954
java_paths = [p for p in paths if effective_suffix(p) == ".java"]
@@ -10561,6 +10576,7 @@ def _has_import_evidence(candidate_id: str) -> bool:
1056110576
all_edges[:] = [e for e in all_edges if not e.pop("_rust_use_group", False)]
1056210577
for e in all_edges:
1056310578
e.pop("_rust_use_binding", None)
10579+
e.pop("_rust_use_name", None)
1056410580

1056510581
# Relativize source_file fields so paths are portable across machines (#555).
1056610582
# When the node's id was itself minted from the absolute path, remap it to a

‎graphify/extractors/rust.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,17 +721,24 @@ def _emit_enum_type(type_node, at_line):
721721
if t == "use_declaration":
722722
arg = node.child_by_field_name("argument")
723723
if arg:
724+
def name_use(written: str, path: str) -> None:
725+
# The name as written, for the corpus rewire (#4439): the id folds its
726+
# case. Not for the standard library, whose `File` is never the corpus's.
727+
if path.lstrip(": ").split("::")[0].strip() not in ("std", "core", "alloc"):
728+
edges[-1]["_rust_use_name"] = written.split(" as ")[0].strip()
724729
module_name = _rust_use_module(_read_text(arg, source))
725730
grouped = arg.type in ("use_list", "scoped_use_list")
726731
if module_name:
727732
tgt_nid = _make_id(module_name)
728733
add_edge(file_nid, tgt_nid, "imports_from", node.start_point[0] + 1, context="import")
734+
name_use(module_name, _read_text(arg, source))
729735
if grouped: # call evidence as in v8, then dropped (extract.py)
730736
edges[-1]["_rust_use_group"] = True
731737
# A group imports what the plain `use` of each of its bindings would.
732738
for binding, line in _rust_use_bindings(arg, source) if grouped else []:
733739
if binding_name := _rust_use_module(binding):
734740
add_edge(file_nid, _make_id(binding_name), "imports_from", line, context="import")
741+
name_use(binding_name, binding)
735742
edges[-1]["_rust_use_binding"] = True # not call evidence: v8 had no such edge
736743
return
737744

‎tests/test_rust_use_trees.py‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,11 +102,12 @@ def test_each_binding_gets_the_plain_use_target(tmp_path: Path):
102102
edges = sorted((e["relation"], e["target"], e["source_location"]) for e in result["edges"]
103103
if e.get("context") == "import")
104104
assert edges == sorted([
105-
("imports_from", "util", "L1"), ("imports_from", "parse", "L1"), ("imports_from", "render_as_draw", "L1"),
105+
# `parse` and `render` are declared once in the corpus, so they land there (#4439)
106+
("imports_from", "util", "L1"), ("imports_from", "src_util_parse", "L1"), ("imports_from", "src_util_render", "L1"),
106107
("imports_from", "deep", "L1"), ("imports_from", "nested", "L1"), ("imports_from", "b", "L2"),
107108
("imports_from", "c", "L2"),
108109
# plain declarations, exactly as v8 emits them
109-
("imports_from", "parse", "L3"), ("imports_from", "read", "L4"), ("imports_from", "bar_as_baz", "L5"),
110+
("imports_from", "src_util_parse", "L3"), ("imports_from", "read", "L4"), ("imports_from", "bar_as_baz", "L5"),
110111
("imports_from", "util", "L6"), ("imports_from", "fmt", "L7")])
111112
sources = {e["source"] for e in result["edges"] if e.get("context") == "import"}
112113
file_node = next(n["id"] for n in result["nodes"] if n.get("label") == "user.rs")
@@ -120,7 +121,7 @@ def test_a_file_whose_only_use_is_a_root_group_gets_edges_from_its_file_node(tmp
120121
result = _extract(tmp_path, {**_FILES, "src/user.rs": "use {crate::util::parse, std::io};\n"})
121122
file_node = next(n["id"] for n in result["nodes"] if n.get("label") == "user.rs")
122123
assert sorted((e["source"], e["target"]) for e in result["edges"] if e.get("context") == "import") == [
123-
(file_node, "io"), (file_node, "parse")]
124+
(file_node, "io"), (file_node, "src_util_parse")]
124125

125126

126127
# Files at the scan root, so file node ids are bare stems: the binding `util`
@@ -206,4 +207,37 @@ def test_a_cache_entry_from_before_the_bindings_is_not_served(tmp_path: Path, mo
206207
result = extract(sorted(tmp_path / name for name in files), root=tmp_path, cache_root=tmp_path / "graphify-out",
207208
parallel=False)
208209
assert sorted(e["target"] for e in result["edges"]
209-
if e.get("context") == "import" and e["source_file"].endswith("user.rs")) == ["parse", "render"]
210+
if e.get("context") == "import" and e["source_file"].endswith("user.rs")) == ["src_util_parse", "src_util_render"]
211+
212+
213+
def _imports(result: dict, name: str) -> list[str]:
214+
return sorted(e["target"] for e in result["edges"]
215+
if e.get("context") == "import" and e["source_file"].endswith(name))
216+
217+
218+
def test_a_use_lands_on_the_declaration_without_an_annotation(tmp_path: Path):
219+
"""#4439: the import reached `Invoice` only when a type annotation left a
220+
sourceless node for the rewire. Constructing the type left the edge on a
221+
bare `invoice`, which build then minted as an external stub tied with it."""
222+
result = _extract(tmp_path, {
223+
"src/lib.rs": "pub mod billing;\npub mod model;\n", "src/model.rs": "pub struct Invoice(pub u64);\n",
224+
"src/billing.rs": "use crate::model::Invoice;\nuse std::fmt;\n\npub fn make() -> u64 {\n Invoice(1).0\n}\n"})
225+
invoice = next(n["id"] for n in result["nodes"] if n["label"] == "Invoice")
226+
# `fmt` has no declaration here: it stays a dangling target, with no node left behind.
227+
assert _imports(result, "billing.rs") == sorted(["fmt", invoice])
228+
assert [n["label"] for n in result["nodes"] if not n.get("source_file")] == []
229+
assert not any(k.startswith("_rust_use") for n in result["nodes"] for k in n)
230+
231+
232+
def test_a_use_of_a_name_declared_twice_stays_unresolved(tmp_path: Path):
233+
result = _extract(tmp_path, {
234+
"src/lib.rs": "pub mod a;\npub mod b;\npub mod user;\n", "src/a.rs": "pub struct Thing;\n",
235+
"src/b.rs": "pub struct Thing;\n", "src/user.rs": "use crate::a::Thing;\n"})
236+
assert _imports(result, "user.rs") == ["thing"]
237+
238+
239+
def test_a_std_use_does_not_land_on_a_same_named_declaration(tmp_path: Path):
240+
result = _extract(tmp_path, {
241+
"src/lib.rs": "pub mod a;\npub mod user;\n", "src/a.rs": "pub struct File;\npub struct Command;\n",
242+
"src/user.rs": "use std::fs::File;\nuse std::{process::Command, io};\n"})
243+
assert _imports(result, "user.rs") == ["command", "file", "io"]

0 commit comments

Comments
 (0)