kernel-swift-parity.test.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. /**
  2. * Kernel↔wasm Swift extraction parity (R7b of the kernel migration).
  3. *
  4. * Asserts the native walker (codegraph-kernel/src/swift.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.swift: the DEDICATED in-class property branch
  8. * (#1020 — computed→property with getter walk, static let/var→constant/
  9. * variable, stored→field, owner-attributed decorator/type/attr-arg refs,
  10. * observed-property field + class-attributed observer calls), extensions
  11. * (multi-segment resolveName, sugar `[Proto]` names, where-clauses),
  12. * everything-is-extends inheritance, the full call matrix (subscript reads,
  13. * `defer`, optional-chaining receivers, #750 re-encode, literal-set
  14. * membership quirks, implicit members), positional return types with the
  15. * nested-generic failure, present-false isAsync, `open`→internal visibility,
  16. * multi-case enum first-only minting, `/** *​/` docs ignored-and-chain-
  17. * breaking, value-ref targets incl. the declared-then-assigned
  18. * assignment-prune case the swift-nio sweep caught, SWIFT_SPEC fn-refs with
  19. * the label-forward skip and #selector shapes) and its CRLF variant (derived
  20. * in-memory — #1329).
  21. *
  22. * The full-repo sweep lives in scripts/kernel-parity.mjs (Alamofire/vapor/
  23. * swift-nio, --max-deferral 0.3 — swift error incidence is structurally
  24. * 9–27% on BOTH arms); this suite keeps the invariant alive in `npm test`.
  25. * Skips when no kernel binary is staged; CODEGRAPH_KERNEL_EXPECT=1 turns
  26. * that into a failure (kernel-scaffold.test.ts).
  27. */
  28. import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
  29. import * as fs from 'fs';
  30. import * as path from 'path';
  31. import { extractFromSource } from '../src/extraction';
  32. import { initGrammars, loadGrammarsForLanguages } from '../src/extraction/grammars';
  33. import { tryKernelExtract, resetKernelForTests } from '../src/extraction/kernel';
  34. import type { ExtractionResult } from '../src/types';
  35. const KERNEL_PATH = path.join(
  36. __dirname,
  37. '..',
  38. 'codegraph-kernel',
  39. 'prebuilds',
  40. `${process.platform}-${process.arch}`,
  41. 'codegraph-kernel.node'
  42. );
  43. const kernelBuilt = fs.existsSync(KERNEL_PATH);
  44. const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'kernel-parity');
  45. function canon(result: ExtractionResult): { nodes: string[]; edges: string[]; refs: string[] } {
  46. return {
  47. nodes: result.nodes
  48. .map(({ updatedAt: _u, ...n }) => JSON.stringify(n, Object.keys(n).sort()))
  49. .sort(),
  50. edges: result.edges.map((e) => JSON.stringify(e, Object.keys(e).sort())).sort(),
  51. refs: result.unresolvedReferences
  52. .map((r) => JSON.stringify(r, Object.keys(r).sort()))
  53. .sort(),
  54. };
  55. }
  56. const ENV_KEYS = ['CODEGRAPH_KERNEL', 'CODEGRAPH_KERNEL_LANGS'] as const;
  57. let savedEnv: Record<string, string | undefined>;
  58. describe.skipIf(!kernelBuilt)('kernel Swift extraction parity', () => {
  59. beforeAll(async () => {
  60. await initGrammars();
  61. await loadGrammarsForLanguages(['swift']);
  62. });
  63. beforeEach(() => {
  64. savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
  65. resetKernelForTests();
  66. });
  67. afterEach(() => {
  68. for (const k of ENV_KEYS) {
  69. if (savedEnv[k] === undefined) delete process.env[k];
  70. else process.env[k] = savedEnv[k];
  71. }
  72. resetKernelForTests();
  73. });
  74. function assertParity(filePath: string, source: string, minNodes = 3): void {
  75. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  76. delete process.env.CODEGRAPH_KERNEL;
  77. const viaKernel = tryKernelExtract(filePath, source, 'swift');
  78. expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
  79. process.env.CODEGRAPH_KERNEL = '0';
  80. const viaWasm = extractFromSource(filePath, source, 'swift');
  81. delete process.env.CODEGRAPH_KERNEL;
  82. const k = canon(viaKernel!);
  83. const w = canon(viaWasm);
  84. expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes);
  85. expect(k.edges, `${filePath}: edges`).toEqual(w.edges);
  86. expect(k.refs, `${filePath}: refs`).toEqual(w.refs);
  87. expect(viaWasm.nodes.length).toBeGreaterThanOrEqual(minNodes);
  88. }
  89. it('torture fixture: property branch, extensions, call matrix, value refs, fn-refs', () => {
  90. const file = path.join(FIXTURE_DIR, 'torture.swift');
  91. assertParity('fixtures/torture.swift', fs.readFileSync(file, 'utf8'), 40);
  92. });
  93. // CRLF variant — the shape every Windows autocrlf checkout has. Derived in
  94. // memory so no platform or editor can silently normalize it away; pins the
  95. // JS-multiline-^ docstring semantics for `///` runs (#1329).
  96. it('torture fixture CRLF parity', () => {
  97. const file = path.join(FIXTURE_DIR, 'torture.swift');
  98. const crlf = fs.readFileSync(file, 'utf8').replace(/(?<!\r)\n/g, '\r\n');
  99. assertParity('fixtures/torture.swift (crlf)', crlf, 40);
  100. });
  101. it('files with parse errors defer to the wasm extractor (recovery is encoding-dependent)', () => {
  102. // A NEW-only regression construct (`#if` between enum cases — the swift
  103. // checklist's grammar-bump delta 5) — errors on the 0.7.3 grammar.
  104. const broken = 'enum E {\n case a\n#if DEBUG\n case b\n#endif\n}\n';
  105. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  106. delete process.env.CODEGRAPH_KERNEL;
  107. expect(tryKernelExtract('src/Broken.swift', broken, 'swift')).toBeNull();
  108. process.env.CODEGRAPH_KERNEL = '0';
  109. const viaWasm = extractFromSource('src/Broken.swift', broken, 'swift');
  110. delete process.env.CODEGRAPH_KERNEL;
  111. expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
  112. });
  113. });