kernel-ccpp-parity.test.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. /**
  2. * Kernel↔wasm C/C++ extraction parity (R7a of the kernel migration).
  3. *
  4. * Asserts the native walker (codegraph-kernel/src/ccpp/) 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 (torture.c / torture.cpp / torture.hpp:
  8. * fn-ptr tables, typedef enum/struct, multi-declarator consts, namespaces
  9. * incl. C++17 nested, out-of-line Cls::method defs, templates + template
  10. * bases, operators, stack construction, local fn-ptrs, UE-macro shapes
  11. * through the hoisted preParse, using-aliases, value-ref shadowing), and
  12. * - Metal/CUDA-shaped sources arriving as language 'cpp' — pinning that the
  13. * route point applies the SAME extension/content-gated preParse blanks to
  14. * the kernel arm (docs/design/ccpp-kernel-port-checklist.md, decision 1/2).
  15. *
  16. * Files with parse errors — including the spaced explicit-operator CALL-SITE
  17. * shape (#1247), which rides an ERROR node — must DEFER to wasm (`defer:`),
  18. * asserted below. The full-repo sweep lives in scripts/kernel-parity.mjs
  19. * (redis/git/fmt et al., run for the §5 gate); this suite keeps the invariant
  20. * alive in `npm test`. Skips when no kernel binary is staged;
  21. * CODEGRAPH_KERNEL_EXPECT=1 turns that into a failure (kernel-scaffold.test.ts).
  22. */
  23. import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
  24. import * as fs from 'fs';
  25. import * as path from 'path';
  26. import { extractFromSource } from '../src/extraction';
  27. import { initGrammars, loadGrammarsForLanguages } from '../src/extraction/grammars';
  28. import { tryKernelExtract, resetKernelForTests } from '../src/extraction/kernel';
  29. import type { ExtractionResult, Language } from '../src/types';
  30. const KERNEL_PATH = path.join(
  31. __dirname,
  32. '..',
  33. 'codegraph-kernel',
  34. 'prebuilds',
  35. `${process.platform}-${process.arch}`,
  36. 'codegraph-kernel.node'
  37. );
  38. const kernelBuilt = fs.existsSync(KERNEL_PATH);
  39. const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'kernel-parity');
  40. function canon(result: ExtractionResult): { nodes: string[]; edges: string[]; refs: string[] } {
  41. return {
  42. nodes: result.nodes
  43. .map(({ updatedAt: _u, ...n }) => JSON.stringify(n, Object.keys(n).sort()))
  44. .sort(),
  45. edges: result.edges.map((e) => JSON.stringify(e, Object.keys(e).sort())).sort(),
  46. refs: result.unresolvedReferences
  47. .map((r) => JSON.stringify(r, Object.keys(r).sort()))
  48. .sort(),
  49. };
  50. }
  51. const ENV_KEYS = ['CODEGRAPH_KERNEL', 'CODEGRAPH_KERNEL_LANGS'] as const;
  52. let savedEnv: Record<string, string | undefined>;
  53. describe.skipIf(!kernelBuilt)('kernel C/C++ extraction parity', () => {
  54. beforeAll(async () => {
  55. await initGrammars();
  56. await loadGrammarsForLanguages(['c', 'cpp']);
  57. });
  58. beforeEach(() => {
  59. savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
  60. resetKernelForTests();
  61. });
  62. afterEach(() => {
  63. for (const k of ENV_KEYS) {
  64. if (savedEnv[k] === undefined) delete process.env[k];
  65. else process.env[k] = savedEnv[k];
  66. }
  67. resetKernelForTests();
  68. });
  69. function assertParity(filePath: string, source: string, language: Language, minNodes = 3): void {
  70. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  71. delete process.env.CODEGRAPH_KERNEL;
  72. const viaKernel = tryKernelExtract(filePath, source, language);
  73. expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
  74. process.env.CODEGRAPH_KERNEL = '0';
  75. const viaWasm = extractFromSource(filePath, source, language);
  76. delete process.env.CODEGRAPH_KERNEL;
  77. const k = canon(viaKernel!);
  78. const w = canon(viaWasm);
  79. expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes);
  80. expect(k.edges, `${filePath}: edges`).toEqual(w.edges);
  81. expect(k.refs, `${filePath}: refs`).toEqual(w.refs);
  82. // Meaningful comparison, not empty-vs-empty (the inline Metal/CUDA
  83. // sources are deliberately small — they pass their exact node count).
  84. expect(viaWasm.nodes.length).toBeGreaterThanOrEqual(minNodes);
  85. }
  86. it('torture fixture (c): fn-ptr tables, typedefs, file-scope consts, value-refs', () => {
  87. const file = path.join(FIXTURE_DIR, 'torture.c');
  88. assertParity('fixtures/torture.c', fs.readFileSync(file, 'utf8'), 'c');
  89. });
  90. it('torture fixture (cpp): namespaces, out-of-line methods, templates, fn-ptrs, UE macros', () => {
  91. const file = path.join(FIXTURE_DIR, 'torture.cpp');
  92. assertParity('fixtures/torture.cpp', fs.readFileSync(file, 'utf8'), 'cpp');
  93. });
  94. it('torture fixture (hpp): fwd decls, extern "C", header templates, reflection markup', () => {
  95. const file = path.join(FIXTURE_DIR, 'torture.hpp');
  96. assertParity('fixtures/torture.hpp', fs.readFileSync(file, 'utf8'), 'cpp');
  97. });
  98. // Metal rides the cpp route: `.metal` maps to language 'cpp' and the
  99. // extension-gated `[[attribute]]` blank must reach the kernel arm through
  100. // the route-point preParse hoist (filePath rides along for the gate).
  101. it('metal-shaped source (.metal → cpp): attribute blanks applied on both arms', () => {
  102. const metal = [
  103. 'struct VertexIn {',
  104. ' float3 position [[attribute(0)]];',
  105. ' float2 uv [[attribute(1)]];',
  106. '};',
  107. 'static float2 scale_uv(float2 uv) { return uv; }',
  108. '',
  109. ].join('\n');
  110. assertParity('fixtures/shader.metal', metal, 'cpp');
  111. });
  112. // CUDA rides the cpp route too: specifier + launch-config blanks are gated
  113. // by extension OR content, and both fire before the kernel call.
  114. it('cuda-shaped source (.cu → cpp): specifier + launch blanks applied on both arms', () => {
  115. const cuda = [
  116. '__global__ void step_kernel(float *data) { data[0] += 1.0f; }',
  117. 'void launch(float *data) { step_kernel<<<1, 256>>>(data); }',
  118. '',
  119. ].join('\n');
  120. assertParity('fixtures/kern.cu', cuda, 'cpp');
  121. });
  122. // Every torture fixture again with CRLF line endings — the shape every
  123. // Windows autocrlf checkout has. Derived in memory (not a checked-in CRLF
  124. // file) so no platform or editor can silently normalize it away. Pins the
  125. // JS-multiline-^ docstring semantics for the C comment markers (#1329).
  126. it.each([
  127. ['torture.c', 'c'],
  128. ['torture.cpp', 'cpp'],
  129. ['torture.hpp', 'cpp'],
  130. ] as const)('torture fixture CRLF parity: %s', (name, lang) => {
  131. const file = path.join(FIXTURE_DIR, name);
  132. const crlf = fs.readFileSync(file, 'utf8').replace(/(?<!\r)\n/g, '\r\n');
  133. assertParity(`fixtures/${name} (crlf)`, crlf, lang);
  134. });
  135. it('spaced explicit-operator call sites defer to the wasm extractor (#1247 rides an ERROR node)', () => {
  136. const source = [
  137. 'struct It { int operator*() const { return 1; } };',
  138. 'int read_it(const It &it) { return it.operator *(); }',
  139. '',
  140. ].join('\n');
  141. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  142. delete process.env.CODEGRAPH_KERNEL;
  143. expect(tryKernelExtract('src/op.cpp', source, 'cpp')).toBeNull();
  144. // The seam still serves the file — through the wasm path, where the
  145. // operator-call recovery emits the `it.operator*` ref.
  146. process.env.CODEGRAPH_KERNEL = '0';
  147. const viaWasm = extractFromSource('src/op.cpp', source, 'cpp');
  148. delete process.env.CODEGRAPH_KERNEL;
  149. expect(
  150. viaWasm.unresolvedReferences.some((r) => r.referenceName === 'it.operator*')
  151. ).toBe(true);
  152. });
  153. it('files with parse errors defer to the wasm extractor (recovery is encoding-dependent)', () => {
  154. const broken = 'void f( {\n return }} 12 (\n';
  155. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  156. delete process.env.CODEGRAPH_KERNEL;
  157. expect(tryKernelExtract('src/broken.c', broken, 'c')).toBeNull();
  158. process.env.CODEGRAPH_KERNEL = '0';
  159. const viaWasm = extractFromSource('src/broken.c', broken, 'c');
  160. delete process.env.CODEGRAPH_KERNEL;
  161. expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
  162. });
  163. });