kernel-rustlang-parity.test.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. /**
  2. * Kernel↔wasm Rust extraction parity (R7b of the kernel migration).
  3. *
  4. * Asserts the native walker (codegraph-kernel/src/rustlang.rs) produces the
  5. * SAME ExtractionResult as the wasm TreeSitterExtractor — nodes, edges, and
  6. * unresolved refs compared as canonicalized multisets — over the checked-in
  7. * torture fixture (torture.rs: impl/trait quirks incl. generic / lifetime /
  8. * reference / scoped / generic-trait impl receivers (#1588), unit structs
  9. * (a bodiless struct IS a definition — both walkers mint a node), phantom
  10. * const identifiers, use-binding refs incl. nested groups + wildcard-emits-
  11. * nothing, chained-call re-encode, turbofish, Rocket route macros body-only,
  12. * fn-ref shapes, value-ref shadowing, attribute-broken docstrings, dead-code
  13. * isAsync) and its CRLF variant (derived in-memory — #1329 docstring
  14. * semantics).
  15. *
  16. * The full-repo sweep lives in scripts/kernel-parity.mjs (ripgrep/tokio/
  17. * rust-analyzer for the §5 gate); this suite keeps the invariant alive in
  18. * `npm test`. Skips when no kernel binary is staged; CODEGRAPH_KERNEL_EXPECT=1
  19. * turns that into a failure (kernel-scaffold.test.ts).
  20. */
  21. import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
  22. import * as fs from 'fs';
  23. import * as path from 'path';
  24. import { extractFromSource } from '../src/extraction';
  25. import { initGrammars, loadGrammarsForLanguages } from '../src/extraction/grammars';
  26. import { tryKernelExtract, resetKernelForTests } from '../src/extraction/kernel';
  27. import type { ExtractionResult } from '../src/types';
  28. const KERNEL_PATH = path.join(
  29. __dirname,
  30. '..',
  31. 'codegraph-kernel',
  32. 'prebuilds',
  33. `${process.platform}-${process.arch}`,
  34. 'codegraph-kernel.node'
  35. );
  36. const kernelBuilt = fs.existsSync(KERNEL_PATH);
  37. const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'kernel-parity');
  38. function canon(result: ExtractionResult): { nodes: string[]; edges: string[]; refs: string[] } {
  39. return {
  40. nodes: result.nodes
  41. .map(({ updatedAt: _u, ...n }) => JSON.stringify(n, Object.keys(n).sort()))
  42. .sort(),
  43. edges: result.edges.map((e) => JSON.stringify(e, Object.keys(e).sort())).sort(),
  44. refs: result.unresolvedReferences
  45. .map((r) => JSON.stringify(r, Object.keys(r).sort()))
  46. .sort(),
  47. };
  48. }
  49. const ENV_KEYS = ['CODEGRAPH_KERNEL', 'CODEGRAPH_KERNEL_LANGS'] as const;
  50. let savedEnv: Record<string, string | undefined>;
  51. describe.skipIf(!kernelBuilt)('kernel Rust extraction parity', () => {
  52. beforeAll(async () => {
  53. await initGrammars();
  54. await loadGrammarsForLanguages(['rust']);
  55. });
  56. beforeEach(() => {
  57. savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
  58. resetKernelForTests();
  59. });
  60. afterEach(() => {
  61. for (const k of ENV_KEYS) {
  62. if (savedEnv[k] === undefined) delete process.env[k];
  63. else process.env[k] = savedEnv[k];
  64. }
  65. resetKernelForTests();
  66. });
  67. function assertParity(filePath: string, source: string, minNodes = 3): void {
  68. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  69. delete process.env.CODEGRAPH_KERNEL;
  70. const viaKernel = tryKernelExtract(filePath, source, 'rust');
  71. expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
  72. process.env.CODEGRAPH_KERNEL = '0';
  73. const viaWasm = extractFromSource(filePath, source, 'rust');
  74. delete process.env.CODEGRAPH_KERNEL;
  75. const k = canon(viaKernel!);
  76. const w = canon(viaWasm);
  77. expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes);
  78. expect(k.edges, `${filePath}: edges`).toEqual(w.edges);
  79. expect(k.refs, `${filePath}: refs`).toEqual(w.refs);
  80. expect(viaWasm.nodes.length).toBeGreaterThanOrEqual(minNodes);
  81. }
  82. it('torture fixture: impl/trait quirks, use bindings, chains, fn-refs, value-refs, route macros', () => {
  83. const file = path.join(FIXTURE_DIR, 'torture.rs');
  84. assertParity('fixtures/torture.rs', fs.readFileSync(file, 'utf8'), 20);
  85. });
  86. // CRLF variant — the shape every Windows autocrlf checkout has. Derived in
  87. // memory so no platform or editor can silently normalize it away; pins the
  88. // JS-multiline-^ docstring semantics for `///` runs (#1329).
  89. it('torture fixture CRLF parity', () => {
  90. const file = path.join(FIXTURE_DIR, 'torture.rs');
  91. const crlf = fs.readFileSync(file, 'utf8').replace(/(?<!\r)\n/g, '\r\n');
  92. assertParity('fixtures/torture.rs (crlf)', crlf, 20);
  93. });
  94. it('files with parse errors defer to the wasm extractor (recovery is encoding-dependent)', () => {
  95. const broken = 'fn f( {\n return }} 12 (\n';
  96. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  97. delete process.env.CODEGRAPH_KERNEL;
  98. expect(tryKernelExtract('src/broken.rs', broken, 'rust')).toBeNull();
  99. process.env.CODEGRAPH_KERNEL = '0';
  100. const viaWasm = extractFromSource('src/broken.rs', broken, 'rust');
  101. delete process.env.CODEGRAPH_KERNEL;
  102. expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
  103. });
  104. });