Explorar o código

feat(kernel): R7b Rust walker — rustlang module, tree-sitter-rust 0.24.2 bump, rust default-routed (#1371)

First R7b language port. Grammar: tree-sitter-rust pinned =0.24.2 + wasm
vendored from tag 77a3747 (parser.c/scanner.c sha-matched against the
crates.io tarball), replacing the 2023 ABI-14 tree-sitter-wasms build —
the bump alone is precision-positive on the wasm path (receiver-qualified
instance-method resolutions replace ambiguous bare-name matches; node
sections byte-identical on ripgrep/tokio).

Walker mirrors the TS reference bug-for-bug per
docs/design/rust-lang-kernel-port-checklist.md (survey artifact): dead-code
isAsync, impl-pushes-no-scope, the impl-Trait-for-Generic<T> trait-receiver
quirk, phantom const identifiers, use-binding triple emission,
wildcard-use-emits-nothing, scoped-supertrait drop, chained-call re-encode
gated on scoped_identifier, Rocket route macros body-only.

Gates: parity sweeps 0 diffs — ripgrep 101/101, tokio 790/790,
rust-analyzer 1217/1488 (271 deferrals are token-macro-table sources that
error on BOTH arms — grammar-inherent); full-init dump-diffs byte-identical
on all three (3,857 / 13,440 / 39,030 nodes); kernel-rustlang-parity suite
(torture + CRLF + defer) in npm test; full suite green x2 with
CODEGRAPH_KERNEL_EXPECT=1.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Colby Mchenry hai 1 mes
pai
achega
f1ca991943

+ 2 - 1
CHANGELOG.md

@@ -11,7 +11,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
 
 ### New Features
 
-- Indexing TypeScript, TSX, JavaScript, JSX, Java, Python, Go, C, and C++ projects is faster: parsing and symbol extraction now run in a native engine when a prebuilt binary is available for your platform (release bundles include one), producing exactly the same graph — verified byte-for-byte against the previous engine on real repositories, from small libraries up to vscode-, dubbo-, django-, git-, and protobuf-scale codebases (Lombok-generated members, C function-pointer tables, and Unreal-Engine-style macro-heavy headers included; CUDA and Metal sources ride the C++ path). The speedup is largest on resource-constrained machines like CI runners. No setup needed: platforms without the native binary, and individual files with syntax errors, automatically use the previous engine, and `CODEGRAPH_KERNEL=0` turns the native path off entirely.
+- Indexing TypeScript, TSX, JavaScript, JSX, Java, Python, Go, C, C++, and Rust projects is faster: parsing and symbol extraction now run in a native engine when a prebuilt binary is available for your platform (release bundles include one), producing exactly the same graph — verified byte-for-byte against the previous engine on real repositories, from small libraries up to vscode-, dubbo-, django-, git-, protobuf-, tokio-, and rust-analyzer-scale codebases (Lombok-generated members, C function-pointer tables, and Unreal-Engine-style macro-heavy headers included; CUDA and Metal sources ride the C++ path). The speedup is largest on resource-constrained machines like CI runners. No setup needed: platforms without the native binary, and individual files with syntax errors, automatically use the previous engine, and `CODEGRAPH_KERNEL=0` turns the native path off entirely.
 - Reference resolution now runs in parallel on large projects. When a project has enough pending references to make it worthwhile (roughly 150k+, typical for big Java/Kotlin/Spring codebases), resolution fans out across worker threads while results are applied in the exact order the single-threaded path would have used — the graph comes out byte-for-byte identical, about twice as fast end-to-end on a 4,000-file Java project in our testing. Small projects keep the single-threaded path automatically (the fan-out costs more than it saves there). Set `CODEGRAPH_NO_PARALLEL_RESOLVE=1` to disable, or `CODEGRAPH_PARALLEL_RESOLVE_MIN=<count>` to tune when it engages.
 - Indexing large projects got another sizeable speedup — about a quarter less wall-clock on the same 4,000-file Java project, with the graph still byte-for-byte identical. Two changes: the database no longer interleaves expensive checkpoint housekeeping into the middle of resolution on a fresh index (it's folded once at the end instead), and while one batch's results are being written out, the worker threads are already resolving the next batch instead of sitting idle.
 - The dynamic-dispatch analysis that runs at the end of indexing (callback, event, and framework wiring) now runs its passes in parallel on large projects, cutting that stage roughly in half there — and a pass that crashes now retries safely instead of failing the whole index, which also makes very large codebases that previously died in this stage more likely to index to completion. Graphs remain byte-for-byte identical.
@@ -28,6 +28,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
 ### Fixes
 
 - TypeScript, TSX, and JavaScript files now parse with up-to-date grammars — modern syntax such as `using` declarations and import attributes no longer trips parse errors that could drop surrounding symbols. (The previously bundled grammars dated from 2023.)
+- Rust files also parse with an up-to-date grammar now (the previously bundled build dated from 2023), which additionally sharpens method-call attribution: calls through struct fields resolve with receiver context instead of falling back to ambiguous bare-name matching, removing a class of wrong call edges on common names like `len` and `start`.
 - Searching or exploring by field names now finds the code that defines them. A query made of object keys or API field names (`profileInfo isTrialEligible quotaInfo billingMethod`) used to return unrelated results while the defining files never appeared, because three retrieval steps each dropped multi-word camelCase terms: an internal case-comparison bug, a match step that only considered classes (never functions or methods), and exploration seeding that required exact symbol-name matches. All three are fixed — `codegraph_explore` with a bag of field names now surfaces the controllers and services that assemble those fields. (#1196)
 - `codegraph.json`'s `includeIgnored` works again for the "folder of repos" layout: when one `.gitignore` rule covers a parent directory (`/repos/`) holding several embedded git repositories, opting in the individual repos (`"includeIgnored": ["repos/a/"]` — the exact spelling `codegraph init`'s own hint suggests) previously matched nothing and indexed zero files, looping the same suggestion back at you. Both spellings now work — name the parent directory to opt in everything under it, or name individual repos to opt in just those — and the hint no longer re-suggests repos that are already configured. (#1295)
 - Method calls on literals (`", ".join(...)` in Python, `"x".split(...)` in JavaScript, and the like) no longer produce call edges to unrelated project functions that happen to share the builtin's name — a codebase with a function called `join`, `get`, or `update` could show phantom callers from every string-builtin use. Additionally, a function nested inside another function is now only matched as a call target from inside its container, since it isn't reachable from anywhere else. Blast-radius and affected-test results get cleaner on Python and JavaScript codebases especially. (#1230)

+ 211 - 0
__tests__/fixtures/kernel-parity/torture.rs

@@ -0,0 +1,211 @@
+//! Torture fixture for the rust kernel walker (R7b) — every quirk in
+//! docs/design/rust-lang-kernel-port-checklist.md, parse-clean.
+
+use std::fmt;
+use crate::mod_a::Item;
+use crate::mod_b::{A, B as C, sub::D};
+use a::{b::{c, d}};
+use foo_single;
+use std::collections::*;
+
+/// Widget docs.
+pub struct Widget {
+    pub n: u32,
+    name: String,
+    field: Deep,
+}
+
+pub struct Unit;
+
+pub struct Pair(u32, u32);
+
+/// Doc broken by the attribute below — must yield NO docstring.
+#[derive(Debug)]
+pub struct Doc {
+    x: u32,
+}
+
+pub struct Deep {
+    z: u32,
+}
+
+pub enum Shape {
+    Circle(f32),
+    Rect { w: f32, h: f32 },
+    Empty,
+}
+
+pub type Alias = Vec<Widget>;
+
+/// Render trait docs.
+pub trait Render: Base + fmt::Debug {
+    fn render(&self);
+    fn hint(&self) -> Size {
+        Size::default()
+    }
+    const CAP: usize = init_cap();
+    type Output;
+}
+
+pub trait Base {}
+
+pub trait Super2: Producer<u32> {}
+
+pub trait Owned: for<'de> Deserialize<'de> {}
+
+impl Render for Widget {
+    fn render(&self) {
+        draw(self);
+    }
+}
+
+impl fmt::Display for Widget {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(f, "w{}", self.n)
+    }
+}
+
+impl Widget {
+    const SCALE: usize = 3;
+
+    fn area(&self) -> u32 {
+        self.n * mul()
+    }
+
+    fn clone_self(&self) -> Self {
+        Self::assoc();
+        Widget {
+            n: self.n,
+            name: String::new(),
+            field: Deep { z: 0 },
+        }
+    }
+
+    fn borrow_widget(&self) -> &Widget {
+        self
+    }
+
+    fn outer(&self) -> u32 {
+        fn inner_helper(v: u32) -> u32 {
+            v
+        }
+        inner_helper(self.n)
+    }
+}
+
+pub struct Container<T> {
+    item: T,
+}
+
+impl<T> Container<T> {
+    fn unwrap(self) -> T {
+        self.item
+    }
+}
+
+impl Render for Container<u32> {
+    fn render(&self) {}
+}
+
+impl Later {
+    fn touch(&self) {}
+}
+
+pub struct Later {
+    z: u32,
+}
+
+/* Block-doc for an async fn — isAsync must stay FALSE (dead-code hook). */
+pub async fn fetch_data(url: &str) -> Result<Response, Error> {
+    let body = get(url).await;
+    client.request().await.send();
+    body
+}
+
+pub fn nested_ret() -> Result<Vec<Widget>, Error> {
+    make_result()
+}
+
+pub fn vec_ret(w: &Widget) -> Vec<Widget> {
+    build_list(w)
+}
+
+pub(crate) fn crate_fn() {}
+
+fn caller() {
+    let w = Widget {
+        n: 1,
+        name: make_name(),
+        field: Deep { z: 1 },
+    };
+    let v = m::Widget { n: 2 };
+    let r = Foo::new().bar();
+    let x = w.method_a().chain_b();
+    let y = w.field.deep_call();
+    let s = "lit".len();
+    let f = 5.0_f64.floor();
+    helper();
+    m::helper2();
+    let t = helper::<u32>(3);
+    (helper)(1);
+    takes(Widget {
+        n: 3,
+        name: n2(),
+        field: Deep { z: 2 },
+    });
+}
+
+fn handler() {}
+fn handler2() {}
+fn cb_a() {}
+fn cb_b() {}
+fn invoke_all(fns: [fn(); 2]) {}
+
+fn register(f: fn()) {
+    f();
+}
+
+pub struct Holder {
+    cb: fn(),
+}
+
+fn wiring(mut o: Holder) {
+    register(handler);
+    o.cb = handler2;
+    let h = Holder { cb: cb_a };
+    let arr = [cb_a, cb_b];
+    let local = handler;
+    let (t1, t2) = (cb_a, cb_b);
+    invoke_all(arr);
+    invoke(foo_single);
+}
+
+static CB: fn() = handler;
+
+const MAX_LIMIT: u32 = OTHER_LIMIT;
+const OTHER_LIMIT: u32 = 99;
+
+fn reads_limits() -> u32 {
+    MAX_LIMIT + OTHER_LIMIT
+}
+
+fn shadowed_read() {
+    let MAX_LIMIT = 5;
+    let _ = MAX_LIMIT;
+}
+
+mod inner {
+    pub fn helper_pub() {}
+    fn hidden() {}
+    pub struct Item2 {
+        pub v: u32,
+    }
+}
+
+fn mount() {
+    let r = routes![a::b::index_h, health_h];
+    let c = catchers![not_found_h];
+    let skipped = rocket::routes![a::x];
+}
+
+routes![top_level_h];

+ 1 - 1
__tests__/kernel-grammar-parity.test.ts

@@ -36,7 +36,7 @@ const kernelBuilt = fs.existsSync(KERNEL_PATH);
 
 // Every kernel-capable language. `jsx` shares the javascript grammar on BOTH
 // paths (langs.rs mirrors WASM_GRAMMAR_FILES), so the distinct grammars are:
-const GRAMMAR_LANGUAGES: Language[] = ['typescript', 'tsx', 'javascript', 'java', 'python', 'go', 'c', 'cpp'];
+const GRAMMAR_LANGUAGES: Language[] = ['typescript', 'tsx', 'javascript', 'java', 'python', 'go', 'c', 'cpp', 'rust'];
 
 describe.skipIf(!kernelBuilt)('kernel↔wasm grammar parity', () => {
   beforeAll(async () => {

+ 117 - 0
__tests__/kernel-rustlang-parity.test.ts

@@ -0,0 +1,117 @@
+/**
+ * Kernel↔wasm Rust extraction parity (R7b of the kernel migration).
+ *
+ * Asserts the native walker (codegraph-kernel/src/rustlang.rs) produces the
+ * SAME ExtractionResult as the wasm TreeSitterExtractor — nodes, edges, and
+ * unresolved refs compared as canonicalized multisets — over the checked-in
+ * torture fixture (torture.rs: impl/trait quirks incl. the
+ * `impl Trait for Generic<T>` trait-receiver bug, unit-struct skip, phantom
+ * const identifiers, use-binding refs incl. nested groups + wildcard-emits-
+ * nothing, chained-call re-encode, turbofish, Rocket route macros body-only,
+ * fn-ref shapes, value-ref shadowing, attribute-broken docstrings, dead-code
+ * isAsync) and its CRLF variant (derived in-memory — #1329 docstring
+ * semantics).
+ *
+ * The full-repo sweep lives in scripts/kernel-parity.mjs (ripgrep/tokio/
+ * rust-analyzer for the §5 gate); this suite keeps the invariant alive in
+ * `npm test`. Skips when no kernel binary is staged; CODEGRAPH_KERNEL_EXPECT=1
+ * turns that into a failure (kernel-scaffold.test.ts).
+ */
+
+import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
+import * as fs from 'fs';
+import * as path from 'path';
+import { extractFromSource } from '../src/extraction';
+import { initGrammars, loadGrammarsForLanguages } from '../src/extraction/grammars';
+import { tryKernelExtract, resetKernelForTests } from '../src/extraction/kernel';
+import type { ExtractionResult } from '../src/types';
+
+const KERNEL_PATH = path.join(
+  __dirname,
+  '..',
+  'codegraph-kernel',
+  'prebuilds',
+  `${process.platform}-${process.arch}`,
+  'codegraph-kernel.node'
+);
+const kernelBuilt = fs.existsSync(KERNEL_PATH);
+
+const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'kernel-parity');
+
+function canon(result: ExtractionResult): { nodes: string[]; edges: string[]; refs: string[] } {
+  return {
+    nodes: result.nodes
+      .map(({ updatedAt: _u, ...n }) => JSON.stringify(n, Object.keys(n).sort()))
+      .sort(),
+    edges: result.edges.map((e) => JSON.stringify(e, Object.keys(e).sort())).sort(),
+    refs: result.unresolvedReferences
+      .map((r) => JSON.stringify(r, Object.keys(r).sort()))
+      .sort(),
+  };
+}
+
+const ENV_KEYS = ['CODEGRAPH_KERNEL', 'CODEGRAPH_KERNEL_LANGS'] as const;
+let savedEnv: Record<string, string | undefined>;
+
+describe.skipIf(!kernelBuilt)('kernel Rust extraction parity', () => {
+  beforeAll(async () => {
+    await initGrammars();
+    await loadGrammarsForLanguages(['rust']);
+  });
+
+  beforeEach(() => {
+    savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
+    resetKernelForTests();
+  });
+
+  afterEach(() => {
+    for (const k of ENV_KEYS) {
+      if (savedEnv[k] === undefined) delete process.env[k];
+      else process.env[k] = savedEnv[k];
+    }
+    resetKernelForTests();
+  });
+
+  function assertParity(filePath: string, source: string, minNodes = 3): void {
+    process.env.CODEGRAPH_KERNEL_LANGS = 'all';
+    delete process.env.CODEGRAPH_KERNEL;
+    const viaKernel = tryKernelExtract(filePath, source, 'rust');
+    expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
+
+    process.env.CODEGRAPH_KERNEL = '0';
+    const viaWasm = extractFromSource(filePath, source, 'rust');
+    delete process.env.CODEGRAPH_KERNEL;
+
+    const k = canon(viaKernel!);
+    const w = canon(viaWasm);
+    expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes);
+    expect(k.edges, `${filePath}: edges`).toEqual(w.edges);
+    expect(k.refs, `${filePath}: refs`).toEqual(w.refs);
+    expect(viaWasm.nodes.length).toBeGreaterThanOrEqual(minNodes);
+  }
+
+  it('torture fixture: impl/trait quirks, use bindings, chains, fn-refs, value-refs, route macros', () => {
+    const file = path.join(FIXTURE_DIR, 'torture.rs');
+    assertParity('fixtures/torture.rs', fs.readFileSync(file, 'utf8'), 20);
+  });
+
+  // CRLF variant — the shape every Windows autocrlf checkout has. Derived in
+  // memory so no platform or editor can silently normalize it away; pins the
+  // JS-multiline-^ docstring semantics for `///` runs (#1329).
+  it('torture fixture CRLF parity', () => {
+    const file = path.join(FIXTURE_DIR, 'torture.rs');
+    const crlf = fs.readFileSync(file, 'utf8').replace(/(?<!\r)\n/g, '\r\n');
+    assertParity('fixtures/torture.rs (crlf)', crlf, 20);
+  });
+
+  it('files with parse errors defer to the wasm extractor (recovery is encoding-dependent)', () => {
+    const broken = 'fn f( {\n  return }} 12 (\n';
+    process.env.CODEGRAPH_KERNEL_LANGS = 'all';
+    delete process.env.CODEGRAPH_KERNEL;
+    expect(tryKernelExtract('src/broken.rs', broken, 'rust')).toBeNull();
+    process.env.CODEGRAPH_KERNEL = '0';
+    const viaWasm = extractFromSource('src/broken.rs', broken, 'rust');
+    delete process.env.CODEGRAPH_KERNEL;
+    expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
+  });
+});

+ 11 - 0
codegraph-kernel/Cargo.lock

@@ -58,6 +58,7 @@ dependencies = [
  "tree-sitter-java",
  "tree-sitter-javascript",
  "tree-sitter-python",
+ "tree-sitter-rust",
  "tree-sitter-typescript",
 ]
 
@@ -550,6 +551,16 @@ dependencies = [
  "tree-sitter-language",
 ]
 
+[[package]]
+name = "tree-sitter-rust"
+version = "0.24.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "439e577dbe07423ec2582ac62c7531120dbfccfa6e5f92406f93dd271a120e45"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
 [[package]]
 name = "tree-sitter-typescript"
 version = "0.23.2"

+ 1 - 0
codegraph-kernel/Cargo.toml

@@ -30,6 +30,7 @@ tree-sitter-go = "0.23"
 # (R7a prep, #1345). A patch bump here without re-vendoring breaks the match.
 tree-sitter-c = "=0.24.2"
 tree-sitter-cpp = "=0.23.4"
+tree-sitter-rust = "=0.24.2"
 
 [build-dependencies]
 napi-build = "2"

+ 4 - 2
codegraph-kernel/src/langs.rs

@@ -15,8 +15,8 @@ use tree_sitter::Language;
 
 /// Languages this kernel binary can extract (reported by contractInfo;
 /// TS-side routing policy decides what actually routes).
-pub const LANGUAGES: [&str; 9] =
-    ["typescript", "tsx", "javascript", "jsx", "java", "python", "go", "c", "cpp"];
+pub const LANGUAGES: [&str; 10] =
+    ["typescript", "tsx", "javascript", "jsx", "java", "python", "go", "c", "cpp", "rust"];
 
 pub fn grammar_for(language: &str) -> Option<Language> {
     match language {
@@ -31,6 +31,8 @@ pub fn grammar_for(language: &str) -> Option<Language> {
         // TS-side — the route point applies preParse before the kernel call).
         "c" => Some(tree_sitter_c::LANGUAGE.into()),
         "cpp" => Some(tree_sitter_cpp::LANGUAGE.into()),
+        // R7b: v0.24.2, sha-matched with the vendored wasm (grammars.ts).
+        "rust" => Some(tree_sitter_rust::LANGUAGE.into()),
         _ => None,
     }
 }

+ 2 - 0
codegraph-kernel/src/lib.rs

@@ -24,6 +24,7 @@ mod ids;
 mod go;
 mod java;
 mod langs;
+mod rustlang;
 mod textutil;
 mod python;
 mod tsjs;
@@ -211,6 +212,7 @@ pub fn extract_file(file_path: String, content: String, language: String) -> Res
         "python" => python::extract(&file_path, &content).map_err(Error::from_reason)?,
         "go" => go::extract(&file_path, &content).map_err(Error::from_reason)?,
         "c" | "cpp" => ccpp::extract(&file_path, &content, &language).map_err(Error::from_reason)?,
+        "rust" => rustlang::extract(&file_path, &content).map_err(Error::from_reason)?,
         _ => tsjs::extract(&file_path, &content, &language).map_err(Error::from_reason)?,
     };
     Ok(ExtractBuffers {

+ 1474 - 0
codegraph-kernel/src/rustlang.rs

@@ -0,0 +1,1474 @@
+//! Rust-language extraction — a faithful port of `TreeSitterExtractor`'s rust
+//! paths (src/extraction/tree-sitter.ts) plus languages/rust.ts. ("rustlang"
+//! because `rust` alone collides with the kernel's own implementation
+//! language.) Survey artifact: docs/design/rust-lang-kernel-port-checklist.md.
+//!
+//! Rust's shape quirks, mirrored exactly (bug-for-bug, all verified against
+//! the TS reference):
+//! - `isAsync` is dead code upstream: it scans DIRECT children for an `async`
+//!   token, but the grammar nests it inside `function_modifiers` — every rust
+//!   fn/method carries isAsync **false** (present-false, never absent).
+//! - impl blocks push NO scope: members re-dispatch at file scope, so an impl
+//!   associated `const` becomes a FILE-level `variable`, and the method↔owner
+//!   `contains` edge is a source-order name scan (an impl ABOVE its struct
+//!   gets no edge). `impl Trait for Generic<T>`'s receiver resolves to the
+//!   TRAIT (the only direct type_identifier), and methods get QN
+//!   `Trait::method` — preserve, never "fix" via the grammar's trait:/type:
+//!   fields.
+//! - `const_item`/`static_item` ride the generic extractVariable fallback:
+//!   kind is always `variable`, no signature, and EVERY direct `identifier`
+//!   child mints a node (`const MAX: u32 = OTHER;` → two nodes, `MAX` + the
+//!   phantom `OTHER`). Top-level initializer values are never body-walked.
+//! - Unit structs (`struct Unit;`, no body field) mint NO node; `mod_item`
+//!   mints no module node and adds no QN prefix.
+//! - Chained-call re-encode is scoped_identifier-gated (`Foo::new().bar()` →
+//!   `Foo::new().bar`); instance chains, parens, `.await`, 2-hop fields, and
+//!   `self` receivers all collapse to the bare method name (`self` is node
+//!   kind `self`, not `identifier`, so it dodges SKIP_RECEIVERS by falling
+//!   through). Turbofish callees keep the raw `helper::<T>` text.
+//! - `use` emits an import node named by the ROOT module (`crate`/`self`/…),
+//!   one root `imports` ref, then one FULL-path `imports` ref per binding;
+//!   `use x::*` (use_wildcard) emits nothing at all.
+//! - Trait supertraits come only from `trait_bounds`; a scoped supertrait
+//!   (`fmt::Debug`) matches no case and is silently dropped.
+//! - Rocket `routes!`/`catchers!` are extracted ONLY inside function bodies,
+//!   and only when the macro name is a bare identifier.
+//! - A rust type alias emits NO ref to its aliased type (the shared code
+//!   reads a `value` field; rust's field is `type`).
+//! - An `attribute_item` between a doc comment and its item breaks the
+//!   docstring sibling chain (`#[derive(..)]` kills the docstring).
+//! Files with parse errors defer to wasm.
+
+use crate::buffers::{
+    build_meta, edge_kind_index, node_kind_index, Arena, BoolFlags, EdgeRow, EmitOut, NodeRow,
+    RefRow, StrRef, Tables, FLAG_IS_ASYNC, FLAG_IS_EXPORTED, FUNCTION_REF_CODE, NONE, NONE_STR,
+};
+use crate::docstring::preceding_docstring;
+use crate::ids;
+use crate::textutil as util;
+use regex::Regex;
+use std::collections::{HashMap, HashSet};
+use std::sync::OnceLock;
+use tree_sitter::{Node, Parser};
+
+const MAX_VALUE_REF_NODES: usize = 20_000;
+
+/// JS `/<[^>]*>/g` — the non-nested generic strip (breaks on nested generics
+/// by design: `Result<Vec<Foo>, E>` → `Result, E>` → returnType undefined).
+fn generic_angle_re() -> &'static Regex {
+    static RE: OnceLock<Regex> = OnceLock::new();
+    RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
+}
+/// JS `/^[A-Za-z_]\w*$/` (ASCII \w — the regex crate's \w is Unicode).
+fn simple_ident_re() -> &'static Regex {
+    static RE: OnceLock<Regex> = OnceLock::new();
+    RE.get_or_init(|| Regex::new(r"^[A-Za-z_][0-9A-Za-z_]*$").unwrap())
+}
+
+struct Scope {
+    row: u32,
+    kind: &'static str,
+    name: String,
+}
+
+#[derive(Default)]
+struct Extra {
+    docstring: Option<String>,
+    signature: Option<String>,
+    return_type: Option<String>,
+    qualified_name: Option<String>,
+    visibility: Option<u8>,
+    is_exported: Option<bool>,
+    is_async: Option<bool>,
+}
+
+struct ValueScope<'t> {
+    row: u32,
+    node: Node<'t>,
+    name: String,
+}
+
+struct Cand {
+    from: u32,
+    name: String,
+    line: u32,
+    column_byte: usize,
+    row: usize,
+}
+
+/// Per-node metadata for the receiver-method owner lookup and
+/// findNodeByName (mirrors the TS scans over `this.nodes` — FIRST match
+/// wins, earlier-in-file only).
+struct NodeMeta {
+    kind: &'static str,
+    name: String,
+}
+
+pub struct Walker<'t> {
+    src: &'t str,
+    file_path: &'t str,
+    line_starts: Vec<usize>,
+    arena: Arena,
+    tables: Tables,
+    stack: Vec<Scope>,
+    nodes_meta: Vec<NodeMeta>,
+    node_ids: Vec<String>,
+    defined_fn_names: HashSet<String>,
+    imported_names: HashSet<String>,
+    fn_ref_cands: Vec<Cand>,
+    fs_values: HashMap<String, u32>,
+    fs_value_counts: HashMap<String, u32>,
+    value_scopes: Vec<ValueScope<'t>>,
+}
+
+pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
+    let grammar = crate::langs::grammar_for("rust").ok_or("no rust grammar")?;
+    let t0 = std::time::Instant::now();
+    let mut parser = Parser::new();
+    parser
+        .set_language(&grammar)
+        .map_err(|e| format!("set_language(rust) failed: {e}"))?;
+    let tree = parser
+        .parse(source, None)
+        .ok_or_else(|| "parser returned null tree".to_string())?;
+    if tree.root_node().has_error() {
+        return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
+    }
+
+    let mut w = Walker {
+        src: source,
+        file_path,
+        line_starts: util::line_starts(source),
+        arena: Arena::default(),
+        tables: Tables::default(),
+        stack: Vec::new(),
+        nodes_meta: Vec::new(),
+        node_ids: Vec::new(),
+        defined_fn_names: HashSet::new(),
+        imported_names: HashSet::new(),
+        fn_ref_cands: Vec::new(),
+        fs_values: HashMap::new(),
+        fs_value_counts: HashMap::new(),
+        value_scopes: Vec::new(),
+    };
+
+    let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
+    let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
+    let mut flags = BoolFlags::default();
+    flags.set(FLAG_IS_EXPORTED, false);
+    let file_id = w.arena.put(&ids::file_node_id(file_path));
+    let name_ref = w.arena.put(base_name);
+    let qn_ref = w.arena.put(file_path);
+    w.tables.push_node(&NodeRow {
+        kind: node_kind_index("file").unwrap(),
+        visibility: 0,
+        flags,
+        start_line: 1,
+        end_line: line_count,
+        start_column: 0,
+        end_column: 0,
+        name: name_ref,
+        qualified_name: qn_ref,
+        id: file_id,
+        docstring: NONE_STR,
+        signature: NONE_STR,
+        decorators: NONE_STR,
+        type_parameters: NONE_STR,
+        return_type: NONE_STR,
+        extra_json: NONE_STR,
+    });
+    w.nodes_meta.push(NodeMeta { kind: "file", name: base_name.to_string() });
+    w.node_ids.push(ids::file_node_id(file_path));
+    w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
+
+    w.visit_node(tree.root_node());
+    w.flush_fn_ref_candidates();
+    w.flush_value_refs(tree.root_node());
+    w.stack.pop();
+
+    let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
+    let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
+    Ok(EmitOut {
+        meta,
+        nodes: w.tables.nodes,
+        edges: w.tables.edges,
+        refs: w.tables.refs,
+        arena: w.arena.into_vec(),
+    })
+}
+
+impl<'t> Walker<'t> {
+    fn text(&self, node: Node) -> &'t str {
+        &self.src[node.byte_range()]
+    }
+    fn line_of(&self, node: Node) -> u32 {
+        node.start_position().row as u32 + 1
+    }
+    fn col_of(&self, node: Node) -> u32 {
+        util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
+    }
+    fn end_col_of(&self, node: Node) -> u32 {
+        util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
+    }
+    fn top_row(&self) -> u32 {
+        self.stack.last().map(|s| s.row).unwrap_or(0)
+    }
+    /// isInsideClassLikeNode — stack TOP only, file doesn't count.
+    fn inside_class_like(&self) -> bool {
+        self.stack
+            .last()
+            .map(|s| matches!(s.kind, "class" | "struct" | "interface" | "trait" | "enum" | "module"))
+            .unwrap_or(false)
+    }
+
+    fn push_ref_at(&mut self, from_row: u32, name: &str, kind_code: u8, node: Node) {
+        let name_ref = self.arena.put(name);
+        self.tables.push_ref(&RefRow {
+            from_idx: from_row,
+            kind: kind_code,
+            line: self.line_of(node),
+            column: self.col_of(node),
+            reference_name: name_ref,
+            candidates: NONE_STR,
+            from_id_str: NONE_STR,
+        });
+        if kind_code == edge_kind_index("imports").unwrap() {
+            if util::simple_name().is_match(name) {
+                self.imported_names.insert(name.to_string());
+            } else if let Some(c) = util::qualified_import().captures(name) {
+                // `::`-separated rust paths match NEITHER regex (separators are
+                // `.`/`\`), so multi-segment use-imports contribute nothing to
+                // the fn-ref gate — the rust gate is effectively same-file-only.
+                self.imported_names.insert(c[1].to_string());
+            }
+        }
+    }
+
+    fn create_node(&mut self, kind: &'static str, name: &str, node: Node<'t>, extra: Extra) -> Option<u32> {
+        if name.is_empty() {
+            return None;
+        }
+        let start_line = self.line_of(node);
+        let id = ids::node_id(self.file_path, kind, name, start_line);
+        let end_line = node.end_position().row as u32 + 1;
+
+        let qualified = extra.qualified_name.unwrap_or_else(|| {
+            let mut parts: Vec<&str> = Vec::new();
+            for s in &self.stack {
+                if s.kind != "file" {
+                    parts.push(&s.name);
+                }
+            }
+            let mut qn = parts.join("::");
+            if !qn.is_empty() {
+                qn.push_str("::");
+            }
+            qn.push_str(name);
+            qn
+        });
+
+        let mut flags = BoolFlags::default();
+        if let Some(v) = extra.is_exported {
+            flags.set(FLAG_IS_EXPORTED, v);
+        }
+        if let Some(v) = extra.is_async {
+            flags.set(FLAG_IS_ASYNC, v);
+        }
+        let name_ref = self.arena.put(name);
+        let qn_ref = self.arena.put(&qualified);
+        let id_ref = self.arena.put(&id);
+        let doc_ref = opt_str(&mut self.arena, extra.docstring.as_deref());
+        let sig_ref = opt_str(&mut self.arena, extra.signature.as_deref());
+        let ret_ref = opt_str(&mut self.arena, extra.return_type.as_deref());
+        let row = self.tables.push_node(&NodeRow {
+            kind: node_kind_index(kind).unwrap(),
+            visibility: extra.visibility.unwrap_or(0),
+            flags,
+            start_line,
+            end_line,
+            start_column: self.col_of(node),
+            end_column: self.end_col_of(node),
+            name: name_ref,
+            qualified_name: qn_ref,
+            id: id_ref,
+            docstring: doc_ref,
+            signature: sig_ref,
+            decorators: NONE_STR,
+            type_parameters: NONE_STR,
+            return_type: ret_ref,
+            extra_json: NONE_STR,
+        });
+        self.nodes_meta.push(NodeMeta { kind, name: name.to_string() });
+        self.node_ids.push(id);
+
+        let parent_row = self.top_row();
+        self.tables.push_edge(&EdgeRow {
+            source_idx: parent_row,
+            target_idx: row,
+            kind: edge_kind_index("contains").unwrap(),
+            provenance: 0,
+            line: NONE,
+            column: NONE,
+            metadata_json: NONE_STR,
+            source_id_str: NONE_STR,
+            target_id_str: NONE_STR,
+        });
+
+        if kind == "function" || kind == "method" {
+            self.defined_fn_names.insert(name.to_string());
+        }
+        // captureValueRefScope: rust consts are kind `variable` — still targets.
+        let target_kind_ok = kind == "constant" || kind == "variable";
+        if target_kind_ok
+            && util::utf16_len(name) >= 3
+            && util::has_upper_or_underscore().is_match(name)
+        {
+            let parent_ok = self
+                .stack
+                .last()
+                .map(|s| matches!(s.kind, "file" | "class" | "module" | "struct" | "enum"))
+                .unwrap_or(false);
+            if parent_ok {
+                self.fs_values.insert(name.to_string(), row);
+                *self.fs_value_counts.entry(name.to_string()).or_insert(0) += 1;
+            }
+        }
+        if matches!(kind, "function" | "method" | "constant" | "variable") {
+            self.value_scopes.push(ValueScope { row, node, name: name.to_string() });
+        }
+        Some(row)
+    }
+
+    /// extractName — nameField `name`, else the identifier-like child scan.
+    fn extract_name(&self, node: Node) -> String {
+        if let Some(name_node) = node.child_by_field_name("name") {
+            return self.text(name_node).to_string();
+        }
+        for i in 0..node.named_child_count() {
+            if let Some(c) = node.named_child(i) {
+                if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") {
+                    return self.text(c).to_string();
+                }
+            }
+        }
+        "<anonymous>".to_string()
+    }
+
+    /// rustExtractor.getSignature: raw params text + ` -> ` + raw return type.
+    fn signature_of(&self, node: Node) -> Option<String> {
+        let params = node.child_by_field_name("parameters")?;
+        let mut sig = self.text(params).to_string();
+        if let Some(rt) = node.child_by_field_name("return_type") {
+            sig.push_str(" -> ");
+            sig.push_str(self.text(rt));
+        }
+        Some(sig)
+    }
+
+    /// rustExtractor.getVisibility: direct `visibility_modifier` child whose
+    /// text contains `pub` → public, else private; none → private.
+    fn visibility_of(&self, node: Node) -> u8 {
+        for i in 0..node.child_count() {
+            if let Some(c) = node.child(i) {
+                if c.kind() == "visibility_modifier" {
+                    return if self.text(c).contains("pub") { 1 } else { 2 };
+                }
+            }
+        }
+        2 // private — Rust defaults to private
+    }
+
+    /// extractRustReturnType (languages/rust.ts:14).
+    fn return_type_of(&self, node: Node) -> Option<String> {
+        let mut rt = node.child_by_field_name("return_type")?;
+        if rt.kind() == "reference_type" {
+            rt = (0..rt.named_child_count())
+                .filter_map(|i| rt.named_child(i))
+                .find(|c| matches!(c.kind(), "type_identifier" | "scoped_type_identifier" | "generic_type"))
+                .unwrap_or(rt);
+        }
+        if matches!(rt.kind(), "primitive_type" | "unit_type" | "tuple_type") {
+            return None;
+        }
+        let text = self.text(rt).trim();
+        let stripped = generic_angle_re().replace_all(text, "");
+        let last = stripped.rsplit("::").next().unwrap_or("").trim();
+        if last.is_empty() || !simple_ident_re().is_match(last) {
+            return None;
+        }
+        Some(if last == "Self" { "self".to_string() } else { last.to_string() })
+    }
+
+    /// rustExtractor.getReceiverType: parent-walk to the nearest impl_item;
+    /// LAST direct type_identifier child wins (for `impl Trait for Generic<T>`
+    /// that's the TRAIT — bug preserved); else the first generic_type's inner
+    /// type_identifier.
+    fn receiver_type_of(&self, node: Node) -> Option<String> {
+        let mut parent = node.parent();
+        while let Some(p) = parent {
+            if p.kind() == "impl_item" {
+                let type_idents: Vec<Node> = (0..p.named_child_count())
+                    .filter_map(|i| p.named_child(i))
+                    .filter(|c| c.kind() == "type_identifier")
+                    .collect();
+                if let Some(last) = type_idents.last() {
+                    return Some(self.text(*last).to_string());
+                }
+                let generic = (0..p.named_child_count())
+                    .filter_map(|i| p.named_child(i))
+                    .find(|c| c.kind() == "generic_type");
+                if let Some(g) = generic {
+                    let inner = (0..g.named_child_count())
+                        .filter_map(|i| g.named_child(i))
+                        .find(|c| c.kind() == "type_identifier");
+                    if let Some(inner) = inner {
+                        return Some(self.text(inner).to_string());
+                    }
+                }
+                return None;
+            }
+            parent = p.parent();
+        }
+        None
+    }
+
+    // --- visitNode ------------------------------------------------------------
+
+    fn visit_node(&mut self, node: Node<'t>) {
+        let kind = node.kind();
+        let mut skip_children = false;
+
+        self.maybe_capture_fn_refs(node);
+
+        if matches!(kind, "function_item" | "function_signature_item") {
+            self.extract_fn_or_method(node);
+            skip_children = true;
+        } else if kind == "trait_item" {
+            self.extract_interface(node);
+            skip_children = true;
+        } else if kind == "struct_item" {
+            self.extract_struct(node);
+            skip_children = true;
+        } else if kind == "enum_item" {
+            self.extract_enum(node);
+            skip_children = true;
+        } else if kind == "type_item" {
+            self.extract_type_alias(node);
+            // extractTypeAlias returns false for rust (plain alias) — children
+            // are visited (nothing in them has a branch).
+        } else if matches!(kind, "let_declaration" | "const_item" | "static_item")
+            && !self.inside_class_like()
+        {
+            // Inside a class-like scope the gate fails and the else-ladder
+            // falls through with children VISITED — a trait const's value
+            // expression emits calls refs from the trait node.
+            self.extract_variable(node);
+            self.scan_fn_ref_subtree(node, 0);
+            skip_children = true;
+        } else if kind == "use_declaration" {
+            self.extract_import(node);
+            // importTypes branch never sets skipChildren.
+        } else if kind == "call_expression" {
+            self.extract_call(node);
+        } else if kind == "struct_expression" {
+            self.extract_instantiation(node);
+        } else if kind == "impl_item" {
+            // Emits the implements back-reference; skipChildren stays false so
+            // the declaration_list is visited at FILE scope (impl pushes
+            // nothing on the stack).
+            self.extract_rust_impl_item(node);
+        }
+
+        if !skip_children {
+            for i in 0..node.named_child_count() {
+                if let Some(c) = node.named_child(i) {
+                    self.visit_node(c);
+                }
+            }
+        }
+    }
+
+    // --- extractors --------------------------------------------------------------
+
+    /// extractFunction/extractMethod, decision resolved once: method iff a
+    /// receiver is found (fn inside an impl — including a NESTED fn inside an
+    /// impl method's body, whose parent walk passes through the outer fn) or
+    /// the stack top is class-like (trait members).
+    fn extract_fn_or_method(&mut self, node: Node<'t>) {
+        let receiver = self.receiver_type_of(node);
+        let as_method = receiver.is_some() || self.inside_class_like();
+
+        let name = self.extract_name(node);
+        if name == "<anonymous>" {
+            if let Some(body) = node.child_by_field_name("body") {
+                self.visit_function_body(body);
+            }
+            return;
+        }
+
+        let extra = Extra {
+            docstring: preceding_docstring(node, self.src),
+            signature: self.signature_of(node),
+            visibility: Some(self.visibility_of(node)),
+            // isAsync hook exists but never finds a direct `async` child (it
+            // nests in function_modifiers) — present-false on every node.
+            is_async: Some(false),
+            return_type: self.return_type_of(node),
+            qualified_name: receiver.as_ref().map(|r| format!("{r}::{name}")),
+            ..Extra::default() // isExported hook absent → flag not set
+        };
+        let kind: &'static str = if as_method { "method" } else { "function" };
+        let Some(row) = self.create_node(kind, &name, node, extra) else { return };
+
+        // Contains edge from the owner: receiver present AND not class-like —
+        // FIRST earlier-in-file struct/class/enum/trait of the receiver's name.
+        if as_method && !self.inside_class_like() {
+            if let Some(receiver) = &receiver {
+                let owner_row = self
+                    .nodes_meta
+                    .iter()
+                    .position(|m| {
+                        m.name == *receiver
+                            && matches!(m.kind, "struct" | "class" | "enum" | "trait")
+                    })
+                    .map(|i| i as u32);
+                if let Some(owner_row) = owner_row {
+                    self.tables.push_edge(&EdgeRow {
+                        source_idx: owner_row,
+                        target_idx: row,
+                        kind: edge_kind_index("contains").unwrap(),
+                        provenance: 0,
+                        line: NONE,
+                        column: NONE,
+                        metadata_json: NONE_STR,
+                        source_id_str: NONE_STR,
+                        target_id_str: NONE_STR,
+                    });
+                }
+            }
+        }
+
+        self.extract_type_annotations(node, row);
+        // extractDecoratorsFor: rust attribute_items are siblings, not
+        // decorator/annotation/attribute node types — complete no-op.
+        self.stack.push(Scope { row, kind, name });
+        if let Some(body) = node.child_by_field_name("body") {
+            self.visit_function_body(body);
+        }
+        self.stack.pop();
+    }
+
+    /// extractInterface — kind `trait` (interfaceKind), inheritance from
+    /// trait_bounds, body children visited with the trait pushed.
+    fn extract_interface(&mut self, node: Node<'t>) {
+        let name = self.extract_name(node);
+        let extra = Extra {
+            docstring: preceding_docstring(node, self.src),
+            ..Extra::default() // no visibility/isExported on the interface path
+        };
+        let Some(row) = self.create_node("trait", &name, node, extra) else { return };
+        self.extract_inheritance(node, row);
+
+        self.stack.push(Scope { row, kind: "trait", name });
+        let body = node.child_by_field_name("body").unwrap_or(node);
+        for i in 0..body.named_child_count() {
+            if let Some(c) = body.named_child(i) {
+                self.visit_node(c);
+            }
+        }
+        self.stack.pop();
+    }
+
+    /// extractStruct — body field REQUIRED (unit structs mint no node; tuple
+    /// structs' ordered_field_declaration_list is a body).
+    fn extract_struct(&mut self, node: Node<'t>) {
+        let Some(body) = node.child_by_field_name("body") else { return };
+        let name = self.extract_name(node);
+        let extra = Extra {
+            docstring: preceding_docstring(node, self.src),
+            visibility: Some(self.visibility_of(node)),
+            ..Extra::default()
+        };
+        let Some(row) = self.create_node("struct", &name, node, extra) else { return };
+        self.extract_inheritance(node, row);
+
+        self.stack.push(Scope { row, kind: "struct", name });
+        for i in 0..body.named_child_count() {
+            if let Some(c) = body.named_child(i) {
+                self.visit_node(c);
+            }
+        }
+        self.stack.pop();
+    }
+
+    /// extractEnum — body required; enum_variant children → enum_member nodes
+    /// (name field only, payloads never walked); other children re-dispatched.
+    fn extract_enum(&mut self, node: Node<'t>) {
+        let Some(body) = node.child_by_field_name("body") else { return };
+        let name = self.extract_name(node);
+        let extra = Extra {
+            docstring: preceding_docstring(node, self.src),
+            visibility: Some(self.visibility_of(node)),
+            ..Extra::default()
+        };
+        let Some(row) = self.create_node("enum", &name, node, extra) else { return };
+        self.extract_inheritance(node, row);
+
+        self.stack.push(Scope { row, kind: "enum", name });
+        for i in 0..body.named_child_count() {
+            let Some(c) = body.named_child(i) else { continue };
+            if c.kind() == "enum_variant" {
+                if let Some(name_node) = c.child_by_field_name("name") {
+                    let vname = self.text(name_node).to_string();
+                    self.create_node("enum_member", &vname, c, Extra::default());
+                }
+            } else {
+                self.visit_node(c);
+            }
+        }
+        self.stack.pop();
+    }
+
+    /// extractTypeAlias — plain `type_alias` node. QUIRK: the alias-value ref
+    /// walk reads a `value` field; rust type_item's field is `type` → no ref
+    /// to the aliased type. Returns children-visited (false) like the TS.
+    fn extract_type_alias(&mut self, node: Node<'t>) {
+        let name = self.extract_name(node);
+        if name == "<anonymous>" {
+            return;
+        }
+        let extra = Extra {
+            docstring: preceding_docstring(node, self.src),
+            ..Extra::default()
+        };
+        self.create_node("type_alias", &name, node, extra);
+    }
+
+    /// extractVariable's generic fallback: kind is ALWAYS `variable` (no
+    /// isConst hook), every direct `identifier` child mints a node positioned
+    /// at the CHILD, docstring shared, isExported present-false, no signature,
+    /// and the initializer value is never body-walked.
+    fn extract_variable(&mut self, node: Node<'t>) {
+        let docstring = preceding_docstring(node, self.src);
+        for i in 0..node.named_child_count() {
+            let Some(child) = node.named_child(i) else { continue };
+            if child.kind() != "identifier" {
+                continue;
+            }
+            let name = self.text(child).to_string();
+            if !name.is_empty() {
+                self.create_node(
+                    "variable",
+                    &name,
+                    child,
+                    Extra {
+                        docstring: docstring.clone(),
+                        is_exported: Some(false),
+                        ..Extra::default()
+                    },
+                );
+            }
+        }
+    }
+
+    /// extractImport via the rust hook: import node named by the ROOT module +
+    /// one generic root `imports` ref + per-binding FULL-path refs.
+    /// `use x::*;` (use_wildcard) → hook returns null → nothing at all.
+    fn extract_import(&mut self, node: Node<'t>) {
+        let use_arg = (0..node.named_child_count())
+            .filter_map(|i| node.named_child(i))
+            .find(|c| matches!(c.kind(), "scoped_use_list" | "scoped_identifier" | "use_list" | "identifier"));
+        let Some(use_arg) = use_arg else { return };
+
+        let module_name = self.root_module(use_arg);
+        let signature = self.text(node).trim().to_string();
+        self.create_node(
+            "import",
+            &module_name.clone(),
+            node,
+            Extra { signature: Some(signature), ..Extra::default() },
+        );
+        let parent = self.top_row();
+        let imports_kind = edge_kind_index("imports").unwrap();
+        if !module_name.is_empty() {
+            self.push_ref_at(parent, &module_name, imports_kind, node);
+        }
+        self.emit_use_binding_refs(node, parent);
+    }
+
+    /// getRootModule (languages/rust.ts:124).
+    fn root_module(&self, n: Node) -> String {
+        let Some(first) = n.named_child(0) else {
+            return self.text(n).to_string();
+        };
+        match first.kind() {
+            "identifier" | "crate" | "super" | "self" => self.text(first).to_string(),
+            "scoped_identifier" => self.root_module(first),
+            _ => self.text(first).to_string(),
+        }
+    }
+
+    /// emitRustUseBindingRefs (tree-sitter.ts:3451) — one FULL-path `imports`
+    /// ref per binding; `Path as Alias` links the source path; leaves that are
+    /// only `self`/`super`/`crate`/`*` are skipped.
+    fn emit_use_binding_refs(&mut self, node: Node<'t>, from_row: u32) {
+        let mut paths: Vec<(String, Node)> = Vec::new();
+        fn join(prefix: &str, seg: &str) -> String {
+            if prefix.is_empty() { seg.to_string() } else { format!("{prefix}::{seg}") }
+        }
+        fn collect<'t>(w: &Walker<'t>, n: Node<'t>, prefix: &str, paths: &mut Vec<(String, Node<'t>)>) {
+            match n.kind() {
+                "identifier" => paths.push((join(prefix, w.text(n)), n)),
+                "scoped_identifier" => {
+                    let full = w.text(n).trim();
+                    paths.push((
+                        if prefix.is_empty() { full.to_string() } else { format!("{prefix}::{full}") },
+                        n,
+                    ));
+                }
+                "scoped_use_list" => {
+                    let seg = n
+                        .child_by_field_name("path")
+                        .map(|p| w.text(p).trim().to_string())
+                        .unwrap_or_default();
+                    let new_prefix = if seg.is_empty() { prefix.to_string() } else { join(prefix, &seg) };
+                    let list = n.child_by_field_name("list").or_else(|| {
+                        (0..n.named_child_count())
+                            .filter_map(|i| n.named_child(i))
+                            .find(|c| c.kind() == "use_list")
+                    });
+                    if let Some(list) = list {
+                        collect(w, list, &new_prefix, paths);
+                    }
+                }
+                "use_list" => {
+                    for i in 0..n.named_child_count() {
+                        if let Some(c) = n.named_child(i) {
+                            collect(w, c, prefix, paths);
+                        }
+                    }
+                }
+                "use_as_clause" => {
+                    let p = n.child_by_field_name("path").or_else(|| n.named_child(0));
+                    if let Some(p) = p {
+                        collect(w, p, prefix, paths);
+                    }
+                }
+                _ => {} // visibility_modifier, use_wildcard, bare crate/self/super
+            }
+        }
+        for i in 0..node.named_child_count() {
+            if let Some(c) = node.named_child(i) {
+                collect(self, c, "", &mut paths);
+            }
+        }
+        let imports_kind = edge_kind_index("imports").unwrap();
+        for (text, n) in paths {
+            let leaf = text.rsplit("::").next().unwrap_or("");
+            if leaf.is_empty() || matches!(leaf, "self" | "super" | "crate" | "*") {
+                continue;
+            }
+            self.push_ref_at(from_row, &text, imports_kind, n);
+        }
+    }
+
+    /// extractCall — the rust paths of the generic else-branch (4312+).
+    fn extract_call(&mut self, node: Node<'t>) {
+        if self.stack.is_empty() {
+            return;
+        }
+        let func = node
+            .child_by_field_name("function")
+            .or_else(|| node.named_child(0));
+        let mut callee_name = String::new();
+
+        if let Some(func) = func {
+            if func.kind() == "field_expression" {
+                let property = func
+                    .child_by_field_name("property")
+                    .or_else(|| func.child_by_field_name("field"))
+                    .or_else(|| func.named_child(1));
+                if let Some(property) = property {
+                    let method_name = self.text(property);
+                    let receiver = func
+                        .child_by_field_name("object")
+                        .or_else(|| func.child_by_field_name("operand"))
+                        .or_else(|| func.child_by_field_name("argument"))
+                        .or_else(|| func.named_child(0));
+                    if let Some(r) = receiver {
+                        if is_literal_receiver(r.kind()) {
+                            return; // emit NOTHING (#1230)
+                        }
+                    }
+                    if let Some(r) = receiver {
+                        match r.kind() {
+                            // rust `self` is node kind `self`, NOT `identifier` —
+                            // it dodges this branch and falls to the bare-name
+                            // fallthrough (same net effect as SKIP_RECEIVERS).
+                            "identifier" | "simple_identifier" | "field_identifier" => {
+                                let receiver_name = self.text(r);
+                                if !matches!(receiver_name, "self" | "this" | "cls" | "super") {
+                                    callee_name = format!("{receiver_name}.{method_name}");
+                                } else {
+                                    callee_name = method_name.to_string();
+                                }
+                            }
+                            "call_expression" => {
+                                // Chained-call re-encode: ONLY an associated-
+                                // function chain (`Foo::new().bar()`, inner
+                                // callee a scoped_identifier). Instance chains
+                                // keep the bare method name.
+                                let inner_fn = r.child_by_field_name("function");
+                                let reencode =
+                                    inner_fn.map(|f| f.kind() == "scoped_identifier").unwrap_or(false);
+                                if reencode {
+                                    let inner: String = self
+                                        .text(inner_fn.unwrap())
+                                        .replace("->", ".")
+                                        .chars()
+                                        .filter(|c| !c.is_whitespace())
+                                        .collect();
+                                    callee_name = format!("{inner}().{method_name}");
+                                } else {
+                                    callee_name = method_name.to_string();
+                                }
+                            }
+                            _ => {
+                                // field_expression 2-hop, parenthesized,
+                                // await_expression, `self` — bare method name.
+                                callee_name = method_name.to_string();
+                            }
+                        }
+                    } else {
+                        callee_name = method_name.to_string();
+                    }
+                }
+            } else if matches!(func.kind(), "scoped_identifier" | "scoped_call_expression") {
+                callee_name = self.text(func).to_string();
+            } else {
+                // identifier; generic_function keeps the raw turbofish text
+                // (`helper::<T>` — unresolvable downstream, preserved).
+                callee_name = self.text(func).to_string();
+            }
+        }
+
+        if !callee_name.is_empty() {
+            // Parenthesized-callee normalization — `(f)(x)` → `f`.
+            if let Some(c) = util::paren_conversion().captures(&callee_name) {
+                callee_name = c[1].to_string();
+            }
+            let from = self.top_row();
+            self.push_ref_at(from, &callee_name.clone(), edge_kind_index("calls").unwrap(), node);
+        }
+    }
+
+    /// extractInstantiation — struct_expression via the GENERIC path: strip
+    /// from the first `<`, keep the trailing `::`/`.` segment (JS slice
+    /// semantics: slice(lastDot+1) after a `::` leaves one `:`, then ONE
+    /// leading `[:.]` is stripped).
+    fn extract_instantiation(&mut self, node: Node<'t>) {
+        if self.stack.is_empty() {
+            return;
+        }
+        let ctor = node
+            .child_by_field_name("constructor")
+            .or_else(|| node.child_by_field_name("type"))
+            .or_else(|| node.child_by_field_name("name"))
+            .or_else(|| node.named_child(0));
+        let Some(ctor) = ctor else { return };
+
+        let mut class_name = self.text(ctor).to_string();
+        if let Some(lt) = class_name.find('<') {
+            if lt > 0 {
+                class_name.truncate(lt);
+            }
+        }
+        let last_dot = class_name.rfind('.').map(|i| i as i64).unwrap_or(-1);
+        let last_colon = class_name.rfind("::").map(|i| i as i64).unwrap_or(-1);
+        let last = last_dot.max(last_colon);
+        if last >= 0 {
+            class_name = class_name[(last + 1) as usize..].to_string();
+            if let Some(rest) = class_name.strip_prefix(&[':', '.'][..]) {
+                class_name = rest.to_string();
+            }
+        }
+        let class_name = class_name.trim().to_string();
+
+        if !class_name.is_empty() {
+            let from = self.top_row();
+            self.push_ref_at(from, &class_name, edge_kind_index("instantiates").unwrap(), node);
+        }
+    }
+
+    /// extractRustRouteMacro — body-walker-only; bare `routes`/`catchers`
+    /// identifiers only (`rocket::routes![…]` is skipped); identifier runs in
+    /// the token tree join with `::`, flushed on `,` and at end.
+    fn extract_rust_route_macro(&mut self, node: Node<'t>) {
+        let Some(macro_name) = node.named_child(0) else { return };
+        let name = self.text(macro_name);
+        if name != "routes" && name != "catchers" {
+            return;
+        }
+        let token_tree = (0..node.named_child_count())
+            .filter_map(|i| node.named_child(i))
+            .find(|c| c.kind() == "token_tree");
+        let Some(token_tree) = token_tree else { return };
+        if self.stack.is_empty() {
+            return;
+        }
+        let from = self.top_row();
+        let refs_kind = edge_kind_index("references").unwrap();
+
+        let mut parts: Vec<&str> = Vec::new();
+        let mut line = 0u32;
+        let mut column_byte = 0usize;
+        let mut row = 0usize;
+        macro_rules! flush {
+            () => {
+                if !parts.is_empty() {
+                    let joined = parts.join("::");
+                    let column = util::col16(self.src, &self.line_starts, row, column_byte);
+                    let name_ref = self.arena.put(&joined);
+                    self.tables.push_ref(&RefRow {
+                        from_idx: from,
+                        kind: refs_kind,
+                        line,
+                        column,
+                        reference_name: name_ref,
+                        candidates: NONE_STR,
+                        from_id_str: NONE_STR,
+                    });
+                    parts.clear();
+                }
+            };
+        }
+        for i in 0..token_tree.child_count() {
+            let Some(t) = token_tree.child(i) else { continue };
+            if t.kind() == "identifier" {
+                if parts.is_empty() {
+                    line = t.start_position().row as u32 + 1;
+                    column_byte = t.start_byte();
+                    row = t.start_position().row;
+                }
+                parts.push(self.text(t));
+            } else if t.kind() == "," {
+                flush!();
+            }
+        }
+        flush!();
+    }
+
+    /// extractInheritance — the rust-reachable cases: trait_bounds
+    /// (supertraits; a scoped `fmt::Debug` bound matches NO case and is
+    /// dropped), the Go embedding check on field_declaration (inert in rust —
+    /// every field has a field_identifier), and the field_declaration_list
+    /// recursion that reaches it.
+    fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) {
+        let extends_kind = edge_kind_index("extends").unwrap();
+        for i in 0..node.named_child_count() {
+            let Some(child) = node.named_child(i) else { continue };
+            match child.kind() {
+                "trait_bounds" => {
+                    for j in 0..child.named_child_count() {
+                        let Some(bound) = child.named_child(j) else { continue };
+                        let type_node: Option<Node> = match bound.kind() {
+                            "type_identifier" => Some(bound),
+                            "generic_type" => (0..bound.named_child_count())
+                                .filter_map(|k| bound.named_child(k))
+                                .find(|c| c.kind() == "type_identifier"),
+                            "higher_ranked_trait_bound" => {
+                                let generic = (0..bound.named_child_count())
+                                    .filter_map(|k| bound.named_child(k))
+                                    .find(|c| c.kind() == "generic_type");
+                                generic
+                                    .and_then(|g| {
+                                        (0..g.named_child_count())
+                                            .filter_map(|k| g.named_child(k))
+                                            .find(|c| c.kind() == "type_identifier")
+                                    })
+                                    .or_else(|| {
+                                        (0..bound.named_child_count())
+                                            .filter_map(|k| bound.named_child(k))
+                                            .find(|c| c.kind() == "type_identifier")
+                                    })
+                            }
+                            _ => None, // scoped_type_identifier: dropped (quirk)
+                        };
+                        if let Some(tn) = type_node {
+                            let name = self.text(tn).to_string();
+                            self.push_ref_at(class_row, &name, extends_kind, tn);
+                        }
+                    }
+                }
+                "field_declaration" => {
+                    let has_field_identifier = (0..child.named_child_count())
+                        .filter_map(|j| child.named_child(j))
+                        .any(|c| c.kind() == "field_identifier");
+                    if !has_field_identifier {
+                        let type_id = (0..child.named_child_count())
+                            .filter_map(|j| child.named_child(j))
+                            .find(|c| c.kind() == "type_identifier");
+                        if let Some(type_id) = type_id {
+                            let name = self.text(type_id).to_string();
+                            self.push_ref_at(class_row, &name, extends_kind, type_id);
+                        }
+                    }
+                }
+                "field_declaration_list" | "class_heritage" => {
+                    self.extract_inheritance(child, class_row);
+                }
+                _ => {}
+            }
+        }
+    }
+
+    /// extractRustImplItem — `impl Trait for Type` back-reference: positional
+    /// type-node filter (NEVER the grammar's trait:/type: fields), ≥2 needed,
+    /// target found by FIRST earlier node of kind struct/enum/class (never
+    /// trait); ref FROM the type's node, named by the trait's full text.
+    fn extract_rust_impl_item(&mut self, node: Node<'t>) {
+        let has_for = (0..node.child_count())
+            .filter_map(|i| node.child(i))
+            .any(|c| c.kind() == "for" && !c.is_named());
+        if !has_for {
+            return;
+        }
+        let type_idents: Vec<Node> = (0..node.named_child_count())
+            .filter_map(|i| node.named_child(i))
+            .filter(|c| matches!(c.kind(), "type_identifier" | "generic_type" | "scoped_type_identifier"))
+            .collect();
+        if type_idents.len() < 2 {
+            return;
+        }
+        let trait_node = type_idents[0];
+        let type_node = type_idents[type_idents.len() - 1];
+
+        let trait_name = self.text(trait_node).to_string();
+        let type_name = if type_node.kind() == "generic_type" {
+            (0..type_node.named_child_count())
+                .filter_map(|i| type_node.named_child(i))
+                .find(|c| c.kind() == "type_identifier")
+                .map(|c| self.text(c).to_string())
+                .unwrap_or_else(|| self.text(type_node).to_string())
+        } else {
+            self.text(type_node).to_string()
+        };
+
+        let target_row = self
+            .nodes_meta
+            .iter()
+            .position(|m| m.name == type_name && matches!(m.kind, "struct" | "enum" | "class"))
+            .map(|i| i as u32);
+        if let Some(target_row) = target_row {
+            self.push_ref_at(target_row, &trait_name, edge_kind_index("implements").unwrap(), trait_node);
+        }
+    }
+
+    /// extractTypeAnnotations — parameters + return_type subtrees, one
+    /// `references` ref per type_identifier leaf not in BUILTIN_TYPES. The
+    /// trailing `type_annotation` child lookup is included for fidelity (the
+    /// rust grammar has no such node — always a no-op).
+    fn extract_type_annotations(&mut self, node: Node<'t>, from_row: u32) {
+        if let Some(params) = node.child_by_field_name("parameters") {
+            self.extract_type_refs_from_subtree(params, from_row);
+        }
+        if let Some(ret) = node.child_by_field_name("return_type") {
+            self.extract_type_refs_from_subtree(ret, from_row);
+        }
+        let type_annotation = (0..node.named_child_count())
+            .filter_map(|i| node.named_child(i))
+            .find(|c| c.kind() == "type_annotation");
+        if let Some(ta) = type_annotation {
+            self.extract_type_refs_from_subtree(ta, from_row);
+        }
+    }
+
+    fn extract_type_refs_from_subtree(&mut self, node: Node<'t>, from_row: u32) {
+        if node.kind() == "type_identifier" {
+            let type_name = self.text(node).to_string();
+            if !type_name.is_empty() && !is_builtin_type(&type_name) {
+                self.push_ref_at(from_row, &type_name, edge_kind_index("references").unwrap(), node);
+            }
+            return;
+        }
+        for i in 0..node.named_child_count() {
+            if let Some(c) = node.named_child(i) {
+                self.extract_type_refs_from_subtree(c, from_row);
+            }
+        }
+    }
+
+    // --- visitFunctionBody -----------------------------------------------------
+
+    fn visit_function_body(&mut self, body: Node<'t>) {
+        self.visit_for_calls_and_structure(body);
+    }
+
+    fn visit_for_calls_and_structure(&mut self, node: Node<'t>) {
+        let kind = node.kind();
+        self.maybe_capture_fn_refs(node);
+
+        // Rocket route macros: handler paths live in a raw token tree.
+        if kind == "macro_invocation" {
+            self.extract_rust_route_macro(node);
+        }
+
+        if kind == "call_expression" {
+            self.extract_call(node);
+        } else if kind == "struct_expression" {
+            self.extract_instantiation(node);
+        }
+
+        // Nested NAMED fns become their own nodes (a nested fn inside an impl
+        // method walks up to the impl and indexes as a METHOD).
+        if matches!(kind, "function_item" | "function_signature_item") {
+            let name = self.extract_name(node);
+            if name != "<anonymous>" {
+                self.extract_fn_or_method(node);
+                return;
+            }
+        }
+
+        // Structural nodes inside bodies.
+        if kind == "struct_item" {
+            self.extract_struct(node);
+            return;
+        }
+        if kind == "enum_item" {
+            self.extract_enum(node);
+            return;
+        }
+        if kind == "trait_item" {
+            self.extract_interface(node);
+            return;
+        }
+
+        for i in 0..node.named_child_count() {
+            if let Some(c) = node.named_child(i) {
+                self.visit_for_calls_and_structure(c);
+            }
+        }
+    }
+
+    // --- fn refs (RUST_SPEC) ----------------------------------------------------
+
+    /// maybeCaptureFnRefs with RUST_SPEC's dispatch: arguments→args,
+    /// assignment_expression→rhs(right), field_initializer→value(value),
+    /// array_expression→list, static_item/let_declaration→varinit(value).
+    /// No layers/unwrap/special — only bare identifiers qualify (`&handler`
+    /// captures nothing). QUIRK: const_item is NOT in the dispatch.
+    fn maybe_capture_fn_refs(&mut self, node: Node<'t>) {
+        enum Mode {
+            Args,
+            Rhs,
+            Value,
+            List,
+            Varinit,
+        }
+        let mode = match node.kind() {
+            "arguments" => Mode::Args,
+            "assignment_expression" => Mode::Rhs,
+            "field_initializer" => Mode::Value,
+            "array_expression" => Mode::List,
+            "static_item" | "let_declaration" => Mode::Varinit,
+            _ => return,
+        };
+        if self.stack.is_empty() {
+            return;
+        }
+        let from = self.top_row();
+
+        let mut values: Vec<Node> = Vec::new();
+        match mode {
+            Mode::Args | Mode::List => {
+                for i in 0..node.named_child_count() {
+                    if let Some(c) = node.named_child(i) {
+                        values.push(c);
+                    }
+                }
+            }
+            Mode::Rhs => {
+                if let Some(rhs) = node.child_by_field_name("right") {
+                    // Param-storage skip: `o.cb = cb`.
+                    let lhs_text = node
+                        .child_by_field_name("left")
+                        .map(|l| self.text(l))
+                        .unwrap_or("");
+                    let lhs_last = util::lhs_last_name()
+                        .captures(lhs_text)
+                        .and_then(|c| c.get(1))
+                        .map(|m| m.as_str());
+                    if !(lhs_last.is_some() && lhs_last == Some(self.text(rhs).trim())) {
+                        values.push(rhs);
+                    }
+                }
+            }
+            Mode::Value => {
+                let v = node.child_by_field_name("value").or_else(|| {
+                    if node.named_child_count() > 0 {
+                        node.named_child(node.named_child_count() - 1)
+                    } else {
+                        None
+                    }
+                });
+                if let Some(v) = v {
+                    values.push(v);
+                }
+            }
+            Mode::Varinit => {
+                // Destructuring skip: a tuple/struct pattern LHS extracts data,
+                // never a function alias (static_item's name is an identifier,
+                // let_declaration's `pattern` field can be a pattern).
+                let name_node = node
+                    .child_by_field_name("name")
+                    .or_else(|| node.child_by_field_name("pattern"));
+                if let Some(nn) = name_node {
+                    if matches!(
+                        nn.kind(),
+                        "object_pattern" | "array_pattern" | "tuple_pattern" | "struct_pattern"
+                    ) {
+                        return;
+                    }
+                }
+                if let Some(v) = node.child_by_field_name("value") {
+                    values.push(v);
+                }
+            }
+        }
+
+        for v in values {
+            // normalizeValue: idTypes = {identifier} only, no layers/unwrap.
+            if v.kind() == "identifier" {
+                let name = self.text(v).to_string();
+                if name.is_empty() || is_stoplisted(&name) {
+                    continue;
+                }
+                let p = v.start_position();
+                self.fn_ref_cands.push(Cand {
+                    from,
+                    name,
+                    line: p.row as u32 + 1,
+                    column_byte: v.start_byte(),
+                    row: p.row,
+                });
+            }
+        }
+    }
+
+    fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32) {
+        if depth > 12 {
+            return;
+        }
+        if depth > 0
+            && matches!(
+                node.kind(),
+                "function_item" | "function_signature_item" | "arrow_function"
+                    | "function_expression" | "lambda_literal" | "lambda_expression"
+            )
+        {
+            return;
+        }
+        self.maybe_capture_fn_refs(node);
+        for i in 0..node.named_child_count() {
+            if let Some(c) = node.named_child(i) {
+                self.scan_fn_ref_subtree(c, depth + 1);
+            }
+        }
+    }
+
+    fn flush_fn_ref_candidates(&mut self) {
+        let cands = std::mem::take(&mut self.fn_ref_cands);
+        if cands.is_empty() || util::is_generated_file(self.file_path) {
+            return;
+        }
+        let mut seen: HashSet<(String, String)> = HashSet::new();
+        for c in cands {
+            if !c.name.starts_with("this.")
+                && !c.name.contains("::")
+                && !self.defined_fn_names.contains(&c.name)
+                && !self.imported_names.contains(&c.name)
+            {
+                continue;
+            }
+            if !seen.insert((self.node_ids[c.from as usize].clone(), c.name.clone())) {
+                continue;
+            }
+            let column = util::col16(self.src, &self.line_starts, c.row, c.column_byte);
+            let name_ref = self.arena.put(&c.name);
+            self.tables.push_ref(&RefRow {
+                from_idx: c.from,
+                kind: FUNCTION_REF_CODE,
+                line: c.line,
+                column,
+                reference_name: name_ref,
+                candidates: NONE_STR,
+                from_id_str: NONE_STR,
+            });
+        }
+    }
+
+    // --- value refs -------------------------------------------------------------
+
+    fn flush_value_refs(&mut self, root: Node<'t>) {
+        let scopes = std::mem::take(&mut self.value_scopes);
+        let mut targets = std::mem::take(&mut self.fs_values);
+        let counts = std::mem::take(&mut self.fs_value_counts);
+        if std::env::var("CODEGRAPH_VALUE_REFS").as_deref() == Ok("0") {
+            return;
+        }
+        if targets.is_empty() || scopes.is_empty() || util::is_generated_file(self.file_path) {
+            return;
+        }
+
+        // Shadow prune — rust declarator shapes: const_item/static_item (name
+        // field) and let_declaration (the shadow source: `pattern` field; a
+        // tuple pattern bumps every named child).
+        let mut decl_counts: HashMap<&str, u32> = HashMap::new();
+        let mut bump = |decl_counts: &mut HashMap<&'t str, u32>, name_node: Option<Node<'t>>, src: &'t str, targets: &HashMap<String, u32>| {
+            if let Some(n) = name_node {
+                if matches!(n.kind(), "identifier" | "simple_identifier") {
+                    let nm = &src[n.byte_range()];
+                    if targets.contains_key(nm) {
+                        *decl_counts.entry(nm).or_insert(0) += 1;
+                    }
+                }
+            }
+        };
+        let mut dstack: Vec<Node> = vec![root];
+        let mut dvisited = 0usize;
+        while let Some(n) = dstack.pop() {
+            if dvisited >= MAX_VALUE_REF_NODES {
+                break;
+            }
+            dvisited += 1;
+            match n.kind() {
+                "const_item" | "static_item" => {
+                    bump(&mut decl_counts, n.child_by_field_name("name"), self.src, &targets)
+                }
+                "let_declaration" => {
+                    let left = n
+                        .child_by_field_name("left")
+                        .or_else(|| n.child_by_field_name("pattern"))
+                        .or_else(|| n.named_child(0));
+                    if let Some(left) = left {
+                        if left.kind() == "identifier" {
+                            bump(&mut decl_counts, Some(left), self.src, &targets);
+                        } else {
+                            for i in 0..left.named_child_count() {
+                                bump(&mut decl_counts, left.named_child(i), self.src, &targets);
+                            }
+                        }
+                    }
+                }
+                _ => {}
+            }
+            for i in 0..n.named_child_count() {
+                if let Some(c) = n.named_child(i) {
+                    dstack.push(c);
+                }
+            }
+        }
+        let shadowed: Vec<String> = decl_counts
+            .iter()
+            .filter(|(nm, c)| **c > counts.get(**nm).copied().unwrap_or(1))
+            .map(|(nm, _)| nm.to_string())
+            .collect();
+        for nm in shadowed {
+            targets.remove(&nm);
+        }
+        if targets.is_empty() {
+            return;
+        }
+
+        let refs_kind = edge_kind_index("references").unwrap();
+        for scope in &scopes {
+            let mut seen: HashSet<&str> = HashSet::new();
+            let mut stack: Vec<Node> = vec![scope.node];
+            let mut visited = 0usize;
+            while let Some(n) = stack.pop() {
+                if visited >= MAX_VALUE_REF_NODES {
+                    break;
+                }
+                visited += 1;
+                if matches!(n.kind(), "identifier" | "constant" | "name" | "simple_identifier") {
+                    let ref_name = self.text(n);
+                    if let Some(&target_row) = targets.get(ref_name) {
+                        let target_id = self.node_ids[target_row as usize].as_str();
+                        if target_id != self.node_ids[scope.row as usize]
+                            && ref_name != scope.name
+                            && !seen.contains(&target_id)
+                        {
+                            seen.insert(target_id);
+                            let meta = self.arena.put(r#"{"valueRef":true}"#);
+                            self.tables.push_edge(&EdgeRow {
+                                source_idx: scope.row,
+                                target_idx: target_row,
+                                kind: refs_kind,
+                                provenance: 0,
+                                line: NONE,
+                                column: NONE,
+                                metadata_json: meta,
+                                source_id_str: NONE_STR,
+                                target_id_str: NONE_STR,
+                            });
+                        }
+                    }
+                }
+                for i in 0..n.named_child_count() {
+                    if let Some(c) = n.named_child(i) {
+                        stack.push(c);
+                    }
+                }
+            }
+        }
+    }
+}
+
+fn is_stoplisted(name: &str) -> bool {
+    matches!(
+        name,
+        "this" | "self" | "super" | "null" | "nil" | "true" | "false" | "undefined" | "new"
+            | "NULL" | "nullptr" | "None"
+    )
+}
+
+/// LITERAL_RECEIVER_TYPES (shared table).
+fn is_literal_receiver(kind: &str) -> bool {
+    matches!(
+        kind,
+        "string" | "string_literal" | "interpreted_string_literal" | "raw_string_literal"
+            | "template_string" | "concatenated_string" | "formatted_string" | "f_string"
+            | "line_string_literal" | "string_content" | "heredoc_body"
+            | "number" | "number_literal" | "integer" | "integer_literal" | "float"
+            | "float_literal" | "int_literal" | "decimal_integer_literal" | "real_literal"
+            | "char_literal" | "character_literal" | "rune_literal" | "regex" | "regex_literal"
+            | "true" | "false" | "boolean_literal" | "bool_literal" | "none" | "null" | "nil"
+            | "null_literal" | "undefined"
+            | "list" | "list_literal" | "array" | "array_literal" | "array_creation_expression"
+            | "dictionary" | "dict_literal" | "object" | "tuple" | "set"
+    )
+}
+
+/// BUILTIN_TYPES (shared table — port the WHOLE set: a rust `String`
+/// type_identifier IS suppressed via the Scala row).
+fn is_builtin_type(name: &str) -> bool {
+    matches!(
+        name,
+        "string" | "number" | "boolean" | "void" | "null" | "undefined" | "never" | "any"
+            | "unknown" | "object" | "symbol" | "bigint" | "true" | "false"
+            | "str" | "bool" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize"
+            | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "f32" | "f64" | "char"
+            | "int" | "long" | "short" | "byte" | "float" | "double"
+            | "int8" | "int16" | "int32" | "int64" | "uint8" | "uint16" | "uint32" | "uint64"
+            | "float32" | "float64" | "complex64" | "complex128" | "rune" | "error"
+            | "Int" | "Long" | "Short" | "Byte" | "Float" | "Double" | "Boolean" | "Char"
+            | "Unit" | "String" | "Any" | "AnyRef" | "AnyVal" | "Nothing" | "Null"
+    )
+}
+
+fn opt_str(arena: &mut Arena, s: Option<&str>) -> StrRef {
+    match s {
+        Some(s) => arena.put(s),
+        None => NONE_STR,
+    }
+}

