kernel-ruby-parity.test.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. /**
  2. * Kernel↔wasm Ruby extraction parity (R7b of the kernel migration).
  3. *
  4. * Asserts the native walker (codegraph-kernel/src/ruby.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. * torture fixture (torture.rb: the importTypes:['call'] funnel and its
  8. * class-body DSL blindness, mixin implements refs WITH filePath (the v2
  9. * ref-flag wire path), module nesting + the hook multiply-capture, the
  10. * sibling-scan visibility trio, require/require_relative path refs incl. the
  11. * Kernel.require and interpolated-path quirks, the ruby call branch
  12. * (`.new` instantiates, constant-receiver references, `&.` joins, raw chain
  13. * text), bare-call statements (do…end vs brace-block blindness), heredocs,
  14. * `=begin` docstring marker survival, value-ref targets + shadow prune,
  15. * `__END__` trailer) and its CRLF variant (derived in-memory — #1329).
  16. *
  17. * The full-repo sweep lives in scripts/kernel-parity.mjs (sinatra/jekyll/
  18. * rails for the §5 gate); this suite keeps the invariant alive in `npm test`.
  19. * Skips when no kernel binary is staged; CODEGRAPH_KERNEL_EXPECT=1 turns that
  20. * into a failure (kernel-scaffold.test.ts).
  21. */
  22. import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
  23. import * as fs from 'fs';
  24. import * as path from 'path';
  25. import { extractFromSource } from '../src/extraction';
  26. import { initGrammars, loadGrammarsForLanguages } from '../src/extraction/grammars';
  27. import { tryKernelExtract, resetKernelForTests } from '../src/extraction/kernel';
  28. import type { ExtractionResult } from '../src/types';
  29. const KERNEL_PATH = path.join(
  30. __dirname,
  31. '..',
  32. 'codegraph-kernel',
  33. 'prebuilds',
  34. `${process.platform}-${process.arch}`,
  35. 'codegraph-kernel.node'
  36. );
  37. const kernelBuilt = fs.existsSync(KERNEL_PATH);
  38. const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'kernel-parity');
  39. function canon(result: ExtractionResult): { nodes: string[]; edges: string[]; refs: string[] } {
  40. return {
  41. nodes: result.nodes
  42. .map(({ updatedAt: _u, ...n }) => JSON.stringify(n, Object.keys(n).sort()))
  43. .sort(),
  44. edges: result.edges.map((e) => JSON.stringify(e, Object.keys(e).sort())).sort(),
  45. refs: result.unresolvedReferences
  46. .map((r) => JSON.stringify(r, Object.keys(r).sort()))
  47. .sort(),
  48. };
  49. }
  50. const ENV_KEYS = ['CODEGRAPH_KERNEL', 'CODEGRAPH_KERNEL_LANGS'] as const;
  51. let savedEnv: Record<string, string | undefined>;
  52. describe.skipIf(!kernelBuilt)('kernel Ruby extraction parity', () => {
  53. beforeAll(async () => {
  54. await initGrammars();
  55. await loadGrammarsForLanguages(['ruby']);
  56. });
  57. beforeEach(() => {
  58. savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
  59. resetKernelForTests();
  60. });
  61. afterEach(() => {
  62. for (const k of ENV_KEYS) {
  63. if (savedEnv[k] === undefined) delete process.env[k];
  64. else process.env[k] = savedEnv[k];
  65. }
  66. resetKernelForTests();
  67. });
  68. function assertParity(filePath: string, source: string, minNodes = 3): void {
  69. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  70. delete process.env.CODEGRAPH_KERNEL;
  71. const viaKernel = tryKernelExtract(filePath, source, 'ruby');
  72. expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
  73. process.env.CODEGRAPH_KERNEL = '0';
  74. const viaWasm = extractFromSource(filePath, source, 'ruby');
  75. delete process.env.CODEGRAPH_KERNEL;
  76. const k = canon(viaKernel!);
  77. const w = canon(viaWasm);
  78. expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes);
  79. expect(k.edges, `${filePath}: edges`).toEqual(w.edges);
  80. expect(k.refs, `${filePath}: refs`).toEqual(w.refs);
  81. expect(viaWasm.nodes.length).toBeGreaterThanOrEqual(minNodes);
  82. }
  83. it('torture fixture: modules/mixins, visibility scan, requires, call zoo, value refs', () => {
  84. const file = path.join(FIXTURE_DIR, 'torture.rb');
  85. assertParity('fixtures/torture.rb', fs.readFileSync(file, 'utf8'), 30);
  86. });
  87. // CRLF variant — the shape every Windows autocrlf checkout has. Derived in
  88. // memory so no platform or editor can silently normalize it away; pins the
  89. // JS-multiline-^ docstring semantics for `#` runs and `=begin` bodies
  90. // (#1329), plus heredoc/`%`-literal CRLF parsing.
  91. it('torture fixture CRLF parity', () => {
  92. const file = path.join(FIXTURE_DIR, 'torture.rb');
  93. const crlf = fs.readFileSync(file, 'utf8').replace(/(?<!\r)\n/g, '\r\n');
  94. assertParity('fixtures/torture.rb (crlf)', crlf, 30);
  95. });
  96. it('mixin implements refs carry filePath through the v2 ref-flag wire path', () => {
  97. const src = 'class Widget\n include Comparable\nend\n';
  98. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  99. delete process.env.CODEGRAPH_KERNEL;
  100. const viaKernel = tryKernelExtract('src/widget.rb', src, 'ruby');
  101. expect(viaKernel).not.toBeNull();
  102. const impl = viaKernel!.unresolvedReferences.find((r) => r.referenceKind === 'implements');
  103. expect(impl?.referenceName).toBe('Comparable');
  104. expect(impl?.filePath).toBe('src/widget.rb');
  105. // Ordinary refs stay un-denormalized.
  106. const other = viaKernel!.unresolvedReferences.find((r) => r.referenceKind !== 'implements');
  107. if (other) expect(other.filePath).toBeUndefined();
  108. });
  109. it('files with parse errors defer to the wasm extractor (recovery is encoding-dependent)', () => {
  110. const broken = 'def broken(\n x = [1,\nend\n';
  111. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  112. delete process.env.CODEGRAPH_KERNEL;
  113. expect(tryKernelExtract('src/broken.rb', broken, 'ruby')).toBeNull();
  114. process.env.CODEGRAPH_KERNEL = '0';
  115. const viaWasm = extractFromSource('src/broken.rb', broken, 'ruby');
  116. delete process.env.CODEGRAPH_KERNEL;
  117. expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
  118. });
  119. });