kernel-scala-parity.test.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. /**
  2. * Kernel↔wasm Scala extraction parity (R7b batch 4 of the kernel migration).
  3. *
  4. * Asserts the native walker (codegraph-kernel/src/scala.rs) produces the SAME
  5. * ExtractionResult as the wasm TreeSitterExtractor — nodes, edges, and
  6. * unresolved refs compared as canonicalized multisets — over the checked-in
  7. * fixtures (torture.scala: first-segment imports, defs-as-methods with the
  8. * top-level function fallback, curried/type-params-first signatures, the
  9. * val/var hook with object-vs-class kinds and initializer invisibility,
  10. * companion pairs sharing a QN namespace, the bodiless-header asymmetry,
  11. * enum cases at case-node positions with invisible tails, extends
  12. * with-chains, `@deprecated(args)` decorates, the #750 capitalized-chain
  13. * re-encode, literal-receiver silence, static reads incl. the write-LHS
  14. * emission, nested-def invisibility with body-local classes extracting
  15. * fully; TortureDocs: scaladoc retention + the CRLF `\r` pin; TortureVref:
  16. * value-ref targets, shadow prune, interpolation reads, the last-wins
  17. * mis-target; TortureFnref: all five capture channels + var-init
  18. * non-capture + eta expansion; TortureGiven/TortureExt: the anon-body and
  19. * extension leak asymmetries — the port's likeliest regression sites;
  20. * TortureIndent: Scala-3 indentation syntax through the external scanner;
  21. * TortureMisc: package objects/braced packages/self-types/super-ctor args/
  22. * unicode columns; TortureScript.sc: top-level statements from the FILE)
  23. * and their CRLF variants (derived in-memory — #1329), plus phantom and
  24. * real-error defer pins.
  25. *
  26. * The full-repo sweeps live in scripts/kernel-parity.mjs (os-lib/cats +
  27. * scala3 compiler/src + library/src with --max-deferral 0.3); this suite
  28. * keeps the invariant alive in `npm test`. Skips when no kernel binary is
  29. * staged; CODEGRAPH_KERNEL_EXPECT=1 turns that into a failure.
  30. */
  31. import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
  32. import * as fs from 'fs';
  33. import * as path from 'path';
  34. import { extractFromSource } from '../src/extraction';
  35. import { initGrammars, loadGrammarsForLanguages } from '../src/extraction/grammars';
  36. import { tryKernelExtract, resetKernelForTests } from '../src/extraction/kernel';
  37. import type { ExtractionResult } from '../src/types';
  38. const KERNEL_PATH = path.join(
  39. __dirname,
  40. '..',
  41. 'codegraph-kernel',
  42. 'prebuilds',
  43. `${process.platform}-${process.arch}`,
  44. 'codegraph-kernel.node'
  45. );
  46. const kernelBuilt = fs.existsSync(KERNEL_PATH);
  47. const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'kernel-parity');
  48. function canon(result: ExtractionResult): { nodes: string[]; edges: string[]; refs: string[] } {
  49. return {
  50. nodes: result.nodes
  51. .map(({ updatedAt: _u, ...n }) => JSON.stringify(n, Object.keys(n).sort()))
  52. .sort(),
  53. edges: result.edges.map((e) => JSON.stringify(e, Object.keys(e).sort())).sort(),
  54. refs: result.unresolvedReferences
  55. .map((r) => JSON.stringify(r, Object.keys(r).sort()))
  56. .sort(),
  57. };
  58. }
  59. const ENV_KEYS = ['CODEGRAPH_KERNEL', 'CODEGRAPH_KERNEL_LANGS'] as const;
  60. let savedEnv: Record<string, string | undefined>;
  61. describe.skipIf(!kernelBuilt)('kernel Scala extraction parity', () => {
  62. beforeAll(async () => {
  63. await initGrammars();
  64. await loadGrammarsForLanguages(['scala']);
  65. });
  66. beforeEach(() => {
  67. savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
  68. resetKernelForTests();
  69. });
  70. afterEach(() => {
  71. for (const k of ENV_KEYS) {
  72. if (savedEnv[k] === undefined) delete process.env[k];
  73. else process.env[k] = savedEnv[k];
  74. }
  75. resetKernelForTests();
  76. });
  77. function assertParity(filePath: string, source: string, minNodes = 2): ExtractionResult {
  78. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  79. delete process.env.CODEGRAPH_KERNEL;
  80. const viaKernel = tryKernelExtract(filePath, source, 'scala');
  81. expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
  82. process.env.CODEGRAPH_KERNEL = '0';
  83. const viaWasm = extractFromSource(filePath, source, 'scala');
  84. delete process.env.CODEGRAPH_KERNEL;
  85. const k = canon(viaKernel!);
  86. const w = canon(viaWasm);
  87. expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes);
  88. expect(k.edges, `${filePath}: edges`).toEqual(w.edges);
  89. expect(k.refs, `${filePath}: refs`).toEqual(w.refs);
  90. expect(viaWasm.nodes.length).toBeGreaterThanOrEqual(minNodes);
  91. return viaKernel!;
  92. }
  93. const FIXTURES = [
  94. ['torture.scala', 40],
  95. ['TortureDocs.scala', 3],
  96. ['TortureVref.scala', 4],
  97. ['TortureFnref.scala', 4],
  98. ['TortureGiven.scala', 3],
  99. ['TortureExt.scala', 1],
  100. ['TortureIndent.scala', 3],
  101. ['TortureMisc.scala', 4],
  102. ['TortureScript.sc', 1],
  103. ] as const;
  104. for (const [file, minNodes] of FIXTURES) {
  105. it(`${file}: parity`, () => {
  106. const src = fs.readFileSync(path.join(FIXTURE_DIR, file), 'utf8');
  107. assertParity(`fixtures/${file}`, src, minNodes);
  108. });
  109. it(`${file}: CRLF parity`, () => {
  110. const src = fs.readFileSync(path.join(FIXTURE_DIR, file), 'utf8');
  111. const crlf = src.replace(/(?<!\r)\n/g, '\r\n');
  112. assertParity(`fixtures/${file} (crlf)`, crlf, minNodes);
  113. });
  114. }
  115. it('torture pins: import first-segment names, companion pairs, value-ref edges', () => {
  116. const src = fs.readFileSync(path.join(FIXTURE_DIR, 'torture.scala'), 'utf8');
  117. const result = assertParity('fixtures/torture.scala', src, 40);
  118. // Imports are named the FIRST path segment.
  119. const imports = result.nodes.filter((n) => n.kind === 'import');
  120. expect(imports.length).toBeGreaterThan(0);
  121. expect(imports.every((n) => !n.name.includes('.'))).toBe(true);
  122. // No namespace node, ever (package headers ignored).
  123. expect(result.nodes.some((n) => n.kind === 'namespace')).toBe(false);
  124. // Value-ref edges exist and are metadata-tagged.
  125. expect(result.edges.some((e) => e.kind === 'references' && e.metadata?.valueRef === true)).toBe(
  126. true
  127. );
  128. });
  129. it('scala-3 PHANTOM hasError defers (flag-true, zero ERROR nodes)', () => {
  130. // Capture-checking postfix `^` — a complete, correct CST whose hasError
  131. // flag is still true. The kernel must defer on the FLAG.
  132. const phantom = 'def f(x: List[Int]^): Int = 1\n';
  133. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  134. delete process.env.CODEGRAPH_KERNEL;
  135. expect(tryKernelExtract('src/phantom.scala', phantom, 'scala')).toBeNull();
  136. process.env.CODEGRAPH_KERNEL = '0';
  137. const viaWasm = extractFromSource('src/phantom.scala', phantom, 'scala');
  138. delete process.env.CODEGRAPH_KERNEL;
  139. expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
  140. });
  141. it('real parse errors defer (given-with syntax)', () => {
  142. const broken = 'trait C\ngiven x: C with { def y = 1 }\n';
  143. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  144. delete process.env.CODEGRAPH_KERNEL;
  145. expect(tryKernelExtract('src/gw.scala', broken, 'scala')).toBeNull();
  146. });
  147. });