+ 19 - 2
docs/design/rust-kernel-migration-plan.md

@@ -127,8 +127,24 @@ them are the ORIGINAL plan and carry expectations that measurement later correct
       **19.1 min kernel-arm** (parse-loop 560 → 356s; R6 26.4 → P1 17.6 on
       the old smaller graph → 19.1 on the new richer one:
       2,048,295 nodes / 6,406,933 edges, two runs byte-same).
-- [ ] **R7b. Remaining long tail** per the tracker (§4) — ruby/php/csharp/rust/… T1s
+- [~] **R7b. Remaining long tail** per the tracker (§4) — ruby/php/csharp/… T1s
       are now ~1-day-each with the walker pattern; T3 may stay TS forever (fine).
+      **rust DONE 2026-07-20** (first R7b port): grammar bumped to
+      tree-sitter-rust v0.24.2 (crate `=0.24.2` + vendored wasm from tag
+      `77a3747`, parser.c/scanner.c sha-matched; replaces the 2023 ABI-14
+      tree-sitter-wasms build — wasm-path bump validated standalone: ripgrep/
+      tokio node sections IDENTICAL, small precision-positive edge churn only,
+      full suite green), walker `codegraph-kernel/src/rustlang.rs` (survey
+      artifact: rust-lang-kernel-port-checklist.md — isAsync dead-code,
+      impl-pushes-no-scope, trait-receiver bug on `impl Trait for Generic<T>`,
+      phantom const identifiers, use-binding triple emission, all preserved
+      bug-for-bug). Gates: parity sweeps **0 diffs** on ripgrep (101/101,
+      0 deferred) / tokio (790/790, 0 deferred) / rust-analyzer (1217/1488,
+      0 diffs; 271 deferrals are token-macro-table sources — `T![~]`, `[$]` —
+      that error on BOTH arms, grammar-inherent like fmt's C++ 42%); full-init
+      dump-diffs **byte-identical** ×3 (3,857 / 13,440 / 39,030 nodes);
+      DEFAULT_ROUTED += rust; kernel-rustlang-parity suite (torture + CRLF +
+      defer) in `npm test`.
 - [ ] **P2. Arc 3, graph richness** (§7b) — product-priority call, standard gates.
 - [ ] **P3. Parked items** (§7c) — only with explicit maintainer approval.
 
@@ -590,7 +606,8 @@ parity before porting the language.
 | go | `languages/go.ts` | T1 | crates.io | Third (tie). Value-reference edges ship here too (#897). **PORTED + DEFAULT-ON (§4e).** | ✅ |
 | ruby, php | dedicated files | T1 | crates.io | Straightforward; PHP property-receiver shapes (#1220/#1251) are RESOLUTION-side, unaffected. | ☐ |
 | csharp | `languages/csharp.ts` | T1 | crates.io | Plain. | ☐ |
-| rust, dart, scala, lua, luau, r | dedicated files | T1 | crates.io (luau/r/scala: verify crate freshness vs our wasm) | Long-tail T1; port opportunistically after the big five. | ☐ |
+| rust | `languages/rust.ts` | T1 | crates.io | **DONE (R7b #1, 2026-07-20)** — `rustlang.rs` walker; grammar bumped to v0.24.2 (crate + vendored wasm together). Parity 0-diff on ripgrep/tokio/rust-analyzer + dump byte-identical ×3; rust-analyzer's parser crates defer 18% (token-macro tables, both-arm parse errors — grammar-inherent). Quirk list: docs/design/rust-lang-kernel-port-checklist.md. | ☑ |
+| dart, scala, lua, luau, r | dedicated files | T1 | crates.io (luau/r/scala: verify crate freshness vs our wasm) | Long-tail T1; port opportunistically after the big five. | ☐ |
 | kotlin | `languages/kotlin.ts` | T1½ | crates.io | Expect/actual pairing is synthesis-side (fine); extraction is clean but validate against a KMP repo. | ☐ |
 | swift | shared + dedicated branch | T1½ | crates.io | **Trap:** in-class property extraction lives in `tree-sitter.ts`'s DEDICATED branch, not `swift.ts` (#1020 — Alamofire went 0→348 props). Gate on Alamofire. | ☐ |
 | c, cpp | `languages/c-cpp.ts` | **T2** | crates.io | **DONE (R7a, 2026-07-17)** — `ccpp/` walker; ALL pre-passes stayed TS-side via the route-point preParse hoist (+6 new blanks added during gating — see the checklist doc); content-based `.h` C-vs-C++ detection stays upstream at detectLanguage. Parity 0-diff + dump byte-identical on redis/git/fmt/protobuf/ALS. | ☑ |

+ 526 - 0
docs/design/rust-lang-kernel-port-checklist.md

@@ -0,0 +1,526 @@
+# Rust-language kernel port (R7b) — the bug-for-bug checklist
+
+("rust-lang" in the filename to avoid confusion with the kernel's own
+implementation language.)
+
+**Status: PORT COMPLETE (2026-07-20)** — walker `codegraph-kernel/src/rustlang.rs`,
+all gates below passed (parity sweeps 0-diff on ripgrep/tokio/rust-analyzer,
+dump gates byte-identical ×3, DEFAULT_ROUTED += rust). This doc remains the
+quirk reference for the walker. Survey basis: every TS-side branch a
+`.rs` file exercises, with file:line anchors as of `ce0ae30` (HEAD at survey
+time). Every grammar-shape claim below was **probed against the vendored
+tree-sitter-rust v0.24.2 wasm** (probe scripts in the session scratchpad), not
+assumed. Read WITH `docs/design/rust-kernel-migration-plan.md` (§0a recipe, §5
+gates) and `docs/design/ccpp-kernel-port-checklist.md` (format precedent).
+
+**Grammar prep is ALREADY STAGED (uncommitted at survey time):** Cargo.toml
+pins `tree-sitter-rust = "=0.24.2"`, `src/extraction/wasm/tree-sitter-rust.wasm`
+is vendored from tag `77a3747` (parser.c/scanner.c sha-matched against the
+crates.io tarball), and `rust` is in `VENDORED_WASM_LANGS` (grammars.ts:291) —
+replacing the 2023-era tree-sitter-wasms build (ABI 14 → 15). Per the recipe:
+land the grammar bump FIRST and get the full suite green before the walker
+exists. Probing showed the 0.24.2 shapes match the old build on every branch
+below (function_modifiers nesting, token trees, impl fields, use shapes), so no
+TS-side behavior change is expected from the bump — but the suite run is the
+proof.
+
+## Architecture decisions
+
+1. **No preParse.** `rustExtractor` has no `preParse` hook, so the route
+   point's `preParsedSource` (kernel/index.ts:76) is a no-op for rust — both
+   arms parse raw bytes. Nothing to hoist, nothing to port.
+2. **Cargo repos take the DECODED path, not raw buffers.** `rustResolver`
+   (resolution/frameworks/rust.ts:22, `languages: ['rust']`, detect =
+   `Cargo.toml` exists) has an `extract()` hook, and parse-worker.ts:93 forces
+   any language with an applicable framework `extract()` onto the decoded
+   `extractFromSource` path (framework nodes/refs merge into the decoded
+   result). So on real Rust repos the kernel win is parse+walk+decode, never
+   the buffers-to-store transport. Don't chase a raw-path number on
+   ripgrep/tokio and conclude the port is broken.
+3. **The framework extractor itself needs NO port.** It is regex-over-raw-source
+   TS (see §Frameworks below) and runs identically after either arm inside
+   `extractFromSource` (tree-sitter.ts:6736-6758). Only the tree-sitter-walk
+   emissions below move to Rust.
+4. **One walker module** (suggest `codegraph-kernel/src/rustlang.rs` — "rust"
+   alone collides with the crate language), registered in `langs.rs`; per-file
+   `has_error()` → `defer:` like every walker.
+5. **`.rs` → `rust`** at detectLanguage (grammars.ts:78), no content sniffing,
+   no dialect. MAX_FILE_SIZE (1 MiB, extraction/index.ts:132) and generated-file
+   skips are orchestrator/TS-side and shared.
+
+## Extractor config (languages/rust.ts — 151 lines, read it whole)
+
+Types: functionTypes=[`function_item`, **`function_signature_item`**] (the
+latter = a trait method DECLARATION `fn render(&self);` — extracted so a
+trait's method set is first-class); classTypes=[] (impl blocks instead);
+methodTypes = same two; interfaceTypes=[`trait_item`] with
+**interfaceKind:'trait'**; structTypes=[`struct_item`]; enumTypes=[`enum_item`];
+enumMemberTypes=[`enum_variant`]; typeAliasTypes=[`type_item`];
+importTypes=[`use_declaration`]; callTypes=[`call_expression`];
+variableTypes=[`let_declaration`, `const_item`, `static_item`].
+nameField=`name`, bodyField=`body`, paramsField=`parameters`,
+returnField=`return_type`.
+
+Hooks PRESENT (port each exactly):
+
+- **getReturnType = extractRustReturnType (rust.ts:14)** — reads the
+  `return_type` field; if `reference_type`, unwrap to the first namedChild of
+  type `type_identifier`/`scoped_type_identifier`/`generic_type` (`?? rt` —
+  falls back to the reference_type itself); then if type ∈
+  {`primitive_type`,`unit_type`,`tuple_type`} → undefined. Else:
+  `text.trim().replace(/<[^>]*>/g, '')`, take last `::` segment, trim; must
+  match `/^[A-Za-z_]\w*$/` else undefined; `'Self'` → the marker **`'self'`**
+  (resolved to the impl's own type at resolution time). QUIRKS: the
+  non-greedy-ish `/<[^>]*>/g` strip breaks on NESTED generics —
+  `Result<Vec<Foo>, E>` → `"Result, E>"` → regex fails → **undefined** (only
+  single-level generics like `Vec<Foo>` → `Vec` survive). `-> &Foo` unwraps to
+  `Foo`; `-> fmt::Result` → `Result`.
+- **getSignature (rust.ts:57)** — `undefined` if no `parameters` field; else
+  raw text of params, plus `' -> ' + <return_type raw text>` when present.
+  Raw `getNodeText` — multi-line params keep their newlines.
+- **isAsync (rust.ts:67) — DEAD CODE BUG, PRESERVE:** scans DIRECT children for
+  `child.type === 'async'`. Probed on v0.24.2: `async` nests inside a
+  `function_modifiers` child (`pub async fn` children:
+  `visibility_modifier, function_modifiers, fn, identifier, parameters, ->,
+  <ret>, block`), so **isAsync always returns false** — no rust node ever gets
+  `isAsync: true`. The walker must reproduce false.
+- **getVisibility (rust.ts:74)** — direct child of type `visibility_modifier`:
+  text `.includes('pub')` → `'public'` else `'private'`; no modifier →
+  `'private'` (so `pub(crate)`/`pub(super)` are all `'public'`).
+- **getReceiverType (rust.ts:83)** — walk PARENT chain to the nearest
+  `impl_item`; there: filter DIRECT namedChildren of type `type_identifier`;
+  if ≥1, return the LAST one's source text (`source.substring(startIndex,
+  endIndex)` — UTF-16 units). If none, find the first `generic_type` child and
+  return its inner `type_identifier` text; else undefined. Never an impl parent
+  → undefined. QUIRK/BUG, PRESERVE: for `impl Trait for Generic<T>` the only
+  direct type_identifier is the TRAIT (probe: `impl Render for Container<T>` →
+  typeIdents=[`Render`] → receiver = **`Render`**, the trait name — methods get
+  qualifiedName `Render::render` and a contains edge from the trait node if one
+  exists in-file). `impl fmt::Display for Fields` is fine
+  (scoped_type_identifier isn't type_identifier → [Fields]). `impl<T>
+  Container<T>` → no direct type_identifiers → generic branch → `Container`.
+  Note `<T>` type_parameters is its own child, its inner T is NOT a direct
+  impl child.
+- **extractImport (rust.ts:120)** — signature = trimmed full `use …;` text.
+  `useArg` = FIRST namedChild of type `scoped_use_list` | `scoped_identifier` |
+  `use_list` | `identifier` (a leading `visibility_modifier` on `pub use` is
+  skipped by the find). moduleName = `getRootModule(useArg)`: recurse into
+  `namedChild(0)` — if type ∈ {identifier, crate, super, self} return its text;
+  if `scoped_identifier` recurse; else return the child's text; no child →
+  whole node text. So `use crate::m::Item` → import node named **`crate`**;
+  `pub use self::sub::read` → **`self`**; `use foo;` → `foo`. QUIRK:
+  `use std::fmt::*;` parses as `use_wildcard`, which is NOT in the useArg list
+  → hook returns null → and because the hook exists, extractImport's
+  `if (this.extractor.extractImport) return;` (tree-sitter.ts:3350) fires →
+  **wildcard uses create NO import node and NO refs at all**. `handledRefs` is
+  not set → the generic path ALSO pushes one `imports` ref for the root module
+  name (`crate`/`self`/`std`/…) from the file node (tree-sitter.ts:3183-3194).
+
+Hooks ABSENT (the walker must NOT do these): `preParse`, `resolveName`,
+`recoverMangledName`, `isMisparsedFunction`, `isConst`, `isStatic`,
+`isExported`, `resolveBody`, `classifyClassNode`, `classifyMethodNode`,
+`extractPropertyName`, `propertyTypes`, `fieldTypes`, `extraClassNodeTypes`,
+`packageTypes`/`extractPackage`, `extractModifiers`, `synthesizeMembers`,
+`extractBareCall`, `visitNode` hook, `skipBodilessClass`, `methodsAreTopLevel`.
+Consequences: every function/struct/enum/trait has `isExported` undefined
+(file node `false`; extractVariable's `?? false` → `false`); `isStatic`
+undefined; **no isConst means `const_item`/`static_item` extract as kind
+`'variable'`, never `'constant'`** (see extractVariable below).
+
+## tree-sitter.ts branches (anchors as of `ce0ae30`)
+
+### visitNode dispatch — what each top-level rust node hits
+
+| Node | Branch | Behavior |
+|---|---|---|
+| `function_item` (top level) | functionTypes, tree-sitter.ts:994 → extractFunction:1517 | not inside class-like at file scope → extractFunction; **first line of extractFunction (1522): if getReceiverType returns a value → extractMethod instead** (this is how impl-block fns become methods — impl_item does NOT push a scope) |
+| `function_signature_item` | same | in a trait body (trait pushed, class-like) → extractMethod; no `body` field → no body walk |
+| `struct_item` | structTypes:1059 → extractStruct:1869 | `body` field required: **unit structs `struct Unit;` have no body → NO node minted** (1876, `record_declaration` exemption is C#-only). Tuple structs have body `ordered_field_declaration_list` → extracted. `field_declaration` children make NO nodes (rust has no fieldTypes) — visitNode recurses into them and finds nothing |
+| `enum_item` | enumTypes:1064 → extractEnum:1914 | body `enum_variant_list`; `enum_variant` children → extractEnumMembers:1958 — **`name` field path: one `enum_member` node from `getChildByField(node,'name')`, then return** (variant payload bodies `B(u32)` / `C { x }` are never walked). Non-variant children (e.g. `attribute_item`) → visitNode (no-op) |
+| `trait_item` | interfaceTypes:1054 → extractInterface:1834 | kind `'trait'` (interfaceKind); extractInheritance sees the `trait_bounds` child (see below); body `declaration_list` children visited with the trait pushed → fn items become methods with QN `Trait::name` via nodeStack |
+| `impl_item` | dedicated branch:1273-1276 → extractRustImplItem:5690 | emits the implements back-reference (below); **skipChildren stays false** → the `declaration_list` is then visited normally by the loop at 1295 (that's how impl members are reached; impl pushes NOTHING on the nodeStack) |
+| `mod_item` | no branch | falls through → children visited. **No `module` node, no qualifiedName prefix** — items inside `mod tests { }` index as if at file scope. (frameworks/rust.ts:329 looks for `kind === 'module'` nodes and finds none from extraction — its `nodes[0]` fallback carries module resolution.) |
+| `use_declaration` | importTypes:1209 → extractImport:3170 | import node + root-module ref (hook, above) + `emitRustUseBindingRefs` (3217-3219, rust-only, below) |
+| `const_item` / `static_item` (top level) | variableTypes:1098 → extractVariable:2538 | **generic fallback branch (2863-2881)**: kind = `'variable'` ALWAYS (no isConst); iterate DIRECT namedChildren; **every child of type `identifier` mints a node** — for `const MAX: u32 = OTHER;` the children are identifier(MAX), primitive_type, identifier(OTHER) → **TWO `variable` nodes, `MAX` and the phantom `OTHER`** (probed). A non-identifier value (call, literal, array, struct_expression) → one node. Nodes get docstring + isExported:false, NO signature (unlike TS/Go branches). skipChildren=true, then `scanFnRefSubtree` (1110) capture-only. **No instantiates/calls refs from top-level initializers** — the value is never walked as a body |
+| `let_declaration` (top level) | variableTypes | only legal inside bodies, so effectively never taken (bodies don't route through extractVariable); it's in variableTypes for the fn-ref dispatch + shadow prune. A body `let` is plain recursion inside visitFunctionBody |
+| `type_item` | typeAliasTypes:1071 → extractTypeAlias:2890 | no resolveTypeAliasKind → plain `type_alias` node. QUIRK: the alias-value ref walk (2976) reads `getChildByField(node,'value')` — rust type_item's field is **`type`**, not `value` → null → **a rust type alias emits NO reference to its aliased type** |
+| associated `const_item` inside `impl` | variableTypes | impl pushes nothing → `!isInsideClassLikeNode()` is true → extracted as a FILE-level `variable` node (contains edge from the file), e.g. `impl Fields { const CAP … }` → variable `CAP`. PRESERVE |
+| associated `const_item` inside `trait` body | variableTypes gate FAILS | trait is pushed (class-like) and `isClassScopeConstantAssignment` needs node.type `assignment` → false → **no node**, but the else-ladder falls through with skipChildren=false → the const's value expression IS visited (a call in it emits a `calls` ref from the trait node) |
+| `associated_type` in trait, `macro_definition`, `attribute_item`, `extern_crate_declaration` | no branch | recursed, nothing extracted |
+| `macro_invocation` (top level) | no branch in visitNode | recursed into token_tree (raw tokens — nothing matches). **Route macros are only extracted inside function bodies** (visitFunctionBody:5141) — a top-level `routes![…]` emits nothing |
+| `struct_expression` | INSTANTIATION_KINDS:359, visitNode:1255 + body walker:5145 | extractInstantiation (below). In practice struct_expressions live in bodies |
+
+### Node creation, IDs, qualified names
+
+- `createNode` (1308): id = `generateNodeId(filePath, kind, name, startRow+1)`
+  = `` `${kind}:${sha256(`${filePath}:${kind}:${name}:${line}`).hex.slice(0,32)}` ``
+  (tree-sitter-helpers.ts:18). The FILE node id is the literal
+  `file:${filePath}` (tree-sitter.ts:509), NOT hashed. **Dedupe/self-checks
+  compare ID STRINGS** (same-(kind,name,line) collisions are routine — `node_ids`
+  vec pattern in every walker).
+- endLine extension via resolveBody (1329) is a no-op for rust (no hook).
+- contains edge from nodeStack top for every created node (1363).
+- qualifiedName = nodeStack names joined `::` (buildQualifiedName:1447;
+  namespacePrefix is always empty outside C/C++). Methods with a receiver
+  override it: `composeReceiverQualifiedName` (1435) = `` `${receiverType}::${name}` ``
+  verbatim for rust (prefix empty → passes through, per the 1433 comment).
+- File node: kind `file`, name basename, qualifiedName = filePath, endLine =
+  `source.split('\n').length`, isExported false.
+
+### extractFunction / extractMethod for rust (1517 / 1737)
+
+- extractFunction: receiverType present → extractMethod (1522). Name via
+  `extractName` → nameField `name` (identifier). No misparse hook. Node gets
+  docstring, signature, visibility, isExported:undefined, isAsync:false (bug
+  above), isStatic:undefined, returnType. Then extractTypeAnnotations,
+  extractDecoratorsFor (rust `attribute_item`s are SIBLINGS, not children, and
+  aren't `decorator`/`annotation`/`marker_annotation`/`attribute` types → **no
+  decorates refs for rust**, and the backward-sibling scan at 5013 stops at the
+  first attribute_item anyway). Push node, walk `body` field (block), pop.
+- extractMethod (reached for impl fns + trait members): receiverType computed
+  again (1742). Gate at 1747: not class-like AND no methodsAreTopLevel AND no
+  receiver → back to extractFunction (trait members pass via class-like; impl
+  fns via receiver). extraProps.qualifiedName = `Type::name` when receiver
+  (1790). **Contains edge from the owner (1798-1813): only when receiver
+  present AND not class-like — finds the FIRST node in `this.nodes` with
+  `name === receiverType && filePath === this.filePath && kind ∈
+  {struct,class,enum,trait}`. Source-order dependent: an impl ABOVE its struct
+  gets no contains edge. `impl Trait for Generic<T>` (receiver=trait bug) links
+  to the TRAIT node if it's in-file.** Then type annotations, decorators
+  (no-op), body walk with the method pushed.
+- **Nested `fn` inside an impl-method's body**: visitFunctionBody:5245 →
+  named → extractFunction → getReceiverType walks parents THROUGH the outer fn
+  to the impl_item → receiver found → extractMethod → a nested helper indexes
+  as a METHOD with QN `Type::inner` + contains edge from the type. PRESERVE.
+- structs/enums/traits declared inside a body are extracted there
+  (5255-5275), contained by the enclosing function node.
+
+### extractCall (3684) — the rust paths
+
+Generic else-branch (4312+), `func = childForFieldName('function') ?? namedChild(0)`:
+
+1. `func.type === 'field_expression'` (method call `x.foo()`): property =
+   `field` field (`property` misses). receiver = object/operand/argument
+   fields → all null for rust → `func.namedChild(0)` (the `value`).
+   - receiver type in LITERAL_RECEIVER_TYPES (373) → emit NOTHING (#1230).
+     Rust members of the set: `string_literal`, `raw_string_literal`,
+     `integer_literal`, `float_literal`, `char_literal`, `boolean_literal`.
+     QUIRK: rust `array_expression`/`tuple_expression`/`struct_expression`
+     receivers are NOT in the set (it has `array`/`array_literal`, other
+     grammars' names) — `[1,2].len()` falls through to the bare-name path and
+     emits `calls` ref `len`. PRESERVE.
+   - receiver `identifier` (not in SKIP_RECEIVERS {self,this,cls,super}) →
+     `recv.method`. NOTE rust `self` is node type `self`, NOT `identifier`,
+     so `self.own()` skips this branch and lands on the fallthrough → bare
+     `own` (same net effect as SKIP, different path — probed).
+   - receiver `call_expression` + rust in the gate list (4413) →
+     chained-call re-encode: `innerFn = receiver.childForFieldName('function')`,
+     `innerCallee = text(innerFn).replace(/->/g,'.').replace(/\s+/g,'')`;
+     **rust re-encodes ONLY when `innerFn.type === 'scoped_identifier'`**
+     (4455) → `Foo::new().bar()` → ref `Foo::new().bar`; an instance chain
+     `x.foo().bar()` (innerFn field_expression) → bare `bar`. When not
+     re-encoding, calleeName = bare methodName.
+   - receiver anything else (`field_expression` 2-hop `v.field.method()`,
+     `parenthesized_expression`, `await_expression`, `self`) → bare
+     methodName (probed all four).
+2. `func.type === 'scoped_identifier'` (4499) → calleeName = FULL text
+   (`Foo::new`, `m::helper2`, `std::mem::swap` — whatever the source spells,
+   whitespace included).
+3. else → calleeName = raw func text: bare `helper` for identifier;
+   **`generic_function` (turbofish `helper::<T>`) keeps the full
+   `helper::<T>` text — unresolvable downstream, PRESERVE** (probed).
+
+Post-processing: the parenthesized-conversion regex (4530) can in principle
+match `(Foo)(x)` shapes — rust parses a parenthesized callee as
+`parenthesized_expression` so text starts `(` → regex CAN fire; harmless and
+must match. Template-arg strip (4542) and cpp fn-ptr fan-out (4556) are
+c/cpp-gated — NOT for rust. Finally one `calls` ref {callerId, name, line =
+call startRow+1, column = call startColumn (UTF-16)}. Inner calls of a chain
+are ALSO visited (the body walker recurses after extractCall), so
+`Foo::new().bar()` emits BOTH `Foo::new().bar` and `Foo::new`.
+
+`extractCall` returns immediately when the nodeStack is empty — never the case
+in practice (file node is pushed).
+
+### extractInstantiation — `struct_expression` (359, 4610)
+
+ctor = constructor/type/**name**(rust)/namedChild(0). Not
+composite_literal/instance_expression → generic path: text; strip from first
+`<`; then `lastDot = max(lastIndexOf('.'), lastIndexOf('::'))` → keep trailing
+segment (`m::Widget { }` → `Widget`); trim; emit `instantiates` ref at the
+struct_expression's position. Fires from visitNode (top-level expressions) AND
+visitFunctionBody (5145). Top-level const/static initializers never reach it
+(extractVariable skips walking — quirk noted above).
+
+### Rocket route macros — extractRustRouteMacro (5048), body-walker-only (5141)
+
+Gate: `this.language === 'rust'`; macroName = `node.namedChild(0)` (the
+`macro` field identifier); name must be EXACTLY `routes` or `catchers` — a
+scoped `rocket::routes![…]` has a scoped_identifier there whose text doesn't
+match → skipped (PRESERVE). tokenTree = first namedChild of type `token_tree`.
+fromId = nodeStack top. Walk `tokenTree.child(i)` (ALL children, anonymous
+included): `identifier` tokens accumulate into `parts` (first one records
+line/column); a `,` token flushes `parts.join('::')` as ONE ref
+{referenceKind: **`references`**}; final flush after the loop (the closing `]`
+is not a flush trigger — the trailing path flushes at end). Probed token
+stream: `[ id :: id :: id , id ]` — `::` are anonymous and skipped by the
+identifier/`,` switch. Consumed by `resolveRustPathReference`
+(import-resolver.ts:1781).
+
+### emitRustUseBindingRefs (3451) — one `imports` ref per use binding
+
+Called from extractImport for every `use_declaration` (3217). Recursive
+`collect(n, prefix)` over the declaration's namedChildren:
+
+- `identifier` → push `join(prefix, text)` (`join` = `prefix ? prefix+'::'+seg : seg`)
+- `scoped_identifier` → push `prefix ? prefix+'::'+trim(fullText) : trim(fullText)`
+  (the FULL path text — `crate::m::Item`, `self::sub::read`)
+- `scoped_use_list` → prefix' = join(prefix, trim(text of `path` field));
+  recurse into `list` field (`?? namedChildren.find(type==='use_list')`)
+- `use_list` → recurse each namedChild with same prefix
+- `use_as_clause` → recurse the `path` field (`?? namedChild(0)`) — links the
+  SOURCE path, not the alias (probed: fields are path/alias)
+- everything else (visibility_modifier, `use_wildcard`, bare `crate`/`self`/
+  `super` nodes) → ignored
+
+Then per collected path: leaf = last `::` segment; skip if leaf ∈
+{self, super, crate, *} or empty; push {fromNodeId: file, referenceName: FULL
+path, referenceKind:'imports', line/col of the collected node}. So
+`use crate::m::{A, B as C, sub::D}` emits `crate::m::A`, `crate::m::B`,
+`crate::m::sub::D` (plus the hook's root-module ref `crate` and the import
+node named `crate`).
+
+### Inheritance — extractInheritance for rust (5291)
+
+Only ONE child type matters for rust nodes: **`trait_bounds`** (5515, on
+trait_item — supertraits `trait Sub: Super + Display`). Per bound child:
+
+- `type_identifier` → name = text
+- `generic_type` (`Deserialize<'de>`) → inner namedChild of type
+  `type_identifier` → its text
+- `higher_ranked_trait_bound` (`for<'de> Deserialize<'de>`) → its
+  `generic_type` child's inner type_identifier, else its own direct
+  `type_identifier`
+- **QUIRK, PRESERVE: `scoped_type_identifier` (`fmt::Debug`) matches NO case →
+  a path-qualified supertrait emits NOTHING** (probed: `trait Render: Base +
+  fmt::Debug` → only `Base`).
+
+Each yields an `extends` ref from the trait node at the bound's position.
+Struct/enum extraction also calls extractInheritance; rust struct_item children
+include `field_declaration_list` → the 5652 recursion descends, but rust
+`field_declaration` always carries a `field_identifier` name so the Go
+struct-embedding branch (5496) never fires. Verify with the torture fixture
+anyway.
+
+### impl Trait for Type — extractRustImplItem (5690)
+
+- hasFor = any child (ALL children) with `type === 'for' && !isNamed` — plain
+  `impl Type { }` → return (no edge; getReceiverType handles member attachment).
+- typeIdents = DIRECT namedChildren of type `type_identifier` | `generic_type`
+  | `scoped_type_identifier`; need ≥2 else return (v0.24.2 has `trait:` and
+  `type:` FIELDS, but the code deliberately uses positional filtering —
+  PRESERVE the positional logic).
+- traitNode = FIRST, typeNode = LAST. traitName: scoped_type_identifier →
+  `source.substring(startIndex,endIndex)` (full `fmt::Display`); else
+  getNodeText. typeName: generic_type → inner type_identifier text (`Container`)
+  else text.
+- targetId = `findNodeByName(typeName)` (5740): FIRST node in `this.nodes`
+  with that name and kind ∈ {struct, enum, class} — **NOT trait**, and
+  source-order dependent (the type must be defined EARLIER in the same file;
+  cross-file impls emit nothing). If found: push
+  {fromNodeId: **the TYPE's node id** (a back-reference), referenceName:
+  traitName (full path text), referenceKind:'implements', line/col of the
+  trait node}.
+
+### Type-annotation references (5752-6112)
+
+`rust` ∈ TYPE_ANNOTATION_LANGUAGES (5753). For every function/method:
+extractTypeAnnotations (5788) walks (a) the `parameters` field subtree and
+(b) the `return_type` field subtree with extractTypeRefsFromSubtree (6090),
+emitting one `references` ref per **`type_identifier` leaf** whose text isn't
+in BUILTIN_TYPES (5768). The set includes the rust primitives (`str bool
+i8…u128 usize isize f32 f64 char`) — mostly redundant since rust primitives
+parse as `primitive_type`, not `type_identifier` — plus cross-language rows
+(`error`, `String` via the Scala block, `Int`/`Any`/…). Port the WHOLE set
+verbatim: a rust `type_identifier` named `String` IS suppressed (Scala row),
+while `Vec`/`Option`/`Box`/`Self` are NOT. QUIRKS, PRESERVE:
+
+- Generic parameters are emitted: `fn get(&self) -> &T` → ref `T`;
+  `Result<Baz, E>` → refs `Result`, `Baz`, `E`.
+- `-> Self` → ref `Self` (type_identifier, not builtin).
+- `scoped_type_identifier` (`fmt::Formatter`) → only the inner
+  `type_identifier` leaf `Formatter` (the `path` identifier is not a
+  type_identifier); the ref is UNQUALIFIED.
+- `where` clauses and `type_parameters` bounds are NOT walked (params +
+  return_type fields only; the type_parameters walk at 5863 is scala-gated).
+- The trailing `type_annotation` child lookup (5873, and
+  extractVariableTypeAnnotation:6074 whose comment says "covers … Rust
+  `: Type`") is a NO-OP for rust — the grammar has no `type_annotation` node
+  (let/const types are direct `type` fields). Dead comment, no behavior.
+- property_signature/method_signature branch (1283) — TS-only node types,
+  never rust.
+
+### Static-member refs, cpp-isms — NOT rust
+
+`rust` ∉ STATIC_MEMBER_LANGS (345) → extractStaticMemberRef no-ops (its call
+in the body walker at 5218 must be a no-op in the walker too — cheap early
+return). namespacePrefix, cppLocalFnPtrs, stack-construction, operator calls,
+template strip: all c/cpp-gated, none apply.
+
+### Docstrings (tree-sitter-helpers.ts:95)
+
+`///` and `//!` are `line_comment` nodes; consecutive preceding named siblings
+of the item accumulate (unshift → source order), then cleanCommentMarkers
+strips `^\/\/[/!]?\s?` per line (multiline `gm` — the CRLF `^`-after-`\r` trap
+from #1329 applies; use `js_multiline_strip` in docstring.rs). QUIRK,
+PRESERVE: **an `attribute_item` between the doc comment and the item breaks
+the sibling chain** — `/// doc` + `#[derive(Debug)]` + `struct Doc` → NO
+docstring (probed; attribute_item is a named sibling and not a comment type).
+DOCSTRING_WRAPPER_TYPES contains no rust wrappers → no climbing. Block
+`/** */`-style (`block_comment`) is also accepted by the sibling scan and
+`/*`-stripped.
+
+### Value-reference edges (398-931) — rust IS in VALUE_REF_LANGS (401)
+
+Port the full machinery (crib go.rs/tsjs): `CODEGRAPH_VALUE_REFS=0` kill;
+MAX_VALUE_REF_NODES=20_000 caps BOTH the prune scan and each reader scan;
+`isGeneratedFile` skip.
+
+- Targets (captureValueRefScope:735): created nodes of kind
+  constant/**variable** (rust consts are `variable` — still targets), name
+  length ≥3 AND `/[A-Z_]/` test, parent scope id starting `file:` (also
+  class:/module:/struct:/enum: — rust consts always land under file:). Count
+  per name in fileScopeValueCounts.
+- Reader scopes: every function/method/constant/variable node.
+- Shadow prune (803-878): DFS of the whole tree counting declarators of
+  target names — rust cases: `const_item`/`static_item` → bump
+  `childForFieldName('name')` (823-825); **`let_declaration`** (the shadow
+  source, 827) → left ?? `pattern` ?? namedChild(0); if the pattern is an
+  `identifier` bump it, else bump every namedChild of the pattern (tuple
+  patterns). bump() only counts `identifier`/`simple_identifier` nodes whose
+  text is a target. After the scan: `declCount > fileScopeCount` → target
+  deleted (a local `let MAX = …` shadows the file `const MAX`).
+- Emission (880-930): per reader scope, DFS its node subtree (rust bodies are
+  children — the Dart/Pascal sibling pull at 891 is inert); each
+  `identifier` (also constant/name/simple_identifier — non-rust) whose text
+  maps to a target and target ≠ self-id and name ≠ scope's own name and not
+  yet seen → EDGE (not unresolved ref): {source: scopeId, target: targetId,
+  kind:'references', metadata:{valueRef:true}}, deduped per (scope,target).
+
+### Function-as-value capture (#756) — RUST_SPEC (function-ref.ts:217)
+
+idTypes={identifier}; dispatch:
+`arguments`→args, `assignment_expression`→rhs(field `right`),
+`field_initializer`→value(field `value`), `array_expression`→list,
+`static_item`→varinit(field `value`), `let_declaration`→varinit(field `value`).
+NO layers/unwrap/special/ungatedModes/addressOfOnly. QUIRK: **`const_item` is
+NOT in the dispatch** — a `const TABLE: [fn(); 2] = [a, b];` captures via the
+inner `array_expression`, but `const CB: fn() = handler;` captures nothing
+(static_item does). Capture mechanics (function-ref.ts:408-597):
+
+- args/list: every namedChild is a candidate value.
+- rhs: the `right` field, with the param-storage skip — if the LHS's last
+  identifier (`/([A-Za-z_$][A-Za-z0-9_$]*)\s*$/` on LHS text) EQUALS the RHS
+  text, skip (`o.cb = cb`).
+- varinit: name/pattern field of type object_pattern/array_pattern/
+  **tuple_pattern/struct_pattern** → skip whole container (destructuring);
+  else the `value` field.
+- normalizeValue: bare `identifier` → candidate (NAME_STOPLIST drops
+  this/self/true/None/…). No unwrap → `&handler` (a rust `reference_expression`)
+  yields NOTHING — rust captures only bare identifiers. explicitRef = false
+  always (idTypes hit).
+- Capture fires from visitNode:990 AND visitFunctionBody:5137 AND
+  scanFnRefSubtree (top-level initializers, halts at nested functionTypes,
+  depth ≤12).
+- Flush gate (flushFnRefCandidates:639): generated-file skip; candidate name
+  must be in definedHere (same-file function/method NAMES) ∪ importedNames.
+  QUIRK, PRESERVE: importedNames admits `SIMPLE_NAME` (`/^[A-Za-z_$][A-Za-z0-9_$]*$/`)
+  or `QUALIFIED_IMPORT` with `.`/`\` separators only — **rust's `::`-separated
+  import refs (`crate::m::helper`) match NEITHER, so rust use-imports
+  contribute nothing to the gate** except single-segment ones (`use foo;` →
+  `foo`, and every root-module ref `crate`/`self`/`std`). Net: the rust fn-ref
+  gate is effectively "defined in this file". Survivors dedupe on
+  `${fromNodeId}|${name}` and push {referenceKind:'function_ref'}.
+
+### Misc shared paths
+
+- Import/refs positions: `line = startPosition.row + 1`,
+  `column = startPosition.column` — **UTF-16 code units** (textutil::col16),
+  as are `startIndex/endIndex` substrings and `.slice(0,100)` truncations.
+- Refs carry NO filePath/language (the store denormalizes) — kernel wire
+  contract is exactly extractFromSource's return.
+- `extract()` wraps everything: file node first, nodeStack=[fileId], no
+  packageNode for rust; flushFnRefCandidates then flushValueRefs at the end.
+- Parse errors: the walker defers `has_error()` files (`defer:` signal);
+  wasm's error recovery is canonical. tree.delete()/source-release are
+  wasm-side concerns.
+
+## Frameworks that consume rust extraction artifacts (stay TS-side)
+
+`rustResolver` (resolution/frameworks/rust.ts) — detect: `Cargo.toml`.
+
+- **`extract()` (regex over raw source, runs in extractFromSource AFTER either
+  arm — NO port needed, but its INPUT contract must hold):** emits `route`
+  nodes with id `` `route:${filePath}:${line}:${METHOD}:${path}` `` (NOT
+  hashed), kind `route`, name `` `${METHOD} ${path}` ``, qualifiedName
+  `` `${filePath}::route:${path}` ``, language `rust`; plus one
+  `references` ref per handler FROM the route node (these framework refs DO
+  carry filePath+language — resolution/types' UnresolvedRef, unlike extraction
+  refs). Covers `#[get("/…")]` attributes (Actix/Rocket), Axum
+  `.route("/p", get(h))` chains, Actix builder `web::resource(...).to(h)`.
+- **Extraction-side emissions the port MUST reproduce for rust resolution to
+  keep working:** (a) `emitRustUseBindingRefs`'s FULL-path `imports` refs and
+  (b) `extractRustRouteMacro`'s `::`-joined `references` refs — both consumed
+  by `resolveRustPathReference` (import-resolver.ts:1446/1781); (c) the
+  root-module `imports` ref that `resolveModule`/cargo-workspace mapping
+  resolves (module refs like `use foo;` → `src/foo.rs` / workspace crates).
+- `cargo-workspace.ts` (path-aliases §) reads Cargo.toml manifests only —
+  untouched.
+
+## Gates (per plan §5, no exceptions)
+
+- **Torture fixture `torture.rs`** (+ CRLF variant, derived in-memory), pinning
+  at minimum: unit struct (NO node) / tuple struct / field struct; enum with
+  unit+tuple+struct variants; trait with supertraits incl. a SCOPED one
+  (`fmt::Debug` — dropped) + `function_signature_item` + default method +
+  associated type/const (no node; const value call attributes to trait);
+  inherent impl (methods, associated const → file-level `variable`); `impl
+  Trait for Type`; `impl fmt::Display for Type` (scoped trait name text);
+  `impl<T> Generic<T>` (generic-branch receiver); **`impl Trait for
+  Generic<T>` (receiver = TRAIT bug)**; impl ABOVE its struct (no contains
+  edge); nested fn inside an impl method (becomes a method); `pub async fn`
+  (isAsync stays false); `-> Self` / `-> &Foo` / `-> Vec<Foo>` /
+  `-> Result<Vec<Foo>, E>` (returnType undefined) / `-> fmt::Result`;
+  turbofish call; `Foo::new().bar()` chain + instance chain `x.foo().bar()`;
+  `self.method()`; 2-hop `v.field.method()`; literal receiver `"x".len()`
+  (nothing); `m::helper()` scoped call; struct_expression plain + `m::Widget`
+  + inside fn args; use forms: single, grouped, `as` alias, nested group
+  path, `pub use`, wildcard (NO import node), bare `use foo;`;
+  `const X: T = OTHER;` (phantom second node) + static with array value;
+  file-scope const read + `let`-shadowed const (value-ref prune); fn-ref
+  shapes: `register(handler)`, `obj.cb = handler2`, `Widget { cb: handler }`,
+  `[cb_a, cb_b]`, `static CB: fn() = handler`, `let cb = handler`, tuple-let
+  skip; `routes![a::b::h1, h2]` + `catchers![x]` + `rocket::routes![…]`
+  (skipped) inside a body AND one at top level (skipped); doc comments incl.
+  `//!`, a `/* */` block, and the attribute-breaks-docstring case; a mod
+  with items (no module node, bare QNs).
+- **Parity sweeps** (`scripts/kernel-parity.mjs`, order-sensitive full-object):
+  **ripgrep (small), tokio (medium), rust-analyzer (large)** — all three also
+  exercise heavy `pub use` re-export hubs and macro use. Then **full-init
+  dump-diffs byte-identical** (kernel arm vs `CODEGRAPH_KERNEL=0`,
+  `dump-graph.mjs`, cmp) on the same three.
+- **Deferral-rate guard: default `--max-deferral 0.1` and expect FAR under it**
+  — rust is not macro-mangled C; parse-error incidence should sit in the
+  ts/java/py/go norm (0–0.42%). Double-digit deferral on a rust sweep means a
+  broken walker, not grammar reality (the c/cpp 0.5 exemption does NOT carry
+  over).
+- Grammar-bump isolation: the vendored v0.24.2 wasm + `=0.24.2` crate pin land
+  FIRST with the full suite green (kernel-grammar-parity sha-matches parser.c;
+  crate + wasm move together or it fails).
+- Suite green with `CODEGRAPH_KERNEL_EXPECT=1`; unit tests for the walker in
+  `__tests__/kernel-rustlang-parity.test.ts` (or folded into the existing
+  parity suites); changelog rides the existing kernel entry.
+- `DEFAULT_ROUTED += rust` (kernel/index.ts:37) only after ALL of the above.
+- Post-route perf sanity: remember decision §arch-2 — Cargo repos take the
+  decoded path (framework extract()), so measure the parse-loop, not the
+  raw-buffer transport.

+ 2 - 1
scripts/kernel-parity.mjs

@@ -48,7 +48,7 @@ if (paths.length === 0) {
   process.exit(2);
 }
 
-const KERNEL_LANGS = new Set(['typescript', 'tsx', 'javascript', 'jsx', 'java', 'python', 'go', 'c', 'cpp']);
+const KERNEL_LANGS = new Set(['typescript', 'tsx', 'javascript', 'jsx', 'java', 'python', 'go', 'c', 'cpp', 'rust']);
 const EXTS = new Map([
   ['.ts', 'typescript'], ['.mts', 'typescript'], ['.cts', 'typescript'],
   ['.tsx', 'tsx'], ['.js', 'javascript'], ['.mjs', 'javascript'],
@@ -58,6 +58,7 @@ const EXTS = new Map([
   ['.c', 'c'], ['.h', 'detect'],
   ['.cpp', 'cpp'], ['.cc', 'cpp'], ['.cxx', 'cpp'], ['.hpp', 'cpp'], ['.hxx', 'cpp'],
   ['.metal', 'cpp'], ['.cu', 'cpp'], ['.cuh', 'cpp'],
+  ['.rs', 'rust'], // R7b
 ]);
 
 /** Collect candidate files. */

+ 4 - 0
src/extraction/grammars.ts

@@ -297,6 +297,10 @@ const VENDORED_WASM_LANGS: ReadonlySet<GrammarLanguage> = new Set([
   // the crates.io tarballs. `.metal`/`.cu` map to language 'cpp', so the
   // dialects ride the same (single, coherent) upgraded grammar.
   'c', 'cpp',
+  // R7b (Rust kernel port prep): tree-sitter-rust v0.24.2 (77a3747),
+  // parser.c/scanner.c sha-matched against the crates.io tarball. Replaces the
+  // 2023-era tree-sitter-wasms build (ABI 14 → 15).
+  'rust',
 ]);
 
 /** Absolute path of a language's grammar WASM (vendored or tree-sitter-wasms). */

+ 6 - 0
src/extraction/kernel/index.ts

@@ -48,6 +48,12 @@ const DEFAULT_ROUTED: ReadonlySet<Language> = new Set<Language>([
   // scripts/kernel-parity.mjs --max-deferral).
   'c',
   'cpp',
+  // R7b (2026-07-20): parity swept 0-diff on ripgrep/tokio/rust-analyzer
+  // (2,108 files byte-parity) + full-init dump-diffs byte-identical. Rust
+  // deferral is ~0% on normal repos; token-macro-table sources (rust-analyzer's
+  // parser crates, 18%) error on BOTH arms — grammar-inherent, not a walker
+  // signal.
+  'rust',
 ]);
 
 /**

BIN=BIN
src/extraction/wasm/tree-sitter-rust.wasm