mirror of
https://github.com/colbymchenry/codegraph.git
synced 2026-10-16 20:53:57 +08:00
ed1a89fb0f
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>
181 lines
7.2 KiB
TypeScript
181 lines
7.2 KiB
TypeScript
/**
|
|
* 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. generic / lifetime /
|
|
* reference / scoped / generic-trait impl receivers (#1588), unit structs
|
|
* (a bodiless struct IS a definition — both walkers mint a node), 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('preserves Tauri command attributes without treating comments or strings as registrations', () => {
|
|
const source = `
|
|
#[tauri::command]
|
|
fn port() -> u16 { 4000 }
|
|
#[tauri :: command(rename_all = "snake_case")]
|
|
/* between attributes */
|
|
#[allow(dead_code)]
|
|
pub async fn settings() {}
|
|
// #[tauri::command]
|
|
fn ordinary() {}
|
|
const TEXT: &str = r#"#[tauri::command]"#;
|
|
fn after_string() {}
|
|
#[other::command]
|
|
fn unrelated() {}
|
|
#[tauri::command]
|
|
fn outer() { fn inner() {} }
|
|
fn next() {}
|
|
`;
|
|
assertParity('commands.rs', source);
|
|
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::<u8>::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);
|
|
});
|
|
|
|
// 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);
|
|
});
|
|
});
|