kernel-kotlin-parity.test.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. /**
  2. * Kernel↔wasm Kotlin extraction parity (R7b of the kernel migration).
  3. *
  4. * Asserts the native walker (codegraph-kernel/src/kotlin.rs — grammar
  5. * compiled from the vendored fwcd 0.3.8 C sources, the arc's first
  6. * vendored-grammar-C language) produces the SAME ExtractionResult as the
  7. * wasm TreeSitterExtractor over the checked-in torture fixture (torture.kt:
  8. * the property hook's scope classification and its initializer walk (a
  9. * lambda / SAM / anonymous-object RHS attributing its calls to the property),
  10. * extension-function receiver QNs
  11. * (`WidgetK::extend`, the qualified `com::qext` bug) + the owner-contains
  12. * fallback, expect/actual → node DECORATORS (the KMP synthesizer feed),
  13. * the bodiless-vs-bodied class header asymmetry, comment-glued
  14. * import/package extents, KDoc dropped-and-chain-breaking docstrings,
  15. * `@Marker` decorates vs `@Anno(args)` nothing, zero type-annotation refs,
  16. * zero instantiates, the #750 capitalized-chain re-encode, paren-then-
  17. * lambda garbage callees, `${X}`-reads-vs-`$X`-non-reads value refs and the
  18. * packaged-file target drop) plus a `.kts` script fixture (file-attributed
  19. * top-level calls), with in-memory CRLF variants (#1329), and two defer
  20. * fixtures — a `fun interface` file and a PHANTOM error (a one-line class
  21. * body sets hasError with a complete, ERROR-node-free CST; the kernel
  22. * trusts the flag).
  23. *
  24. * The full-repo sweep lives in scripts/kernel-parity.mjs (okio/okhttp/
  25. * kotlinx.coroutines — expected deferrals 23/49/51, grammar-inherent).
  26. * Skips when no kernel binary is staged; CODEGRAPH_KERNEL_EXPECT=1 turns
  27. * that into a failure (kernel-scaffold.test.ts).
  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 } 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 Kotlin extraction parity', () => {
  60. beforeAll(async () => {
  61. await initGrammars();
  62. await loadGrammarsForLanguages(['kotlin']);
  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(filePath: string, source: string, minNodes = 3): void {
  76. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  77. delete process.env.CODEGRAPH_KERNEL;
  78. const viaKernel = tryKernelExtract(filePath, source, 'kotlin');
  79. expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
  80. process.env.CODEGRAPH_KERNEL = '0';
  81. const viaWasm = extractFromSource(filePath, source, 'kotlin');
  82. delete process.env.CODEGRAPH_KERNEL;
  83. const k = canon(viaKernel!);
  84. const w = canon(viaWasm);
  85. expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes);
  86. expect(k.edges, `${filePath}: edges`).toEqual(w.edges);
  87. expect(k.refs, `${filePath}: refs`).toEqual(w.refs);
  88. expect(viaWasm.nodes.length).toBeGreaterThanOrEqual(minNodes);
  89. }
  90. const FIXTURES: Array<{ file: string; minNodes: number }> = [
  91. { file: 'torture.kt', minNodes: 40 },
  92. { file: 'TortureScript.kts', minNodes: 2 },
  93. ];
  94. for (const { file, minNodes } of FIXTURES) {
  95. it(`${file}: hook properties, receivers, decorators, calls, value refs`, () => {
  96. const src = fs.readFileSync(path.join(FIXTURE_DIR, file), 'utf8');
  97. assertParity(`fixtures/${file}`, src, minNodes);
  98. });
  99. it(`${file} CRLF parity`, () => {
  100. const src = fs.readFileSync(path.join(FIXTURE_DIR, file), 'utf8');
  101. const crlf = src.replace(/(?<!\r)\n/g, '\r\n');
  102. assertParity(`fixtures/${file} (crlf)`, crlf, minNodes);
  103. });
  104. }
  105. it('fun-interface files defer to the wasm extractor (grammar-inherent error)', () => {
  106. const src = 'package p\n\nfun interface Transformer {\n fun transform(x: Int): Int\n}\n\nfun after() { work() }\n';
  107. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  108. delete process.env.CODEGRAPH_KERNEL;
  109. expect(tryKernelExtract('src/FunIface.kt', src, 'kotlin')).toBeNull();
  110. process.env.CODEGRAPH_KERNEL = '0';
  111. const viaWasm = extractFromSource('src/FunIface.kt', src, 'kotlin');
  112. delete process.env.CODEGRAPH_KERNEL;
  113. // The wasm arm's misparse-recovery hook still mints the interface node.
  114. expect(viaWasm.nodes.some((n) => n.kind === 'interface' && n.name === 'Transformer')).toBe(true);
  115. });
  116. it('PHANTOM errors defer too — hasError with a complete, ERROR-node-free CST', () => {
  117. const src = 'abstract class A { abstract fun i(): Int }\n';
  118. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  119. delete process.env.CODEGRAPH_KERNEL;
  120. expect(tryKernelExtract('src/Phantom.kt', src, 'kotlin')).toBeNull();
  121. process.env.CODEGRAPH_KERNEL = '0';
  122. const viaWasm = extractFromSource('src/Phantom.kt', src, 'kotlin');
  123. delete process.env.CODEGRAPH_KERNEL;
  124. expect(viaWasm.nodes.some((n) => n.kind === 'class' && n.name === 'A')).toBe(true);
  125. });
  126. });