1
0

kernel-r-parity.test.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. /**
  2. * Kernel↔wasm R extraction parity (R7b batch 4 of the kernel migration).
  3. *
  4. * Asserts the native walker (codegraph-kernel/src/rlang.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.R: every visitNode-hook branch — function/variable/
  8. * constant assignments in all five operators, the class quartet
  9. * setClass/setRefClass/R6Class/ggproto with list()+direct methods and
  10. * extends refs, setGeneric/setMethod, the import quintet with its five
  11. * silent-consumption shapes, class-idiom variable suppression, chained/
  12. * right-assign/precedence-ghost gaps — plus the raw-text callee zoo
  13. * (`pkg::fn`, `obj$meth`, `"strfn"` quotes kept, `(handler)` conversion,
  14. * `calls "return"`), duplicate same-(kind,name,line) ids, parse-clean raw
  15. * strings/underscore-pipe/trailing commas, and UTF-16 emoji columns) and its
  16. * CRLF variant (derived in-memory — #1329).
  17. *
  18. * The full-repo sweep lives in scripts/kernel-parity.mjs (dplyr/ggplot2/shiny
  19. * for the §5 gate); this suite keeps the invariant alive in `npm test`.
  20. * Skips when no kernel binary is staged; CODEGRAPH_KERNEL_EXPECT=1 turns that
  21. * 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 } 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 R extraction parity', () => {
  54. beforeAll(async () => {
  55. await initGrammars();
  56. await loadGrammarsForLanguages(['r']);
  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, minNodes = 3): ExtractionResult {
  70. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  71. delete process.env.CODEGRAPH_KERNEL;
  72. const viaKernel = tryKernelExtract(filePath, source, 'r');
  73. expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
  74. process.env.CODEGRAPH_KERNEL = '0';
  75. const viaWasm = extractFromSource(filePath, source, 'r');
  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. expect(viaWasm.nodes.length).toBeGreaterThanOrEqual(minNodes);
  83. return viaKernel!;
  84. }
  85. it('torture fixture: hook branches, class quartet, import quintet, call zoo', () => {
  86. const file = path.join(FIXTURE_DIR, 'torture.R');
  87. const result = assertParity('fixtures/torture.R', fs.readFileSync(file, 'utf8'), 40);
  88. // Pin the R-distinctive quirks on the KERNEL arm so both arms drifting
  89. // together can't silently lose them (checklist §The visitNode hook):
  90. // return/next/break are named nodes in v1.2.0 — `return(g(x))` emits a
  91. // literal `calls "return"` ref alongside `calls g`.
  92. const refNames = result.unresolvedReferences.map((r) => r.referenceName);
  93. expect(refNames).toContain('return');
  94. // Dynamic-arg imports are consumed SILENTLY — the `file.path` call inside
  95. // `source(file.path("R", "dyn.R"))` vanishes (subtree never visited).
  96. expect(refNames).not.toContain('file.path');
  97. // The named-first-argument bug: `library(help = docpkg)` imports docpkg.
  98. expect(result.nodes.some((n) => n.kind === 'import' && n.name === 'docpkg')).toBe(true);
  99. // Class-idiom suppression: Account has a class node but NO variable twin.
  100. expect(result.nodes.some((n) => n.kind === 'class' && n.name === 'Account')).toBe(true);
  101. expect(result.nodes.some((n) => n.kind === 'variable' && n.name === 'Account')).toBe(false);
  102. // No R node ever carries a docstring (roxygen is dropped).
  103. expect(result.nodes.every((n) => n.docstring === undefined)).toBe(true);
  104. });
  105. // CRLF variant — the shape every Windows autocrlf checkout has. Derived in
  106. // memory so no platform or editor can silently normalize it away. The only
  107. // LF↔CRLF extraction difference for R is `\r\n` bytes inside multi-line
  108. // import signatures — both arms must agree byte-for-byte.
  109. it('torture fixture CRLF parity', () => {
  110. const file = path.join(FIXTURE_DIR, 'torture.R');
  111. const crlf = fs.readFileSync(file, 'utf8').replace(/(?<!\r)\n/g, '\r\n');
  112. assertParity('fixtures/torture.R (crlf)', crlf, 40);
  113. });
  114. // BOM variant — the err-battery pinned BOM sources as parse-clean; derive it
  115. // in-memory for the same reason as CRLF.
  116. it('torture fixture BOM parity', () => {
  117. const file = path.join(FIXTURE_DIR, 'torture.R');
  118. const bom = '' + fs.readFileSync(file, 'utf8');
  119. assertParity('fixtures/torture.R (bom)', bom, 40);
  120. });
  121. it('files with parse errors defer to the wasm extractor (recovery is encoding-dependent)', () => {
  122. // `x <-` with no rhs is a MISSING-node incomplete (genuinely broken).
  123. const broken = 'ok_fn <- function() 1\nx <-\n';
  124. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  125. delete process.env.CODEGRAPH_KERNEL;
  126. expect(tryKernelExtract('src/broken.R', broken, 'r')).toBeNull();
  127. process.env.CODEGRAPH_KERNEL = '0';
  128. const viaWasm = extractFromSource('src/broken.R', broken, 'r');
  129. delete process.env.CODEGRAPH_KERNEL;
  130. expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
  131. });
  132. });