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 <ewidusoc498@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Colby Mchenry
2026-10-05 21:59:11 +00:00
committed by GitHub
co-authored by danusha2345 Claude Opus 5.5
parent 7210d2fd4c
commit ed1a89fb0f
7 changed files with 540 additions and 15 deletions
+48 -5
View File
@@ -383,9 +383,21 @@ const MEMBER_ACCESS_TYPES: ReadonlySet<string> = 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<string> = 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<string> = 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);
}
}
};
+23 -2
View File
@@ -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(`(?<![\\w$:])${name}\\b`).test(line) ? new RegExp(`((?:[A-Za-z_]\\w*\\s*::\\s*)*)([A-Za-z_]\\w*)\\s*::\\s*${name}\\b`).exec(line) : null);
if (pathed) {
@@ -5454,6 +5467,14 @@ export function isRustNameInScope(candidate: Node, ref: UnresolvedRef, context:
return uses.names.has(name) || rustGlobCovers(uses, candidate, ref);
}
/** Whether `type` is a Rust enum that declares `variant` (#2328). */
function declaresRustVariant(type: Node, variant: string, context: ResolutionContext): boolean {
if (type.kind !== 'enum') return false;
const qualified = `${type.qualifiedName}::${variant}`;
const named = context.getNodesInFileNamed?.(type.filePath, variant) ?? context.getNodesInFile(type.filePath);
return named.some((n) => 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/) ?? [];