eutaxy 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,14 @@
1
1
  import { E as canonicalJson, T as getPath, _ as defaultBounds, a as explore, c as CrashSignal, d as withoutNetwork, f as patchGlobals, g as toJson, i as proxiedSide, l as InjectedEffectError, m as settleOn, n as DifferentialStuck, r as compareSides, t as observeCore, u as installScriptedFetch, v as validateScenario } from "./src-BO7I3f-1.mjs";
2
2
  import { n as atLeastOncePerMessage$1 } from "./delivery-invariants-hmhwh_qD.mjs";
3
- import { a as emitRegressionTest, f as evaluate, g as describeVerdict, h as describeType, m as render, n as renderSpecs, o as aggregate, p as conforms, r as renderText, s as checkSpecModule, t as renderJson, u as shrinkRefutation } from "./src-DzpZxvQi.mjs";
4
- import { n as isSpec } from "./combinators-N4LmG4p4.mjs";
5
- import { createRequire } from "node:module";
3
+ import { _ as endpointNumber, a as renderText, b as describeVerdict, c as aggregate, f as shrinkRefutation, g as endpointBigInt, h as conforms, i as renderSpecs, l as checkSpecModule, m as evaluate, n as renderSpecReport, r as renderSpecReportJson, s as emitRegressionTest, t as renderJson, v as render, y as describeType } from "./src-BZtuuu_j.mjs";
4
+ import { n as isSpec } from "./combinators-CVjxodAJ.mjs";
5
+ import { createRequire, registerHooks } from "node:module";
6
6
  import { spawn } from "node:child_process";
7
7
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
8
8
  import { basename, dirname, join, relative, resolve } from "node:path";
9
9
  import { homedir, tmpdir } from "node:os";
10
10
  import { pathToFileURL } from "node:url";
11
+ import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
11
12
  // packages/cli/src/args.ts
12
13
  function parseArgs(argv, booleans = []) {
13
14
  const positionals = [];
@@ -334,6 +335,21 @@ function skipAngles(tokens, i) {
334
335
  }
335
336
  return tokens.length;
336
337
  }
338
+ /**
339
+ * The tokens inside the list opened at `i` and closed before `end`. A
340
+ * closing `>>` also closes lists inside this one: the inner ones keep
341
+ * their `>`s, so `Array<Array<number>>` reads as it is written.
342
+ */
343
+ function anglesInner(tokens, i, end) {
344
+ const inner = tokens.slice(i + 1, end - 1);
345
+ const close = tokens[end - 1];
346
+ if (close?.kind === "punct" && /^>{2,}$/.test(close.text)) inner.push({
347
+ ...close,
348
+ text: close.text.slice(1),
349
+ end: close.end - 1
350
+ });
351
+ return inner;
352
+ }
337
353
  /** Type parameter names of the list opened at `i` (`<T, E extends X = Y>`), and the index past it. */
338
354
  function typeParams(tokens, i) {
339
355
  const names = [];
@@ -356,8 +372,36 @@ function typeParams(tokens, i) {
356
372
  end
357
373
  };
358
374
  }
375
+ /** Keywords after which an expression continues on the next line. */
376
+ const continuing = new Set("new extends typeof await yield void delete in of instanceof".split(" "));
359
377
  const declarationStarts$1 = new Set("export import function interface type const let var class enum declare async abstract namespace module".split(" "));
360
378
  /**
379
+ * The local names one `import` statement binds, from the token after
380
+ * `import`: `{ a, type B, c as D }`, a default, `* as ns` and
381
+ * `x = require(…)`. An import for its effects, `import(…)` and
382
+ * `import.meta` bind none.
383
+ */
384
+ function importBindings(tokens, from) {
385
+ const out = [];
386
+ let j = from;
387
+ if (isWord$1(tokens[j], "type") && !isPunct$1(tokens[j + 1], ",") && !isWord$1(tokens[j + 1], "from")) j++;
388
+ const first = tokens[j];
389
+ if (!first || first.kind === "string" || isPunct$1(first, "(") || isPunct$1(first, ".")) return out;
390
+ for (; j < tokens.length; j++) {
391
+ const t = tokens[j];
392
+ if (isWord$1(t, "from") || t.kind === "string" || isPunct$1(t, ";") || isPunct$1(t, "=")) break;
393
+ if (isPunct$1(t, "{")) {
394
+ const end = skipGroup$2(tokens, j);
395
+ for (const spec of splitTopLevel$1(tokens.slice(j + 1, end - 1), ",")) {
396
+ const last = spec[spec.length - 1];
397
+ if (last?.kind === "ident") out.push(last.text);
398
+ }
399
+ j = end - 1;
400
+ } else if (t.kind === "ident" && t.text !== "as") out.push(t.text);
401
+ }
402
+ return out;
403
+ }
404
+ /**
361
405
  * The module's top-level type declarations. An alias runs to its `;`, or
362
406
  * to the next declaration keyword on a later line (automatic semicolon
363
407
  * insertion); groups are skipped whole.
@@ -365,12 +409,45 @@ const declarationStarts$1 = new Set("export import function interface type const
365
409
  function typeDeclarations(tokens, lineOf) {
366
410
  const out = /* @__PURE__ */ new Map();
367
411
  let i = 0;
412
+ const startsStatement = (k) => {
413
+ const before = tokens[k - 1];
414
+ if (before === void 0 || isPunct$1(before, ";") || isPunct$1(before, "}")) return true;
415
+ if ((before.kind === "punct" ? /^(\)|\]|>+|\+\+|--)$/.test(before.text) : !continuing.has(before.text)) && lineOf(before.end) < lineOf(tokens[k].start)) return true;
416
+ return [
417
+ "export",
418
+ "default",
419
+ "declare",
420
+ "abstract",
421
+ "const"
422
+ ].includes(before.text) && startsStatement(k - 1);
423
+ };
368
424
  while (i < tokens.length) {
369
425
  const t = tokens[i];
370
426
  if (t.kind === "punct" && opens$1.has(t.text)) {
371
427
  i = skipGroup$2(tokens, i);
372
428
  continue;
373
429
  }
430
+ if (isWord$1(t, "import") && startsStatement(i)) {
431
+ for (const name of importBindings(tokens, i + 1)) out.set(name, {
432
+ name,
433
+ params: [],
434
+ tokens: [],
435
+ unsupported: "imported from another module"
436
+ });
437
+ i++;
438
+ continue;
439
+ }
440
+ if ((isWord$1(t, "class") || isWord$1(t, "enum")) && tokens[i + 1]?.kind === "ident" && startsStatement(i)) {
441
+ const name = tokens[i + 1].text;
442
+ if (!out.has(name)) out.set(name, {
443
+ name,
444
+ params: [],
445
+ tokens: [],
446
+ unsupported: `a ${t.text}`
447
+ });
448
+ i += 2;
449
+ continue;
450
+ }
374
451
  if (t.kind !== "ident" || t.text !== "interface" && t.text !== "type") {
375
452
  i++;
376
453
  continue;
@@ -437,6 +514,31 @@ function typeDeclarations(tokens, lineOf) {
437
514
  });
438
515
  i = end;
439
516
  }
517
+ for (const name of ["Array", "ReadonlyArray"]) {
518
+ if (out.has(name)) continue;
519
+ if (tokens.some((t, k) => {
520
+ if (t.text !== name) return false;
521
+ if (isWord$1(tokens[k + 1], "as")) return false;
522
+ if ([
523
+ "class",
524
+ "enum",
525
+ "interface",
526
+ "type",
527
+ "namespace"
528
+ ].includes(tokens[k - 1]?.text ?? "")) return true;
529
+ for (let j = k - 1; j >= 0; j--) {
530
+ const u = tokens[j];
531
+ if (isWord$1(u, "import")) return !(isPunct$1(tokens[j + 1], ":") || isPunct$1(tokens[j + 1], "(") || isPunct$1(tokens[j + 1], "."));
532
+ if (isWord$1(u, "from") || u.kind === "string" || isPunct$1(u, ";")) return false;
533
+ }
534
+ return false;
535
+ })) out.set(name, {
536
+ name,
537
+ params: [],
538
+ tokens: [],
539
+ unsupported: "declared or imported by the module"
540
+ });
541
+ }
440
542
  return out;
441
543
  }
