fix(rust): stop prelude types becoming god nodes and label constructors

Rust's standard-library types were absent from _LANGUAGE_BUILTIN_GLOBALS, so
every Option/Vec/String/Result annotation was extracted as a domain type and
resolved to a few canonical nodes with corpus-wide degree (String led a
1,200-file workspace with ~1,700 edges).

Add a Rust-only _RUST_BUILTIN_TYPES set, kept separate so the same names still
resolve as user types in other languages, and skip those names in the Rust
type-reference and call collectors. The filter is definition-aware: a file that
defines its own `struct Result<T>` keeps its references.

A tuple-struct construction (`ClientId(id)`) targets a data definition, not a
callable, so it is now emitted as `references[constructor]` instead of `calls`
in both the in-file and cross-file paths; a real function call still emits
`calls`.

(cherry picked from commit 88cb2a8cd1)
This commit is contained in:
Liam McElhaney authored and safishamsi committed 2026-10-02 17:10:07 +01:00
1 parent 4babf7b173
commit 7f1d45dee2
4 files changed
+229 -22

No files matched your search

+16 -2
View File
@@ -8330,6 +8330,14 @@ def extract(
nid_to_file_nid[n["id"]] = _file_node_id(sf_rel)
existing_pairs = {(e["source"], e["target"]) for e in all_edges}
# nid -> label, so a resolved Rust call target can be told apart from a
# constructor: a function/method node is labelled `name()` / `.name()`, a
# data definition (struct/enum/trait) carries the bare name. A cross-file
# `Foo(x)` onto a bare-name node constructs a value; it is not a function
# call and must not count as one.
nid_to_label: dict[str, str] = {
n["id"]: str(n.get("label", "")) for n in resolution_nodes if n.get("id")
}
# Call-like pairs only, for the indirect_call dedup: an `imports` edge from a
# file to the symbol it imports is EXPECTED and must not suppress an
# indirect_call to that same symbol (JS/TS named imports create such an edge).
@@ -8543,11 +8551,17 @@ def extract(
# 0.85 rather than 0.8 — the rubric's INFERRED set is discrete
# and does not contain 0.8 (#2813).
confidence_score = 0.85
_tgt_label = nid_to_label.get(tgt, "")
is_rust_constructor = bool(
str(rc.get("source_file", "")).endswith(".rs")
and _tgt_label
and not _tgt_label.endswith(")")
)
all_edges.append({
"source": caller,
"target": tgt,
"relation": "calls",
"context": "call",
"relation": "references" if is_rust_constructor else "calls",
"context": "constructor" if is_rust_constructor else "call",
"confidence": confidence,
"confidence_score": confidence_score,
"source_file": rc.get("source_file", ""),
+27
View File
@@ -51,6 +51,33 @@ _LANGUAGE_BUILTIN_GLOBALS: frozenset[str] = frozenset({
})
# Rust prelude / std types. Kept separate from _LANGUAGE_BUILTIN_GLOBALS so the
# filter applies to Rust type references only: the same names are ordinary user
# types elsewhere (Python `pathlib.Path`, a Kotlin `Result`), and folding them
# into the shared set would suppress those. Without this set a Rust codebase
# resolves every `Option`/`Vec`/`String`/`Result` annotation to one canonical
# node, making the language's own primitives the top god nodes.
_RUST_BUILTIN_TYPES: frozenset[str] = frozenset({
# prelude types and aliases
"String", "str", "Option", "Result", "Vec", "VecDeque", "Box", "Rc",
"Arc", "Weak", "RefCell", "Cell", "Cow", "Pin",
# collections
"HashMap", "HashSet", "BTreeMap", "BTreeSet", "BinaryHeap",
# paths / OS strings
"Path", "PathBuf", "OsStr", "OsString", "CStr", "CString",
# time / ranges / markers
"Duration", "Instant", "SystemTime", "Ordering", "Range", "RangeInclusive",
"RangeFrom", "RangeTo", "RangeFull", "PhantomData", "ManuallyDrop",
"NonZeroU8", "NonZeroU16", "NonZeroU32", "NonZeroU64", "NonZeroUsize",
# variants and core traits
"Some", "None", "Ok", "Err", "Self",
"Default", "Clone", "Copy", "Debug", "Display", "Error", "From", "Into",
"TryFrom", "TryInto", "AsRef", "AsMut", "Iterator", "IntoIterator",
"Extend", "PartialEq", "Eq", "PartialOrd", "Ord", "Hash", "Send", "Sync",
"Sized", "Drop", "Deref", "DerefMut", "Future", "Fn", "FnMut", "FnOnce",
})
def _make_id(*parts: str) -> str:
return make_id(*parts)
+72 -20
View File
@@ -3,11 +3,33 @@ from __future__ import annotations
from pathlib import Path
from graphify.extractors.base import _LANGUAGE_BUILTIN_GLOBALS, _file_stem, _make_id, _read_text
from graphify.extractors.base import (
_LANGUAGE_BUILTIN_GLOBALS,
_RUST_BUILTIN_TYPES,
_file_stem,
_make_id,
_read_text,
)
def _rust_collect_type_refs(node, source: bytes, generic: bool, out: list[tuple[str, str]]) -> None:
"""Walk a Rust type expression; append (name, role) tuples."""
def _rust_collect_type_refs(
node,
source: bytes,
generic: bool,
out: list[tuple[str, str]],
local_types: frozenset[str] = frozenset(),
) -> None:
"""Walk a Rust type expression; append (name, role) tuples.
A name in ``_RUST_BUILTIN_TYPES`` is skipped unless ``local_types`` holds it:
a file that defines its own ``struct Result<T>`` shadows the prelude, and its
references must survive. Filtering the bare name alone would erase a
legitimate user type that happens to share a std name.
"""
def _keep(text: str) -> bool:
return bool(text) and (text not in _RUST_BUILTIN_TYPES or text in local_types)
if node is None:
return
t = node.type
@@ -15,12 +37,12 @@ def _rust_collect_type_refs(node, source: bytes, generic: bool, out: list[tuple[
return
if t == "type_identifier":
text = _read_text(node, source)
if text:
if _keep(text):
out.append((text, "generic_arg" if generic else "type"))
return
if t == "scoped_type_identifier":
text = _read_text(node, source).rsplit("::", 1)[-1]
if text:
if _keep(text):
out.append((text, "generic_arg" if generic else "type"))
return
if t == "generic_type":
@@ -32,23 +54,23 @@ def _rust_collect_type_refs(node, source: bytes, generic: bool, out: list[tuple[
break
if name_node is not None:
text = _read_text(name_node, source).rsplit("::", 1)[-1]
if text:
if _keep(text):
out.append((text, "generic_arg" if generic else "type"))
for c in node.children:
if c.type == "type_arguments":
for arg in c.children:
if arg.is_named:
_rust_collect_type_refs(arg, source, True, out)
_rust_collect_type_refs(arg, source, True, out, local_types)
return
if t in ("reference_type", "pointer_type", "array_type", "tuple_type", "slice_type"):
for c in node.children:
if c.is_named:
_rust_collect_type_refs(c, source, generic, out)
_rust_collect_type_refs(c, source, generic, out, local_types)
return
if node.is_named:
for c in node.children:
if c.is_named:
_rust_collect_type_refs(c, source, generic, out)
_rust_collect_type_refs(c, source, generic, out, local_types)
def _rust_simple_generic_impl_key(node, source: bytes) -> str | None:
@@ -132,6 +154,24 @@ def extract_rust(path: Path) -> dict:
function_bodies: list[tuple[str, object, str | None, str | None]] = []
impl_keys: dict[str, str | None] = {}
# Names this file defines as a type (struct/enum/trait/union/alias) before it
# starts referring to them. A local definition shadows the prelude, so its
# references must not be dropped by the builtin-name filter further down.
local_types: set[str] = set()
def _scan_local_types(scan_node) -> None:
if scan_node.type in ("struct_item", "enum_item", "trait_item", "union_item", "type_item"):
name_node = scan_node.child_by_field_name("name")
if name_node is not None:
name = _read_text(name_node, source)
if name:
local_types.add(name)
for child in scan_node.children:
_scan_local_types(child)
_scan_local_types(root)
local_type_names = frozenset(local_types)
def add_node(nid: str, label: str, line: int) -> None:
if nid not in seen_ids:
seen_ids.add(nid)
@@ -248,7 +288,7 @@ def extract_rust(path: Path) -> dict:
continue
type_node = p.child_by_field_name("type")
refs: list[tuple[str, str]] = []
_rust_collect_type_refs(type_node, source, False, refs)
_rust_collect_type_refs(type_node, source, False, refs, local_type_names)
for ref_name, role in refs:
ctx = "generic_arg" if role == "generic_arg" else "parameter_type"
tgt = ensure_named_node(ref_name, line)
@@ -257,7 +297,7 @@ def extract_rust(path: Path) -> dict:
return_type = func_node.child_by_field_name("return_type")
if return_type is not None:
refs = []
_rust_collect_type_refs(return_type, source, False, refs)
_rust_collect_type_refs(return_type, source, False, refs, local_type_names)
for ref_name, role in refs:
ctx = "generic_arg" if role == "generic_arg" else "return_type"
tgt = ensure_named_node(ref_name, line)
@@ -337,7 +377,7 @@ def extract_rust(path: Path) -> dict:
if not sub.is_named:
continue
refs: list[tuple[str, str]] = []
_rust_collect_type_refs(sub, source, False, refs)
_rust_collect_type_refs(sub, source, False, refs, local_type_names)
for idx, (ref_name, _role) in enumerate(refs):
tgt = ensure_named_node(ref_name, line)
if tgt == item_nid:
@@ -364,7 +404,7 @@ def extract_rust(path: Path) -> dict:
type_node = fc
break
refs = []
_rust_collect_type_refs(type_node, source, False, refs)
_rust_collect_type_refs(type_node, source, False, refs, local_type_names)
for ref_name, role in refs:
ctx = "generic_arg" if role == "generic_arg" else "field"
tgt = ensure_named_node(ref_name, field.start_point[0] + 1)
@@ -386,7 +426,7 @@ def extract_rust(path: Path) -> dict:
"primitive_type", "tuple_type", "array_type"):
continue
refs = []
_rust_collect_type_refs(tc, source, False, refs)
_rust_collect_type_refs(tc, source, False, refs, local_type_names)
for ref_name, role in refs:
ctx = "generic_arg" if role == "generic_arg" else "field"
tgt = ensure_named_node(ref_name, fline)
@@ -406,7 +446,7 @@ def extract_rust(path: Path) -> dict:
if type_node is None:
return
refs2: list[tuple[str, str]] = []
_rust_collect_type_refs(type_node, source, False, refs2)
_rust_collect_type_refs(type_node, source, False, refs2, local_type_names)
for ref_name, role in refs2:
ctx = "generic_arg" if role == "generic_arg" else "field"
tgt = ensure_named_node(ref_name, at_line)
@@ -481,7 +521,7 @@ def extract_rust(path: Path) -> dict:
type_node = node.child_by_field_name("type")
if type_node is not None:
refs: list[tuple[str, str]] = []
_rust_collect_type_refs(type_node, source, False, refs)
_rust_collect_type_refs(type_node, source, False, refs, local_type_names)
for ref_name, role in refs:
tgt = ensure_named_node(ref_name, line)
if tgt == item_nid:
@@ -507,7 +547,7 @@ def extract_rust(path: Path) -> dict:
impl_type_bare = type_name.split("<")[0].strip()
if trait_node is not None and impl_nid is not None:
refs: list[tuple[str, str]] = []
_rust_collect_type_refs(trait_node, source, False, refs)
_rust_collect_type_refs(trait_node, source, False, refs, local_type_names)
for idx, (ref_name, _role) in enumerate(refs):
tgt = ensure_named_node(ref_name, node.start_point[0] + 1)
if tgt == impl_nid:
@@ -564,6 +604,13 @@ def extract_rust(path: Path) -> dict:
normalised = raw.strip("()").lstrip(".")
label_to_nid[normalised] = n["id"]
# Nodes whose label has no `()` suffix are data definitions (structs, enums,
# traits, statics), not callables. In Rust `Foo(x)` / `Foo { .. }` onto one
# of them constructs a value rather than invoking a function, so the edge is
# a `references` (context "constructor"), not a `calls`. Without this a
# newtype used everywhere (`ClientId(id)`) reads as a top call hub.
type_nids: set[str] = {n["id"] for n in nodes if not n["label"].endswith(")")}
seen_call_pairs: set[tuple[str, str]] = set()
raw_calls: list[dict] = []
@@ -600,18 +647,23 @@ def extract_rust(path: Path) -> dict:
name = func_node.child_by_field_name("name")
if name:
callee_name = _read_text(name, source)
if callee_name and callee_name not in _LANGUAGE_BUILTIN_GLOBALS:
if (
callee_name
and callee_name not in _LANGUAGE_BUILTIN_GLOBALS
and (callee_name not in _RUST_BUILTIN_TYPES or callee_name in local_types)
):
tgt_nid = label_to_nid.get(callee_name)
if tgt_nid and tgt_nid != caller_nid:
pair = (caller_nid, tgt_nid)
if pair not in seen_call_pairs:
seen_call_pairs.add(pair)
line = node.start_point[0] + 1
is_constructor = tgt_nid in type_nids
edges.append({
"source": caller_nid,
"target": tgt_nid,
"relation": "calls",
"context": "call",
"relation": "references" if is_constructor else "calls",
"context": "constructor" if is_constructor else "call",
"confidence": "EXTRACTED",
"source_file": str_path,
"source_location": f"L{line}",
+114
View File
@@ -0,0 +1,114 @@
"""Rust prelude types must not become hubs, and constructions are not calls.
Two Rust-space extraction bugs:
1. ``_LANGUAGE_BUILTIN_GLOBALS`` lists ECMAScript / Python / Swift builtins but
no Rust standard-library type. Every ``Option<T>`` / ``Vec<T>`` / ``String``
annotation was therefore extracted as a domain type, and the language's own
primitives resolved to a few canonical nodes carrying corpus-wide degree.
2. A tuple-struct construction (``ClientId(id)``) was emitted as ``calls``, so
a newtype used as a key everywhere read as the top call hub.
These tests pin both: prelude types produce no node, a real function call still
produces ``calls``, and a construction produces ``references[constructor]``.
"""
from __future__ import annotations
from graphify.extract import extract
def test_rust_prelude_types_produce_no_nodes(tmp_path):
(tmp_path / "a.rs").write_text(
"pub fn parse(items: Vec<String>, name: Option<String>) -> Result<u32, String> {\n"
" let mut seen: std::collections::HashMap<String, u32> = std::collections::HashMap::new();\n"
" let _ = &mut seen;\n"
" Ok(name.map(|_| 1u32).unwrap_or(0))\n"
"}\n",
encoding="utf-8",
)
(tmp_path / "b.rs").write_text(
"pub struct Widget {\n"
" pub name: String,\n"
" pub parts: Vec<u32>,\n"
"}\n"
"pub fn widget() -> Widget {\n"
' Widget { name: String::new(), parts: Vec::new() }\n'
"}\n",
encoding="utf-8",
)
r = extract(sorted(tmp_path.glob("*.rs")), cache_root=tmp_path / "graphify-out")
labels = {n["label"] for n in r["nodes"]}
for builtin in ("Option", "Vec", "String", "Result", "HashMap"):
assert builtin not in labels, f"prelude type {builtin} must not become a node"
assert "Widget" in labels, "a user-defined type must still become a node"
def test_rust_newtype_construction_is_reference_not_call(tmp_path):
(tmp_path / "ids.rs").write_text(
"pub struct ClientId(pub u32);\n", encoding="utf-8")
(tmp_path / "use_ids.rs").write_text(
"use crate::ids::ClientId;\n"
"pub fn wrap(raw: u32) -> u32 {\n"
" let _id = ClientId(raw);\n"
" raw\n"
"}\n",
encoding="utf-8")
r = extract(sorted(tmp_path.glob("*.rs")), cache_root=tmp_path / "graphify-out")
cid = next(n["id"] for n in r["nodes"] if n["label"] == "ClientId")
related = [e for e in r["edges"] if e["target"] == cid]
assert related, "the construction edge must exist"
assert all(e["relation"] != "calls" for e in related), related
assert any(
e["relation"] == "references" and e.get("context") == "constructor"
for e in related
), related
def test_rust_same_file_construction_is_reference_not_call(tmp_path):
(tmp_path / "ids.rs").write_text(
"pub struct ClientId(pub u32);\n"
"pub fn wrap(raw: u32) -> u32 {\n"
" let _id = ClientId(raw);\n"
" raw\n"
"}\n",
encoding="utf-8")
r = extract(sorted(tmp_path.glob("*.rs")), cache_root=tmp_path / "graphify-out")
cid = next(n["id"] for n in r["nodes"] if n["label"] == "ClientId")
related = [e for e in r["edges"] if e["target"] == cid and str(e["source"]).endswith("wrap")]
assert related, "the construction edge must exist"
assert all(e["relation"] != "calls" for e in related), related
assert any(e.get("context") == "constructor" for e in related), related
def test_rust_locally_defined_prelude_name_is_kept(tmp_path):
# A crate may shadow a prelude name (its own `struct Result<T>`). The filter
# must not erase references to a type the file actually defines.
(tmp_path / "shadow.rs").write_text(
"pub struct Result<T>(pub T);\n"
"pub struct Holder {\n"
" pub value: Result<u32>,\n"
"}\n",
encoding="utf-8")
r = extract(sorted(tmp_path.glob("*.rs")), cache_root=tmp_path / "graphify-out")
result_ids = [n["id"] for n in r["nodes"] if n["label"] == "Result"]
assert result_ids, "a locally defined Result must still become a node"
referenced = [
e for e in r["edges"]
if e["target"] in result_ids and e["relation"] == "references"
]
assert referenced, "references to the locally defined Result must survive"
def test_rust_function_call_still_emits_calls(tmp_path):
(tmp_path / "lib.rs").write_text(
"pub fn helper() -> u32 { 1 }\n"
"pub fn run() -> u32 { helper() }\n",
encoding="utf-8")
r = extract(sorted(tmp_path.glob("*.rs")), cache_root=tmp_path / "graphify-out")
rels = {e["relation"] for e in r["edges"] if str(e["target"]).endswith("helper")}
assert "calls" in rels, f"a real function call must stay `calls`; got {rels}"