1
0

kernel-rustlang-parity.test.ts 4.7 KB

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