kernel-lua-parity.test.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. /**
  2. * Kernel↔wasm Lua + Luau extraction parity (R7b batch 4 of the kernel
  3. * migration).
  4. *
  5. * Asserts the native walker (codegraph-kernel/src/lua.rs — one module, two
  6. * dialects) produces the SAME ExtractionResult as the wasm
  7. * TreeSitterExtractor — nodes, edges, and unresolved refs compared as
  8. * canonicalized multisets — over the checked-in torture fixtures
  9. * (torture.lua: the require quintet incl. Roblox instance paths, the
  10. * BFS-string-win and .field/dynamic silences, receiver-QN methods
  11. * `M.sub.deep::chained` and `_G::installed`, the top-level
  12. * local-vs-global initializer-visibility inversion, body-level
  13. * `calls "require"`, table fn-ref registries with dedupe and the
  14. * `M.cb = cb` param-storage skip, the raw-text callee zoo with colon/
  15. * bracket/call-result callees and the `(handler)` conversion, LuaDoc
  16. * `- `-keeping docstrings, `<const>` attributes, one-line duplicate-id
  17. * declarations; torture.luau: `--!strict` docstring joining, `export type`
  18. * isExported, verbatim `Generic<T>` alias names, the typeof(require(...))
  19. * alias+import pair, typed signatures with return suffixes, interpolation/
  20. * if-expression/compound-assign call shapes) and their CRLF variants
  21. * (derived in-memory — #1329, pinning the block-comment `\r\n` docstring
  22. * byte), plus glue-chain and defer pins.
  23. *
  24. * The full-repo sweeps live in scripts/kernel-parity.mjs (kong/lazy.nvim/
  25. * lua-resty-core + lune/Fusion for the §5 gate); this suite keeps the
  26. * invariant alive in `npm test`. Skips when no kernel binary is staged;
  27. * CODEGRAPH_KERNEL_EXPECT=1 turns that into a failure.
  28. */
  29. import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
  30. import * as fs from 'fs';
  31. import * as path from 'path';
  32. import { extractFromSource } from '../src/extraction';
  33. import { initGrammars, loadGrammarsForLanguages } from '../src/extraction/grammars';
  34. import { tryKernelExtract, resetKernelForTests } from '../src/extraction/kernel';
  35. import type { ExtractionResult, Language } from '../src/types';
  36. const KERNEL_PATH = path.join(
  37. __dirname,
  38. '..',
  39. 'codegraph-kernel',
  40. 'prebuilds',
  41. `${process.platform}-${process.arch}`,
  42. 'codegraph-kernel.node'
  43. );
  44. const kernelBuilt = fs.existsSync(KERNEL_PATH);
  45. const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'kernel-parity');
  46. function canon(result: ExtractionResult): { nodes: string[]; edges: string[]; refs: string[] } {
  47. return {
  48. nodes: result.nodes
  49. .map(({ updatedAt: _u, ...n }) => JSON.stringify(n, Object.keys(n).sort()))
  50. .sort(),
  51. edges: result.edges.map((e) => JSON.stringify(e, Object.keys(e).sort())).sort(),
  52. refs: result.unresolvedReferences
  53. .map((r) => JSON.stringify(r, Object.keys(r).sort()))
  54. .sort(),
  55. };
  56. }
  57. const ENV_KEYS = ['CODEGRAPH_KERNEL', 'CODEGRAPH_KERNEL_LANGS'] as const;
  58. let savedEnv: Record<string, string | undefined>;
  59. describe.skipIf(!kernelBuilt)('kernel Lua/Luau extraction parity', () => {
  60. beforeAll(async () => {
  61. await initGrammars();
  62. await loadGrammarsForLanguages(['lua', 'luau']);
  63. });
  64. beforeEach(() => {
  65. savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
  66. resetKernelForTests();
  67. });
  68. afterEach(() => {
  69. for (const k of ENV_KEYS) {
  70. if (savedEnv[k] === undefined) delete process.env[k];
  71. else process.env[k] = savedEnv[k];
  72. }
  73. resetKernelForTests();
  74. });
  75. function assertParity(
  76. filePath: string,
  77. source: string,
  78. lang: Language,
  79. minNodes = 3
  80. ): ExtractionResult {
  81. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  82. delete process.env.CODEGRAPH_KERNEL;
  83. const viaKernel = tryKernelExtract(filePath, source, lang);
  84. expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
  85. process.env.CODEGRAPH_KERNEL = '0';
  86. const viaWasm = extractFromSource(filePath, source, lang);
  87. delete process.env.CODEGRAPH_KERNEL;
  88. const k = canon(viaKernel!);
  89. const w = canon(viaWasm);
  90. expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes);
  91. expect(k.edges, `${filePath}: edges`).toEqual(w.edges);
  92. expect(k.refs, `${filePath}: refs`).toEqual(w.refs);
  93. expect(viaWasm.nodes.length).toBeGreaterThanOrEqual(minNodes);
  94. return viaKernel!;
  95. }
  96. it('torture.lua: requires, receiver QNs, visibility inversion, callee zoo, fn-refs', () => {
  97. const file = path.join(FIXTURE_DIR, 'torture.lua');
  98. const result = assertParity('fixtures/torture.lua', fs.readFileSync(file, 'utf8'), 'lua', 20);
  99. // Kernel-arm pins so both arms drifting together can't silently lose the
  100. // dialect-defining quirks (checklist §Require hook / §extractCall):
  101. const refs = result.unresolvedReferences;
  102. // Top-level requires became imports; the body-level require is a CALL.
  103. expect(result.nodes.some((n) => n.kind === 'import' && n.name === 'app.core')).toBe(true);
  104. expect(refs.some((r) => r.referenceKind === 'calls' && r.referenceName === 'require')).toBe(
  105. true
  106. );
  107. // Roblox instance path → trailing segment; string-win beats the path.
  108. expect(result.nodes.some((n) => n.kind === 'import' && n.name === 'Signal')).toBe(true);
  109. expect(result.nodes.some((n) => n.kind === 'import' && n.name === 'Child')).toBe(true);
  110. // Colon callees keep the colon, self never stripped.
  111. expect(refs.some((r) => r.referenceName === 'self:helperMethod')).toBe(true);
  112. // Receiver-qualified method QNs are verbatim dotted receivers.
  113. expect(result.nodes.some((n) => n.kind === 'method' && n.qualifiedName === 'M.sub.deep::chained')).toBe(true);
  114. // lua functions carry NO isExported (undefined — not false).
  115. const fn = result.nodes.find((n) => n.kind === 'function' && n.name === 'topFn');
  116. expect(fn?.isExported).toBeUndefined();
  117. // variables DO carry isExported === false.
  118. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'core');
  119. expect(v?.isExported).toBe(false);
  120. });
  121. it('torture.lua CRLF parity (block-comment docstrings keep interior \\r\\n)', () => {
  122. const file = path.join(FIXTURE_DIR, 'torture.lua');
  123. const crlf = fs.readFileSync(file, 'utf8').replace(/(?<!\r)\n/g, '\r\n');
  124. assertParity('fixtures/torture.lua (crlf)', crlf, 'lua', 20);
  125. });
  126. it('torture.luau: type aliases, export flags, typed signatures, typeof-require', () => {
  127. const file = path.join(FIXTURE_DIR, 'torture.luau');
  128. const result = assertParity(
  129. 'fixtures/torture.luau',
  130. fs.readFileSync(file, 'utf8'),
  131. 'luau',
  132. 10
  133. );
  134. // luau functions carry isExported === false (present bit); methods stay
  135. // undefined — the one lua↔luau node-payload flag divergence.
  136. const fn = result.nodes.find((n) => n.kind === 'function' && n.isExported === false);
  137. expect(fn).toBeTruthy();
  138. const method = result.nodes.find((n) => n.kind === 'method');
  139. if (method) expect(method.isExported).toBeUndefined();
  140. // export type → isExported true.
  141. expect(result.nodes.some((n) => n.kind === 'type_alias' && n.isExported === true)).toBe(true);
  142. });
  143. it('torture.luau CRLF parity', () => {
  144. const file = path.join(FIXTURE_DIR, 'torture.luau');
  145. const crlf = fs.readFileSync(file, 'utf8').replace(/(?<!\r)\n/g, '\r\n');
  146. assertParity('fixtures/torture.luau (crlf)', crlf, 'luau', 10);
  147. });
  148. it('newline-glue chains emit byte-verbatim multi-link refs', () => {
  149. // Lua's statement ambiguity: a call statement followed by a line starting
  150. // `(` parses as ONE glued chain — the middle links' "callees" are whole
  151. // inner function_call texts, embedded newline/tab included.
  152. const glued = 'local helper = require("app.helper")\nfunction M:go(obj)\n\tobj:foo():bar()\n\t(helper)(4)\nend\n';
  153. const result = assertParity('fixtures/glue.lua', glued, 'lua', 3);
  154. const names = result.unresolvedReferences
  155. .filter((r) => r.referenceKind === 'calls')
  156. .map((r) => r.referenceName);
  157. expect(names).toContain('obj:foo():bar()\n\t(helper)');
  158. expect(names).toContain('obj:foo():bar()');
  159. expect(names).toContain('obj:foo():bar');
  160. expect(names).toContain('obj:foo');
  161. });
  162. it('one-line duplicate declarations emit duplicate-id rows verbatim', () => {
  163. const src = 'local x = 1; local x = 2\n';
  164. const result = assertParity('fixtures/dup.lua', src, 'lua', 2);
  165. const xs = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'x');
  166. expect(xs).toHaveLength(2);
  167. expect(xs[0]!.id).toBe(xs[1]!.id);
  168. });
  169. it('cross-dialect syntax defers to the wasm extractor', () => {
  170. // Luau syntax in a .lua file and a luau default type parameter both
  171. // ERROR (grammar-inherent, both-arm) — the kernel defers per-file.
  172. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  173. delete process.env.CODEGRAPH_KERNEL;
  174. expect(tryKernelExtract('src/compound.lua', 'x += 1\n', 'lua')).toBeNull();
  175. expect(
  176. tryKernelExtract('src/defaultparam.luau', 'type S<T = U> = {}\n', 'luau')
  177. ).toBeNull();
  178. process.env.CODEGRAPH_KERNEL = '0';
  179. const viaWasm = extractFromSource('src/compound.lua', 'x += 1\n', 'lua');
  180. delete process.env.CODEGRAPH_KERNEL;
  181. expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
  182. });
  183. });