1
0

kernel-kotlin-parity.test.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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, extension-function receiver QNs
  9. * (`WidgetK::extend`, the qualified `com::qext` bug) + the owner-contains
  10. * fallback, expect/actual → node DECORATORS (the KMP synthesizer feed),
  11. * the bodiless-vs-bodied class header asymmetry, comment-glued
  12. * import/package extents, KDoc dropped-and-chain-breaking docstrings,
  13. * `@Marker` decorates vs `@Anno(args)` nothing, zero type-annotation refs,
  14. * zero instantiates, the #750 capitalized-chain re-encode, paren-then-
  15. * lambda garbage callees, `${X}`-reads-vs-`$X`-non-reads value refs and the
  16. * packaged-file target drop) plus a `.kts` script fixture (file-attributed
  17. * top-level calls), with in-memory CRLF variants (#1329), and two defer
  18. * fixtures — a `fun interface` file and a PHANTOM error (a one-line class
  19. * body sets hasError with a complete, ERROR-node-free CST; the kernel
  20. * trusts the flag).
  21. *
  22. * The full-repo sweep lives in scripts/kernel-parity.mjs (okio/okhttp/
  23. * kotlinx.coroutines — expected deferrals 23/49/51, grammar-inherent).
  24. * Skips when no kernel binary is staged; CODEGRAPH_KERNEL_EXPECT=1 turns
  25. * that into a failure (kernel-scaffold.test.ts).
  26. */
  27. import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
  28. import * as fs from 'fs';
  29. import * as path from 'path';
  30. import { extractFromSource } from '../src/extraction';
  31. import { initGrammars, loadGrammarsForLanguages } from '../src/extraction/grammars';
  32. import { tryKernelExtract, resetKernelForTests } from '../src/extraction/kernel';
  33. import type { ExtractionResult } from '../src/types';
  34. const KERNEL_PATH = path.join(
  35. __dirname,
  36. '..',
  37. 'codegraph-kernel',
  38. 'prebuilds',
  39. `${process.platform}-${process.arch}`,
  40. 'codegraph-kernel.node'
  41. );
  42. const kernelBuilt = fs.existsSync(KERNEL_PATH);
  43. const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'kernel-parity');
  44. function canon(result: ExtractionResult): { nodes: string[]; edges: string[]; refs: string[] } {
  45. return {
  46. nodes: result.nodes
  47. .map(({ updatedAt: _u, ...n }) => JSON.stringify(n, Object.keys(n).sort()))
  48. .sort(),
  49. edges: result.edges.map((e) => JSON.stringify(e, Object.keys(e).sort())).sort(),
  50. refs: result.unresolvedReferences
  51. .map((r) => JSON.stringify(r, Object.keys(r).sort()))
  52. .sort(),
  53. };
  54. }
  55. const ENV_KEYS = ['CODEGRAPH_KERNEL', 'CODEGRAPH_KERNEL_LANGS'] as const;
  56. let savedEnv: Record<string, string | undefined>;
  57. describe.skipIf(!kernelBuilt)('kernel Kotlin extraction parity', () => {
  58. beforeAll(async () => {
  59. await initGrammars();
  60. await loadGrammarsForLanguages(['kotlin']);
  61. });
  62. beforeEach(() => {
  63. savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
  64. resetKernelForTests();
  65. });
  66. afterEach(() => {
  67. for (const k of ENV_KEYS) {
  68. if (savedEnv[k] === undefined) delete process.env[k];
  69. else process.env[k] = savedEnv[k];
  70. }
  71. resetKernelForTests();
  72. });
  73. function assertParity(filePath: string, source: string, minNodes = 3): void {
  74. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  75. delete process.env.CODEGRAPH_KERNEL;
  76. const viaKernel = tryKernelExtract(filePath, source, 'kotlin');
  77. expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
  78. process.env.CODEGRAPH_KERNEL = '0';
  79. const viaWasm = extractFromSource(filePath, source, 'kotlin');
  80. delete process.env.CODEGRAPH_KERNEL;
  81. const k = canon(viaKernel!);
  82. const w = canon(viaWasm);
  83. expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes);
  84. expect(k.edges, `${filePath}: edges`).toEqual(w.edges);
  85. expect(k.refs, `${filePath}: refs`).toEqual(w.refs);
  86. expect(viaWasm.nodes.length).toBeGreaterThanOrEqual(minNodes);
  87. }
  88. const FIXTURES: Array<{ file: string; minNodes: number }> = [
  89. { file: 'torture.kt', minNodes: 40 },
  90. { file: 'TortureScript.kts', minNodes: 2 },
  91. ];
  92. for (const { file, minNodes } of FIXTURES) {
  93. it(`${file}: hook properties, receivers, decorators, calls, value refs`, () => {
  94. const src = fs.readFileSync(path.join(FIXTURE_DIR, file), 'utf8');
  95. assertParity(`fixtures/${file}`, src, minNodes);
  96. });
  97. it(`${file} CRLF parity`, () => {
  98. const src = fs.readFileSync(path.join(FIXTURE_DIR, file), 'utf8');
  99. const crlf = src.replace(/(?<!\r)\n/g, '\r\n');
  100. assertParity(`fixtures/${file} (crlf)`, crlf, minNodes);
  101. });
  102. }
  103. it('fun-interface files defer to the wasm extractor (grammar-inherent error)', () => {
  104. const src = 'package p\n\nfun interface Transformer {\n fun transform(x: Int): Int\n}\n\nfun after() { work() }\n';
  105. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  106. delete process.env.CODEGRAPH_KERNEL;
  107. expect(tryKernelExtract('src/FunIface.kt', src, 'kotlin')).toBeNull();
  108. process.env.CODEGRAPH_KERNEL = '0';
  109. const viaWasm = extractFromSource('src/FunIface.kt', src, 'kotlin');
  110. delete process.env.CODEGRAPH_KERNEL;
  111. // The wasm arm's misparse-recovery hook still mints the interface node.
  112. expect(viaWasm.nodes.some((n) => n.kind === 'interface' && n.name === 'Transformer')).toBe(true);
  113. });
  114. it('PHANTOM errors defer too — hasError with a complete, ERROR-node-free CST', () => {
  115. const src = 'abstract class A { abstract fun i(): Int }\n';
  116. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  117. delete process.env.CODEGRAPH_KERNEL;
  118. expect(tryKernelExtract('src/Phantom.kt', src, 'kotlin')).toBeNull();
  119. process.env.CODEGRAPH_KERNEL = '0';
  120. const viaWasm = extractFromSource('src/Phantom.kt', src, 'kotlin');
  121. delete process.env.CODEGRAPH_KERNEL;
  122. expect(viaWasm.nodes.some((n) => n.kind === 'class' && n.name === 'A')).toBe(true);
  123. });
  124. });