Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

feat(graph): Rust use crate::… → resolved file→module import edges (breadth tier)

Shrish Dwivedi7f831145f2bd
diff --git a/src/graph/generic.ts b/src/graph/generic.ts
index 675b11bb..34606db2 100644
--- a/src/graph/generic.ts
+++ b/src/graph/generic.ts
@@ -216,11 +216,47 @@ export function extractGeneric(rel: string, source: string, langName: string): E
walkExtract(tree.rootNode as TsNode, mkDef); // no tags.scm → symbols only
}
// The preprocessor is invisible to tags.scm, but in C/C++ a local `#include "x.h"`
- // IS the dependency graph — capture it as a file→file import.
+ // IS the dependency graph — capture it as a file→file import. Likewise a Rust
+ // `use crate::…` is an in-crate module dependency.
if (langName === "c" || langName === "cpp") extractIncludes(tree.rootNode as TsNode, rel, rawEdges);
+ else if (langName === "rust") extractUses(tree.rootNode as TsNode, rel, rawEdges);
return { nodes, rawEdges };
}
+/** Rust `use crate::a::b::Item` → a file→module `imports` raw edge whose specifier is the
+ * crate-relative module path (`a/b`). Only in-crate imports are captured; `std::`,
+ * `super::`, `self::`, external crates, and globs are skipped — resolve.ts settles the
+ * path against the file's crate root, and drops it when it can't. */
+function extractUses(root: TsNode, rel: string, rawEdges: RawEdge[]): void {
+ const visit = (n: TsNode): void => {
+ if (n.type === "use_declaration") {
+ const spec = rustUseModule(n.text);
+ if (spec !== null) rawEdges.push({ source: rel, relation: "imports", specifier: spec ? `crate/${spec}` : "crate", file: rel });
+ }
+ for (let i = 0; i < (n.namedChildCount ?? 0); i++) {
+ const c = n.namedChild?.(i);
+ if (c) visit(c);
+ }
+ };
+ visit(root);
+}
+
+/** The crate-relative path a Rust `use crate::…` names (`::`→`/`), or null when it is not
+ * an in-crate import. The FULL path is returned — including any trailing item segment —
+ * because a single `crate::lexical` can be either a module OR a crate-root item; the
+ * resolver settles that by finding the longest prefix that is a real module file. A
+ * `{ … }` group has no single item, so its prefix (before `{`) is the path. */
+function rustUseModule(text: string): string | null {
+ let s = text.replace(/^\s*use\s+/, "").replace(/;\s*$/, "").trim();
+ const brace = s.indexOf("{");
+ if (brace >= 0) s = s.slice(0, brace).replace(/::\s*$/, "");
+ else s = s.replace(/\s+as\s+\w+$/, "");
+ s = s.trim();
+ if (s !== "crate" && !s.startsWith("crate::")) return null; // only in-crate absolute imports
+ if (s.includes("*")) return null; // glob — no single module target
+ return s.replace(/^crate::?/, "").replace(/\s+/g, "").replace(/::/g, "/"); // "" = crate root
+}
+
/** C/C++ `#include "header.h"` → a file→file `imports` raw edge. Only LOCAL includes
* (quoted) are captured; system includes (`<stdio.h>`) are skipped — high volume, and
* there is no in-repo target to navigate to. resolve.ts settles the quoted path to an
diff --git a/src/graph/resolve.ts b/src/graph/resolve.ts
index 99e59bb1..b58cdcbc 100644
--- a/src/graph/resolve.ts
+++ b/src/graph/resolve.ts
@@ -58,6 +58,10 @@ export function resolveEdges(
// file node ids, so an `#include` reached through an `-I` dir (not relative to the
// including file) still resolves to the in-repo header when the suffix is unique.
const cFilesBySuffix = new Map<string, string[]>();
+ // Rust crate roots: the directory holding a `lib.rs` or `main.rs`. A `use crate::a::b`
+ // resolves to `<crate root>/a/b.rs` (or `.../a/b/mod.rs`), relative to the crate the
+ // importing file belongs to — so a workspace with several crates stays unambiguous.
+ const rustCrateRoots: string[] = [];
const hasGoModules = !!opts.goModules?.length;
for (const n of nodes) {
if (n.kind === "file") {
@@ -76,6 +80,11 @@ export function resolveEdges(
const parts = toPosixPath(n.path).split("/");
for (let i = 0; i < parts.length; i++) push(cFilesBySuffix, parts.slice(i).join("/"), n.id);
}
+ {
+ const p = toPosixPath(n.path);
+ if (p === "lib.rs" || p === "main.rs") rustCrateRoots.push("");
+ else if (p.endsWith("/lib.rs") || p.endsWith("/main.rs")) rustCrateRoots.push(posix.dirname(p));
+ }
continue;
}
push(globalName, n.name, n);
@@ -121,7 +130,9 @@ export function resolveEdges(
? resolveJavaImport(e.specifier, javaFilesBySuffix)
: C_EXT.test(e.file)
? resolveCInclude(e.specifier, e.file, byId, cFilesBySuffix)
- : resolveImport(e.specifier, e.file, byId);
+ : e.file.endsWith(".rs")
+ ? resolveRustUse(e.specifier, e.file, byId, rustCrateRoots)
+ : resolveImport(e.specifier, e.file, byId);
add(e.source, target, "imports", "extracted");
} else if (e.relation === "extends" || e.relation === "implements") {
const kinds: Kind[] = e.relation === "implements" ? ["interface"] : ["class", "interface"];
@@ -355,6 +366,54 @@ function resolveCInclude(
return spec; // system/out-of-repo/ambiguous — keep the string, do not guess
}
+/**
+ * Resolve a Rust `crate`-relative module path (`crate/a/b`, from `use crate::a::b::Item`)
+ * to the in-repo module file — `<crate root>/a/b.rs` or `<crate root>/a/b/mod.rs`, where
+ * the crate root is the `lib.rs`/`main.rs` directory the importing file lives under. The
+ * per-file crate root keeps a multi-crate workspace unambiguous. Not found or ambiguous
+ * (two roots, both `a/b.rs` and `a/b/mod.rs`) stays a `crate::…` string — never a guess.
+ */
+function resolveRustUse(spec: string, file: string, byId: Map<string, NodeV1>, crateRoots: string[]): string {
+ const full = spec.replace(/^crate\/?/, ""); // "crate/a/b/Item" → "a/b/Item"; "crate" → ""
+ const fpath = toPosixPath(file);
+ // the crate this file belongs to: the longest root that contains it (workspace-safe)
+ const owning = crateRoots
+ .filter((r) => r === "" ? true : fpath === r || fpath.startsWith(`${r}/`))
+ .sort((a, b) => b.length - a.length);
+ // No owning crate root (e.g. an integration test under `tests/`, whose `crate::` is the
+ // TEST binary's own root, not a lib) → do NOT search every crate in a workspace: that
+ // resolves `crate::util` to some unrelated crate's util.rs. Keep it a string instead.
+ if (owning.length === 0) return full === "" ? "crate" : `crate::${full.replace(/\//g, "::")}`;
+ const roots = [owning[0]];
+ const segs = full === "" ? [] : full.split("/");
+ const hitsFor = (rels: string[]): Set<string> => {
+ const hits = new Set<string>();
+ for (const r of roots) for (const rel of rels) {
+ const cand = r === "" ? rel : `${r}/${rel}`;
+ if (byId.has(cand)) hits.add(cand);
+ }
+ return hits;
+ };
+ // Try the longest module prefix first, shrinking toward — but NOT past — the first
+ // segment. `crate::a::b::C` resolves as module `a/b` (C is the item); `crate::net` as
+ // module `net`. The first prefix naming exactly one in-repo file wins; two matches at a
+ // level are ambiguous → drop rather than guess.
+ for (let k = segs.length; k >= 1; k--) {
+ const modPath = segs.slice(0, k).join("/");
+ const hits = hitsFor([`${modPath}.rs`, `${modPath}/mod.rs`]);
+ if (hits.size === 1) return [...hits][0];
+ if (hits.size > 1) break;
+ }
+ // The crate root (`lib.rs`/`main.rs`) is a target ONLY for `use crate::Item` or
+ // `use crate::{…}` — a deeper path whose module chain didn't resolve is genuinely
+ // unknown (a re-export, an inline `mod`, or out-of-tree), so keep it as a string.
+ if (segs.length <= 1) {
+ const hits = hitsFor(["lib.rs", "main.rs"]);
+ if (hits.size === 1) return [...hits][0];
+ }
+ return full === "" ? "crate" : `crate::${full.replace(/\//g, "::")}`;
+}
+
/**
* Resolve a Go import package path to an in-repo file node when it points inside one of
* the repo's modules; otherwise return the raw specifier (stdlib or third-party package).
diff --git a/test/generic-extract.test.ts b/test/generic-extract.test.ts
index 649a4180..f3402fb0 100644
--- a/test/generic-extract.test.ts
+++ b/test/generic-extract.test.ts
@@ -180,6 +180,54 @@ test("breadth tier: C #include becomes a resolved file→file import (local only
assert.deepEqual(targetsOf("src/amb.c"), ["util.h"], "ambiguous include kept external, never guessed");
});
+// Rust `use crate::…` → a file→module import, resolved against the file's crate root
+// (the lib.rs/main.rs dir). The longest-prefix rule disambiguates a module from an item
+// and a `foo.rs` from a `foo/mod.rs`; std/super/external/glob are skipped, and an
+// unresolvable in-crate path is kept as a `crate::…` string, never guessed.
+test("breadth tier: Rust use crate::… resolves to the in-repo module (longest-prefix, drop-rather-than-guess)", async () => {
+ await warmGenericGrammars(["rust"]);
+ const files: Record<string, string> = {
+ "src/lib.rs": "pub mod error;\npub mod net;\n",
+ "src/error.rs": "pub struct Error;\n",
+ "src/net/mod.rs": "pub mod tcp;\n",
+ "src/net/tcp.rs": "pub struct Stream;\n",
+ "src/app.rs":
+ "use crate::error::Error;\n" + // item under a module → src/error.rs
+ "use crate::net::tcp::Stream;\n" + // nested module → src/net/tcp.rs
+ "use crate::net;\n" + // single-segment module → src/net/mod.rs
+ "use crate::missing::Thing;\n" + // in-crate but no such file → kept as string
+ "use std::io::Read;\n" + // external — skipped
+ "use super::sibling::Thing;\n" + // relative — skipped
+ "use serde::Serialize;\n" + // external crate — skipped
+ "fn go() {}\n",
+ // an integration test lives OUTSIDE the crate root (src/); its `crate::` is the test
+ // binary's own root, not the lib — so it must NOT resolve across to src/error.rs.
+ "tests/it.rs": "use crate::error::Error;\nfn t() {}\n",
+ };
+ const nodes = [], raw = [];
+ for (const [rel, src] of Object.entries(files)) {
+ const r = extractGeneric(rel, src, "rust");
+ nodes.push(...r.nodes); raw.push(...r.rawEdges);
+ }
+ const imports = resolveEdges(nodes, raw).filter((e) => e.relation === "imports" && e.source === "src/app.rs");
+ const targets = imports.map((e) => e.target).sort();
+
+ assert.ok(targets.includes("src/error.rs"), "crate::error::Error → error.rs");
+ assert.ok(targets.includes("src/net/tcp.rs"), "crate::net::tcp::Stream → net/tcp.rs");
+ assert.ok(targets.includes("src/net/mod.rs"), "crate::net (single-segment module) → net/mod.rs");
+ // in-crate but unresolvable → the full path kept as a string, never a guessed file edge
+ // (crucially NOT silently resolved to the crate-root lib.rs)
+ assert.ok(targets.includes("crate::missing::Thing"), "unresolved in-crate path kept as a string");
+ // std / super / external crate are not in-crate imports — no edge at all
+ assert.ok(!targets.some((t) => /io|sibling|serde|Read|Serialize/.test(t)), "external/relative use skipped");
+ assert.equal(imports.length, 4, "exactly the 4 crate:: uses became edges");
+
+ // an integration test's `crate::error::Error` must NOT cross into src/error.rs — its
+ // crate root is unknown (it's the test binary), so it stays a string, never a false edge
+ const fromTest = resolveEdges(nodes, raw).filter((e) => e.relation === "imports" && e.source === "tests/it.rs");
+ assert.deepEqual(fromTest.map((e) => e.target), ["crate::error::Error"], "test-binary crate:: never resolves into the lib");
+});
+
test("buildGraph + checkGraph handle a breadth-tier (.rs) repo end-to-end", async () => {
const dir = mkdtempSync(join(tmpdir(), "graft-rust-"));
mkdirSync(join(dir, "src"), { recursive: true });