kernel-tsjs-parity.test.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /**
  2. * Kernel↔wasm TS/JS extraction parity (R2 of the kernel migration).
  3. *
  4. * Asserts the native walker (codegraph-kernel/src/tsjs/) produces the SAME
  5. * ExtractionResult as the wasm TreeSitterExtractor — nodes, edges, and
  6. * unresolved refs compared as canonicalized multisets — over:
  7. * - the checked-in torture fixtures (every ported feature: components/HOCs,
  8. * stores, RTK, vuex, fn-refs, value-ref shadowing, decorators, enums,
  9. * type-alias members/tuple contracts, re-exports, JSX, field methods), and
  10. * - this repo's own extraction sources (real-world TS).
  11. *
  12. * The full-repo sweep lives in scripts/kernel-parity.mjs (excalidraw et al.,
  13. * run for the §5 gate); this suite keeps the invariant alive in `npm test`.
  14. * Skips when no kernel binary is staged; CODEGRAPH_KERNEL_EXPECT=1 turns that
  15. * into a failure (wired in kernel-scaffold.test.ts).
  16. */
  17. import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
  18. import * as fs from 'fs';
  19. import * as path from 'path';
  20. import { extractFromSource } from '../src/extraction';
  21. import { initGrammars, loadGrammarsForLanguages } from '../src/extraction/grammars';
  22. import { tryKernelExtract, resetKernelForTests } from '../src/extraction/kernel';
  23. import type { ExtractionResult, Language } from '../src/types';
  24. const KERNEL_PATH = path.join(
  25. __dirname,
  26. '..',
  27. 'codegraph-kernel',
  28. 'prebuilds',
  29. `${process.platform}-${process.arch}`,
  30. 'codegraph-kernel.node'
  31. );
  32. const kernelBuilt = fs.existsSync(KERNEL_PATH);
  33. const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'kernel-parity');
  34. const REAL_SOURCES = [
  35. 'src/extraction/kernel/loader.ts',
  36. 'src/extraction/kernel/decode.ts',
  37. 'src/extraction/parse-pool.ts',
  38. 'src/extraction/function-ref.ts',
  39. 'src/mcp/tools.ts',
  40. ];
  41. function canon(result: ExtractionResult): { nodes: string[]; edges: string[]; refs: string[] } {
  42. return {
  43. nodes: result.nodes
  44. .map(({ updatedAt: _u, ...n }) => JSON.stringify(n, Object.keys(n).sort()))
  45. .sort(),
  46. edges: result.edges.map((e) => JSON.stringify(e, Object.keys(e).sort())).sort(),
  47. refs: result.unresolvedReferences
  48. .map((r) => JSON.stringify(r, Object.keys(r).sort()))
  49. .sort(),
  50. };
  51. }
  52. const ENV_KEYS = ['CODEGRAPH_KERNEL', 'CODEGRAPH_KERNEL_LANGS'] as const;
  53. let savedEnv: Record<string, string | undefined>;
  54. describe.skipIf(!kernelBuilt)('kernel TS/JS extraction parity', () => {
  55. beforeAll(async () => {
  56. await initGrammars();
  57. await loadGrammarsForLanguages(['typescript', 'tsx', 'javascript', 'jsx', 'java', 'python', 'go']);
  58. });
  59. beforeEach(() => {
  60. savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
  61. resetKernelForTests();
  62. });
  63. afterEach(() => {
  64. for (const k of ENV_KEYS) {
  65. if (savedEnv[k] === undefined) delete process.env[k];
  66. else process.env[k] = savedEnv[k];
  67. }
  68. resetKernelForTests();
  69. });
  70. function assertParity(filePath: string, source: string, language: Language): ExtractionResult {
  71. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  72. delete process.env.CODEGRAPH_KERNEL;
  73. const viaKernel = tryKernelExtract(filePath, source, language);
  74. expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
  75. process.env.CODEGRAPH_KERNEL = '0';
  76. const viaWasm = extractFromSource(filePath, source, language);
  77. delete process.env.CODEGRAPH_KERNEL;
  78. const k = canon(viaKernel!);
  79. const w = canon(viaWasm);
  80. expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes);
  81. expect(k.edges, `${filePath}: edges`).toEqual(w.edges);
  82. expect(k.refs, `${filePath}: refs`).toEqual(w.refs);
  83. // Meaningful comparison, not empty-vs-empty.
  84. expect(viaWasm.nodes.length).toBeGreaterThan(3);
  85. return viaWasm;
  86. }
  87. it.each([
  88. ['ts', 'typescript'], ['tsx', 'tsx'], ['js', 'javascript'], ['jsx', 'jsx'],
  89. ] as const)('leaves nested identifier receivers unresolved and keeps argument calls: %s (#1566)', (ext, language) => {
  90. const result = assertParity(`fixture.${ext}`, `
  91. function readKey() { return 'answer'; }
  92. function local() {
  93. const values = new Map();
  94. return values.get(readKey());
  95. }
  96. function nested(holder) {
  97. holder.values.get(readKey());
  98. holder.values?.get(readKey());
  99. holder['values'].get(readKey());
  100. holder.deep.values.get(readKey());
  101. }
  102. `, language);
  103. const nested = result.nodes.find((n) => n.name === 'nested' && n.kind === 'function');
  104. expect(nested).toBeDefined();
  105. expect(result.unresolvedReferences.filter((r) => r.referenceKind === 'calls' && r.fromNodeId === nested!.id)
  106. .map((r) => r.referenceName)).toEqual(['readKey', 'readKey', 'readKey', 'readKey']);
  107. expect(result.unresolvedReferences.some((r) => r.referenceName === 'values.get')).toBe(true);
  108. });
  109. it('torture fixture (tsx): components, stores, RTK, fn-refs, value-refs, decorators', () => {
  110. const file = path.join(FIXTURE_DIR, 'torture.tsx');
  111. assertParity('fixtures/torture.tsx', fs.readFileSync(file, 'utf8'), 'tsx');
  112. });
  113. it('torture fixture (js): field methods, wrappers, vuex module shape', () => {
  114. const file = path.join(FIXTURE_DIR, 'torture.js');
  115. assertParity('fixtures/torture.js', fs.readFileSync(file, 'utf8'), 'javascript');
  116. });
  117. it('torture fixture (java): Lombok, anonymous classes, method refs, chains', () => {
  118. const file = path.join(FIXTURE_DIR, 'Torture.java');
  119. assertParity('fixtures/Torture.java', fs.readFileSync(file, 'utf8'), 'java');
  120. });
  121. it('torture fixture (python): decorators, self fn-refs, imports, shadowing', () => {
  122. const file = path.join(FIXTURE_DIR, 'torture.py');
  123. assertParity('fixtures/torture.py', fs.readFileSync(file, 'utf8'), 'python');
  124. });
  125. it('torture fixture (go): receivers, embedding, interfaces, composite literals', () => {
  126. const file = path.join(FIXTURE_DIR, 'torture.go');
  127. assertParity('fixtures/torture.go', fs.readFileSync(file, 'utf8'), 'go');
  128. });
  129. it.each(REAL_SOURCES)('real source parity: %s', (rel) => {
  130. const file = path.join(__dirname, '..', rel);
  131. assertParity(rel, fs.readFileSync(file, 'utf8'), 'typescript');
  132. });
  133. // Every torture fixture again with CRLF line endings — the shape every
  134. // Windows autocrlf checkout has. Derived in memory (not a checked-in CRLF
  135. // file) so no platform or editor can silently normalize it away. Pins the
  136. // JS-multiline-^ semantics in the kernel's docstring cleaning: JS `^`/m
  137. // anchors after \r too, so the block-continuation `\s*` eats the `\n` and
  138. // the cleaned docstring keeps a bare `\r` (caught on the Windows VM leg of
  139. // the O2 gate; diverged in the kernel until docstring.rs mirrored it).
  140. it.each([
  141. ['torture.tsx', 'tsx'],
  142. ['torture.js', 'javascript'],
  143. ['Torture.java', 'java'],
  144. ['torture.py', 'python'],
  145. ['torture.go', 'go'],
  146. ] as const)('torture fixture CRLF parity: %s', (name, lang) => {
  147. const file = path.join(FIXTURE_DIR, name);
  148. const crlf = fs.readFileSync(file, 'utf8').replace(/(?<!\r)\n/g, '\r\n');
  149. assertParity(`fixtures/${name} (crlf)`, crlf, lang);
  150. });
  151. it('files with parse errors defer to the wasm extractor (recovery is encoding-dependent)', () => {
  152. // tree-sitter error RECOVERY differs between UTF-8 (native) and UTF-16
  153. // (web-tree-sitter) parsing — same grammar, same core version — so the
  154. // kernel defers any erroring file to keep routing graph-neutral.
  155. const broken = 'export function f( {\n return }} 12 (\n';
  156. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  157. delete process.env.CODEGRAPH_KERNEL;
  158. expect(tryKernelExtract('src/broken.ts', broken, 'typescript')).toBeNull();
  159. // The seam still serves the file — through the wasm path.
  160. process.env.CODEGRAPH_KERNEL = '0';
  161. const viaWasm = extractFromSource('src/broken.ts', broken, 'typescript');
  162. delete process.env.CODEGRAPH_KERNEL;
  163. expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
  164. });
  165. it('typescript fixture parsed as plain typescript variant', () => {
  166. // Same content through the non-tsx grammar exercises the typescript
  167. // (vs tsx) LangSpec pairing.
  168. const file = path.join(__dirname, '..', 'src/extraction/kernel/index.ts');
  169. assertParity('src/extraction/kernel/index.ts', fs.readFileSync(file, 'utf8'), 'typescript');
  170. });
  171. });