mirror of
https://github.com/colbymchenry/codegraph.git
synced 2026-10-25 03:49:59 +08:00
A Ruby call on a constant written with its namespace, like Billing::ChargeCard.call(...) or ::Foo.call, recorded no edge. Both extractors (the kernel's ruby.rs and the wasm one) emitted the receiver's references ref only for a bare `constant` receiver, so a scope_resolution receiver got none. The call ref itself, Billing::ChargeCard.call, matched no resolver strategy either: the method-call patterns reject a `::` in the receiver. A class used only through such calls showed no callers and no dependents. Fix: - Both engines treat a constant path (a constant, or a scope_resolution of constants, a leading `::` included) as a constant receiver and emit the references ref under the receiver as written. A path through a value (obj::Thing, self.class::LIMIT) still emits none, and .new stays an instantiation. - A new resolver step, src/resolution/ruby-constant-paths.ts, resolves a Ruby references ref written as such a path, and a calls ref on one, the way Ruby looks the constant up: the class or module around the reference, then each namespace outside it, then the top level; a `::`-rooted path at the top level only. A call reaches the class's or module's own method, else the first one its ancestry declares (rubyAncestry, now exported). The step runs before the pre-filter, which dropped `::`-rooted names, and it is exclusive: a path the project doesn't declare (ActiveRecord::Base) or a class without the method links nothing, never a namesake by its last name, and production code never reaches a class only a test declares. Validation: - New __tests__/ruby-namespaced-receiver.test.ts (8 cases, each on the kernel and on wasm, plus a sync case) and a parity case in kernel-ruby-parity.test.ts. On main 16 of the 22 tests in the two files fail (the rest are guards and the old parity cases); all pass with the fix. Reverting only the resolver step, or only the wasm extractor, turns 13 and 10 of them red. - A/B against main (kernel path), every edge triaged: sinatra +23 edges, rubocop +168, mastodon's Ruby tree (4,363 files) +676; 0 removed, nodes identical. 866 of 867 are right: references by the path as written or under an enclosing namespace (each such case checked against the call site's own nesting), calls to a class method, a module_function method, or an inherited class method. 1 is wrong: Paperclip::Transcoder.make reaches the instance method `make`, since a singleton method and an instance method share one qualified name today; a bare Transcoder.make does the same on main. Controls express and flask are byte-identical. - kernel-parity.mjs --lang ruby: sinatra 147/147, rubocop 1799/1801 (the same 2 deferred on main), mastodon 3333/3333, 0 diffs. The fix arm's kernel and wasm graphs are byte-identical on sinatra and rubocop. - Index time, median of 3 interleaved runs: +0.4% to +1.7%, the same as the controls (+0.8%, +1.3%). Fixes #2503 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
176 lines
7.3 KiB
TypeScript
176 lines
7.3 KiB
TypeScript
/**
|
|
* Kernel↔wasm Ruby extraction parity (R7b of the kernel migration).
|
|
*
|
|
* Asserts the native walker (codegraph-kernel/src/ruby.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.rb: the importTypes:['call'] funnel and its
|
|
* class-body DSL blindness, mixin implements refs WITH filePath (the v2
|
|
* ref-flag wire path), module nesting + the hook multiply-capture, the
|
|
* sibling-scan visibility trio, require/require_relative path refs incl. the
|
|
* Kernel.require and interpolated-path quirks, the ruby call branch
|
|
* (`.new` instantiates, constant-receiver references, `&.` joins, raw chain
|
|
* text), bare-call statements (do…end vs brace-block blindness), heredocs,
|
|
* `=begin` docstring marker survival, value-ref targets + shadow prune,
|
|
* `__END__` trailer) and its CRLF variant (derived in-memory — #1329).
|
|
*
|
|
* The full-repo sweep lives in scripts/kernel-parity.mjs (sinatra/jekyll/
|
|
* rails 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 Ruby extraction parity', () => {
|
|
beforeAll(async () => {
|
|
await initGrammars();
|
|
await loadGrammarsForLanguages(['ruby']);
|
|
});
|
|
|
|
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, 'ruby');
|
|
expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
|
|
|
|
process.env.CODEGRAPH_KERNEL = '0';
|
|
const viaWasm = extractFromSource(filePath, source, 'ruby');
|
|
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: modules/mixins, visibility scan, requires, call zoo, value refs', () => {
|
|
const file = path.join(FIXTURE_DIR, 'torture.rb');
|
|
assertParity('fixtures/torture.rb', fs.readFileSync(file, 'utf8'), 30);
|
|
});
|
|
|
|
// 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 and `=begin` bodies
|
|
// (#1329), plus heredoc/`%`-literal CRLF parsing.
|
|
it('torture fixture CRLF parity', () => {
|
|
const file = path.join(FIXTURE_DIR, 'torture.rb');
|
|
const crlf = fs.readFileSync(file, 'utf8').replace(/(?<!\r)\n/g, '\r\n');
|
|
assertParity('fixtures/torture.rb (crlf)', crlf, 30);
|
|
});
|
|
|
|
// A receiver written with its namespace (`Billing::ChargeCard.call`, `::Foo.call`)
|
|
// is a constant read, as a bare `ChargeCard.call`'s is (#2503): both backends
|
|
// emit the same `references` ref for it, under the receiver as written, at
|
|
// the receiver. A path through a value (`obj::Thing`, `self.class::LIMIT`)
|
|
// names no constant the index can know, and `.new` stays an instantiation.
|
|
it('namespaced constant receivers', () => {
|
|
const src = [
|
|
'class Callers',
|
|
' def a',
|
|
' Billing::ChargeCard.call(amount: 1)',
|
|
' ::Billing::ChargeCard.call',
|
|
' ::Foo.call',
|
|
' Users::Create&.call',
|
|
' A::B::C.run!',
|
|
' Config::DEFAULTS.fetch(:x)',
|
|
' Foo::Bar::baz',
|
|
' obj::Thing.go',
|
|
' self.class::LIMIT.times { }',
|
|
' Billing::ChargeCard.new(amount: 3)',
|
|
' end',
|
|
'end',
|
|
'',
|
|
].join('\n');
|
|
assertParity('src/callers.rb', src);
|
|
process.env.CODEGRAPH_KERNEL = '0';
|
|
const refs = extractFromSource('src/callers.rb', src, 'ruby').unresolvedReferences
|
|
.filter((r) => r.referenceKind === 'references' || r.referenceKind === 'instantiates')
|
|
.map((r) => `${r.referenceKind} ${r.referenceName} ${r.line}:${r.column}`);
|
|
delete process.env.CODEGRAPH_KERNEL;
|
|
expect(refs.sort()).toEqual([
|
|
'instantiates ChargeCard 12:4',
|
|
'references ::Billing::ChargeCard 4:4',
|
|
'references ::Foo 5:4',
|
|
'references A::B::C 7:4',
|
|
'references Billing::ChargeCard 3:4',
|
|
'references Config::DEFAULTS 8:4',
|
|
'references Foo::Bar 9:4',
|
|
'references Users::Create 6:4',
|
|
]);
|
|
});
|
|
|
|
it('mixin implements refs carry filePath through the v2 ref-flag wire path', () => {
|
|
const src = 'class Widget\n include Comparable\nend\n';
|
|
process.env.CODEGRAPH_KERNEL_LANGS = 'all';
|
|
delete process.env.CODEGRAPH_KERNEL;
|
|
const viaKernel = tryKernelExtract('src/widget.rb', src, 'ruby');
|
|
expect(viaKernel).not.toBeNull();
|
|
const impl = viaKernel!.unresolvedReferences.find((r) => r.referenceKind === 'implements');
|
|
expect(impl?.referenceName).toBe('Comparable');
|
|
expect(impl?.filePath).toBe('src/widget.rb');
|
|
// Ordinary refs stay un-denormalized.
|
|
const other = viaKernel!.unresolvedReferences.find((r) => r.referenceKind !== 'implements');
|
|
if (other) expect(other.filePath).toBeUndefined();
|
|
});
|
|
|
|
it('files with parse errors defer to the wasm extractor (recovery is encoding-dependent)', () => {
|
|
const broken = 'def broken(\n x = [1,\nend\n';
|
|
process.env.CODEGRAPH_KERNEL_LANGS = 'all';
|
|
delete process.env.CODEGRAPH_KERNEL;
|
|
expect(tryKernelExtract('src/broken.rb', broken, 'ruby')).toBeNull();
|
|
process.env.CODEGRAPH_KERNEL = '0';
|
|
const viaWasm = extractFromSource('src/broken.rb', broken, 'ruby');
|
|
delete process.env.CODEGRAPH_KERNEL;
|
|
expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
|
|
});
|
|
});
|