Applied from PR #4581 (authorship preserved); stale cache-schema bump dropped for one combined bump. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
3bab26798e
commit
14514b37f6
3 files changed
+157
-24
No files matched your search
+23
-11
@@ -285,16 +285,21 @@ def extract_rust(path: Path) -> dict:
|
||||
# define, so an in-file `Type::f()` / `self.f()` binds to a method of that type.
|
||||
impl_methods: dict[tuple[str, str], set[str]] = {}
|
||||
|
||||
# Nodes by id, so a declaration's node is found without scanning every node
|
||||
# (once per declaration, that scan was quadratic in the file's size).
|
||||
node_by_id: dict[str, dict] = {}
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
node_by_id[nid] = {
|
||||
"id": nid,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
})
|
||||
}
|
||||
nodes.append(node_by_id[nid])
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
@@ -337,15 +342,15 @@ def extract_rust(path: Path) -> dict:
|
||||
|
||||
def _scan_type_items(node) -> None:
|
||||
t = node.type
|
||||
if t in ("struct_item", "enum_item", "trait_item", "function_item",
|
||||
"function_signature_item", "static_item", "const_item"):
|
||||
if t in ("struct_item", "enum_item", "trait_item", "union_item", "type_item",
|
||||
"function_item", "function_signature_item", "static_item", "const_item"):
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node:
|
||||
name = _read_text(name_node, source)
|
||||
if t in ("static_item", "const_item") and name == "_":
|
||||
return
|
||||
nid = _make_id(stem, name)
|
||||
is_type = t in ("struct_item", "enum_item", "trait_item")
|
||||
is_type = t in ("struct_item", "enum_item", "trait_item", "union_item", "type_item")
|
||||
items_by_id.setdefault(nid, set()).add((is_type, name))
|
||||
if is_type:
|
||||
declared_type_names.setdefault(nid, set()).add(name)
|
||||
@@ -407,14 +412,15 @@ def extract_rust(path: Path) -> dict:
|
||||
# file's path (with extension) into the id and blocks the rewire, which is
|
||||
# the phantom-duplicate-node bug (#1402).
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
node_by_id[nid] = {
|
||||
"id": nid,
|
||||
"label": name,
|
||||
"file_type": "code",
|
||||
"source_file": "",
|
||||
"source_location": "",
|
||||
"origin_file": str_path,
|
||||
})
|
||||
}
|
||||
nodes.append(node_by_id[nid])
|
||||
return nid
|
||||
|
||||
def emit_param_return_refs(func_node, func_nid: str, line: int) -> None:
|
||||
@@ -514,14 +520,20 @@ def extract_rust(path: Path) -> dict:
|
||||
macro_nids_by_name.setdefault(macro_name, macro_nid)
|
||||
return
|
||||
|
||||
if t in ("struct_item", "enum_item", "trait_item"):
|
||||
# An associated type in an `impl` body (`type Output = Meters;`) is a
|
||||
# type_item too, but not a file-level item: it would mint one colliding
|
||||
# `Output` node per `impl Add`. Only an alias at module level is one.
|
||||
if t == "type_item" and node.parent is not None and node.parent.parent is not None \
|
||||
and node.parent.parent.type == "impl_item":
|
||||
return
|
||||
if t in ("struct_item", "enum_item", "trait_item", "union_item", "type_item"):
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node:
|
||||
item_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
item_nid = file_item_nid(_make_id(stem, item_name), item_name)
|
||||
add_node(item_nid, item_name, line)
|
||||
declaration_node = next(n for n in nodes if n["id"] == item_nid)
|
||||
declaration_node = node_by_id[item_nid]
|
||||
declaration_node["_rust_declaration_count"] = (
|
||||
declaration_node.get("_rust_declaration_count", 0) + 1
|
||||
)
|
||||
@@ -545,7 +557,7 @@ def extract_rust(path: Path) -> dict:
|
||||
else:
|
||||
add_edge(item_nid, tgt, "references", line,
|
||||
context="generic_arg")
|
||||
if t == "struct_item":
|
||||
if t in ("struct_item", "union_item"):
|
||||
for c in node.children:
|
||||
if c.type != "field_declaration_list":
|
||||
continue
|
||||
@@ -729,7 +741,7 @@ def extract_rust(path: Path) -> dict:
|
||||
impl_keys[impl_nid] = impl_key
|
||||
elif impl_keys[impl_nid] != impl_key:
|
||||
impl_keys[impl_nid] = None
|
||||
impl_node = next(n for n in nodes if n["id"] == impl_nid)
|
||||
impl_node = node_by_id[impl_nid]
|
||||
if impl_keys[impl_nid]:
|
||||
impl_node["_rust_impl_key"] = impl_keys[impl_nid]
|
||||
else:
|
||||
|
||||
+18
-13
@@ -503,11 +503,12 @@ def test_rust_forward_type_reference_resolves_to_local_declaration(tmp_path):
|
||||
|
||||
|
||||
def test_rust_forward_reference_prescan_skips_items_that_are_not_nodes(tmp_path):
|
||||
"""#3782: only struct/enum/trait declarations become nodes, so only they may
|
||||
resolve a forward reference. A `type` alias, a `union`, a struct declared in a
|
||||
function body, a name declared nowhere in the file and a generic type that only
|
||||
an `impl` names produce no node of that name here; references to them must keep
|
||||
their sourceless stub instead of being dropped."""
|
||||
"""#3782: only file-level type declarations (struct/enum/trait, and since
|
||||
#4285 `type` aliases and unions) become nodes, so only they may resolve a
|
||||
forward reference. A struct declared in a function body, a name declared
|
||||
nowhere in the file and a generic type that only an `impl` names produce no
|
||||
node of that name here; references to them must keep their sourceless stub
|
||||
instead of being dropped."""
|
||||
p = tmp_path / "shapes.rs"
|
||||
p.write_text(
|
||||
"fn user(a: &Alias, u: &Bits, l: &Local, e: &Elsewhere, w: &Wrapper<u8>) {}\n"
|
||||
@@ -534,6 +535,9 @@ def test_rust_forward_reference_prescan_skips_items_that_are_not_nodes(tmp_path)
|
||||
}
|
||||
for name in ("Alias", "Bits", "Local", "Elsewhere", "Wrapper"):
|
||||
assert name in targets, f"reference to {name} was dropped"
|
||||
for name in ("Alias", "Bits"):
|
||||
assert targets[name]["source_file"] == str(p), name
|
||||
for name in ("Local", "Elsewhere", "Wrapper"):
|
||||
assert targets[name]["source_file"] == "", name
|
||||
|
||||
|
||||
@@ -620,13 +624,14 @@ def test_rust_forward_reference_to_a_casefold_colliding_type_resolves_to_it(tmp_
|
||||
|
||||
|
||||
def test_rust_forward_reference_keeps_its_stub_when_a_non_type_shares_the_name(tmp_path):
|
||||
"""#3782: a `type HANDLE` alias is not a node, and `fn Handle()` beside
|
||||
`struct Handle {}` has the type's exact name, so the two still share one node
|
||||
that walk() gives to whichever comes first. A reference above the
|
||||
declarations keeps the sourceless stub v8's extractor gives it."""
|
||||
for name, user, other, label in (
|
||||
("alias_collision.rs", "fn user(h: HANDLE) {}", "type HANDLE = usize;", "HANDLE"),
|
||||
("same_name_fn.rs", "fn user(h: &Handle) {}", "fn Handle() {}", "Handle"),
|
||||
"""#3782: `fn Handle()` beside `struct Handle {}` has the type's exact name,
|
||||
so the two still share one node that walk() gives to whichever comes first.
|
||||
A reference above the declarations keeps the sourceless stub v8's extractor
|
||||
gives it. A `type HANDLE` alias is a type node of its own since #4285 (the
|
||||
two types are salted apart), so a reference to it lands on it."""
|
||||
for name, user, other, label, sourced in (
|
||||
("alias_collision.rs", "fn user(h: HANDLE) {}", "type HANDLE = usize;", "HANDLE", True),
|
||||
("same_name_fn.rs", "fn user(h: &Handle) {}", "fn Handle() {}", "Handle", False),
|
||||
):
|
||||
p = tmp_path / name
|
||||
p.write_text(
|
||||
@@ -639,7 +644,7 @@ def test_rust_forward_reference_keeps_its_stub_when_a_non_type_shares_the_name(t
|
||||
for e in r["edges"]
|
||||
if e["relation"] == "references" and e["target"] in by_id
|
||||
]
|
||||
assert targets == [(label, "")], name
|
||||
assert targets == [(label, str(p) if sourced else "")], name
|
||||
|
||||
|
||||
def test_rust_forward_reference_resolves_when_no_other_item_shares_the_id(tmp_path):
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Rust `type` aliases and `union` items are declarations (#4285, item 5).
|
||||
|
||||
extract_rust emitted nodes for `struct`, `enum` and `trait` only, so a field,
|
||||
parameter or return typed with an alias or a union declared in the same file
|
||||
resolved through ensure_named_node to a SOURCELESS stub, which the corpus
|
||||
rewire could then grow into a cross-file hub. Both are now type nodes in their
|
||||
declaring file. A union's fields reference their types as a struct's do; an
|
||||
alias is a bare node (its right-hand side is not walked). An associated type in
|
||||
an `impl` (`type Output = Foo;`) is the same tree-sitter node but not a
|
||||
file-level item, so it still emits nothing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extract import extract
|
||||
from graphify.extractors.rust import extract_rust
|
||||
|
||||
_SOURCE = """\
|
||||
pub type Callback = fn(i32) -> i32;
|
||||
pub type Res<T> = Result<T, Error>;
|
||||
pub struct Error;
|
||||
pub union Bits {
|
||||
i: u32,
|
||||
e: Error,
|
||||
}
|
||||
pub struct Button {
|
||||
cb: Callback,
|
||||
bits: Bits,
|
||||
}
|
||||
pub fn run(cb: Callback, b: Bits) -> Res<Callback> {
|
||||
Ok(cb)
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _extract(tmp_path: Path, source: str = _SOURCE, name: str = "lib.rs") -> tuple[dict, Path]:
|
||||
path = tmp_path / name
|
||||
path.write_text(source, encoding="utf-8")
|
||||
return extract_rust(path), path
|
||||
|
||||
|
||||
def _by_label(result: dict, label: str) -> list[dict]:
|
||||
return [n for n in result["nodes"] if n["label"] == label]
|
||||
|
||||
|
||||
def test_alias_and_union_are_sourced_nodes_in_their_file(tmp_path: Path):
|
||||
result, path = _extract(tmp_path)
|
||||
for label, line in (("Callback", "L1"), ("Res", "L2"), ("Bits", "L4")):
|
||||
[node] = _by_label(result, label)
|
||||
assert node["source_file"] == str(path), label
|
||||
assert node["source_location"] == line, label
|
||||
assert [n["label"] for n in result["nodes"] if not n.get("source_file")] == []
|
||||
|
||||
|
||||
def test_alias_and_union_are_contained_by_the_file(tmp_path: Path):
|
||||
result, _ = _extract(tmp_path)
|
||||
by_id = {n["id"]: n["label"] for n in result["nodes"]}
|
||||
contained = {by_id.get(e["target"]) for e in result["edges"] if e["relation"] == "contains"}
|
||||
assert {"Callback", "Res", "Bits"} <= contained
|
||||
|
||||
|
||||
def test_references_bind_to_the_local_declarations(tmp_path: Path):
|
||||
result, _ = _extract(tmp_path)
|
||||
by_id = {n["id"]: n["label"] for n in result["nodes"]}
|
||||
refs = {
|
||||
(by_id.get(e["source"]), by_id.get(e["target"]))
|
||||
for e in result["edges"] if e["relation"] == "references"
|
||||
}
|
||||
assert {("Button", "Callback"), ("Button", "Bits"), ("run()", "Callback"),
|
||||
("run()", "Bits"), ("run()", "Res")} <= refs
|
||||
|
||||
|
||||
def test_union_fields_reference_their_types(tmp_path: Path):
|
||||
result, _ = _extract(tmp_path)
|
||||
by_id = {n["id"]: n["label"] for n in result["nodes"]}
|
||||
field_refs = {
|
||||
(by_id.get(e["source"]), by_id.get(e["target"]))
|
||||
for e in result["edges"]
|
||||
if e["relation"] == "references" and e.get("context") == "field"
|
||||
}
|
||||
assert ("Bits", "Error") in field_refs
|
||||
|
||||
|
||||
def test_an_impl_associated_type_is_not_a_file_level_node(tmp_path: Path):
|
||||
source = (
|
||||
"use std::ops::Add;\npub struct Meters(pub f64);\n"
|
||||
"impl Add for Meters {\n type Output = Meters;\n"
|
||||
" fn add(self, o: Meters) -> Meters { Meters(self.0 + o.0) }\n}\n"
|
||||
)
|
||||
result, _ = _extract(tmp_path, source)
|
||||
assert _by_label(result, "Output") == []
|
||||
|
||||
|
||||
def test_a_cross_file_reference_lands_on_the_alias(tmp_path: Path):
|
||||
"""The alias carries the declaration count the corpus tie-break reads, so a
|
||||
reference from another file rewires onto it instead of a stub."""
|
||||
(tmp_path / "Cargo.toml").write_text(
|
||||
'[package]\nname = "demo"\nversion = "0.1.0"\nedition = "2021"\n', encoding="utf-8")
|
||||
src = tmp_path / "src"
|
||||
src.mkdir()
|
||||
(src / "lib.rs").write_text("pub mod types;\npub mod user;\n", encoding="utf-8")
|
||||
(src / "types.rs").write_text("pub type Callback = fn(i32) -> i32;\n", encoding="utf-8")
|
||||
(src / "user.rs").write_text(
|
||||
"use crate::types::Callback;\npub struct Button {\n cb: Callback,\n}\n", encoding="utf-8")
|
||||
paths = sorted(src.glob("*.rs"))
|
||||
result = extract(paths, root=tmp_path, cache_root=tmp_path / "graphify-out", parallel=False)
|
||||
[alias] = [n for n in result["nodes"] if n["label"] == "Callback"]
|
||||
assert alias["source_file"].endswith("types.rs")
|
||||
by_id = {n["id"]: n for n in result["nodes"]}
|
||||
targets = {
|
||||
e["target"] for e in result["edges"]
|
||||
if e["relation"] == "references" and by_id.get(e["source"], {}).get("label") == "Button"
|
||||
}
|
||||
assert targets == {alias["id"]}, json.dumps(result["edges"], indent=1)
|
||||
Reference in new issue
Block a user