Files
codegraph/__tests__/kernel-scala-parity.test.ts
T
bdd687b49f feat(kernel): R7b Scala walker — scala module, vendored-grammar-C master@0aca5d0a6f, scala default-routed (#1385)
R7b batch 4 #3 (docs/design/scala-kernel-port-checklist.md is the
authoritative quirk list). The third vendored-grammar-C language and the
biggest grammar in the tree (35MB parser.c): the vendored wasm is
tree-sitter/tree-sitter-scala master@0aca5d0a6f — a post-v0.26.0 generation
sync that is not a release (the 0.26.0 crate is 30 states BEHIND, so a
crate pin would be a silent downgrade). NO wasm change: production has
parsed with this exact revision since #91 — the kernel-grammar-parity row
(ABI 15, 26,650 states, 32 fields, id-by-id tables) is the whole alignment
proof.

Preserved bug-for-bug (all probe-pinned): the leak-through asymmetries —
extension methods mint NO nodes (first def's body calls leak to the
enclosing scope, later defs invisible, and the braced form resolves its
body field to the `{` TOKEN via first-match-wins field lookup → whole
extension invisible); anonymous `new T { … }` template_body members leak to
the enclosing scope (findAnonymousClassBody misses template_body); the
bodied-vs-bodiless class asymmetry (bodiless headers walk class_parameters
→ default-value calls emit FROM the class; bodied ones never see them) —
plus first-segment import names (`import com.example.C` → `com`), the
val/var hook keyed on the enclosing-definition NODE TYPE (object vals →
constants/value-ref targets, class/trait/enum/given vals → fields) with
consumed initializers, every def routed through extractMethod with the
top-level function fallback, nested defs in bodies minting NOTHING (the
inverse of kotlin) while body-local classes extract fully, curried
signatures keeping only the FIRST parameter list (type params win the
`parameters` field), enum cases positioned at the CASE node with invisible
params/extends tails, extends with-chains via scalaBaseTypeName,
`@deprecated(args)` decorates, the #750 capitalized-chain re-encode
(`WidgetS.create().render`), literal-receiver silence, static-member reads
AND writes, infix invisibility, `derives` silence, scaladoc retention with
the CRLF `\r` pin, full value-reference machinery (shadow prune, last-wins
same-name targets, `$X`/`${X}` interpolation reads), and SCALA_SPEC
fn-refs (bare ids + postfix eta unwrap + varinit, var-init non-capture).

