1
0

kernel-dart-parity.test.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. /**
  2. * Kernel↔wasm Dart extraction parity (R7b batch 4 of the kernel migration —
  3. * the final R7b language).
  4. *
  5. * Asserts the native walker (codegraph-kernel/src/dart.rs) produces the SAME
  6. * ExtractionResult as the wasm TreeSitterExtractor — nodes, edges, and
  7. * unresolved refs compared as canonicalized multisets — over the checked-in
  8. * fixtures (torture.dart: the master inventory — imports incl. deferred
  9. * invisibility, dartdoc in all three comment forms with the
  10. * annotation-broken chain, stacked annotations in reverse order, the
  11. * static_final_declaration constants hook, the full ctor set with the
  12. * unnamed-ctor skip and named-ctor renaming, operator methods as
  13. * `<anonymous>`, the extractBareCall matrix incl. cascade invisibility and
  14. * `?.`-as-`.`, the `ConfigT.load()` calls+references double emission,
  15. * extends/with/implements ref kinds, enum `with` silence, anonymous
  16. * extensions named after the ON type, value-ref targets with the sibling
  17. * body pull; TortureDoubleWalk.dart: THE SIBLING-BODY DOUBLE-WALK — the
  18. * duplicate local-function nodes with the same id under different parents
  19. * and the exact duplicated-ref interleave; TortureFnrefDart.dart: fn-ref
  20. * capture channels incl. named-argument non-capture and the file/class
  21. * twins; TortureMini/TortureSigs/TortureCtors/TortureVrefDart: signatures
  22. * verbatim, prefixed-return-type prefix bug, const factories invisible,
  23. * value-ref matrix with `$X` vs `${X}` asymmetry) and their CRLF variants
  24. * (derived in-memory — #1329), plus defer and generated-file pins.
  25. *
  26. * The full-repo sweeps live in scripts/kernel-parity.mjs (shelf/bloc/flutter
  27. * with --max-deferral 0.3); this suite keeps the invariant alive in
  28. * `npm test`. Skips when no kernel binary is staged; CODEGRAPH_KERNEL_EXPECT=1
  29. * turns that into a failure.
  30. */
  31. import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
  32. import * as fs from 'fs';
  33. import * as path from 'path';
  34. import { extractFromSource } from '../src/extraction';
  35. import { initGrammars, loadGrammarsForLanguages } from '../src/extraction/grammars';
  36. import { tryKernelExtract, resetKernelForTests } from '../src/extraction/kernel';
  37. import type { ExtractionResult } from '../src/types';
  38. const KERNEL_PATH = path.join(
  39. __dirname,
  40. '..',
  41. 'codegraph-kernel',
  42. 'prebuilds',
  43. `${process.platform}-${process.arch}`,
  44. 'codegraph-kernel.node'
  45. );
  46. const kernelBuilt = fs.existsSync(KERNEL_PATH);
  47. const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'kernel-parity');
  48. function canon(result: ExtractionResult): { nodes: string[]; edges: string[]; refs: string[] } {
  49. return {
  50. nodes: result.nodes
  51. .map(({ updatedAt: _u, ...n }) => JSON.stringify(n, Object.keys(n).sort()))
  52. .sort(),
  53. edges: result.edges.map((e) => JSON.stringify(e, Object.keys(e).sort())).sort(),
  54. refs: result.unresolvedReferences
  55. .map((r) => JSON.stringify(r, Object.keys(r).sort()))
  56. .sort(),
  57. };
  58. }
  59. const ENV_KEYS = ['CODEGRAPH_KERNEL', 'CODEGRAPH_KERNEL_LANGS'] as const;
  60. let savedEnv: Record<string, string | undefined>;
  61. describe.skipIf(!kernelBuilt)('kernel Dart extraction parity', () => {
  62. beforeAll(async () => {
  63. await initGrammars();
  64. await loadGrammarsForLanguages(['dart']);
  65. });
  66. beforeEach(() => {
  67. savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
  68. resetKernelForTests();
  69. });
  70. afterEach(() => {
  71. for (const k of ENV_KEYS) {
  72. if (savedEnv[k] === undefined) delete process.env[k];
  73. else process.env[k] = savedEnv[k];
  74. }
  75. resetKernelForTests();
  76. });
  77. function assertParity(filePath: string, source: string, minNodes = 2): ExtractionResult {
  78. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  79. delete process.env.CODEGRAPH_KERNEL;
  80. const viaKernel = tryKernelExtract(filePath, source, 'dart');
  81. expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
  82. process.env.CODEGRAPH_KERNEL = '0';
  83. const viaWasm = extractFromSource(filePath, source, 'dart');
  84. delete process.env.CODEGRAPH_KERNEL;
  85. const k = canon(viaKernel!);
  86. const w = canon(viaWasm);
  87. expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes);
  88. expect(k.edges, `${filePath}: edges`).toEqual(w.edges);
  89. expect(k.refs, `${filePath}: refs`).toEqual(w.refs);
  90. expect(viaWasm.nodes.length).toBeGreaterThanOrEqual(minNodes);
  91. return viaKernel!;
  92. }
  93. const FIXTURES = [
  94. ['torture.dart', 30],
  95. ['TortureDoubleWalk.dart', 5],
  96. ['TortureFnrefDart.dart', 3],
  97. ['TortureMini.dart', 5],
  98. ['TortureSigs.dart', 4],
  99. ['TortureCtors.dart', 3],
  100. ['TortureVrefDart.dart', 4],
  101. ] as const;
  102. for (const [file, minNodes] of FIXTURES) {
  103. it(`${file}: parity`, () => {
  104. const src = fs.readFileSync(path.join(FIXTURE_DIR, file), 'utf8');
  105. assertParity(`fixtures/${file}`, src, minNodes);
  106. });
  107. it(`${file}: CRLF parity`, () => {
  108. const src = fs.readFileSync(path.join(FIXTURE_DIR, file), 'utf8');
  109. const crlf = src.replace(/(?<!\r)\n/g, '\r\n');
  110. assertParity(`fixtures/${file} (crlf)`, crlf, minNodes);
  111. });
  112. }
  113. it('double-walk pins: duplicate local-fn nodes share an id; refs interleave', () => {
  114. const src = fs.readFileSync(path.join(FIXTURE_DIR, 'TortureDoubleWalk.dart'), 'utf8');
  115. const result = assertParity('fixtures/TortureDoubleWalk.dart', src, 5);
  116. // Local functions are minted TWICE — same (kind,name,line) → the SAME id
  117. // — once under the enclosing function, once under the file/class (the
  118. // sibling-body revisit). A dedupe here would silently diverge.
  119. const byId = new Map<string, number>();
  120. for (const n of result.nodes) byId.set(n.id, (byId.get(n.id) ?? 0) + 1);
  121. const dupes = [...byId.values()].filter((c) => c > 1);
  122. expect(dupes.length).toBeGreaterThan(0);
  123. });
  124. it('generated files extract but skip fn-ref and value-ref flushes', () => {
  125. const src = fs.readFileSync(path.join(FIXTURE_DIR, 'TortureVrefDart.dart'), 'utf8');
  126. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  127. delete process.env.CODEGRAPH_KERNEL;
  128. const viaKernel = tryKernelExtract('lib/model.g.dart', src, 'dart');
  129. expect(viaKernel).not.toBeNull();
  130. process.env.CODEGRAPH_KERNEL = '0';
  131. const viaWasm = extractFromSource('lib/model.g.dart', src, 'dart');
  132. delete process.env.CODEGRAPH_KERNEL;
  133. const k = canon(viaKernel!);
  134. const w = canon(viaWasm);
  135. expect(k.nodes).toEqual(w.nodes);
  136. expect(k.edges).toEqual(w.edges);
  137. expect(k.refs).toEqual(w.refs);
  138. // The skips: no function_ref refs, no valueRef edges.
  139. expect(viaKernel!.unresolvedReferences.some((r) => r.referenceKind === 'function_ref')).toBe(
  140. false
  141. );
  142. expect(viaKernel!.edges.some((e) => e.metadata?.valueRef === true)).toBe(false);
  143. });
  144. it('empty object patterns defer (the dominant dart-3 error class)', () => {
  145. const broken = 'int f(Object x) => switch (x) { Init() => 1, _ => 0 };\n';
  146. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  147. delete process.env.CODEGRAPH_KERNEL;
  148. expect(tryKernelExtract('lib/pat.dart', broken, 'dart')).toBeNull();
  149. process.env.CODEGRAPH_KERNEL = '0';
  150. const viaWasm = extractFromSource('lib/pat.dart', broken, 'dart');
  151. delete process.env.CODEGRAPH_KERNEL;
  152. expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
  153. });
  154. it('unnamed `library;` defers', () => {
  155. const broken = '/// Doc.\nlibrary;\n\nvoid f() {}\n';
  156. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  157. delete process.env.CODEGRAPH_KERNEL;
  158. expect(tryKernelExtract('lib/lib.dart', broken, 'dart')).toBeNull();
  159. });
  160. });