442
544
  const unknown$2 = (text) => ({
@@ -520,11 +622,20 @@ var TypeReader = class {
520
622
  }
521
623
  return unknown$2(this.since(from));
522
624
  }
625
+ /** A primary type and its `[]` suffixes, each an array; `T[K]` (indexed access) is unknown. */
523
626
  postfix() {
524
627
  const from = this.at;
525
- const t = this.primary();
628
+ let t = this.primary();
526
629
  let indexed = false;
527
630
  while (isPunct$1(this.peek(), "[")) {
631
+ if (isPunct$1(this.peek(1), "]")) {
632
+ this.at += 2;
633
+ t = {
634
+ kind: "array",
635
+ element: t
636
+ };
637
+ continue;
638
+ }
528
639
  indexed = true;
529
640
  this.at = skipGroup$2(this.tokens, this.at);
530
641
  }
@@ -589,9 +700,10 @@ var TypeReader = class {
589
700
  kind: "literal",
590
701
  value: t.text === "true"
591
702
  };
592
- case "readonly":
593
- this.postfix();
594
- return unknown$2(this.since(from));
703
+ case "readonly": {
704
+ const t = this.postfix();
705
+ return t.kind === "array" ? t : unknown$2(this.since(from));
706
+ }
595
707
  case "typeof":
596
708
  case "keyof":
597
709
  this.postfix();
@@ -607,11 +719,15 @@ var TypeReader = class {
607
719
  const args = [];
608
720
  if (isPunct$1(this.peek(), "<")) {
609
721
  const end = skipAngles(this.tokens, this.at);
610
- const inner = this.tokens.slice(this.at + 1, end - 1);
722
+ const inner = anglesInner(this.tokens, this.at, end);
611
723
  for (const group of splitTopLevel$1(inner, ",")) args.push(readType(group, this.env));
612
724
  this.at = end;
613
725
  }
614
726
  const decl = this.env.declarations.get(t.text);
727
+ if (!decl && (t.text === "Array" || t.text === "ReadonlyArray")) return args.length === 1 ? {
728
+ kind: "array",
729
+ element: args[0]
730
+ } : unknown$2(this.since(from));
615
731
  if (!decl) return unknown$2(this.since(from));
616
732
  if (decl.unsupported) return unknown$2(this.since(from));
617
733
  if (this.env.expanding.has(t.text)) return unknown$2(this.since(from));
@@ -707,7 +823,13 @@ function splitMembers(tokens) {
707
823
  /** Whether `t` starts a new member after `current` (a member is `name: type`; a type never ends in a keyword or name followed by a name on a later line). */
708
824
  function isNameStart(current, t) {
709
825
  const last = current[current.length - 1];
710
- if (last.kind === "punct") return false;
826
+ if (last.kind === "punct" && !/^(\]|\)|\}|>+)$/.test(last.text)) return false;
827
+ if ([
828
+ "readonly",
829
+ "keyof",
830
+ "typeof",
831
+ "unique"
832
+ ].includes(last.text)) return false;
711
833
  return (t.kind === "ident" ? t : void 0) !== void 0 && last.end < t.start;
712
834
  }
713
835
  // packages/prover/src/reader/specs.ts
@@ -1380,6 +1502,7 @@ function readSpecSide(source, moduleSpecifiers, specSpecifiers) {
1380
1502
  if (!isPunct(tokens[j], "{")) fail("forall's second argument must be an object literal { when, ensures }", tokens[j]);
1381
1503
  const objectEnd = skipGroup$1(tokens, j);
1382
1504
  j++;
1505
+ let sample;
1383
1506
  let when;
1384
1507
  let ensures;
1385
1508
  while (j < objectEnd - 1) {
@@ -1388,10 +1511,13 @@ function readSpecSide(source, moduleSpecifiers, specSpecifiers) {
1388
1511
  j++;
1389
1512
  continue;
1390
1513
  }
1391
- if (key.kind !== "ident" || key.text !== "when" && key.text !== "ensures") fail(`forall's properties are when and ensures, found ${key.text}`, key);
1514
+ if (key.kind !== "ident" || key.text !== "sample" && key.text !== "when" && key.text !== "ensures") fail(`forall's properties are sample, when and ensures, found ${key.text}`, key);
1392
1515
  if (!isPunct(tokens[j + 1], ":")) fail(`${key.text} must be written as ${key.text}: (…) => …`, key);
1393
1516
  const read = arrow(j + 2, key.text);
1394
- if (key.text === "when") {
1517
+ if (key.text === "sample") {
1518
+ if (sample) fail("sample is given twice", key);
1519
+ sample = read.arrow;
1520
+ } else if (key.text === "when") {
1395
1521
  if (when) fail("when is given twice", key);
1396
1522
  when = read.arrow;
1397
1523
  } else {
@@ -1407,6 +1533,7 @@ function readSpecSide(source, moduleSpecifiers, specSpecifiers) {
1407
1533
  name: name.text,
1408
1534
  kind: "forall",
1409
1535
  fn: arg.fn,
1536
+ ...sample ? { sample } : {},
1410
1537
  ...when ? { when } : {},
1411
1538
  ensures,
1412
1539
  text: ensures.body.replace(/\s+/g, " ").trim(),
@@ -1431,6 +1558,47 @@ function readSpecSide(source, moduleSpecifiers, specSpecifiers) {
1431
1558
  }))
1432
1559
  };
1433
1560
  }
1561
+ /** The tighter of two endpoints on one side; the first when they cannot be compared. */
1562
+ function tighter(first, second, side) {
1563
+ if (!first) return second;
1564
+ if (!second) return first;
1565
+ const integral = (e) => !/[.eE]/.test(e.value);
1566
+ let order;
1567
+ try {
1568
+ if (integral(first) && integral(second)) {
1569
+ const a = endpointBigInt(first.value);
1570
+ const b = endpointBigInt(second.value);
1571
+ order = a === b ? 0 : a > b ? 1 : -1;
1572
+ } else {
1573
+ const a = endpointNumber(first.value);
1574
+ const b = endpointNumber(second.value);
1575
+ if (Number.isNaN(a) || Number.isNaN(b)) return first;
1576
+ order = a === b ? 0 : a > b ? 1 : -1;
1577
+ }
1578
+ } catch {
1579
+ return first;
1580
+ }
1581
+ if (order !== 0) return (side === "lower" ? order > 0 : order < 0) ? first : second;
1582
+ return first.inclusive ? second : first;
1583
+ }
1584
+ /**
1585
+ * Two hints on one binder as one: integer when either says so, the
1586
+ * tighter bound on each side, the first's regex (two cannot be combined,
1587
+ * and the draws are checked against both arrows anyway).
1588
+ */
1589
+ function combineHints(first, second) {
1590
+ if (!first) return second;
1591
+ if (!second) return first;
1592
+ const lower = tighter(first.lower, second.lower, "lower");
1593
+ const upper = tighter(first.upper, second.upper, "upper");
1594
+ const regex = first.regex ?? second.regex;
1595
+ return {
1596
+ ...first.integer || second.integer ? { integer: true } : {},
1597
+ ...lower ? { lower } : {},
1598
+ ...upper ? { upper } : {},
1599
+ ...regex ? { regex } : {}
1600
+ };
1601
+ }
1434
1602
  /** Read a module and its spec file. */
1435
1603
  function readSpecs(input) {
1436
1604
  const moduleSide = readModuleSide(input.module);
@@ -1465,7 +1633,13 @@ function readSpecs(input) {
1465
1633
  });
1466
1634
  continue;
1467
1635
  }
1468
- const hints = s.when ? hintsOf(s.when) : /* @__PURE__ */ new Map();
1636
+ const fromSample = s.sample ? hintsOf(s.sample) : /* @__PURE__ */ new Map();
1637
+ const fromWhen = s.when ? hintsOf(s.when) : /* @__PURE__ */ new Map();
1638
+ const hints = /* @__PURE__ */ new Map();
1639
+ for (const i of /* @__PURE__ */ new Set([...fromSample.keys(), ...fromWhen.keys()])) {
1640
+ const h = combineHints(fromWhen.get(i), fromSample.get(i));
1641
+ if (h) hints.set(i, h);
1642
+ }
1469
1643
  const binders = decl.params.map((p, i) => {
1470
1644
  const name = s.ensures?.params[i] ?? p.name ?? `arg${i}`;
1471
1645
  const hint = hints.get(i);
@@ -1479,6 +1653,7 @@ function readSpecs(input) {
1479
1653
  name: s.name,
1480
1654
  kind: s.kind,
1481
1655
  binders,
1656
+ ...s.sample ? { sample: s.sample } : {},
1482
1657
  ...s.when ? { when: s.when } : {},
1483
1658
  ...s.ensures ? { ensures: s.ensures } : {},
1484
1659
  imports,
@@ -1623,13 +1798,50 @@ function typeAnnotation(r, declared, bad = /* @__PURE__ */ new Map()) {
1623
1798
  const alternatives = [];
1624
1799
  if (r.isPunct("|")) r.at++;
1625
1800
  for (;;) {
1626
- alternatives.push(alternative(r, declared, bad));
1801
+ alternatives.push(listed(r, declared, bad));
1627
1802
  if (!r.isPunct("|")) break;
1628
1803
  r.at++;
1629
1804
  }
1630
- if (r.isPunct("[") || r.isPunct("<") || r.isPunct("&")) r.fail(`type …${r.peek()?.text}… (arrays, generics and intersections are outside the subset)`);
1805
+ if (r.isPunct("[") || r.isPunct("<") || r.isPunct("&")) r.fail(`type …${r.peek()?.text}… (generics, intersections and index access are outside the subset; an array is readonly T[] or T[])`);
1631
1806
  return classify(alternatives, r, first);
1632
1807
  }
1808
+ /**
1809
+ * One alternative with its `[]` suffixes, each a list of it, or
1810
+ * `readonly` before one that has them; a parenthesized type is one
1811
+ * alternative. Only a type is listed: `"a"[]` and `null[]` are not read.
1812
+ */
1813
+ function listed(r, declared, bad) {
1814
+ const start = r.peek();
1815
+ const readonly = r.isWord("readonly");
1816
+ if (readonly) r.at++;
1817
+ let a;
1818
+ if (r.isPunct("(")) {
1819
+ const open = r.take();
1820
+ a = {
1821
+ kind: "type",
1822
+ type: typeAnnotation(r, declared, bad),
1823
+ token: open
1824
+ };
1825
+ r.expectPunct(")");
1826
+ } else a = alternative(r, declared, bad);
1827
+ let lists = 0;
1828
+ while (r.isPunct("[") && r.isPunct("]", 1)) {
1829
+ if (a.kind !== "type") r.fail("an array of literals or null (declare its element type)", a.token);
1830
+ r.at += 2;
1831
+ a = {
1832
+ kind: "type",
1833
+ type: {
1834
+ kind: "list",
1835
+ element: a.type
1836
+ },
1837
+ token: a.token
1838
+ };
1839
+ lists++;
1840
+ }
1841
+ if (readonly && lists === 0) r.fail("readonly before a type that is not an array", start);
1842
+ if (a.kind === "type" && start && r.isPunct("[")) r.fail("index access in a type", r.peek());
1843
+ return a;
1844
+ }
1633
1845
  function alternative(r, declared, bad) {
1634
1846
  const t = r.take();
1635
1847
  if (t.kind === "string") return {
@@ -1679,6 +1891,7 @@ function alternative(r, declared, bad) {
1679
1891
  type: alias,
1680
1892
  token: t
1681
1893
  };
1894
+ if (t.text === "Array" || t.text === "ReadonlyArray") r.fail(`${t.text}<…> (the subset spells an array readonly T[] or T[])`, t);
1682
1895
  r.fail(`type ${t.text} (the subset has number, boolean, string, null, and the module's own record types, unions and aliases)`, t);
1683
1896
  }
1684
1897
  /**
@@ -2168,22 +2381,50 @@ var FunctionParser = class {
2168
2381
  if (r.isPunct(";")) r.at++;
2169
2382
  return value;
2170
2383
  }
2384
+ /** `xs[0]` just read, with `??` next: `expression` takes it if it is the whole left operand. */
2385
+ pendingIndex;
2171
2386
  expression(scope) {
2172
2387
  const r = this.r;
2173
- const left = this.binary(scope, 0);
2388
+ const start = r.at;
2389
+ let left = this.binary(scope, 0);
2390
+ if (r.isPunct("??")) {
2391
+ const pending = this.pendingIndex;
2392
+ if (!pending || pending.at !== r.at || left !== pending.list || !this.indexOnly(start)) r.fail("?? after anything but xs[0] (write xs[0] ?? fallback, parenthesized where it meets other operators)");
2393
+ this.pendingIndex = void 0;
2394
+ r.at++;
2395
+ left = {
2396
+ kind: "headOr",
2397
+ list: pending.list,
2398
+ fallback: this.binary(scope, 0)
2399
+ };
2400
+ if (r.isPunct("??")) r.fail("a chain of ??");
2401
+ }
2174
2402
  if (r.isPunct("?")) {
2175
2403
  r.at++;
2176
2404
  const then = this.expression(scope);
2177
2405
  r.expectPunct(":");
2406
+ const otherwise = this.expression(scope);
2178
2407
  return {
2179
2408
  kind: "cond",
2180
2409
  test: left,
2181
2410
  ifTrue: then,
2182
- ifFalse: this.expression(scope)
2411
+ ifFalse: otherwise
2183
2412
  };
2184
2413
  }
2185
2414
  return left;
2186
2415
  }
2416
+ /** Whether the tokens from `start` to here hold no operator outside brackets: an operand and its `[0]`. */
2417
+ indexOnly(start) {
2418
+ let depth = 0;
2419
+ for (let i = start; i < this.r.at; i++) {
2420
+ const t = this.r.tokens[i];
2421
+ if (t.kind !== "punct") continue;
2422
+ if (t.text === "(" || t.text === "[" || t.text === "{") depth++;
2423
+ else if (t.text === ")" || t.text === "]" || t.text === "}") depth--;
2424
+ else if (depth === 0 && t.text !== ".") return false;
2425
+ }
2426
+ return true;
2427
+ }
2187
2428
  binary(scope, level) {
2188
2429
  if (level >= levels.length) return this.unary(scope);
2189
2430
  let left = this.binary(scope, level + 1);
@@ -2197,7 +2438,6 @@ var FunctionParser = class {
2197
2438
  "/",
2198
2439
  "%",
2199
2440
  "**",
2200
- "??",
2201
2441
  "<<",
2202
2442
  ">>",
2203
2443
  "&",
@@ -2247,6 +2487,10 @@ var FunctionParser = class {
2247
2487
  if (r.isPunct(".")) {
2248
2488
  r.at++;
2249
2489
  const field = r.ident();
2490
+ if (r.isPunct("(")) {
2491
+ e = this.method(scope, e, field);
2492
+ continue;
2493
+ }
2250
2494
  e = {
2251
2495
  kind: "field",
2252
2496
  object: e,
@@ -2255,7 +2499,18 @@ var FunctionParser = class {
2255
2499
  continue;
2256
2500
  }
2257
2501
  if (r.isPunct("?.")) r.fail("optional chaining");
2258
- if (r.isPunct("[")) r.fail("index access");
2502
+ if (r.isPunct("[")) {
2503
+ const open = r.take();
2504
+ const index = r.take();
2505
+ if (index.kind !== "number" || index.text !== "0" || !r.isPunct("]")) r.fail("index access other than xs[0] ?? fallback", open);
2506
+ r.at++;
2507
+ if (!r.isPunct("??")) r.fail("xs[0] without ?? fallback (it is undefined on an empty list)", open);
2508
+ this.pendingIndex = {
2509
+ list: e,
2510
+ at: r.at
2511
+ };
2512
+ return e;
2513
+ }
2259
2514
  if (r.isPunct("(")) {
2260
2515
  if (e.kind === "var" && scope.has(e.name)) r.fail(`a call to ${e.name}, which names a value here, not the module's function`);
2261
2516
  if (e.kind !== "var" || !this.functions.has(e.name)) r.fail(e.kind !== "var" ? "a call to a computed callee" : this.declared.has(e.name) ? `a call to ${e.name}, which is outside the subset` : this.aliases ? `a call to ${e.name}, which is not a function imported from the module beside the spec file` : `a call to ${e.name}, which this module does not declare`);
@@ -2326,12 +2581,98 @@ var FunctionParser = class {
2326
2581
  return e;
2327
2582
  }
2328
2583
  if (t.text === "{") return this.record(scope);
2329
- if (t.text === "[") r.fail("an array literal", t);
2584
+ if (t.text === "[") return this.listLiteral(scope);
2330
2585
  r.fail(`unexpected ${t.text}`, t);
2331
2586
  break;
2332
2587
  default: r.fail(`unexpected ${t.text}`, t);
2333
2588
  }
2334
2589
  }
2590
+ /** `[a, b]` or `[a, b, ...rest]`, the `[` taken. */
2591
+ listLiteral(scope) {
2592
+ const r = this.r;
2593
+ const items = [];
2594
+ let rest;
2595
+ while (!r.isPunct("]")) {
2596
+ if (rest) r.fail("a spread that is not last in an array literal");
2597
+ if (r.isPunct("...")) {
2598
+ r.at++;
2599
+ rest = this.expression(scope);
2600
+ } else items.push(this.expression(scope));
2601
+ if (r.isPunct(",")) r.at++;
2602
+ else if (!r.isPunct("]")) r.fail(`unexpected ${r.peek()?.text} in an array literal`);
2603
+ }
2604
+ r.at++;
2605
+ return {
2606
+ kind: "list",
2607
+ items,
2608
+ ...rest ? { rest } : {}
2609
+ };
2610
+ }
2611
+ /** `(a, b) => body` or `a => body`, an expression body only; the names it binds go into scope. */
2612
+ callback(scope, arity, what) {
2613
+ const r = this.r;
2614
+ const names = [];
2615
+ if (r.isPunct("(")) {
2616
+ r.at++;
2617
+ while (!r.isPunct(")")) {
2618
+ names.push(r.ident());
2619
+ if (r.isPunct(":")) r.fail(`a type annotation on ${what}'s parameter`);
2620
+ if (r.isPunct(",")) r.at++;
2621
+ }
2622
+ r.at++;
2623
+ } else names.push(r.ident());
2624
+ if (names.length === 0 || names.length > arity) r.fail(`${what} takes a callback of 1 to ${arity} parameter(s), given ${names.length}`);
2625
+ for (const n of names) if (scope.has(n) || this.declared.has(n)) r.fail(`${what}'s parameter ${n} shadows a name already bound here`);
2626
+ if (new Set(names).size !== names.length) r.fail(`${what}'s parameters repeat a name`);
2627
+ r.expectPunct("=>");
2628
+ if (r.isPunct("{")) r.fail(`a block body in ${what}'s callback (write an expression)`);
2629
+ const inner = new Map(scope);
2630
+ for (const n of names) inner.set(n, { kind: "null" });
2631
+ return {
2632
+ names,
2633
+ body: this.expression(inner)
2634
+ };
2635
+ }
2636
+ /** A method call on a list: slice(1), map, flatMap, every, some, reduce; the `(` not yet taken. */
2637
+ method(scope, list, name) {
2638
+ const r = this.r;
2639
+ r.at++;
2640
+ let e;
2641
+ if (name === "slice") {
2642
+ const one = r.take();
2643
+ if (one.kind !== "number" || one.text !== "1") r.fail("slice with an argument other than 1", one);
2644
+ e = {
2645
+ kind: "tail",
2646
+ list
2647
+ };
2648
+ } else if (name === "map" || name === "flatMap" || name === "every" || name === "some") {
2649
+ const { names, body } = this.callback(scope, 2, name);
2650
+ e = {
2651
+ kind: "iterate",
2652
+ op: name,
2653
+ list,
2654
+ item: names[0],
2655
+ ...names[1] === void 0 ? {} : { index: names[1] },
2656
+ body
2657
+ };
2658
+ } else if (name === "reduce") {
2659
+ const { names, body } = this.callback(scope, 2, "reduce");
2660
+ if (names.length !== 2) r.fail("reduce takes a callback of (accumulator, item)");
2661
+ r.expectPunct(",");
2662
+ const init = this.expression(scope);
2663
+ e = {
2664
+ kind: "fold",
2665
+ list,
2666
+ acc: names[0],
2667
+ item: names[1],
2668
+ body,
2669
+ init
2670
+ };
2671
+ } else r.fail(`the method ${name} (the subset has slice(1), map, flatMap, every, some and reduce)`);
2672
+ if (r.isPunct(",")) r.at++;
2673
+ r.expectPunct(")");
2674
+ return e;
2675
+ }
2335
2676
  record(scope) {
2336
2677
  const r = this.r;
2337
2678
  const fields = [];
@@ -2376,6 +2717,7 @@ function describe(t) {
2376
2717
  case "record":
2377
2718
  case "union": return t.name;
2378
2719
  case "nullable": return `${describe(t.inner)} | null`;
2720
+ case "list": return t.element.kind === "nullable" ? `(${describe(t.element)})[]` : `${describe(t.element)}[]`;
2379
2721
  default: return t.kind;
2380
2722
  }
2381
2723
  }
@@ -2387,6 +2729,8 @@ const sameType = (a, b) => JSON.stringify(a) === JSON.stringify(b);
2387
2729
  */
2388
2730
  function fits(actual, expected, ctx) {
2389
2731
  if (sameType(actual, expected)) return true;
2732
+ if (actual.kind === "nothing") return true;
2733
+ if (actual.kind === "list" && expected.kind === "list") return fits(actual.element, expected.element, ctx);
2390
2734
  if (expected.kind === "union") return actual.kind === "record" && ctx.records.get(actual.name)?.union === expected.name;
2391
2735
  if (expected.kind === "nullable") return actual.kind === "null" || (actual.kind === "nullable" ? fits(actual.inner, expected.inner, ctx) : fits(actual, expected.inner, ctx));
2392
2736
  return false;
@@ -2395,6 +2739,13 @@ function fits(actual, expected, ctx) {
2395
2739
  function join$1(a, b, ctx) {
2396
2740
  if (fits(a, b, ctx)) return b;
2397
2741
  if (fits(b, a, ctx)) return a;
2742
+ if (a.kind === "list" && b.kind === "list") {
2743
+ const element = join$1(a.element, b.element, ctx);
2744
+ return element && {
2745
+ kind: "list",
2746
+ element
2747
+ };
2748
+ }
2398
2749
  if (a.kind === "record" && b.kind === "record") {
2399
2750
  const ua = ctx.records.get(a.name)?.union;
2400
2751
  if (ua !== void 0 && ua === ctx.records.get(b.name)?.union) return {
@@ -2433,7 +2784,7 @@ function comparable(l, r) {
2433
2784
  if (r.kind === "null") return l.kind === "nullable";
2434
2785
  return sameType(base(l), base(r)) && !isReference(base(l));
2435
2786
  }
2436
- const isReference = (t) => t.kind === "record" || t.kind === "union";
2787
+ const isReference = (t) => t.kind === "record" || t.kind === "union" || t.kind === "list";
2437
2788
  /**
2438
2789
  * The names a test, holding or failing, shows to be non-null: `x !== null`
2439
2790
  * holding, `x === null` failing, through `!`, `&&` (holding) and `||`
@@ -2541,8 +2892,94 @@ function insertNarrows(e, scope, ctx, fail) {
2541
2892
  body: go(e.body, inner)
2542
2893
  };
2543
2894
  }
2895
+ case "list": return {
2896
+ kind: "list",
2897
+ items: e.items.map((x) => go(x, scope)),
2898
+ ...e.rest ? { rest: go(e.rest, scope) } : {}
2899
+ };
2900
+ case "tail": return {
2901
+ kind: "tail",
2902
+ list: go(e.list, scope)
2903
+ };
2904
+ case "headOr": return {
2905
+ kind: "headOr",
2906
+ list: go(e.list, scope),
2907
+ fallback: go(e.fallback, scope)
2908
+ };
2909
+ case "iterate": {
2910
+ const list = go(e.list, scope);
2911
+ return {
2912
+ ...e,
2913
+ list,
2914
+ body: go(e.body, iterateScope(e, list, scope, ctx, fail))
2915
+ };
2916
+ }
2917
+ case "fold": {
2918
+ const list = go(e.list, scope);
2919
+ const init = go(e.init, scope);
2920
+ const inner = new Map(scope);
2921
+ inner.set(e.acc, typeOf(init, scope, ctx, fail));
2922
+ inner.set(e.item, elementOf(typeOf(list, scope, ctx, fail), "reduce", fail));
2923
+ return {
2924
+ ...e,
2925
+ list,
2926
+ init,
2927
+ body: go(e.body, inner)
2928
+ };
2929
+ }
2544
2930
  }
2545
2931
  }
2932
+ /**
2933
+ * The element type of a list expression's type. An operation on an empty
2934
+ * array no type is given for (`[].length`, `[].slice(1)`) is refused: an
2935
+ * engine could only guess the element type, and such code has a plain
2936
+ * value to write instead; `const xs: T[] = []` gives one.
2937
+ */
2938
+ function elementOf(t, what, fail) {
2939
+ if (t.kind !== "list") fail(`${what} on a ${describe(t)}, not a list`);
2940
+ if (holdsNothing(t)) fail(`${what} on an empty array of no declared type (annotate it: const xs: T[] = [])`);
2941
+ return t.element;
2942
+ }
2943
+ /** Whether a type holds the element type of an empty array literal anywhere in it (`[[]]` does). */
2944
+ function holdsNothing(t) {
2945
+ if (t.kind === "nothing") return true;
2946
+ if (t.kind === "list") return holdsNothing(t.element);
2947
+ if (t.kind === "nullable") return holdsNothing(t.inner);
2948
+ return false;
2949
+ }
2950
+ /** The scope inside an iteration's callback: the item an element, the index an integer. */
2951
+ function iterateScope(e, list, scope, ctx, fail) {
2952
+ const inner = new Map(scope);
2953
+ inner.set(e.item, elementOf(typeOf(list, scope, ctx, fail), e.op, fail));
2954
+ if (e.index !== void 0) inner.set(e.index, { kind: "int" });
2955
+ return inner;
2956
+ }
2957
+ /**
2958
+ * The scope inside a fold's callback and the accumulator's type: the
2959
+ * initial value's, widened once to the body's when the body's holds it.
2960
+ * A callback that takes the accumulator apart as a list needs the initial
2961
+ * value typed (`xs.reduce((acc, x) => [x, ...acc], [])` does not
2962
+ * type-check in TypeScript either).
2963
+ */
2964
+ function foldScope(e, list, init, scope, ctx, fail) {
2965
+ const item = elementOf(typeOf(list, scope, ctx, fail), "reduce", fail);
2966
+ const at = (acc) => new Map([
2967
+ ...scope,
2968
+ [e.acc, acc],
2969
+ [e.item, item]
2970
+ ]);
2971
+ const start = typeOf(init, scope, ctx, fail);
2972
+ const body = typeOf(e.body, at(start), ctx, fail);
2973
+ if (fits(body, start, ctx)) return {
2974
+ scope: at(start),
2975
+ acc: start
2976
+ };
2977
+ if (fits(start, body, ctx) && fits(typeOf(e.body, at(body), ctx, fail), body, ctx)) return {
2978
+ scope: at(body),
2979
+ acc: body
2980
+ };
2981
+ fail(`reduce's callback makes a ${describe(body)} from an accumulator of ${describe(start)}`);
2982
+ }
2546
2983
  /** The type of an expression in a scope; records are matched by their fields' names. */
2547
2984
  function typeOf(e, scope, ctx, fail) {
2548
2985
  switch (e.kind) {
@@ -2614,6 +3051,7 @@ function typeOf(e, scope, ctx, fail) {
2614
3051
  case "let": {
2615
3052
  const inferred = typeOf(e.value, scope, ctx, fail);
2616
3053
  if (e.type && !fits(inferred, e.type, ctx)) fail(`const ${e.name} is annotated ${describe(e.type)} but holds a ${describe(inferred)}`);
3054
+ if (!e.type && holdsNothing(inferred)) fail(`const ${e.name} holds an empty array of no declared type (annotate it: const ${e.name}: T[] = [])`);
2617
3055
  return typeOf(e.body, new Map([...scope, [e.name, e.type ?? inferred]]), ctx, fail);
2618
3056
  }
2619
3057
  case "call": {
@@ -2629,6 +3067,11 @@ function typeOf(e, scope, ctx, fail) {
2629
3067
  }
2630
3068
  case "field": {
2631
3069
  const o = typeOf(e.object, scope, ctx, fail);
3070
+ if (o.kind === "list") {
3071
+ if (e.field !== "length") fail(`${e.field} read from a list (the subset has length)`);
3072
+ elementOf(o, "length", fail);
3073
+ return { kind: "int" };
3074
+ }
2632
3075
  if (o.kind === "nullable") fail(`field ${e.field} read from a ${describe(o)}: compare it with null first, which narrows it`);
2633
3076
  if (o.kind === "union") {
2634
3077
  const types = [...ctx.records.values()].filter((rec) => rec.union === o.name).map((rec) => rec.fields.find((x) => x.name === e.field)?.type);
@@ -2665,6 +3108,47 @@ function typeOf(e, scope, ctx, fail) {
2665
3108
  name: chosen[0].name
2666
3109
  };
2667
3110
  }
3111
+ case "list": {
3112
+ let element = { kind: "nothing" };
3113
+ const add = (t) => {
3114
+ const joined = join$1(element, t, ctx);
3115
+ if (!joined) fail(`an array literal of a ${describe(element)} and a ${describe(t)}`);
3116
+ element = joined;
3117
+ };
3118
+ for (const item of e.items) add(typeOf(item, scope, ctx, fail));
3119
+ if (e.rest) add(elementOf(typeOf(e.rest, scope, ctx, fail), "a spread", fail));
3120
+ return {
3121
+ kind: "list",
3122
+ element
3123
+ };
3124
+ }
3125
+ case "tail": {
3126
+ const t = typeOf(e.list, scope, ctx, fail);
3127
+ elementOf(t, "slice", fail);
3128
+ return t;
3129
+ }
3130
+ case "headOr": {
3131
+ const element = elementOf(typeOf(e.list, scope, ctx, fail), "[0]", fail);
3132
+ if (element.kind === "nullable" || element.kind === "null") fail("xs[0] ?? on a list of a nullable type (?? replaces a null element too)");
3133
+ const fallback = typeOf(e.fallback, scope, ctx, fail);
3134
+ const joined = join$1(element, fallback, ctx);
3135
+ if (!joined) fail(`?? between a ${describe(element)} and a ${describe(fallback)}`);
3136
+ return joined;
3137
+ }
3138
+ case "iterate": {
3139
+ const body = typeOf(e.body, iterateScope(e, e.list, scope, ctx, fail), ctx, fail);
3140
+ if (e.op === "map") return {
3141
+ kind: "list",
3142
+ element: body
3143
+ };
3144
+ if (e.op === "flatMap") return {
3145
+ kind: "list",
3146
+ element: elementOf(body, "flatMap's callback result", fail)
3147
+ };
3148
+ if (body.kind !== "bool") fail(`${e.op}'s callback returns a ${describe(body)}, not a boolean`);
3149
+ return { kind: "bool" };
3150
+ }
3151
+ case "fold": return foldScope(e, e.list, e.init, scope, ctx, fail).acc;
2668
3152
  }
2669
3153
  }
2670
3154
  /**
@@ -2761,6 +3245,24 @@ function boundNames(e, out = /* @__PURE__ */ new Set()) {
2761
3245
  out.add(e.name);
2762
3246
  boundNames(e.value, out);
2763
3247
  return boundNames(e.body, out);
3248
+ case "list":
3249
+ for (const x of e.items) boundNames(x, out);
3250
+ return e.rest ? boundNames(e.rest, out) : out;
3251
+ case "tail": return boundNames(e.list, out);
3252
+ case "headOr":
3253
+ boundNames(e.list, out);
3254
+ return boundNames(e.fallback, out);
3255
+ case "iterate":
3256
+ out.add(e.item);
3257
+ if (e.index !== void 0) out.add(e.index);
3258
+ boundNames(e.list, out);
3259
+ return boundNames(e.body, out);
3260
+ case "fold":
3261
+ out.add(e.acc);
3262
+ out.add(e.item);
3263
+ boundNames(e.list, out);
3264
+ boundNames(e.init, out);
3265
+ return boundNames(e.body, out);
2764
3266
  }
2765
3267
  }
2766
3268
  /** A name not among `taken`: the name with underscores appended. */
@@ -2845,8 +3347,65 @@ function renameVars(e, names, taken = /* @__PURE__ */ new Set([
2845
3347
  body: renameVars(e.body, inner, /* @__PURE__ */ new Set([...taken, bound]))
2846
3348
  };
2847
3349
  }
3350
+ case "list": return {
3351
+ kind: "list",
3352
+ items: e.items.map(go),
3353
+ ...e.rest ? { rest: go(e.rest) } : {}
3354
+ };
3355
+ case "tail": return {
3356
+ kind: "tail",
3357
+ list: go(e.list)
3358
+ };
3359
+ case "headOr": return {
3360
+ kind: "headOr",
3361
+ list: go(e.list),
3362
+ fallback: go(e.fallback)
3363
+ };
3364
+ case "iterate": {
3365
+ const { inner, bound, scoped } = bindAll([e.item, ...e.index === void 0 ? [] : [e.index]], names, taken);
3366
+ return {
3367
+ ...e,
3368
+ list: go(e.list),
3369
+ item: bound[0],
3370
+ ...e.index === void 0 ? {} : { index: bound[1] },
3371
+ body: renameVars(e.body, inner, scoped)
3372
+ };
3373
+ }
3374
+ case "fold": {
3375
+ const { inner, bound, scoped } = bindAll([e.acc, e.item], names, taken);
3376
+ return {
3377
+ ...e,
3378
+ list: go(e.list),
3379
+ init: go(e.init),
3380
+ acc: bound[0],
3381
+ item: bound[1],
3382
+ body: renameVars(e.body, inner, scoped)
3383
+ };
3384
+ }
2848
3385
  }
2849
3386
  }
3387
+ /**
3388
+ * The renames inside a callback that binds `own` names, as for a let:
3389
+ * each shadows a rename of its own name, and one that is a rename's target
3390
+ * moves to a fresh name so it captures nothing.
3391
+ */
3392
+ function bindAll(own, names, taken) {
3393
+ const inner = new Map(names);
3394
+ const targets = new Set(names.values());
3395
+ const scoped = new Set(taken);
3396
+ return {
3397
+ inner,
3398
+ bound: own.map((n) => {
3399
+ inner.delete(n);
3400
+ if (!targets.has(n)) return n;
3401
+ const moved = fresh(n, scoped);
3402
+ scoped.add(moved);
3403
+ inner.set(n, moved);
3404
+ return moved;
3405
+ }),
3406
+ scoped
3407
+ };
3408
+ }
2850
3409
  /** The functions an expression calls. */
2851
3410
  function callees(e, out = /* @__PURE__ */ new Set()) {
2852
3411
  switch (e.kind) {
@@ -2877,6 +3436,20 @@ function callees(e, out = /* @__PURE__ */ new Set()) {
2877
3436
  case "let":
2878
3437
  callees(e.value, out);
2879
3438
  return callees(e.body, out);
3439
+ case "list":
3440
+ for (const x of e.items) callees(x, out);
3441
+ return e.rest ? callees(e.rest, out) : out;
3442
+ case "tail": return callees(e.list, out);
3443
+ case "headOr":
3444
+ callees(e.list, out);
3445
+ return callees(e.fallback, out);
3446
+ case "iterate":
3447
+ callees(e.list, out);
3448
+ return callees(e.body, out);
3449
+ case "fold":
3450
+ callees(e.list, out);
3451
+ callees(e.init, out);
3452
+ return callees(e.body, out);
2880
3453
  }
2881
3454
  }
2882
3455
  /**
@@ -3080,11 +3653,19 @@ function readSubset(source, functions) {
3080
3653
  return false;
3081
3654
  };
3082
3655
  for (const [name, fn] of [...read]) if (reaches(name, name)) {
3656
+ const on = [...callees(fn.body)].every((c) => c === name || !reaches(c, name)) ? structuralOn(fn) : void 0;
3657
+ if (on !== void 0) {
3658
+ read.set(name, {
3659
+ ...fn,
3660
+ structural: on
3661
+ });
3662
+ continue;
3663
+ }
3083
3664
  read.delete(name);
3084
3665
  outside.set(name, {
3085
3666
  name,
3086
3667
  line: fn.line,
3087
- message: `${name} is recursive (it reaches itself through its calls); recursion is not in the subset yet`
3668
+ message: `${name} is recursive in a way the subset does not take: it takes a function calling itself on a list parameter's slice(1), after a first test of that list's length against 0 (if (xs.length === 0) return …)`
3088
3669
  });
3089
3670
  }
3090
3671
  for (let changed = true; changed;) {
@@ -3103,7 +3684,7 @@ function readSubset(source, functions) {
3103
3684
  }
3104
3685
  const ordered = [];
3105
3686
  const placed = /* @__PURE__ */ new Set();
3106
- while (ordered.length < read.size) for (const [name, fn] of read) if (!placed.has(name) && [...callees(fn.body)].every((c) => placed.has(c))) {
3687
+ while (ordered.length < read.size) for (const [name, fn] of read) if (!placed.has(name) && [...callees(fn.body)].every((c) => c === name || placed.has(c))) {
3107
3688
  ordered.push(fn);
3108
3689
  placed.add(name);
3109
3690
  }
@@ -3114,6 +3695,73 @@ function readSubset(source, functions) {
3114
3695
  outside: [...outside.values()]
3115
3696
  };
3116
3697
  }
3698
+ /**
3699
+ * The list parameter a function recurses on structurally, or undefined:
3700
+ * its body is `if (p.length === 0) … else …` for a list parameter p, the
3701
+ * test and the first branch do not call it, and every call to it in the
3702
+ * other branch passes `p.slice(1)` for p. Lean takes such a definition as
3703
+ * a match on `[]` and `head :: tail`, recursing on the tail.
3704
+ */
3705
+ function structuralOn(fn) {
3706
+ const body = fn.body;
3707
+ if (body.kind !== "cond") return void 0;
3708
+ const t = body.test;
3709
+ if (t.kind !== "binary" || t.op !== "===") return void 0;
3710
+ const sides = [t.left, t.right];
3711
+ const zero = sides.find((x) => x.kind === "int" && x.value === "0");
3712
+ const len = sides.find((x) => x !== zero);
3713
+ if (!zero || len?.kind !== "field" || len.field !== "length" || len.object.kind !== "var") return void 0;
3714
+ const list = len.object.name;
3715
+ const at = fn.params.findIndex((p) => p.name === list && p.type.kind === "list");
3716
+ if (at < 0) return void 0;
3717
+ if (callees(t).has(fn.name) || callees(body.ifTrue).has(fn.name)) return void 0;
3718
+ const calls = selfCalls(body.ifFalse, fn.name);
3719
+ const onTail = (a) => a?.kind === "tail" && a.list.kind === "var" && a.list.name === list;
3720
+ return calls.length > 0 && calls.every((c) => onTail(c.args[at])) ? at : void 0;
3721
+ }
3722
+ /** Every call to `name` in an expression. */
3723
+ function selfCalls(e, name) {
3724
+ const out = [];
3725
+ const walk = (x) => {
3726
+ if (x.kind === "call" && x.callee === name) out.push(x);
3727
+ for (const child of children(x)) walk(child);
3728
+ };
3729
+ walk(e);
3730
+ return out;
3731
+ }
3732
+ /** An expression's direct subexpressions. */
3733
+ function children(e) {
3734
+ switch (e.kind) {
3735
+ case "int":
3736
+ case "bool":
3737
+ case "string":
3738
+ case "null":
3739
+ case "var": return [];
3740
+ case "narrow": return [e.body];
3741
+ case "neg":
3742
+ case "not":
3743
+ case "isInteger": return [e.operand];
3744
+ case "binary": return [e.left, e.right];
3745
+ case "cond": return [
3746
+ e.test,
3747
+ e.ifTrue,
3748
+ e.ifFalse
3749
+ ];
3750
+ case "call": return [...e.args];
3751
+ case "field": return [e.object];
3752
+ case "record": return e.fields.map((f) => f.value);
3753
+ case "let": return [e.value, e.body];
3754
+ case "list": return [...e.items, ...e.rest ? [e.rest] : []];
3755
+ case "tail": return [e.list];
3756
+ case "headOr": return [e.list, e.fallback];
3757
+ case "iterate": return [e.list, e.body];
3758
+ case "fold": return [
3759
+ e.list,
3760
+ e.init,
3761
+ e.body
3762
+ ];
3763
+ }
3764
+ }
3117
3765
  /** Whether an expression holds a node of the kinds named. */
3118
3766
  function hasNode(e, kinds) {
3119
3767
  if (kinds.has(e.kind)) return true;
@@ -3133,6 +3781,11 @@ function hasNode(e, kinds) {
3133
3781
  case "field": return hasNode(e.object, kinds);
3134
3782
  case "record": return e.fields.some((f) => hasNode(f.value, kinds));
3135
3783
  case "let": return hasNode(e.value, kinds) || hasNode(e.body, kinds);
3784
+ case "list": return e.items.some((x) => hasNode(x, kinds)) || (e.rest ? hasNode(e.rest, kinds) : false);
3785
+ case "tail": return hasNode(e.list, kinds);
3786
+ case "headOr": return hasNode(e.list, kinds) || hasNode(e.fallback, kinds);
3787
+ case "iterate": return hasNode(e.list, kinds) || hasNode(e.body, kinds);
3788
+ case "fold": return hasNode(e.list, kinds) || hasNode(e.init, kinds) || hasNode(e.body, kinds);
3136
3789
  }
3137
3790
  }
3138
3791
  /**
@@ -3142,18 +3795,37 @@ function hasNode(e, kinds) {
3142
3795
  * types bring (`null`, narrowing), or which call such a function; each is
3143
3796
  * reported outside with `reason`.
3144
3797
  */
3145
- function restrictModule(module, takes, reason) {
3798
+ function restrictModule(module, takes, reason, bodies = /* @__PURE__ */ new Set(["null", "narrow"])) {
3146
3799
  const badRecords = /* @__PURE__ */ new Set();
3800
+ for (const u of module.unions) if (!takes({
3801
+ kind: "union",
3802
+ name: u.name
3803
+ })) badRecords.add(`union:${u.name}`);
3147
3804
  for (let changed = true; changed;) {
3148
3805
  changed = false;
3149
3806
  for (const rec of module.records) if (!badRecords.has(rec.name) && rec.fields.some((f) => !typeTaken(f.type, takes, badRecords))) {
3150
3807
  badRecords.add(rec.name);
3151
3808
  changed = true;
3152
3809
  }
3810
+ for (const u of module.unions) {
3811
+ if (!badRecords.has(`union:${u.name}`) && u.members.some((m) => badRecords.has(m.record))) {
3812
+ badRecords.add(`union:${u.name}`);
3813
+ changed = true;
3814
+ }
3815
+ if (takes({
3816
+ kind: "union",
3817
+ name: u.name
3818
+ }) && badRecords.has(`union:${u.name}`)) {
3819
+ for (const m of u.members) if (!badRecords.has(m.record)) {
3820
+ badRecords.add(m.record);
3821
+ changed = true;
3822
+ }
3823
+ }
3824
+ }
3153
3825
  }
3154
3826
  const outside = new Map(module.outside.map((o) => [o.name, o]));
3155
3827
  const kept = new Map(module.functions.map((f) => [f.name, f]));
3156
- const uses = (f) => !f.params.every((p) => typeTaken(p.type, takes, badRecords)) || !typeTaken(f.returns, takes, badRecords) || hasNode(f.body, /* @__PURE__ */ new Set(["null", "narrow"]));
3828
+ const uses = (f) => !f.params.every((p) => typeTaken(p.type, takes, badRecords)) || !typeTaken(f.returns, takes, badRecords) || annotations(f.body).some((t) => !typeTaken(t, takes, badRecords)) || hasNode(f.body, bodies);
3157
3829
  for (const f of module.functions) if (uses(f)) {
3158
3830
  kept.delete(f.name);
3159
3831
  outside.set(f.name, {
@@ -3178,10 +3850,7 @@ function restrictModule(module, takes, reason) {
3178
3850
  }
3179
3851
  return {
3180
3852
  records: module.records.filter((r) => !badRecords.has(r.name)),
3181
- unions: module.unions.filter((u) => takes({
3182
- kind: "union",
3183
- name: u.name
3184
- })),
3853
+ unions: module.unions.filter((u) => !badRecords.has(`union:${u.name}`)),
3185
3854
  functions: module.functions.filter((f) => kept.has(f.name)),
3186
3855
  outside: [...outside.values()]
3187
3856
  };
@@ -3189,9 +3858,27 @@ function restrictModule(module, takes, reason) {
3189
3858
  function typeTaken(t, takes, badRecords) {
3190
3859
  if (!takes(t)) return false;
3191
3860
  if (t.kind === "record") return !badRecords.has(t.name);
3861
+ if (t.kind === "union") return !badRecords.has(`union:${t.name}`);
3192
3862
  if (t.kind === "nullable") return typeTaken(t.inner, takes, badRecords);
3863
+ if (t.kind === "list") return typeTaken(t.element, takes, badRecords);
3193
3864
  return true;
3194
3865
  }
3866
+ /** The types a body's `const` annotations name. */
3867
+ function annotations(e, out = []) {
3868
+ if (e.kind === "let" && e.type) out.push(e.type);
3869
+ for (const c of children(e)) annotations(c, out);
3870
+ return out;
3871
+ }
3872
+ /** The expression kinds only lists bring, for an engine that does not take them. */
3873
+ const listKinds = /* @__PURE__ */ new Set([
3874
+ "list",
3875
+ "tail",
3876
+ "headOr",
3877
+ "iterate",
3878
+ "fold"
3879
+ ]);
3880
+ /** Whether an expression is one only lists bring (a type guard over `listKinds`). */
3881
+ const isListExpr = (e) => listKinds.has(e.kind);
3195
3882
  // packages/prover-lean/src/emit.ts
3196
3883
  /**
3197
3884
  * Lean 4 for a module in the subset and the properties on it. The
@@ -3200,8 +3887,9 @@ function typeTaken(t, takes, badRecords) {
3200
3887
  * the claim over its binders, with the precondition as a hypothesis.
3201
3888
  * Booleans stay `Bool` in terms, as in TypeScript, and become propositions
3202
3889
  * with `= true` where a statement needs one; comparisons are `decide`d.
3203
- * Every theorem is closed by one tactic script, so what Lean checks is the
3204
- * statement, not a hand proof.
3890
+ * Every theorem is closed by one tactic script, except where a proof is
3891
+ * supplied beside the spec file (`supplied.ts`): then the statement is
3892
+ * fixed as a definition first, and the supplied tactics must prove it.
3205
3893
  */
3206
3894
  /**
3207
3895
  * TypeScript names as Lean identifiers that can clash with nothing Lean
@@ -3229,6 +3917,8 @@ function leanType(t) {
3229
3917
  case "bool": return "Bool";
3230
3918
  case "string": return "String";
3231
3919
  case "record": return ident$1.record(t.name);
3920
+ case "list": return `(List ${leanType(t.element)})`;
3921
+ case "nothing": return fail$1("the element type of an empty array, which nothing gives");
3232
3922
  case "nullable":
3233
3923
  case "union":
3234
3924
  case "null": return fail$1(`a ${t.kind} type, which the Lean engine does not take yet`);
@@ -3263,7 +3953,9 @@ function term$1(e, scope, env) {
3263
3953
  case "int": return `(${e.value} : Int)`;
3264
3954
  case "bool": return e.value ? "true" : "false";
3265
3955
  case "string": return leanString(e.value);
3266
- case "var": return ident$1.variable(e.name);
3956
+ case "var":
3957
+ if (env.cons?.list === e.name) return `(${env.cons.head} :: ${env.cons.tail})`;
3958
+ return ident$1.variable(e.name);
3267
3959
  case "null":
3268
3960
  case "narrow": return fail$1("null, which the Lean engine does not take yet");
3269
3961
  case "neg": return `(-${t(e.operand)})`;
@@ -3293,7 +3985,9 @@ function term$1(e, scope, env) {
3293
3985
  break;
3294
3986
  case "cond": return `(if ${t(e.test)} = true then ${t(e.ifTrue)} else ${t(e.ifFalse)})`;
3295
3987
  case "call": return `(${ident$1.fn(e.callee)}${e.args.map((a) => ` ${t(a)}`).join("")})`;
3296
- case "field": return `${t(e.object)}.${ident$1.field(e.field)}`;
3988
+ case "field":
3989
+ if (typeOf(e.object, scope, env.ctx, fail$1).kind === "list") return `(Int.ofNat (List.length ${t(e.object)}))`;
3990
+ return `${t(e.object)}.${ident$1.field(e.field)}`;
3297
3991
  case "record": {
3298
3992
  const type = typeOf(e, scope, env.ctx, fail$1);
3299
3993
  const name = type.kind === "record" ? ident$1.record(type.name) : fail$1("a record literal of no record type");
@@ -3301,8 +3995,42 @@ function term$1(e, scope, env) {
3301
3995
  }
3302
3996
  case "let": {
3303
3997
  const inner = new Map(scope);
3304
- inner.set(e.name, typeOf(e.value, scope, env.ctx, fail$1));
3305
- return `(let ${ident$1.variable(e.name)} := ${t(e.value)}; ${term$1(e.body, inner, env)})`;
3998
+ const bound = e.type ?? typeOf(e.value, scope, env.ctx, fail$1);
3999
+ inner.set(e.name, bound);
4000
+ const annotated = e.type ? ` : ${leanType(e.type)}` : "";
4001
+ return `(let ${ident$1.variable(e.name)}${annotated} := ${t(e.value)}; ${term$1(e.body, inner, env)})`;
4002
+ }
4003
+ case "list":
4004
+ if (e.items.length === 0 && !e.rest) return "[]";
4005
+ if (!e.rest) return `[${e.items.map(t).join(", ")}]`;
4006
+ return `(${[...e.items.map(t), t(e.rest)].join(" :: ")})`;
4007
+ case "tail":
4008
+ if (e.list.kind === "var" && env.cons?.list === e.list.name) return env.cons.tail;
4009
+ return `(List.tail ${t(e.list)})`;
4010
+ case "headOr":
4011
+ if (e.list.kind === "var" && env.cons?.list === e.list.name) return env.cons.head;
4012
+ return `(List.headD ${t(e.list)} ${t(e.fallback)})`;
4013
+ case "iterate": {
4014
+ const listType = typeOf(e.list, scope, env.ctx, fail$1);
4015
+ if (listType.kind !== "list") fail$1(`${e.op} on a ${listType.kind}`);
4016
+ const inner = new Map(scope);
4017
+ inner.set(e.item, listType.element);
4018
+ if (e.index !== void 0) inner.set(e.index, { kind: "int" });
4019
+ const body = term$1(e.body, inner, env);
4020
+ const nat = e.index === void 0 ? "" : quote(`nv_${e.index}`);
4021
+ const fn = e.index === void 0 ? `(fun ${ident$1.variable(e.item)} => ${body})` : `(fun (${ident$1.variable(e.item)}, ${nat}) => let ${ident$1.variable(e.index)} := Int.ofNat ${nat}; ${body})`;
4022
+ const list = e.index === void 0 ? t(e.list) : `(List.zipIdx ${t(e.list)})`;
4023
+ if (e.op === "map") return `(List.map ${fn} ${list})`;
4024
+ if (e.op === "flatMap") return `(List.flatMap ${fn} ${list})`;
4025
+ return `(${e.op === "every" ? "List.all" : "List.any"} ${list} ${fn})`;
4026
+ }
4027
+ case "fold": {
4028
+ const listType = typeOf(e.list, scope, env.ctx, fail$1);
4029
+ if (listType.kind !== "list") fail$1(`reduce on a ${listType.kind}`);
4030
+ const inner = new Map(scope);
4031
+ inner.set(e.acc, typeOf(e, scope, env.ctx, fail$1));
4032
+ inner.set(e.item, listType.element);
4033
+ return `(List.foldl (fun ${ident$1.variable(e.acc)} ${ident$1.variable(e.item)} => ${term$1(e.body, inner, env)}) ${t(e.init)} ${t(e.list)})`;
3306
4034
  }
3307
4035
  }
3308
4036
  }
@@ -3310,7 +4038,23 @@ function emitFunction$1(f, module) {
3310
4038
  const e = env$1(module);
3311
4039
  const scope = new Map(f.params.map((p) => [p.name, p.type]));
3312
4040
  const params = f.params.map((p) => `(${ident$1.variable(p.name)} : ${leanType(p.type)})`).join(" ");
3313
- return `def ${ident$1.fn(f.name)} ${params} : ${leanType(f.returns)} :=\n ${term$1(f.body, scope, e)}`;
4041
+ const head = `def ${ident$1.fn(f.name)} ${params} : ${leanType(f.returns)} :=`;
4042
+ if (f.structural === void 0 || f.body.kind !== "cond") return `${head}\n ${term$1(f.body, scope, e)}`;
4043
+ const list = f.params[f.structural].name;
4044
+ const cons = {
4045
+ list,
4046
+ head: quote(`vh_${list}`),
4047
+ tail: quote(`vt_${list}`)
4048
+ };
4049
+ return [
4050
+ head,
4051
+ ` match ${ident$1.variable(list)} with`,
4052
+ ` | [] => ${term$1(f.body.ifTrue, scope, e)}`,
4053
+ ` | ${cons.head} :: ${cons.tail} => ${term$1(f.body.ifFalse, scope, {
4054
+ ...e,
4055
+ cons
4056
+ })}`
4057
+ ].join("\n");
3314
4058
  }
3315
4059
  /**
3316
4060
  * The subset type a binder ranges over, or `OutsideSubset`: `number` is
@@ -3348,6 +4092,10 @@ function binderType$1(name, t, module) {
3348
4092
  case "undefined":
3349
4093
  fail$1(`binder ${name} over ${t.kind}`);
3350
4094
  break;
4095
+ case "array": return {
4096
+ kind: "list",
4097
+ element: binderType$1(name, t.element, module)
4098
+ };
3351
4099
  case "unknown": fail$1(`binder ${name} over ${t.text}, which the reader could not read`);
3352
4100
  }
3353
4101
  }
@@ -3422,16 +4170,31 @@ function tactics(module, property, hypotheses) {
3422
4170
  function theoremName(index, fn, property) {
3423
4171
  return `t${index}_${fn}_${property}`.replace(/[^A-Za-z0-9_]/g, "_");
3424
4172
  }
3425
- /** The whole file: structures, definitions, one theorem per property, then any extra lines (translation checks). */
3426
- function emitModule(module, properties, extra = []) {
4173
+ /** A tactic block at the indentation a `by` takes: its common indentation stripped, two spaces put back. */
4174
+ function indented(block) {
4175
+ const lines = block.split("\n");
4176
+ const widths = lines.filter((l) => l.trim() !== "").map((l) => /^ */.exec(l)?.[0].length ?? 0);
4177
+ const common = widths.length > 0 ? Math.min(...widths) : 0;
4178
+ return lines.map((l) => l.trim() === "" ? "" : ` ${l.slice(common)}`).join("\n");
4179
+ }
4180
+ /**
4181
+ * The whole file: structures, definitions, one theorem per property, any
4182
+ * extra lines (translation checks), then the properties with supplied
4183
+ * proofs: each statement fixed as a definition before any supplied text,
4184
+ * the supplied lemmas, each theorem proving its definition with the
4185
+ * supplied tactics, and `#print axioms` for each.
4186
+ */
4187
+ function emitModule(module, properties, extra = [], supplied) {
3427
4188
  const parts = [
3428
4189
  "-- Generated by Eutaxy's first-party engine from the module and its spec file; the theorems are its properties.",
3429
4190
  "set_option linter.unusedSimpArgs false",
4191
+ "set_option linter.unusedVariables false",
3430
4192
  ...module.records.map(emitRecord),
3431
4193
  ...module.functions.map((f) => emitFunction$1(f, module))
3432
4194
  ];
3433
4195
  const theorems = [];
3434
4196
  const skipped = [];
4197
+ const later = [];
3435
4198
  for (const { function: fn, property } of properties) {
3436
4199
  let body;
3437
4200
  try {
@@ -3445,7 +4208,18 @@ function emitModule(module, properties, extra = []) {
3445
4208
  });
3446
4209
  continue;
3447
4210
  }
3448
- const name = theoremName(theorems.length + skipped.length, fn, property.name);
4211
+ const name = theoremName(theorems.length + skipped.length + later.length, fn, property.name);
4212
+ const proof = supplied?.proofs.get(property.name);
4213
+ if (proof !== void 0) {
4214
+ later.push({
4215
+ fn,
4216
+ property: property.name,
4217
+ name,
4218
+ statement: body.text,
4219
+ proof
4220
+ });
4221
+ continue;
4222
+ }
3449
4223
  const text = `theorem ${name} :\n ${body.text} := by\n${tactics(module, property, body.hypotheses)}`;
3450
4224
  const from = parts.join("\n\n").split("\n").length + 2;
3451
4225
  parts.push(text);
@@ -3458,10 +4232,49 @@ function emitModule(module, properties, extra = []) {
3458
4232
  });
3459
4233
  }
3460
4234
  parts.push(...extra);
4235
+ const lineAfter = () => parts.join("\n\n").split("\n").length + 2;
4236
+ let lemmas;
4237
+ if (later.length > 0) {
4238
+ for (const l of later) parts.push(`def s_${l.name} : Prop :=\n ${l.statement}`);
4239
+ if (supplied && supplied.lemmas !== "") {
4240
+ const from = lineAfter();
4241
+ parts.push(supplied.lemmas);
4242
+ lemmas = {
4243
+ from,
4244
+ to: from + supplied.lemmas.split("\n").length - 1
4245
+ };
4246
+ }
4247
+ const ownProofs = [];
4248
+ for (const l of later) {
4249
+ const text = `theorem ${l.name} : s_${l.name} := by\n unfold s_${l.name}\n${indented(l.proof)}`;
4250
+ const from = lineAfter();
4251
+ parts.push(text);
4252
+ ownProofs.push({
4253
+ function: l.fn,
4254
+ property: l.property,
4255
+ name: l.name,
4256
+ from,
4257
+ to: from + text.split("\n").length - 1,
4258
+ supplied: true
4259
+ });
4260
+ }
4261
+ for (const t of ownProofs) {
4262
+ const typeLine = lineAfter();
4263
+ parts.push(`#check @${t.name}`);
4264
+ const axiomsLine = lineAfter();
4265
+ parts.push(`#print axioms ${t.name}`);
4266
+ theorems.push({
4267
+ ...t,
4268
+ axiomsLine,
4269
+ typeLine
4270
+ });
4271
+ }
4272
+ }
3461
4273
  return {
3462
4274
  source: `${parts.join("\n\n")}\n`,
3463
4275
  theorems,
3464
- skipped
4276
+ skipped,
4277
+ ...lemmas ? { lemmas } : {}
3465
4278
  };
3466
4279
  }
3467
4280
  /**
@@ -3490,7 +4303,14 @@ function leanString(value) {
3490
4303
  * command that installs it. Diagnostics come back as `file:line:col:
3491
4304
  * severity: message` lines, which the engine maps to theorems.
3492
4305
  */
3493
- /** The Lean release the engine's contract corpus is checked against. */
4306
+ /**
4307
+ * The Lean release the engine's contract corpus is checked against. On a
4308
+ * bump: run the corpus and the supplied-proof tests on the new release,
4309
+ * and read its release notes for a new command that runs code while a
4310
+ * file is checked (a `#` command is already refused; a new word goes into
4311
+ * `supplied.ts`'s refused list in the same change). CI caches the
4312
+ * toolchain by this file's hash.
4313
+ */
3494
4314
  const leanToolchain = "leanprover/lean4:v4.35.0";
3495
4315
  const leanVersion = "4.35.0";
3496
4316
  /** How to put the pinned toolchain on this machine. */
@@ -3594,29 +4414,31 @@ async function findLean() {
3594
4414
  return { unavailable: `no Lean toolchain found; ${installHint$1}` };
3595
4415
  }
3596
4416
  /** Parse Lean's diagnostics for the one file it was given. */
3597
- function diagnostics(output) {
4417
+ /**
4418
+ * Lean's messages from `--json` output: one object per line, each with
4419
+ * its position. Lines that are not such an object (whatever a program
4420
+ * writes to the terminal) are not messages and are skipped, so nothing in
4421
+ * the checked file can pose as a message at a position it is not at.
4422
+ */
4423
+ function jsonDiagnostics(output) {
3598
4424
  const out = [];
3599
- const re = /^(?:.*?):(\d+):(\d+): (error|warning|info): (.*)$/;
3600
- let current;
3601
- const flush = (c) => out.push({
3602
- line: c.line,
3603
- column: c.column,
3604
- severity: c.severity,
3605
- message: c.lines.join("\n").trimEnd()
3606
- });
3607
4425
  for (const raw of output.split("\n")) {
3608
- const m = re.exec(raw);
3609
- if (m) {
3610
- if (current) flush(current);
3611
- current = {
3612
- line: Number(m[1]),
3613
- column: Number(m[2]),
3614
- severity: m[3],
3615
- lines: [m[4]]
3616
- };
3617
- } else if (current) current.lines.push(raw);
4426
+ if (!raw.startsWith("{")) continue;
4427
+ let m;
4428
+ try {
4429
+ m = JSON.parse(raw);
4430
+ } catch {
4431
+ continue;
4432
+ }
4433
+ const severity = m.severity === "error" ? "error" : m.severity === "warning" ? "warning" : m.severity === "information" ? "info" : void 0;
4434
+ if (severity === void 0 || typeof m.pos?.line !== "number" || typeof m.data !== "string") continue;
4435
+ out.push({
4436
+ line: m.pos.line,
4437
+ column: typeof m.pos.column === "number" ? m.pos.column : 0,
4438
+ severity,
4439
+ message: m.data.trimEnd()
4440
+ });
3618
4441
  }
3619
- if (current) flush(current);
3620
4442
  return out;
3621
4443
  }
3622
4444
  /** Write the source to a scratch directory pinned to the toolchain and check it. */
@@ -3625,13 +4447,17 @@ async function checkLean(toolchain, source, options = {}) {
3625
4447
  try {
3626
4448
  writeFileSync(join(dir, "lean-toolchain"), `${leanToolchain}\n`);
3627
4449
  writeFileSync(join(dir, "Eutaxy.lean"), source);
3628
- const result = await run$1(toolchain.command, [...toolchain.args, "Eutaxy.lean"], {
4450
+ const result = await run$1(toolchain.command, [
4451
+ ...toolchain.args,
4452
+ "--json",
4453
+ "Eutaxy.lean"
4454
+ ], {
3629
4455
  cwd: dir,
3630
4456
  timeoutMs: options.timeoutMs ?? 12e4
3631
4457
  });
3632
4458
  return {
3633
4459
  run: result,
3634
- diagnostics: diagnostics(`${result.stdout}\n${result.stderr}`)
4460
+ diagnostics: jsonDiagnostics(`${result.stdout}\n${result.stderr}`)
3635
4461
  };
3636
4462
  } finally {
3637
4463
  if (!options.keep) rmSync(dir, {
@@ -3640,10 +4466,183 @@ async function checkLean(toolchain, source, options = {}) {
3640
4466
  });
3641
4467
  }
3642
4468
  }
4469
+ // packages/prover-lean/src/supplied.ts
4470
+ /** The axioms a supplied proof may rest on: Lean's standard ones. */
4471
+ const standardAxioms = /* @__PURE__ */ new Set([
4472
+ "propext",
4473
+ "Classical.choice",
4474
+ "Quot.sound"
4475
+ ]);
4476
+ /**
4477
+ * Words a supplied proof may not use, anywhere in the file, comments and
4478
+ * strings included: what adds axioms or trusted code (`axiom`, `sorry`,
4479
+ * `unsafe`, `implemented_by`, `extern`, `opaque`, `native_decide`),
4480
+ * switches checks off (`set_option`), registers code Lean would run while
4481
+ * the file is checked (`attribute`, `initialize`, `simproc` and the like)
4482
+ * or changes how text reads (`macro`, `syntax`, `notation` and the like),
4483
+ * and `import`. The list narrows when a legitimate proof is refused and
4484
+ * grows only with a Lean bump that adds such a command (see
4485
+ * `leanToolchain`); never because of what a hostile file could do, which
4486
+ * the design answers.
4487
+ */
4488
+ const refusedWords = [
4489
+ "sorry",
4490
+ "admit",
4491
+ "axiom",
4492
+ "unsafe",
4493
+ "implemented_by",
4494
+ "extern",
4495
+ "opaque",
4496
+ "native_decide",
4497
+ "set_option",
4498
+ "macro",
4499
+ "macro_rules",
4500
+ "syntax",
4501
+ "notation",
4502
+ "infix",
4503
+ "infixl",
4504
+ "infixr",
4505
+ "prefix",
4506
+ "postfix",
4507
+ "elab",
4508
+ "elab_rules",
4509
+ "import",
4510
+ "attribute",
4511
+ "initialize",
4512
+ "simproc",
4513
+ "dsimproc",
4514
+ "simproc_decl",
4515
+ "dsimproc_decl",
4516
+ "section",
4517
+ "namespace",
4518
+ "variable",
4519
+ "include",
4520
+ "omit",
4521
+ "universe"
4522
+ ];
4523
+ /** Command families refused by how a word starts: `run_cmd`, `builtin_initialize`, `register_option`, `declare_syntax_cat`. */
4524
+ const refusedStarts = [
4525
+ "run_",
4526
+ "builtin_",
4527
+ "register_",
4528
+ "declare_"
4529
+ ];
4530
+ /**
4531
+ * Refused wherever they appear, inside a name too: every command run
4532
+ * while the file is checked starts with `#`, and every attribute (which
4533
+ * can hand Lean a tactic, an elaborator or a simplification procedure to
4534
+ * run) with `@[`.
4535
+ */
4536
+ const refusedAnywhere = ["#", "@["];
4537
+ /** Lean's ASCII identifier characters after the first. */
4538
+ const identRest = /[A-Za-z0-9_'!?]/u;
4539
+ /**
4540
+ * Whether the text just before `at` continues a name, so that a word
4541
+ * starting there is part of that name rather than a token of its own.
4542
+ * Only a run of identifier characters that starts with an ASCII letter or
4543
+ * `_` counts: one that starts with a digit is a numeral, and Lean starts a
4544
+ * new token right after a numeral (`0xfsorry` is `0xf`, then `sorry`).
4545
+ * Anything else (`.`, `«`, Unicode) counts as a boundary, which refuses
4546
+ * more, never less.
4547
+ */
4548
+ function continuesName(text, at) {
4549
+ let i = at;
4550
+ while (i > 0 && identRest.test(text[i - 1])) i--;
4551
+ return i < at && /[A-Za-z_]/u.test(text[i]);
4552
+ }
4553
+ /** The first refused word or command the text holds, as a token of its own, or undefined. */
4554
+ function refusedIn(text) {
4555
+ const anywhere = refusedAnywhere.find((w) => text.includes(w));
4556
+ if (anywhere !== void 0) return anywhere;
4557
+ for (const [words, whole] of [[refusedWords, true], [refusedStarts, false]]) for (const w of words) for (let at = text.indexOf(w); at >= 0; at = text.indexOf(w, at + 1)) {
4558
+ if (continuesName(text, at)) continue;
4559
+ if (whole && identRest.test(text[at + w.length] ?? "")) continue;
4560
+ return w;
4561
+ }
4562
+ }
4563
+ /** `-- proof: <property>`: any name the spec file can export, Unicode letters included. */
4564
+ const marker = /^-- proof: (\S+)\s*$/u;
4565
+ /** Read a proof file: its lemmas, its proofs by property, or why it is refused. */
4566
+ function readSupplied(file, text) {
4567
+ const lemmas = [];
4568
+ const proofs = /* @__PURE__ */ new Map();
4569
+ let current = lemmas;
4570
+ let twice;
4571
+ for (const line of text.split("\n")) {
4572
+ const m = marker.exec(line);
4573
+ if (!m) {
4574
+ current.push(line);
4575
+ continue;
4576
+ }
4577
+ const name = m[1];
4578
+ twice ??= proofs.has(name) ? name : void 0;
4579
+ current = [];
4580
+ proofs.set(name, current);
4581
+ }
4582
+ if (twice !== void 0) return refuse({
4583
+ file,
4584
+ proofs
4585
+ }, `${file} proves ${twice} twice`);
4586
+ const word = refusedIn(text);
4587
+ if (word !== void 0) return refuse({
4588
+ file,
4589
+ proofs
4590
+ }, `${file} uses ${word}, which a supplied proof may not (it could add an axiom, switch a check off, run code while the file is checked or change how the statement reads)`);
4591
+ return {
4592
+ file,
4593
+ lemmas: lemmas.join("\n").trim(),
4594
+ proofs: new Map([...proofs].map(([k, v]) => [k, v.join("\n").replace(/\s+$/, "")]))
4595
+ };
4596
+ }
4597
+ /** The file refused: none of its proofs is used, and every property it names says why. */
4598
+ function refuse(supplied, reason) {
4599
+ return {
4600
+ file: supplied.file,
4601
+ lemmas: "",
4602
+ proofs: new Map([...supplied.proofs.keys()].map((k) => [k, ""])),
4603
+ refused: reason
4604
+ };
4605
+ }
4606
+ /** Lean's messages at one line: an audit is read only when Lean's own message is the only one there. */
4607
+ function onlyAt(messages, line) {
4608
+ const at = messages.filter((m) => m.line === line);
4609
+ return at.length === 1 && at[0]?.severity === "info" ? at[0].message : void 0;
4610
+ }
4611
+ /**
4612
+ * The axioms Lean reports a theorem depends on: the message of the
4613
+ * `#print axioms` at `line`, Eutaxy's own audit command, and no other.
4614
+ * Undefined unless that message is the only one at the line: anything
4615
+ * else there (a forged copy, printed by code the file ran) makes the
4616
+ * audit unreadable rather than letting either message stand.
4617
+ */
4618
+ function axiomsOf(messages, line, theorem) {
4619
+ const message = onlyAt(messages, line);
4620
+ if (message === void 0) return void 0;
4621
+ if (message === `'${theorem}' does not depend on any axioms`) return [];
4622
+ const prefix = `'${theorem}' depends on axioms: [`;
4623
+ if (message.startsWith(prefix) && message.endsWith("]")) return message.slice(prefix.length, -1).split(",").map((x) => x.trim()).filter((x) => x.length > 0);
4624
+ }
4625
+ /**
4626
+ * Whether Lean's message at the `#check` of a supplied theorem shows it
4627
+ * proves exactly its fixed statement `s_<name>`: no hypothesis added (a
4628
+ * section variable would show as `False → …`).
4629
+ */
4630
+ function provesExactly(messages, line, theorem) {
4631
+ return onlyAt(messages, line) === `${theorem} : s_${theorem}`;
4632
+ }
3643
4633
  // packages/prover-lean/src/prove.ts
4634
+ /**
4635
+ * The engine: a module's functions through the subset reader, the emitter
4636
+ * and Lean, and each property's outcome back. One Lean run per module;
4637
+ * errors are mapped to theorems by line, so one failed proof does not hide
4638
+ * another. A proof that fails is `gave_up` (the engine is weak or the
4639
+ * claim is false; Lean does not say which), a function or property outside
4640
+ * the subset is `unsupported`, and no pinned toolchain is `unavailable`.
4641
+ * `total` is proved by Lean accepting the definition.
4642
+ */
3644
4643
  const engineName$1 = "lean";
3645
4644
  /** The types this engine translates: the integers, Bool, String and records of those. */
3646
- const leanTakes = (t) => t.kind === "int" || t.kind === "bool" || t.kind === "string" || t.kind === "record";
4645
+ const leanTakes = (t) => t.kind === "int" || t.kind === "bool" || t.kind === "string" || t.kind === "record" || t.kind === "list" && leanTakes(t.element);
3647
4646
  /** What every PROVEN verdict of this engine rests on. */
3648
4647
  const engineAssumptions$1 = [
3649
4648
  "number is modelled as the unbounded integers: no overflow, no fractions, no NaN",
@@ -3651,6 +4650,10 @@ const engineAssumptions$1 = [
3651
4650
  "the function and its callees are the module's own, pure and total; nothing outside the module is modelled",
3652
4651
  `the proof was checked by the Lean ${leanVersion} kernel on the emitted statement, not by Eutaxy`
3653
4652
  ];
4653
+ /** What a PROVEN over arrays rests on besides: the list model. */
4654
+ const listAssumption = "an array is modelled as a Lean List, dense: a sparse array, whose holes JavaScript's array methods skip, is outside every array binder's domain";
4655
+ /** What a PROVEN that unfolds a recursive function rests on besides: that the JavaScript returns. */
4656
+ const recursionAssumption = "a recursive function is modelled as returning on every input: JavaScript's call stack is bounded, so on a long enough list the code throws (RangeError) where the model returns";
3654
4657
  const proven$1 = {
3655
4658
  kind: "PROVEN",
3656
4659
  engine: {
@@ -3692,10 +4695,13 @@ function prepare$1(input) {
3692
4695
  property
3693
4696
  })));
3694
4697
  const specErrors = specs.errors;
4698
+ const proofFile = input.specPath?.replace(/\.ts$/, ".lean");
4699
+ const supplied = proofFile !== void 0 && existsSync(proofFile) ? readSupplied(basename(proofFile), readFileSync(proofFile, "utf8")) : void 0;
3695
4700
  try {
3696
4701
  return {
3697
4702
  module,
3698
- emitted: emitModule(module, properties, input.extra),
4703
+ ...supplied ? { supplied } : {},
4704
+ emitted: emitModule(module, properties, input.extra, supplied && !supplied.refused ? supplied : void 0),
3699
4705
  fns,
3700
4706
  outside,
3701
4707
  specErrors
@@ -3716,9 +4722,25 @@ function prepare$1(input) {
3716
4722
  };
3717
4723
  }
3718
4724
  }
4725
+ /**
4726
+ * A supplied proof's outcome: given up on when its lemmas or its tactics
4727
+ * do not compile, or when it rests on an axiom beyond Lean's standard
4728
+ * ones (`sorry` is one); PROVEN otherwise, saying it was supplied.
4729
+ */
4730
+ function suppliedOutcome(file, error, axioms, exact, assumptions) {
4731
+ if (error) return unknown$1("gave_up", `the proof supplied in ${file} does not close: ${error.message.split("\n")[0]}`);
4732
+ if (!exact) return unknown$1("gave_up", `the proof supplied in ${file} proves more hypotheses than its statement has (a section variable?), or Lean did not report its type`);
4733
+ if (axioms === void 0) return unknown$1("gave_up", `Lean did not report the axioms of the proof supplied in ${file}`);
4734
+ const beyond = axioms.filter((a) => !standardAxioms.has(a));
4735
+ if (beyond.length > 0) return unknown$1("gave_up", `the proof supplied in ${file} rests on ${beyond.join(", ")}, beyond Lean's standard axioms`);
4736
+ return {
4737
+ ...proven$1,
4738
+ assumptions: [...assumptions, `the proof was supplied in ${file}, not found by the engine's tactic script; Lean's kernel checked it against the statement Eutaxy emitted, and it rests on no axioms beyond propext, Classical.choice and Quot.sound`]
4739
+ };
4740
+ }
3719
4741
  /** Prove a module's properties with the pinned Lean. */
3720
4742
  async function proveModule$1(input) {
3721
- const { emitted, fns, outside, specErrors } = prepare$1(input);
4743
+ const { module, emitted, fns, outside, specErrors, supplied } = prepare$1(input);
3722
4744
  const inSubset = fns.filter((f) => !outside.has(f.name));
3723
4745
  const unsupported = fns.filter((f) => outside.has(f.name)).flatMap((f) => f.properties.map((property) => ({
3724
4746
  function: f.name,
@@ -3743,7 +4765,9 @@ async function proveModule$1(input) {
3743
4765
  const errors = checked.diagnostics.filter((d) => d.severity === "error");
3744
4766
  const inTheorem = (d) => emitted.theorems.find((t) => d.line >= t.from && d.line <= t.to);
3745
4767
  if (checked.run.code === null || checked.run.code !== 0 && errors.length === 0) return rest(unknown$1("unavailable", `Lean could not be run: ${checked.run.stderr.trim() || `exit ${checked.run.code}`}`));
3746
- const elsewhere = errors.filter((d) => !inTheorem(d));
4768
+ const inLemmas = (d) => emitted.lemmas !== void 0 && d.line >= emitted.lemmas.from && d.line <= emitted.lemmas.to;
4769
+ const lemmaErrors = errors.filter(inLemmas);
4770
+ const elsewhere = errors.filter((d) => !inTheorem(d) && !inLemmas(d));
3747
4771
  if (elsewhere.length > 0) {
3748
4772
  const where = elsewhere.map((d) => `line ${d.line}: ${d.message.split("\n")[0]}`).join("; ");
3749
4773
  return rest(unknown$1("unsupported", `the emitted Lean did not compile: ${where}`));
@@ -3756,7 +4780,11 @@ async function proveModule$1(input) {
3756
4780
  property: property.name,
3757
4781
  outcome: {
3758
4782
  ...proven$1,
3759
- assumptions: [...engineAssumptions$1, "Lean accepted the definition, so it terminates on every input"]
4783
+ assumptions: [
4784
+ ...engineAssumptions$1,
4785
+ ...modelAssumptions(property, fn.name, module),
4786
+ "Lean accepted the definition, so it terminates on every input"
4787
+ ]
3760
4788
  }
3761
4789
  });
3762
4790
  continue;
@@ -3770,12 +4798,31 @@ async function proveModule$1(input) {
3770
4798
  });
3771
4799
  continue;
3772
4800
  }
4801
+ if (supplied?.refused && supplied.proofs.has(property.name)) {
4802
+ results.push({
4803
+ function: fn.name,
4804
+ property: property.name,
4805
+ outcome: unknown$1("gave_up", supplied.refused)
4806
+ });
4807
+ continue;
4808
+ }
3773
4809
  const theorem = emitted.theorems.find((t) => t.function === fn.name && t.property === property.name);
3774
4810
  const failed = theorem ? errors.filter((d) => d.line >= theorem.from && d.line <= theorem.to) : [];
4811
+ if (theorem?.supplied && supplied) {
4812
+ results.push({
4813
+ function: fn.name,
4814
+ property: property.name,
4815
+ outcome: suppliedOutcome(supplied.file, lemmaErrors[0] ?? failed[0], axiomsOf(checked.diagnostics, theorem.axiomsLine ?? 0, theorem.name), provesExactly(checked.diagnostics, theorem.typeLine ?? 0, theorem.name), [...engineAssumptions$1, ...modelAssumptions(property, fn.name, module)])
4816
+ });
4817
+ continue;
4818
+ }
3775
4819
  results.push({
3776
4820
  function: fn.name,
3777
4821
  property: property.name,
3778
- outcome: failed.length === 0 ? proven$1 : unknown$1("gave_up", `Lean could not close the proof: ${failed[0].message.split("\n")[0]}`)
4822
+ outcome: failed.length === 0 ? {
4823
+ ...proven$1,
4824
+ assumptions: [...engineAssumptions$1, ...modelAssumptions(property, fn.name, module)]
4825
+ } : unknown$1("gave_up", `Lean could not close the proof: ${failed[0].message.split("\n")[0]}`)
3779
4826
  });
3780
4827
  }
3781
4828
  return {
@@ -3793,6 +4840,60 @@ const leanProver = {
3793
4840
  },
3794
4841
  prove: (input) => proveModule$1(input)
3795
4842
  };
4843
+ /** The list and recursion models a proof rests on, where its claim may meet them. */
4844
+ function modelAssumptions(property, fn, module) {
4845
+ const arrows = [property.when?.body ?? "", property.ensures?.body ?? ""].join("\n");
4846
+ const roots = [fn, ...property.imports.filter((i) => new RegExp(`(^|[^\\w$])${i.local.replace(/\$/g, "\\$")}($|[^\\w$])`).test(arrows)).map((i) => i.fn)];
4847
+ return [...usesLists(property, roots, module) ? [listAssumption] : [], ...reached(roots, module).some((f) => f.structural !== void 0) ? [recursionAssumption] : []];
4848
+ }
4849
+ /**
4850
+ * The functions a property's claim may unfold: its function, the module
4851
+ * functions its arrows call, and, through their calls, everything they
4852
+ * reach.
4853
+ */
4854
+ function reached(roots, module) {
4855
+ const byName = new Map(module.functions.map((f) => [f.name, f]));
4856
+ const out = /* @__PURE__ */ new Map();
4857
+ const visit = (name) => {
4858
+ const f = byName.get(name);
4859
+ if (!f || out.has(name)) return;
4860
+ out.set(name, f);
4861
+ const walk = (e) => {
4862
+ if (e.kind === "call") visit(e.callee);
4863
+ for (const c of children(e)) walk(c);
4864
+ };
4865
+ walk(f.body);
4866
+ };
4867
+ for (const r of roots) visit(r);
4868
+ return [...out.values()];
4869
+ }
4870
+ /**
4871
+ * Whether a list can be in play in a property: a binder whose type holds
4872
+ * an array at any depth, or a function the claim may unfold that holds a
4873
+ * list in its types (through records too) or builds one.
4874
+ */
4875
+ function usesLists(property, roots, module) {
4876
+ const records = new Map(module.records.map((r) => [r.name, r]));
4877
+ const seen = /* @__PURE__ */ new Set();
4878
+ const hasList = (t) => {
4879
+ if (t.kind === "list") return true;
4880
+ if (t.kind === "nullable") return hasList(t.inner);
4881
+ if (t.kind === "record" && !seen.has(t.name)) {
4882
+ seen.add(t.name);
4883
+ return records.get(t.name)?.fields.some((f) => hasList(f.type)) ?? false;
4884
+ }
4885
+ return false;
4886
+ };
4887
+ const hasArray = (t) => {
4888
+ if (t.kind === "array") return true;
4889
+ if (t.kind === "union") return t.members.some(hasArray);
4890
+ if (t.kind === "record") return t.fields.some((f) => hasArray(f.type));
4891
+ return false;
4892
+ };
4893
+ const builds = (e) => listKinds.has(e.kind) || children(e).some(builds);
4894
+ const arrowLists = [property.when, property.ensures].some((a) => a !== void 0 && /\[|\.(map|flatMap|every|some|reduce|slice|length)\b/.test(a.body));
4895
+ return property.binders.some((b) => hasArray(b.type)) || arrowLists || reached(roots, module).some((f) => hasList(f.returns) || f.params.some((p) => hasList(p.type)) || builds(f.body));
4896
+ }
3796
4897
  // packages/prover-smt/src/emit.ts
3797
4898
  /**
3798
4899
  * SMT-LIB 2 for a module in the subset and the properties on it, as Z3
@@ -3831,6 +4932,7 @@ const ident = {
3831
4932
  };
3832
4933
  /** The short name a sort has inside option names: `Opt.F64`, `Opt.R_X`. */
3833
4934
  function sortName(t, module) {
4935
+ if (t.kind === "list" || t.kind === "nothing") return fail(listsOutside);
3834
4936
  switch (t.kind) {
3835
4937
  case "int": return "F64";
3836
4938
  case "bool": return "Bool";
@@ -3846,6 +4948,7 @@ function unionOf(record, module) {
3846
4948
  return module.records.find((r) => r.name === record)?.union;
3847
4949
  }
3848
4950
  function sort(t, module) {
4951
+ if (t.kind === "list" || t.kind === "nothing") return fail(listsOutside);
3849
4952
  switch (t.kind) {
3850
4953
  case "int": return F64;
3851
4954
  case "bool": return "Bool";
@@ -3895,6 +4998,8 @@ function env(module) {
3895
4998
  }
3896
4999
  };
3897
5000
  }
5001
+ /** Why a list, or an operation on one, is refused here. */
5002
+ const listsOutside = "arrays are not in this engine's subset (the Lean engine takes them)";
3898
5003
  const fail = (message) => {
3899
5004
  throw new OutsideSubset(message, 0);
3900
5005
  };
@@ -3909,6 +5014,7 @@ function membersOf(union, env) {
3909
5014
  const tester = (constructorSymbol) => constructorSymbol.startsWith("|") ? `|is-${constructorSymbol.slice(1)}` : `is-${constructorSymbol}`;
3910
5015
  /** `===` of two terms of a type, as JavaScript has it. */
3911
5016
  function sameAs(a, b, t, env) {
5017
+ if (t.kind === "list" || t.kind === "nothing") return fail(listsOutside);
3912
5018
  switch (t.kind) {
3913
5019
  case "int": return `(fp.eq ${a} ${b})`;
3914
5020
  case "bool":
@@ -3929,6 +5035,7 @@ function sameAs(a, b, t, env) {
3929
5035
  */
3930
5036
  function term(e, scope, env, expected) {
3931
5037
  const t = (x, want) => term(x, scope, env, want);
5038
+ if (isListExpr(e)) return fail(listsOutside);
3932
5039
  const typed = (x) => {
3933
5040
  const key = JSON.stringify([...scope]);
3934
5041
  let byScope = env.types.get(x);
@@ -4151,6 +5258,9 @@ function binderType(name, t, module) {
4151
5258
  case "undefined":
4152
5259
  fail(`binder ${name} over ${t.kind}`);
4153
5260
  break;
5261
+ case "array":
5262
+ fail(`binder ${name} over ${describeType(t)}: arrays are not in the engine's subset yet`);
5263
+ break;
4154
5264
  case "unknown": fail(`binder ${name} over ${t.text}, which the reader could not read`);
4155
5265
  }
4156
5266
  }
@@ -4609,7 +5719,7 @@ const key = (fn, property) => `${fn}\u0000${property}`;
4609
5719
  function prepare(input) {
4610
5720
  const wanted = input.functions ? new Set(input.functions) : void 0;
4611
5721
  const fns = input.specs.functions.filter((f) => !wanted || wanted.has(f.name));
4612
- const module = readSubset(input.source, fns.map((f) => f.name));
5722
+ const module = restrictModule(readSubset(input.source, fns.map((f) => f.name)), (t) => t.kind !== "list" && t.kind !== "nothing", "arrays are not in this engine's subset (the Lean engine takes them)", listKinds);
4613
5723
  const outside = /* @__PURE__ */ new Map();
4614
5724
  for (const o of module.outside) if (fns.some((f) => f.name === o.name)) outside.set(o.name, `outside the engine's subset${o.line > 0 ? ` (line ${o.line})` : ""}: ${o.message}`);
4615
5725
  for (const fn of fns) {
@@ -5009,6 +6119,16 @@ const provers = {
5009
6119
  lean: leanProver,
5010
6120
  smt: smtProver
5011
6121
  };
6122
+ /** The engines named, or the error naming the first unknown one. */
6123
+ function enginesNamed(names) {
6124
+ const engines = [];
6125
+ for (const name of names) {
6126
+ const engine = provers[name];
6127
+ if (!engine) return { error: `unknown prover ${name}; known: ${Object.keys(provers).join(", ")}` };
6128
+ engines.push(engine);
6129
+ }
6130
+ return { engines };
6131
+ }
5012
6132
  /**
5013
6133
  * The PROVEN rung, on the Node side: each engine on each observed spec
5014
6134
  * module's source, the outcomes folded into the simulator's verdicts.
@@ -5146,16 +6266,12 @@ async function runCheck(o) {
5146
6266
  const verdict = report.verdict;
5147
6267
  let specs = report.specs ?? [];
5148
6268
  if (o.provers && o.provers.length > 0) {
5149
- const engines = [];
5150
- for (const name of o.provers) {
5151
- const engine = provers[name];
5152
- if (!engine) {
5153
- o.stderr(`unknown prover ${name}; known: ${Object.keys(provers).join(", ")}\n`);
5154
- return exitCodes.error;
5155
- }
5156
- engines.push(engine);
6269
+ const named = enginesNamed(o.provers);
6270
+ if ("error" in named) {
6271
+ o.stderr(`${named.error}\n`);
6272
+ return exitCodes.error;
5157
6273
  }
5158
- specs = await proveSpecs(dir, transport.observed ?? [], specs, engines, specModules);
6274
+ specs = await proveSpecs(dir, transport.observed ?? [], specs, named.engines, specModules);
5159
6275
  }
5160
6276
  const printed = o.provers && o.provers.length > 0 ? {
5161
6277
  ...transport.report,
@@ -5194,27 +6310,165 @@ async function runCheck(o) {
5194
6310
  });
5195
6311
  }
5196
6312
  }
6313
+ // packages/cli/src/report.ts
6314
+ /**
6315
+ * `eutaxy report [dir]`: every spec file under a directory through the
6316
+ * ladder, on the Node side. No scenario runs, so the ladder starts at
6317
+ * `TESTED` (inputs drawn from the parameter types); `--prover` adds the
6318
+ * `PROVEN` rung. Each module runs in a worker thread of its own, started
6319
+ * on this file: what the module prints goes to stderr, its state starts
6320
+ * fresh, and a property that never returns ends with the module's budget.
6321
+ * A module that only loads inside workerd gets `UNKNOWN` until an engine
6322
+ * reads it.
6323
+ */
6324
+ function unknownAll(m, cause, reason) {
6325
+ return m.specs.functions.flatMap((fn) => fn.properties.map((p) => ({
6326
+ module: m.key,
6327
+ function: fn.name,
6328
+ property: p.name,
6329
+ text: p.text,
6330
+ kind: "UNKNOWN",
6331
+ cause,
6332
+ reason,
6333
+ assumptions: []
6334
+ })));
6335
+ }
6336
+ /**
6337
+ * Inside the worker: a relative import from a `.ts` file that Node cannot
6338
+ * resolve is tried as TypeScript resolves it, so `./domain.js` and
6339
+ * `./domain` find `domain.ts` (or `domain/index.ts`), as `tsc` would.
6340
+ */
6341
+ function resolveAsTypeScript() {
6342
+ registerHooks({ resolve(specifier, context, nextResolve) {
6343
+ try {
6344
+ return nextResolve(specifier, context);
6345
+ } catch (err) {
6346
+ if (!(specifier.startsWith("./") || specifier.startsWith("../")) || !context.parentURL?.endsWith(".ts")) throw err;
6347
+ const stem = specifier.endsWith(".js") ? specifier.slice(0, -3) : specifier;
6348
+ for (const candidate of [`${stem}.ts`, `${stem}/index.ts`]) try {
6349
+ return nextResolve(candidate, context);
6350
+ } catch {}
6351
+ throw err;
6352
+ }
6353
+ } });
6354
+ }
6355
+ /** Inside the worker: load the module and its spec file, run the `TESTED` rung. */
6356
+ async function testHere(m, seed) {
6357
+ resolveAsTypeScript();
6358
+ let namespace;
6359
+ let props;
6360
+ try {
6361
+ namespace = await import(pathToFileURL(m.path).href);
6362
+ props = await import(pathToFileURL(m.specPath).href);
6363
+ } catch (err) {
6364
+ return unknownAll(m, "unavailable", `the module or its spec file did not load in Node: ${err instanceof Error ? err.message : String(err)}`);
6365
+ }
6366
+ return checkSpecModule(m.key, m.specs, props, namespace, {
6367
+ calls: [],
6368
+ unobservable: {}
6369
+ }, {
6370
+ checked: false,
6371
+ tested: { seed }
6372
+ });
6373
+ }
6374
+ const input = isMainThread ? void 0 : workerData;
6375
+ if (input?.kind === "eutaxy-report-module" && input.module && input.seed !== void 0) parentPort?.postMessage(await testHere(input.module, input.seed));
6376
+ /**
6377
+ * One module's verdicts at the `TESTED` rung, from a worker thread. What
6378
+ * the module writes goes to `stderr`; a module that does not load, or does
6379
+ * not finish within the budget, leaves each property `UNKNOWN`.
6380
+ */
6381
+ function testModule(m, seed, budgetMs, stderr) {
6382
+ return new Promise((done) => {
6383
+ const worker = new Worker(new URL(import.meta.url), {
6384
+ workerData: {
6385
+ kind: "eutaxy-report-module",
6386
+ module: m,
6387
+ seed
6388
+ },
6389
+ stdout: true,
6390
+ stderr: true
6391
+ });
6392
+ worker.stdout.on("data", (d) => stderr(d.toString()));
6393
+ worker.stderr.on("data", (d) => stderr(d.toString()));
6394
+ let settled = false;
6395
+ const finish = (verdicts) => {
6396
+ if (settled) return;
6397
+ settled = true;
6398
+ clearTimeout(timer);
6399
+ worker.terminate();
6400
+ done(verdicts);
6401
+ };
6402
+ const timer = setTimeout(() => finish(unknownAll(m, "gave_up", `the module's properties did not finish within ${budgetMs} ms on generated inputs (one may never return)`)), budgetMs);
6403
+ worker.once("message", (verdicts) => finish(verdicts));
6404
+ worker.once("error", (err) => finish(unknownAll(m, "unavailable", `the module's worker failed: ${err.message}`)));
6405
+ worker.once("exit", (code) => finish(unknownAll(m, "unavailable", `the module's worker exited (${code}) before reporting`)));
6406
+ });
6407
+ }
6408
+ async function runReport(o) {
6409
+ const root = resolve(o.cwd, o.dir ?? ".");
6410
+ let engines = [];
6411
+ if (o.provers && o.provers.length > 0) {
6412
+ const named = enginesNamed(o.provers);
6413
+ if ("error" in named) {
6414
+ o.stderr(`${named.error}\n`);
6415
+ return exitCodes.error;
6416
+ }
6417
+ engines = named.engines;
6418
+ }
6419
+ let modules;
6420
+ try {
6421
+ modules = findSpecModules(root);
6422
+ } catch (err) {
6423
+ o.stderr(`cannot read ${root}: ${err instanceof Error ? err.message : String(err)}\n`);
6424
+ return exitCodes.error;
6425
+ }
6426
+ if (modules.length === 0) {
6427
+ o.stderr(`no spec files (*.props.ts) under ${root}\n`);
6428
+ return exitCodes.error;
6429
+ }
6430
+ const errors = modules.flatMap((m) => m.specs.errors.map((e) => `${m.key}${e.line > 0 ? `:${e.line}` : ""}: ${e.message}`));
6431
+ if (errors.length > 0) {
6432
+ for (const e of errors) o.stderr(`${e}\n`);
6433
+ return exitCodes.error;
6434
+ }
6435
+ let specs = [];
6436
+ for (const m of modules) specs = [...specs, ...await testModule(m, o.seed ?? "report", o.moduleBudgetMs ?? 6e4, o.stderr)];
6437
+ if (engines.length > 0) specs = await proveSpecs(root, modules.map((m) => ({
6438
+ module: m.key,
6439
+ functions: m.specs.functions.map((f) => f.name)
6440
+ })), specs, engines, modules);
6441
+ o.stdout(`${o.json ? renderSpecReportJson(specs) : renderSpecReport(specs)}\n`);
6442
+ return specs.some((v) => v.kind === "REFUTED" || v.kind === "CONFLICT") ? exitCodes.VIOLATED : exitCodes.BOUNDED;
6443
+ }
5197
6444
  // packages/cli/src/main.ts
5198
- const usage = `eutaxy — deterministic simulation checks for Cloudflare Workers
6445
+ const usage = `eutaxy — deterministic simulation checks and spec verdicts for Cloudflare Workers
5199
6446
 
5200
6447
  Usage:
5201
6448
  eutaxy check <scenario.sim.ts> [options]
6449
+ eutaxy report [dir] [--prover <names>] [--seed <seed>] [--json]
5202
6450
 
5203
- Options:
6451
+ check options:
5204
6452
  --wrangler <path> wrangler config (default: wrangler.jsonc/json/toml beside the scenario)
5205
6453
  --seed <seed> exploration seed (default: the scenario file name)
5206
6454
  --max-runs <n> cap on exploration runs in addition to the scenario's time budget
5207
6455
  --budget-ms <n> replace the scenario's time budget (with --max-runs, the run cap decides)
5208
6456
  --exhaustive run every schedule within the bounds once (with partial-order reduction)
5209
6457
  --prover <names> also run the PROVEN rung with these engines on the scenario's specs
5210
- (comma-separated; known: lean)
6458
+ (comma-separated; known: lean, smt)
5211
6459
  --json print the versioned JSON report instead of text
5212
6460
  --out <path> where to write the regression test on a violation
5213
6461
  --no-regression do not write a regression test
5214
6462
  --expect-violation write a regression test that asserts the violation (for corpora)
5215
6463
  --keep keep the generated .eutaxy/ files
5216
6464
 
6465
+ report runs every spec file (*.props.ts) under dir (default: the current directory)
6466
+ through the TESTED rung, on inputs drawn from the parameter types with the seed
6467
+ (default: report), and the PROVEN rung with --prover. No scenario runs, so nothing
6468
+ is CHECKED.
6469
+
5217
6470
  Exit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED or CONFLICT spec, 2 UNSUPPORTED, 3 error.
6471
+ report: 0, or 1 for a REFUTED or CONFLICT spec, 3 error.
5218
6472
  `;
5219
6473
  async function main(argv, io) {
5220
6474
  const { positionals, flags } = parseArgs(argv, [
@@ -5230,6 +6484,44 @@ async function main(argv, io) {
5230
6484
  io.stdout(usage);
5231
6485
  return command ? exitCodes.BOUNDED : exitCodes.error;
5232
6486
  }
6487
+ for (const k of [
6488
+ "wrangler",
6489
+ "seed",
6490
+ "max-runs",
6491
+ "budget-ms",
6492
+ "prover",
6493
+ "out"
6494
+ ]) if (flags[k] === true) {
6495
+ io.stderr(`--${k} needs a value\n`);
6496
+ return exitCodes.error;
6497
+ }
6498
+ const str = (k) => typeof flags[k] === "string" ? flags[k] : void 0;
6499
+ const provers = (str("prover") ?? "").split(",").map((n) => n.trim()).filter((n) => n.length > 0);
6500
+ if (command === "report") {
6501
+ if (positionals.length > 2) {
6502
+ io.stderr(`report takes one directory\n\n${usage}`);
6503
+ return exitCodes.error;
6504
+ }
6505
+ const other = Object.keys(flags).find((k) => ![
6506
+ "prover",
6507
+ "seed",
6508
+ "json"
6509
+ ].includes(k));
6510
+ if (other !== void 0) {
6511
+ io.stderr(`report does not take --${other}\n`);
6512
+ return exitCodes.error;
6513
+ }
6514
+ const dir = positionals[1];
6515
+ return runReport({
6516
+ cwd: io.cwd,
6517
+ ...dir === void 0 ? {} : { dir },
6518
+ ...provers.length > 0 ? { provers } : {},
6519
+ ...str("seed") ? { seed: str("seed") } : {},
6520
+ json: flags["json"] === true,
6521
+ stdout: io.stdout,
6522
+ stderr: io.stderr
6523
+ });
6524
+ }
5233
6525
  if (command !== "check") {
5234
6526
  io.stderr(`unknown command ${command}\n\n${usage}`);
5235
6527
  return exitCodes.error;
@@ -5239,7 +6531,6 @@ async function main(argv, io) {
5239
6531
  io.stderr(`check needs a scenario file\n\n${usage}`);
5240
6532
  return exitCodes.error;
5241
6533
  }
5242
- const str = (k) => typeof flags[k] === "string" ? flags[k] : void 0;
5243
6534
  const maxRunsText = str("max-runs");
5244
6535
  const maxRuns = maxRunsText === void 0 ? void 0 : Number(maxRunsText);
5245
6536
  if (maxRuns !== void 0 && !(Number.isInteger(maxRuns) && maxRuns > 0)) {
@@ -5252,7 +6543,6 @@ async function main(argv, io) {
5252
6543
  io.stderr(`--budget-ms must be a positive integer, got ${JSON.stringify(budgetText)}\n`);
5253
6544
  return exitCodes.error;
5254
6545
  }
5255
- const provers = (str("prover") ?? "").split(",").map((n) => n.trim()).filter((n) => n.length > 0);
5256
6546
  return runCheck({
5257
6547
  scenario,
5258
6548
  cwd: io.cwd,
@@ -8228,4 +9518,4 @@ async function checkInWorkerd(input) {
8228
9518
  }
8229
9519
  export { snapshotD1 as A, r2Rows as C, workflow as D, unique as E, expectHolds as M, main as N, workflowRows as O, cloudflareRegressionTest as P, r2Op as S, refines as T, httpResponse as _, d1Param as a, queueAck as b, d1Schema as c, durableObject as d, durableObjectRows as f, http as g, fetchCall as h, atLeastOncePerMessage as i, check as j, workflowStep as k, d1Write as l, external as m, runDifferential as n, d1Read as o, everyRow as p, createCloudflarePlatform as r, d1Rows as s, checkInWorkerd as t, defineScenario as u, implies as v, references as w, r2Bucket as x, queue as y };
8230
9520
 
8231
- //# sourceMappingURL=src-CMoBPQuE.mjs.map
9521
+ //# sourceMappingURL=src-B9L96rZW.mjs.map