Gates: parity sweeps first-run 0-diff on os-lib/cats/scala3-compiler-src/
scala3-library-src — 1,935 clean files byte-parity, deferrals 0/15/57/116
matching the survey's predictions exactly (scala-3's PHANTOM hasError
files — flag-true, zero ERROR nodes, capture-checking `^` — defer on the
FLAG); full-init dumps byte-identical ×3 (os-lib, cats, scala3 whole-repo
950,889 dump lines); kernel-scala-parity suite (9 fixtures + 9 in-memory
CRLF variants incl. Scala-3 indentation through the external scanner +
phantom/real-error defer pins + first-segment/namespace/value-ref pins);
full suite 2,669 green ×3 with CODEGRAPH_KERNEL_EXPECT=1
(kernel-scaffold's stays-wasm example moved scala → pascal).
DEFAULT_ROUTED += scala (19 langs).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 19:02:52 -05:00

165 lines
6.8 KiB
TypeScript

/**
* Kernel↔wasm Scala extraction parity (R7b batch 4 of the kernel migration).
*
* Asserts the native walker (codegraph-kernel/src/scala.rs) produces the SAME
* ExtractionResult as the wasm TreeSitterExtractor — nodes, edges, and
* unresolved refs compared as canonicalized multisets — over the checked-in
* fixtures (torture.scala: first-segment imports, defs-as-methods with the
* top-level function fallback, curried/type-params-first signatures, the
* val/var hook with object-vs-class kinds and initializer invisibility,
* companion pairs sharing a QN namespace, the bodiless-header asymmetry,
* enum cases at case-node positions with invisible tails, extends
* with-chains, `@deprecated(args)` decorates, the #750 capitalized-chain
* re-encode, literal-receiver silence, static reads incl. the write-LHS
* emission, nested-def invisibility with body-local classes extracting
* fully; TortureDocs: scaladoc retention + the CRLF `\r` pin; TortureVref:
* value-ref targets, shadow prune, interpolation reads, the last-wins
* mis-target; TortureFnref: all five capture channels + var-init
* non-capture + eta expansion; TortureGiven/TortureExt: the anon-body and
* extension leak asymmetries — the port's likeliest regression sites;
* TortureIndent: Scala-3 indentation syntax through the external scanner;
* TortureMisc: package objects/braced packages/self-types/super-ctor args/
* unicode columns; TortureScript.sc: top-level statements from the FILE)
* and their CRLF variants (derived in-memory — #1329), plus phantom and
* real-error defer pins.
*
* The full-repo sweeps live in scripts/kernel-parity.mjs (os-lib/cats +
* scala3 compiler/src + library/src with --max-deferral 0.3); 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.
*/
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 Scala extraction parity', () => {
beforeAll(async () => {
await initGrammars();
await loadGrammarsForLanguages(['scala']);
});
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 = 2): ExtractionResult {
process.env.CODEGRAPH_KERNEL_LANGS = 'all';
delete process.env.CODEGRAPH_KERNEL;
const viaKernel = tryKernelExtract(filePath, source, 'scala');
expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
process.env.CODEGRAPH_KERNEL = '0';
const viaWasm = extractFromSource(filePath, source, 'scala');
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);
return viaKernel!;
}
const FIXTURES = [
['torture.scala', 40],
['TortureDocs.scala', 3],
['TortureVref.scala', 4],
['TortureFnref.scala', 4],
['TortureGiven.scala', 3],
['TortureExt.scala', 1],
['TortureIndent.scala', 3],
['TortureMisc.scala', 4],
['TortureScript.sc', 1],
] as const;
for (const [file, minNodes] of FIXTURES) {
it(`${file}: parity`, () => {
const src = fs.readFileSync(path.join(FIXTURE_DIR, file), 'utf8');
assertParity(`fixtures/${file}`, src, minNodes);
});
it(`${file}: CRLF parity`, () => {
const src = fs.readFileSync(path.join(FIXTURE_DIR, file), 'utf8');
const crlf = src.replace(/(?<!\r)\n/g, '\r\n');
assertParity(`fixtures/${file} (crlf)`, crlf, minNodes);
});
}
it('torture pins: import first-segment names, companion pairs, value-ref edges', () => {
const src = fs.readFileSync(path.join(FIXTURE_DIR, 'torture.scala'), 'utf8');
const result = assertParity('fixtures/torture.scala', src, 40);
// Imports are named the FIRST path segment.
const imports = result.nodes.filter((n) => n.kind === 'import');
expect(imports.length).toBeGreaterThan(0);
expect(imports.every((n) => !n.name.includes('.'))).toBe(true);
// No namespace node, ever (package headers ignored).
expect(result.nodes.some((n) => n.kind === 'namespace')).toBe(false);
// Value-ref edges exist and are metadata-tagged.
expect(result.edges.some((e) => e.kind === 'references' && e.metadata?.valueRef === true)).toBe(
true
);
});
it('scala-3 PHANTOM hasError defers (flag-true, zero ERROR nodes)', () => {
// Capture-checking postfix `^` — a complete, correct CST whose hasError
// flag is still true. The kernel must defer on the FLAG.
const phantom = 'def f(x: List[Int]^): Int = 1\n';
process.env.CODEGRAPH_KERNEL_LANGS = 'all';
delete process.env.CODEGRAPH_KERNEL;
expect(tryKernelExtract('src/phantom.scala', phantom, 'scala')).toBeNull();
process.env.CODEGRAPH_KERNEL = '0';
const viaWasm = extractFromSource('src/phantom.scala', phantom, 'scala');
delete process.env.CODEGRAPH_KERNEL;
expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
});
it('real parse errors defer (given-with syntax)', () => {
const broken = 'trait C\ngiven x: C with { def y = 1 }\n';
process.env.CODEGRAPH_KERNEL_LANGS = 'all';
delete process.env.CODEGRAPH_KERNEL;
expect(tryKernelExtract('src/gw.scala', broken, 'scala')).toBeNull();
});
});