markers.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import type { CompileDiagnostic } from "../../src/index.js";
  2. // Dotty-style neg-test markers: one trailing `// error` per expected diagnostic
  3. // on that line (`// error // error` = two). Marker-free files must compile clean.
  4. const TRAILING_MARKERS = /(?:[ \t]*\/\/ error)+[ \t]*$/;
  5. const SINGLE_MARKER = /\/\/ error/g;
  6. /** Parse expected diagnostic counts per 1-based line from trailing markers. */
  7. export function parseExpectedErrors(source: string): Map<number, number> {
  8. const expected = new Map<number, number>();
  9. source.split(/\r?\n/).forEach((line, index) => {
  10. const match = TRAILING_MARKERS.exec(line);
  11. if (!match) return;
  12. const count = match[0].match(SINGLE_MARKER)?.length ?? 0;
  13. if (count > 0) expected.set(index + 1, count);
  14. });
  15. return expected;
  16. }
  17. /**
  18. * Strict bidirectional diff: every marker must be hit and every diagnostic must
  19. * be covered by a marker. Returns human-readable mismatches (empty = pass).
  20. */
  21. export function diffAgainstMarkers(
  22. expected: Map<number, number>,
  23. diagnostics: readonly CompileDiagnostic[],
  24. ): string[] {
  25. const actual = new Map<number, CompileDiagnostic[]>();
  26. for (const diagnostic of diagnostics) {
  27. const bucket = actual.get(diagnostic.line) ?? [];
  28. bucket.push(diagnostic);
  29. actual.set(diagnostic.line, bucket);
  30. }
  31. const lines = [...new Set([...expected.keys(), ...actual.keys()])].sort((a, b) => a - b);
  32. const failures: string[] = [];
  33. for (const line of lines) {
  34. const want = expected.get(line) ?? 0;
  35. const got = actual.get(line) ?? [];
  36. if (got.length === want) continue;
  37. const detail = got.length > 0 ? ` — ${got.map((d) => d.message).join(" | ")}` : "";
  38. failures.push(`line ${line}: expected ${want} error(s), got ${got.length}${detail}`);
  39. }
  40. return failures;
  41. }