From ed1a89fb0f9ad996632497463f158bdaf7b68e2c Mon Sep 17 00:00:00 2001 From: Colby Mchenry Date: Mon, 5 Oct 2026 21:59:11 +0000 Subject: [PATCH] fix(rust): a variant path references the enum that declares it (#2328) (#2354) Using an enum only through its variants (`mode::Mode::A` in an expression, `mode::Mode::A => 1` / `Mode::B => ...` in a match, a `Mode::C(x)` or `Mode::D { .. }` pattern) recorded no reference to the enum, so code that builds or matches variants was missing from the enum's callers and impact. Only a type annotation (`fn takes(_m: Mode)`) produced one. Cause: Rust was not in the static-member pass, which turns `Enum.value` / `Type::CONST` reads into references for Java, C#, Kotlin, Swift, Scala, Dart, PHP and C++, and a path to a variant that is not a call or a struct literal reaches no other extractor. Fix: - Extraction (wasm extractor and native kernel, mirrored): a path whose last segment is capitalized emits a `references` ref named by its receiver (the segment before it; `Self` read as the impl's type, nothing in a trait), positioned at the receiver, so a `mode::` prefix scopes it exactly as it scopes a type annotation. Covers value reads, match arms, `|` / `if let` patterns, tuple- and struct-variant patterns and a variant passed as a value. A call's callee (`Mode::C(1)`, `Foo::new()`), a struct literal, a longer path's prefix, a `use` tree and a lowercase receiver or member emit nothing. - Resolution (isRustNameInScope): a reference written `Name::Variant` or `Self::Variant` lands only on an enum that declares that variant, after the usual Rust scoping (module path, `use`, glob, prelude, std and dependency imports). ripgrep's `Match::None` reaches `ignore`'s enum, not the matcher's `struct Match`; std variants (`Ordering::Less`, `Option::Some`) never reach a same-named project enum; associated consts and functions (`Limits::MAX`, `Mode::ALL`, `Foo::new()`) reference no type. `Self::X` is read as the impl's type, never through a path written elsewhere on its line. Adapted from #2330 by @danusha2345: the extraction half (both walkers) and most of the tests are theirs. Changed here: - The resolver accepts a declared variant only. #2330 also accepted any type whose file holds a variable or const of the item's name; impl consts are file-level variables in the graph, so that cannot tell a type's associated const from another type's or a top-level one. - The walkers check the node kind before looking at its parent, and the body walk hands the parent down: #2330 called `parent()`, which walks down from the tree's root, for every node of every body, which nearly doubled the kernel's Rust extraction time on tokio (2.1 s -> 3.9 s); now within noise of main. - EXTRACTION_VERSION is not bumped again (already 28 on main). Verification: __tests__/rust-enum-variant-reference.test.ts (10 tests): 6 fail on main in wasm mode, in kernel mode, and with this TypeScript over main's kernel binary; 10/10 pass in both modes. The kernel parity case covers every shape and asserts the refs exist; the kernel-parity sweep over ripgrep, alacritty and tokio is 1004/1006 files byte-parity, 0 diffs (2 parse-error files defer to wasm by policy). Validation (native kernel loaded, main -> branch, edges keyed by QN/kind/file/line): ripgrep +822/-0, alacritty +917/-0, tokio +665/-0, all `references -> enum`, node counts unchanged. Every added edge's source reads `Name::Variant` / `Self::Variant` at its column and its target enum declares that variant; no std enum targets. New symbol->enum pairs: ripgrep +220, alacritty +253, tokio +254; enums with no referencer before and one now: 31 / 13 / 31. One wrong target on tokio (`oneshot::error::TryRecvError::Empty` -> mpsc's `TryRecvError`) comes from the existing path rule that checks only the last module segment, which type annotations share. Index time on tokio stays within noise of main (interleaved runs; resolveOne time 27.7 s vs 31.2 s summed over workers). Co-authored-by: danusha2345 Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 1 + __tests__/kernel-rustlang-parity.test.ts | 40 ++ __tests__/rust-enum-variant-reference.test.ts | 347 ++++++++++++++++++ codegraph-kernel/src/rustlang.rs | 72 +++- .../design/rust-lang-kernel-port-checklist.md | 17 +- src/extraction/tree-sitter.ts | 53 ++- src/resolution/name-matcher.ts | 25 +- 7 files changed, 540 insertions(+), 15 deletions(-) create mode 100644 __tests__/rust-enum-variant-reference.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 047fb9d5e..d46e1fef9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - In Go, calls into a module whose `go.mod` is not at the project root now resolve, whether it is a `server/` backend next to a `web/` frontend or one of several modules side by side as in etcd, so calls like `store.New()` and `s.db.CreateItem()` find their targets instead of being treated as calls into a third-party package. A name written through a package, like a `job.OPCommand` result type or a field of type `artifact.Manager`, now links to that package's symbol rather than a same-named one elsewhere, which also corrects links in projects with a single `go.mod`. Re-index Go projects after upgrading. Thanks @GoDiao for the report and @danusha2345 for the fix. (#2322) - Indexing a project that includes large bundled JavaScript files, such as a copy of pdf.js or d3, is fast again: since 1.6.2, resolving the calls in a JavaScript or TypeScript file re-read the file's text above each call, so a single bundled library could add many seconds to an index. The graph it builds is unchanged. Thanks @bompus for the report. (#2334) - The time `codegraph init` and `codegraph index` print beside the node and edge counts now covers the whole run, resolving references and linking included, and `codegraph sync` reports its whole run the same way. Before, it counted only reading and parsing the files, which can be a small part of an index, so a slow index looked fast. Thanks @bompus for the report. (#2334) +- In Rust, code that uses an enum only through its variants, like `mode::Mode::A` in an expression, a `Mode::B =>` match arm or `Self::A` inside the enum's own `impl`, now shows up in that enum's callers and impact, linked to the enum that actually declares the variant rather than to a same-named type elsewhere. Standard-library variants like `Ordering::Less` or `Option::Some` and associated items like `Foo::new()` or `Foo::MAX` don't count as using a project enum. Re-index Rust projects after upgrading. Thanks @mg-mg-mg for the report and @danusha2345. (#2328) ## [1.6.2] - 2026-10-03 diff --git a/__tests__/kernel-rustlang-parity.test.ts b/__tests__/kernel-rustlang-parity.test.ts index 3380ae67a..523aab0fd 100644 --- a/__tests__/kernel-rustlang-parity.test.ts +++ b/__tests__/kernel-rustlang-parity.test.ts @@ -113,6 +113,46 @@ fn next() {} assertParity('commands.rs', source.replace(/\n/g, '\r\n')); }); + it('variant paths reference their receiver (#2328)', () => { + const source = ` +use crate::mode::{self, Mode}; +const DEFAULT: Mode = Mode::A; +impl Mode { + fn flip(&self) -> u8 { + let _s = "ü"; let _x = Self::B; + match self { Self::A => 1, Mode::C(x) => *x, mode::Mode::D { x } => *x, _ => 0 } + } +} +trait Tr { fn t(&self) { let _ = Self::K; } } +fn uses() { + use crate::mode::Mode::A; + let _a = crate::mode::Mode::A; let _b = Mode::C(1); let _c = Mode::D { x: 2 }; + let _d = Mode::new(); let _e = util::take(3); let _f = u8::MAX; let _g = Limits::MAX; + let _h = xs.map(Mode::C); let _i = Option::::None; let _j = Mode::A.flip(); + if let Mode::C(x) | Mode::B = m {} + match o { Option::Some(_) => std::cmp::Ordering::Less, _ => cmp::Ordering::Greater }; +} +`; + assertParity('variants.rs', source); + assertParity('variants.rs', source.replace(/\n/g, '\r\n')); + + // Not vacuous: each path to a capitalized member outside a call's callee, + // a struct literal and a `use` is a `references` ref to its receiver + // (`Self` read as the impl's type; none in a trait). The resolver decides + // which of them name a project enum's variant. + process.env.CODEGRAPH_KERNEL = '0'; + const refs = extractFromSource('variants.rs', source, 'rust').unresolvedReferences; + delete process.env.CODEGRAPH_KERNEL; + const lines = source.split('\n'); + const paths = refs + .filter((r) => r.referenceKind === 'references' && /^\w+\s*::/.test(lines[r.line - 1]!.slice(r.column))) + .map((r) => `${r.referenceName}:${r.line}`); + expect(paths.sort()).toEqual([ + 'Limits:14', 'Mode:13', 'Mode:15', 'Mode:15', 'Mode:16', 'Mode:16', 'Mode:3', 'Mode:6', + 'Mode:7', 'Mode:7', 'Mode:7', 'Option:17', 'Ordering:17', 'Ordering:17', + ]); + }); + 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); diff --git a/__tests__/rust-enum-variant-reference.test.ts b/__tests__/rust-enum-variant-reference.test.ts new file mode 100644 index 000000000..6d7aee2c5 --- /dev/null +++ b/__tests__/rust-enum-variant-reference.test.ts @@ -0,0 +1,347 @@ +/** + * A Rust enum used only through its variants is a dependency of the code that + * uses them (#2328). `mode::Mode::A` in an expression, `Mode::B => …` in a + * `match`, a `Mode::C(x)` / `Mode::D { .. }` pattern and `Self::A` in the + * enum's impl reference the enum that declares the variant — the same + * `references` edge a type annotation (`fn takes(_m: Mode)`) produces. Nothing + * else read through a path does: not an associated const or function + * (`Limits::MAX`, `Mode::new()`), not a standard-library enum's variant. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { CodeGraph } from '../src'; + +let root: string; +let cg: CodeGraph | undefined; +beforeEach(() => { root = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-rust-variant-ref-')); }); +afterEach(() => { cg?.close(); cg = undefined; fs.rmSync(root, { recursive: true, force: true }); }); + +async function index(files: Record) { + fs.mkdirSync(path.join(root, 'src')); + fs.writeFileSync(path.join(root, 'Cargo.toml'), '[package]\nname = "repro"\nversion = "0.1.0"\nedition = "2021"\n'); + for (const [file, text] of Object.entries(files)) fs.writeFileSync(path.join(root, 'src', file), text); + cg = await CodeGraph.init(root, { index: true }); +} + +/** The enum named `name` declared in `src/`. */ +function enumIn(file: string, name = 'Mode') { + const node = cg!.getNodesByKind('enum').find((n) => n.filePath === `src/${file}` && n.name === name); + expect(node, `enum ${name} in ${file}`).toBeDefined(); + return node!; +} + +/** `file:name` of every symbol with a `references` edge to the node. */ +function referencers(nodeId: string): string[] { + const names = cg!.getIncomingEdges(nodeId) + .filter((e) => e.kind === 'references') + .map((e) => cg!.getNode(e.source)!) + .map((n) => `${n.filePath.replace(/^src\//, '')}:${n.name}`); + return [...new Set(names)].sort(); +} + +const MODE = `pub enum Mode { + A, + B, + C(u8), + D { x: u8 }, +} + +pub fn takes(_m: Mode) {} + +pub fn current() -> Mode { Mode::B } +`; + +describe('Rust enum variant paths reference their enum (#2328)', () => { + it('the issue: a variant path in an expression and in match arms, through the module', async () => { + await index({ + 'mode.rs': MODE, + 'variant_use.rs': `use crate::mode; + +pub fn code(flag: bool) -> u8 { + let m = if flag { mode::Mode::A } else { mode::Mode::B }; + match m { + mode::Mode::A => 1, + mode::Mode::B => 2, + _ => 3, + } +} +`, + 'main.rs': `mod mode; +mod variant_use; + +fn main() { + mode::takes(mode::Mode::A); + let _ = variant_use::code(true); +} +`, + }); + expect(referencers(enumIn('mode.rs').id)).toEqual(['main.rs:main', 'mode.rs:current', 'mode.rs:takes', 'variant_use.rs:code']); + }); + + it('a bare `Mode::A` after `use crate::mode::Mode;`', async () => { + await index({ + 'lib.rs': 'pub mod mode;\npub mod bare;\n', + 'mode.rs': MODE, + 'bare.rs': `use crate::mode::{self, Mode}; + +pub fn pick() -> u8 { + let _m = Mode::B; + 0 +} + +pub fn score() -> u8 { + match mode::current() { + Mode::A => 1, + _ => 0, + } +} +`, + }); + expect(referencers(enumIn('mode.rs').id)).toEqual(['bare.rs:pick', 'bare.rs:score', 'mode.rs:current', 'mode.rs:takes']); + const pick = cg!.getNodesByKind('function').find((n) => n.name === 'pick')!; + const at = cg!.getOutgoingEdges(pick.id).filter((e) => e.kind === 'references').map((e) => `${e.line}:${e.column}`); + expect(at).toEqual(['4:13']); + }); + + it('tuple and struct variant patterns, and a variant read as a value', async () => { + await index({ + 'lib.rs': 'pub mod mode;\npub mod pat;\n', + 'mode.rs': MODE, + 'pat.rs': `use crate::mode::{self, Mode}; + +pub fn tuple() -> u8 { + match mode::current() { + Mode::C(x) => x, + _ => 0, + } +} + +pub fn structure() -> u8 { + if let crate::mode::Mode::D { x } = mode::current() { x } else { 0 } +} + +pub fn ctor_value(xs: Vec) -> usize { + xs.into_iter().map(Mode::C).count() +} +`, + }); + expect(referencers(enumIn('mode.rs').id)).toEqual([ + 'mode.rs:current', 'mode.rs:takes', 'pat.rs:ctor_value', 'pat.rs:structure', 'pat.rs:tuple', + ]); + }); + + it('constructing a tuple or struct variant stays linked to the variant itself', async () => { + await index({ + 'lib.rs': 'pub mod mode;\npub mod build;\n', + 'mode.rs': MODE, + 'build.rs': `use crate::mode::Mode; + +pub fn build() { + let _c = Mode::C(3); + let _d = Mode::D { x: 2 }; +} +`, + }); + const build = cg!.getNodesByKind('function').find((n) => n.name === 'build')!; + const out = cg!.getOutgoingEdges(build.id).map((e) => `${e.kind}:${cg!.getNode(e.target)!.qualifiedName}`).sort(); + expect(out).toEqual(['calls:Mode::C', 'instantiates:Mode::D']); + }); + + it('`Self::A` inside `impl Mode`, in the enum\'s file and in another one', async () => { + await index({ + 'lib.rs': 'pub mod mode;\npub mod ops;\n', + 'mode.rs': `${MODE} +impl Mode { + pub fn flip(&self) -> u8 { + match self { + Self::A => 1, + _ => 0, + } + } +} +`, + 'ops.rs': `use crate::mode::Mode; + +impl Mode { + pub fn is_b(&self) -> bool { + if let Self::B = self { true } else { false } + } +} +`, + }); + expect(referencers(enumIn('mode.rs').id)).toEqual(['mode.rs:current', 'mode.rs:flip', 'mode.rs:takes', 'ops.rs:is_b']); + }); + + it('a variant imported by name and used bare has no path to read the enum from', async () => { + await index({ + 'lib.rs': 'pub mod mode;\npub mod other;\npub mod glob;\n', + 'mode.rs': MODE, + 'other.rs': 'pub enum Mode {\n A,\n Z,\n}\n', + 'glob.rs': `use crate::mode::Mode::*; + +pub fn bare(m: u8) -> u8 { + match m { + 0 => { let _ = A; 1 } + _ => 0, + } +} +`, + }); + // Out of scope (#2328 is about paths): a bare name gives no receiver, and + // it must never land on the other module's same-named enum either. + expect(referencers(enumIn('mode.rs').id)).toEqual(['mode.rs:current', 'mode.rs:takes']); + expect(referencers(enumIn('other.rs').id)).toEqual([]); + }); + + it('the path picks the type that declares the variant, never a same-named type without it', async () => { + await index({ + 'lib.rs': 'pub mod matching;\npub mod other;\npub mod user;\n', + 'matching.rs': 'pub enum Match {\n None,\n Ignore,\n}\n', + 'other.rs': 'pub struct Match;\n', + 'user.rs': `use crate::matching::Match; + +pub enum ColorChoice { + Auto, + Ansi, +} + +pub fn first() -> u8 { + let _m = Match::None; + 0 +} + +pub fn color() -> u8 { + let _c = termcolor::ColorChoice::AlwaysAnsi; + 0 +} +`, + }); + expect(referencers(enumIn('matching.rs', 'Match').id)).toEqual(['user.rs:first']); + const struct = cg!.getNodesByKind('struct').find((n) => n.filePath === 'src/other.rs')!; + expect(referencers(struct.id)).toEqual([]); + // `termcolor`'s ColorChoice, not the file's own enum, which has no `AlwaysAnsi`. + expect(referencers(enumIn('user.rs', 'ColorChoice').id)).toEqual([]); + }); + + it('an associated const or function read through a type is not a variant path', async () => { + await index({ + 'lib.rs': 'pub mod mode;\npub mod limits;\npub mod user;\n', + 'mode.rs': `${MODE} +impl Mode { + pub const ALL: [u8; 2] = [0, 1]; + pub fn count() -> usize { Self::ALL.len() } +} +`, + 'limits.rs': 'pub struct Limits;\n\nimpl Limits {\n pub const MAX: u8 = 3;\n pub fn new() -> Self { Limits }\n}\n', + 'user.rs': `use crate::limits::Limits; +use crate::mode::Mode; + +pub fn cap() -> u8 { + Limits::MAX +} + +pub fn all() -> usize { + Mode::ALL.len() +} + +pub fn make() { + let _l = Limits::new(); + let _f = Limits::new; +} +`, + }); + // Only variants: the enum's own `count` and every reader of `Mode::ALL` / + // `Limits::MAX` stay off, and `Limits::new` links the function, not the type. + expect(referencers(enumIn('mode.rs').id)).toEqual(['mode.rs:current', 'mode.rs:takes']); + const limits = cg!.getNodesByKind('struct').find((n) => n.name === 'Limits')!; + expect(referencers(limits.id)).toEqual([]); + const make = cg!.getNodesByKind('function').find((n) => n.name === 'make')!; + expect(cg!.getOutgoingEdges(make.id).map((e) => `${e.kind}:${cg!.getNode(e.target)!.qualifiedName}`)).toEqual(['calls:Limits::new']); + }); + + it('std and prelude enums never reach a same-named project enum', async () => { + await index({ + 'lib.rs': 'pub mod shapes;\npub mod user;\n', + 'shapes.rs': `pub enum Ordering { + Less, + Greater, +} + +pub enum Option { + Some, + None, +} +`, + 'user.rs': `use std::cmp::{self, Ordering}; + +pub fn sorted(a: u8, b: u8) -> bool { + a.cmp(&b) == Ordering::Less || b.cmp(&a) == cmp::Ordering::Greater || a.cmp(&b) != std::cmp::Ordering::Less +} + +pub fn first(o: Option) -> u8 { + match o { + Option::Some(x) => x, + Option::None => 0, + } +} + +pub fn bare(o: Option, r: Result) -> u8 { + match (o, r) { + (Some(x), Ok(_)) => x, + (None, Err(())) => 0, + _ => 1, + } +} +`, + }); + expect(referencers(enumIn('shapes.rs', 'Ordering').id)).toEqual([]); + expect(referencers(enumIn('shapes.rs', 'Option').id)).toEqual([]); + for (const variant of cg!.getNodesByKind('enum_member')) { + expect(cg!.getIncomingEdges(variant.id).filter((e) => e.kind !== 'contains'), variant.qualifiedName).toEqual([]); + } + }); + + it('a module path, an associated function and a same-named enum elsewhere are not references to the enum', async () => { + await index({ + 'lib.rs': 'pub mod mode;\npub mod other;\npub mod util;\npub mod paths;\n', + 'mode.rs': `${MODE} +impl Mode { + pub fn new() -> Mode { Mode::A } +} +`, + 'other.rs': 'pub enum Mode {\n A,\n Z,\n}\n', + 'util.rs': 'pub fn take(x: u8) -> u8 { x }\n', + 'paths.rs': `use crate::mode; +use crate::other; +use crate::util; + +pub fn via_module() -> u8 { + util::take(3) +} + +pub fn via_ctor() { + let _m = mode::Mode::new(); +} + +pub fn via_other() -> u8 { + match other::Mode::A { + other::Mode::Z => 1, + _ => 0, + } +} + +pub fn via_mode() { + let _m = mode::Mode::A; +} +`, + }); + const viaModule = cg!.getNodesByKind('function').find((n) => n.name === 'via_module')!; + expect(cg!.getOutgoingEdges(viaModule.id).filter((e) => e.kind === 'references')).toEqual([]); + expect(referencers(enumIn('other.rs').id)).toEqual(['paths.rs:via_other']); + // `new`'s own `Mode::A` and return type; `via_ctor` calls an associated + // function, which links the function, not the enum. + expect(referencers(enumIn('mode.rs').id)).toEqual(['mode.rs:current', 'mode.rs:new', 'mode.rs:takes', 'paths.rs:via_mode']); + }); +}); diff --git a/codegraph-kernel/src/rustlang.rs b/codegraph-kernel/src/rustlang.rs index 1dbc689b4..64253f043 100644 --- a/codegraph-kernel/src/rustlang.rs +++ b/codegraph-kernel/src/rustlang.rs @@ -66,6 +66,11 @@ fn simple_ident_re() -> &'static Regex { static RE: OnceLock = OnceLock::new(); RE.get_or_init(|| Regex::new(r"^[A-Za-z_][0-9A-Za-z_]*$").unwrap()) } +/// extractStaticMemberRef's capitalized-receiver test. +fn capitalized_re() -> &'static Regex { + static RE: OnceLock = OnceLock::new(); + RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap()) +} struct Scope { row: u32, @@ -1183,10 +1188,12 @@ impl<'t> Walker<'t> { fn visit_function_body(&mut self, body: Node<'t>) { stack_guard!(); - self.visit_for_calls_and_structure(body); + self.visit_for_calls_and_structure(body, None); } - fn visit_for_calls_and_structure(&mut self, node: Node<'t>) { + /// `parent` is `node`'s parent, handed down by the walk (None at a body's + /// root): `Node::parent()` walks down from the tree's root on every call. + fn visit_for_calls_and_structure(&mut self, node: Node<'t>, parent: Option>) { stack_guard!(); let kind = node.kind(); self.maybe_capture_fn_refs(node); @@ -1201,6 +1208,7 @@ impl<'t> Walker<'t> { } else if kind == "struct_expression" { self.extract_instantiation(node); } + self.extract_static_member_ref(node, parent); // Nested NAMED fns become their own nodes (a nested fn inside an impl // method walks up to the impl and indexes as a METHOD). @@ -1232,11 +1240,69 @@ impl<'t> Walker<'t> { for i in 0..node.named_child_count() { if let Some(c) = node.named_child(i) { - self.visit_for_calls_and_structure(c); + self.visit_for_calls_and_structure(c, Some(node)); } } } + /// extractStaticMemberRef — the rust branch (#2328): an enum variant + /// written as a path (`Mode::A`, `mode::Mode::B`, a `Mode::C(x)` / + /// `Mode::D { .. }` pattern, `Self::A` in an impl) references the receiver + /// — the segment before the member, at the place it is written; the + /// resolver keeps it only on an enum that declares the member. A lowercase + /// receiver (module) or member (fn), a call's callee or a struct literal's + /// name (both already linked to their member), a path's prefix and a `use` + /// tree emit nothing. Mirrored byte-for-byte — change both. + fn extract_static_member_ref(&mut self, node: Node<'t>, parent: Option>) { + let kind = node.kind(); + if (kind != "scoped_identifier" && kind != "scoped_type_identifier") || self.stack.is_empty() { + return; + } + // Looked up only at a body's root (a `const X: M = M::A;` value). + let Some(parent) = parent.or_else(|| node.parent()) else { return }; + let member_path = if kind == "scoped_identifier" { + !matches!( + parent.kind(), + "scoped_identifier" + | "scoped_type_identifier" + | "use_declaration" + | "use_list" + | "scoped_use_list" + | "use_as_clause" + | "use_wildcard" + ) + } else { + parent.kind() == "struct_pattern" + }; + if !member_path { + return; + } + if parent.kind() == "call_expression" + && parent.child_by_field_name("function").map(|f| f.start_byte()) == Some(node.start_byte()) + { + return; + } + let Some(member) = node.child_by_field_name("name") else { return }; + let mut recv = node.child_by_field_name("path"); + if let Some(r) = recv { + if r.kind() == "scoped_identifier" { + recv = r.child_by_field_name("name"); + } + } + let Some(recv) = recv else { return }; + if recv.kind() != "identifier" || !self.text(member).starts_with(|c: char| c.is_ascii_uppercase()) { + return; + } + let mut text = self.text(recv).to_string(); + if text == "Self" { + text = self.receiver_type_of(node).unwrap_or_default(); + } + if capitalized_re().is_match(&text) { + let owner = self.top_row(); + self.push_ref_at(owner, &text, edge_kind_index("references").unwrap(), recv); + } + } + // --- fn refs (RUST_SPEC) ---------------------------------------------------- /// maybeCaptureFnRefs with RUST_SPEC's dispatch: arguments→args, diff --git a/docs/design/rust-lang-kernel-port-checklist.md b/docs/design/rust-lang-kernel-port-checklist.md index 6b44e6ed9..605013a9e 100644 --- a/docs/design/rust-lang-kernel-port-checklist.md +++ b/docs/design/rust-lang-kernel-port-checklist.md @@ -370,12 +370,19 @@ while `Vec`/`Option`/`Box`/`Self` are NOT. QUIRKS, PRESERVE: - property_signature/method_signature branch (1283) — TS-only node types, never rust. -### Static-member refs, cpp-isms — NOT rust +### Static-member refs (rust since #2328); 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. +`rust` ∈ STATIC_MEMBER_LANGS since #2328, with its own branch in +extractStaticMemberRef (body walker only; the kernel's +`extract_static_member_ref`, called at the same point of the walk): a +`scoped_identifier` whose member is capitalized — unless it is a call's +callee, the prefix of a longer path or part of a `use` tree — and a +`struct_pattern`'s `scoped_type_identifier` emit one `references` ref named by +the receiver (the segment before the member; `Self` → the impl's type via +getReceiverType, nothing inside a trait), positioned at the receiver. The +resolver keeps it only on an enum that declares the member as a variant. +namespacePrefix, cppLocalFnPtrs, stack-construction, operator calls, template +strip: all c/cpp-gated, none apply. ### Docstrings (tree-sitter-helpers.ts:95) diff --git a/src/extraction/tree-sitter.ts b/src/extraction/tree-sitter.ts index 05b37146d..39e93b588 100644 --- a/src/extraction/tree-sitter.ts +++ b/src/extraction/tree-sitter.ts @@ -383,9 +383,21 @@ const MEMBER_ACCESS_TYPES: ReadonlySet = new Set([ * already-covered types). Don't re-add `member_expression`/`attribute` here. * VB.NET (#2305) sends the member with its receiver instead, and its resolver * decides whether the receiver is a type (see extractVbMemberRead). + * Rust imports too, but a variant is usually written through a path that names + * its module, not its enum (`mode::Mode::A` under `use crate::mode;`), so no + * `use` names the enum at all (#2328). */ const STATIC_MEMBER_LANGS: ReadonlySet = new Set([ - 'java', 'csharp', 'kotlin', 'swift', 'scala', 'dart', 'php', 'cpp', 'vbnet', + 'java', 'csharp', 'kotlin', 'swift', 'scala', 'dart', 'php', 'cpp', 'vbnet', 'rust', +]); + +/** + * Parents of a Rust `scoped_identifier` that is not a member written as a + * value or a pattern: the prefix of a longer path, or a `use` tree. + */ +const RUST_NON_MEMBER_PATH_PARENTS: ReadonlySet = new Set([ + 'scoped_identifier', 'scoped_type_identifier', + 'use_declaration', 'use_list', 'scoped_use_list', 'use_as_clause', 'use_wildcard', ]); /** @@ -5528,7 +5540,7 @@ export class TreeSitterExtractor { * where types are Capitalized by convention, and skipped when the access is a * call's callee (the call extractor already links the method). */ - private extractStaticMemberRef(node: SyntaxNode): void { + private extractStaticMemberRef(node: SyntaxNode, knownParent?: SyntaxNode): void { if (!STATIC_MEMBER_LANGS.has(this.language)) return; if (this.nodeStack.length === 0) return; const ownerId = this.nodeStack[this.nodeStack.length - 1]; @@ -5547,6 +5559,35 @@ export class TreeSitterExtractor { return; } + // Rust writes an enum variant as a path: read (`Mode::A`, `mode::Mode::B`, + // `xs.map(Mode::C)`), matched (`Mode::C(x) =>`, `Mode::D { .. } =>`), or + // `Self::A` in an impl (#2328). The receiver — the segment before the + // member — is referenced where it is written, so a `mode::` / `other::` + // prefix scopes it as it scopes a type annotation, and the resolver keeps it + // only on an enum that declares the member (an associated const read the + // same way, `Limits::MAX`, links nothing). A lowercase receiver is a module + // and a lowercase member a function (`util::take`, `Foo::new`); a call's + // callee (`Mode::C(1)`) and a struct literal's name are already linked to + // their member; the prefix of a longer path and a `use` tree name no member. + // Mirrored by the native kernel's `extract_static_member_ref` — change both. + if (this.language === 'rust') { + if (node.type !== 'scoped_identifier' && node.type !== 'scoped_type_identifier') return; + // Looked up only at a body's root (a `const X: M = M::A;` value). + const parent = knownParent ?? node.parent; + if (!parent) return; + if (node.type === 'scoped_type_identifier' ? parent.type !== 'struct_pattern' + : RUST_NON_MEMBER_PATH_PARENTS.has(parent.type)) return; + if (parent.type === 'call_expression' && getChildByField(parent, 'function')?.startIndex === node.startIndex) return; + const member = getChildByField(node, 'name'); + let recv = getChildByField(node, 'path'); + if (recv?.type === 'scoped_identifier') recv = getChildByField(recv, 'name'); + if (!member || recv?.type !== 'identifier' || !/^[A-Z]/.test(getNodeText(member, this.source))) return; + let text = getNodeText(recv, this.source); + if (text === 'Self') text = this.extractor!.getReceiverType?.(node, this.source) ?? ''; + if (/^[A-Z][A-Za-z0-9_]*$/.test(text)) this.pushStaticMemberRef(text, ownerId, recv); + return; + } + if (!MEMBER_ACCESS_TYPES.has(node.type)) return; // Skip `Type.method()` — the access is the callee of a call, already linked. @@ -6098,7 +6139,9 @@ export class TreeSitterExtractor { private visitFunctionBody(body: SyntaxNode, _functionId: string): void { if (!this.extractor) return; - const visitForCallsAndStructure = (node: SyntaxNode): void => { + // `parent` is handed down by the walk (absent at the body's root): reading + // `node.parent` walks down from the tree's root on every call. + const visitForCallsAndStructure = (node: SyntaxNode, parent?: SyntaxNode): void => { const nodeType = node.type; // A function-like macro defined inside a body is still a macro (#1838). @@ -6213,7 +6256,7 @@ export class TreeSitterExtractor { } // Static-member / value-read: `Enum.value`, `Type.CONST`, `Foo::BAR`. - this.extractStaticMemberRef(node); + this.extractStaticMemberRef(node, parent); // A member read that may run code — Dart's `x.area` calls the getter // `area` (#2338). The resolver links it to a getter, as a call, or to @@ -6351,7 +6394,7 @@ export class TreeSitterExtractor { for (let i = 0; i < node.namedChildCount; i++) { const child = node.namedChild(i); if (child) { - visitForCallsAndStructure(child); + visitForCallsAndStructure(child, node); } } }; diff --git a/src/resolution/name-matcher.ts b/src/resolution/name-matcher.ts index 15503a4e8..fa867a106 100644 --- a/src/resolution/name-matcher.ts +++ b/src/resolution/name-matcher.ts @@ -5397,9 +5397,22 @@ export function isRustNameInScope(candidate: Node, ref: UnresolvedRef, context: // Bare in the SOURCE: the index keeps `crate::error::Result` by its last // segment, and a path is not a prelude lookup. const line = context.getFileLines?.(ref.filePath)?.[ref.line - 1] ?? context.readFile(ref.filePath)?.split('\n')[ref.line - 1]; + // A variant path — `Mode::A`, `mode::Mode::B`, a `Mode::C(x)` pattern, or + // `Self::A` in an impl, where the reference names the impl's type (#2328) — + // reads the enum that declares that variant, and nothing else: ripgrep's + // `Match::None` is `ignore`'s enum, not the matcher's `struct Match`. An + // associated const or function read the same way (`Limits::MAX`, `Mode::ALL`) + // is not a variant, so it references no type. + const at = line === undefined ? '' : line.slice(ref.column); + const typeRead = ref.referenceKind === 'references' && /^\w+$/.test(name); + const viaSelf = typeRead && name !== 'Self' && /^Self\s*::/.test(at); + const variant = typeRead && (viaSelf || (at.startsWith(name) && !/^\w/.test(at.slice(name.length)))) + ? /^\w+\s*::\s*([A-Z]\w*)/.exec(at)?.[1] : undefined; + if (variant !== undefined && !declaresRustVariant(candidate, variant, context)) return false; // Written through a path on its line (`jsont::SubMatch { … }`, `io::Result<…>`), - // wherever the reference's column points. - const pathed = line === undefined ? null + // wherever the reference's column points. `Self::A` names the impl's type, not + // whatever path the line writes elsewhere. + const pathed = line === undefined || viaSelf ? null : (line.startsWith(name, ref.column) && /::\s*$/.test(line.slice(0, ref.column)) ? /((?:[A-Za-z_]\w*\s*::\s*)*)([A-Za-z_]\w*)?\s*::\s*$/.exec(line.slice(0, ref.column)) : !new RegExp(`(? n.kind === 'enum_member' && n.qualifiedName === qualified); +} + /** The line of the `impl` / `trait` header above `ref` in its file (0 for none). */ function rustEnclosingImplLine(ref: UnresolvedRef, context: ResolutionContext): number { const lines = context.getFileLines?.(ref.filePath) ?? context.readFile(ref.filePath)?.split(/\r?\n/) ?? [];