gdp-wired 0.43.0 → 0.45.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.
Files changed (79) hide show
  1. package/README.md +8 -3
  2. package/dist/core/c/reader.js +22 -7
  3. package/dist/core/check.js +3 -2
  4. package/dist/core/cli.d.ts +7 -0
  5. package/dist/core/cli.js +184 -12
  6. package/dist/core/counts.d.ts +1 -1
  7. package/dist/core/counts.js +30 -12
  8. package/dist/core/data.d.ts +6 -1
  9. package/dist/core/data.js +894 -152
  10. package/dist/core/dsl.d.ts +2 -0
  11. package/dist/core/dsl.js +88 -10
  12. package/dist/core/effect-prims.d.ts +60 -0
  13. package/dist/core/effect-prims.js +625 -0
  14. package/dist/core/effect.d.ts +17 -1
  15. package/dist/core/effect.js +108 -4
  16. package/dist/core/ex/harness.exs +2 -0
  17. package/dist/core/ex/reader.exs +17 -1
  18. package/dist/core/exists.d.ts +15 -1
  19. package/dist/core/exists.js +263 -41
  20. package/dist/core/extract-c.d.ts +2 -0
  21. package/dist/core/extract-c.js +22 -13
  22. package/dist/core/extract-check.d.ts +7 -0
  23. package/dist/core/extract-check.js +57 -4
  24. package/dist/core/extract-ex.js +5 -5
  25. package/dist/core/extract-go-check.js +22 -17
  26. package/dist/core/extract-go.d.ts +3 -0
  27. package/dist/core/extract-go.js +24 -9
  28. package/dist/core/extract-jvm.js +68 -16
  29. package/dist/core/extract-print.js +3 -0
  30. package/dist/core/extract-py.js +5 -5
  31. package/dist/core/extract-rb.js +5 -5
  32. package/dist/core/extract-read.d.ts +8 -0
  33. package/dist/core/extract-read.js +55 -0
  34. package/dist/core/extract-rs.js +28 -25
  35. package/dist/core/extract-shapes.js +20 -0
  36. package/dist/core/extract-sol.js +23 -12
  37. package/dist/core/extract-step.d.ts +59 -3
  38. package/dist/core/extract-step.js +334 -64
  39. package/dist/core/extract-swift.js +22 -15
  40. package/dist/core/extract.d.ts +1 -0
  41. package/dist/core/extract.js +27 -2
  42. package/dist/core/fresh.d.ts +2 -2
  43. package/dist/core/fresh.js +7 -3
  44. package/dist/core/go/reader.go +7 -1
  45. package/dist/core/infer.js +113 -40
  46. package/dist/core/jvm/Harness.java +8 -1
  47. package/dist/core/jvm/JavaReader.java +10 -2
  48. package/dist/core/jvm/Jvm.java +18 -2
  49. package/dist/core/jvm/KtReader.java +60 -5
  50. package/dist/core/machine.d.ts +2 -0
  51. package/dist/core/machine.js +32 -6
  52. package/dist/core/py/harness.py +128 -24
  53. package/dist/core/py/reader.py +50 -5
  54. package/dist/core/rb/reader.rb +52 -5
  55. package/dist/core/rs/src/main.rs +10 -0
  56. package/dist/core/sol/Replay.sol +52 -0
  57. package/dist/core/sol/harness.py +511 -0
  58. package/dist/core/solver.js +5 -4
  59. package/dist/core/system.d.ts +62 -1
  60. package/dist/core/system.js +274 -6
  61. package/dist/core/transfer.js +17 -0
  62. package/dist/core/watch.js +1 -1
  63. package/dist/interchange/check.d.ts +18 -1
  64. package/dist/interchange/check.js +19 -12
  65. package/dist/interchange/cli.d.ts +2 -0
  66. package/dist/interchange/cli.js +45 -0
  67. package/dist/interchange/format.d.ts +5 -1
  68. package/dist/interchange/format.js +25 -9
  69. package/dist/kernel/cdcl.js +65 -14
  70. package/dist/kernel/epr.js +35 -5
  71. package/dist/kernel/kernel.d.ts +2 -0
  72. package/dist/kernel/kernel.js +67 -40
  73. package/dist/kernel/prove.d.ts +22 -0
  74. package/dist/kernel/prove.js +156 -7
  75. package/dist/kernel/reader.js +3 -2
  76. package/dist/lean-kernel/emit.d.ts +9 -3
  77. package/dist/lean-kernel/emit.js +170 -29
  78. package/dist/lean-kernel/library.js +1 -1
  79. package/package.json +12 -3
package/dist/core/data.js CHANGED
@@ -26,7 +26,7 @@
26
26
  // using the others at the fields of their datatypes (mutual induction). Lemmas the law needs are found by the values
27
27
  // (theory exploration: equations between terms the random values agree on, then the shapes of a predicate kept), proven
28
28
  // the same way at lower levels, and used at the terms of the law they match.
29
- import { argsKey, atMost as leC, get, n as k, same as eqC, walk, x as ev } from "./machine.js";
29
+ import { argsKey, atMost as leC, get, n as k, same as eqC, walk, x as ev, lcg } from "./machine.js";
30
30
  import { substC, substE } from "../kernel/kernel.js";
31
31
  import { and as andC, implies, proveCyclic } from "./cyclic.js";
32
32
  import { clock, counted, pairedKeys, withDeadline } from "../kernel/prove.js";
@@ -192,6 +192,15 @@ export class Data {
192
192
  if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name))
193
193
  throw new Error(`${name}: a datatype's name is letters and digits`);
194
194
  const all = Object.entries(decl).map(([c, fs]) => ({ name: c, fields: Object.entries(fs).map(([f, s]) => ({ name: f, sort: s })) }));
195
+ // (a constructor is a member of its datatype, D.c, and its map D.c beside D.tag and D.size: none of the datatype's own
196
+ // members, constructor or toString included, nor tag or size; each name letters and digits, so no map is another's)
197
+ for (const c of all) {
198
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(c.name) || c.name in this || ['ctors', 'tag', 'size'].includes(c.name))
199
+ throw new Error(`${name}.${c.name}: a constructor's name is letters and digits, and none of a datatype's own (tag, size, ${['name', 'make', 'constructor'].join(', ')}, ...)`);
200
+ for (const f of c.fields)
201
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(f.name))
202
+ throw new Error(`${name}.${c.name}.${f.name}: a field's name is letters and digits`);
203
+ }
195
204
  for (const c of all)
196
205
  for (const f of c.fields)
197
206
  if (isDataField(f.sort) && !group.includes(f.sort.data) && !declared.has(f.sort.data))
@@ -303,6 +312,11 @@ export function define(name, params, ret, body, opts = {}) {
303
312
  if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name))
304
313
  throw new Error(`${name}: a function's name is letters and digits`);
305
314
  const ps = Object.entries(params).map(([n, s]) => ({ name: n, sort: s }));
315
+ // (a parameter is read as f.p, a match's binding as field#k, a value as f#value or f#r0: a name of letters and digits is
316
+ // none of them)
317
+ for (const q of ps)
318
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(q.name))
319
+ throw new Error(`${name}(${q.name}): a parameter's name is letters and digits`);
306
320
  const stated = opts.measure && measureOf(name, ps, opts.measure);
307
321
  let built, rec, failed;
308
322
  // The recursion, checked once (a refusal kept and given again).
@@ -337,7 +351,11 @@ export function define(name, params, ret, body, opts = {}) {
337
351
  return Object.assign(call, { fn });
338
352
  }
339
353
  // An uninterpreted function of a natural (a law about every f): `const f = fnParam('f')`, `f(x)`.
340
- export const fnParam = (name) => Object.assign((x) => new Nat({ op: 'apply', param: name, arg: natX(x) }), { param: name });
354
+ export const fnParam = (name) => {
355
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name))
356
+ throw new Error(`${name}: a function parameter's name is letters and digits`);
357
+ return Object.assign((x) => new Nat({ op: 'apply', param: name, arg: natX(x) }), { param: name });
358
+ };
341
359
  const paramsIn = (t) => { const out = []; walk(t, o => { if (o.op === 'apply')
342
360
  out.push(o.param); }); return out; };
343
361
  // Each object once, in walk's order (a term shared within another is visited where walk first reaches it).
@@ -436,14 +454,15 @@ function recursion(fn) {
436
454
  if (!got) {
437
455
  const why = `${fn.name}: not structural recursion (no parameter whose field every recursive call passes${members.length > 1 ? `, in its ring ${names.join(', ')}` : ''}${members.some(f => f.stated) ? '; a measure is given' : ''})`;
438
456
  // (each of the ring given its own measure and proofs: Data.lean's wf_fix_unique_ring)
439
- const ts = termination(members, why);
457
+ const ts = terminationKept(members, why);
440
458
  members.forEach((f, a) => { f.rec = { ring: names, measure: ts[a].measure, termination: ts[a] }; });
441
459
  return { ring: names, measure: ts[0].measure, termination: ts[0] };
442
460
  }
443
461
  members.forEach((f, a) => { f.rec = { decreases: got[a], ring: names }; });
444
462
  return { decreases: got[0], ring: names };
445
463
  }
446
- export const terminationMs = { ms: 10_000 };
464
+ export const terminationMs = { ms: 10_000 }, guardedMs = { ms: 12_000 };
465
+ const guardedLeft = { ms: 0 };
447
466
  // (an integer's size is its value where it is positive, 0 below: Lean's Int.toNat; a measure that reads one is read in
448
467
  // the integers, its value the same, compare/chc-adt's naturals written as Int)
449
468
  const measurable = (s) => s === 'nat' || s === 'int' || s instanceof Data;
@@ -512,7 +531,7 @@ const padded = (ring, ms) => {
512
531
  };
513
532
  const ringText = (ring, ms) => (ring.length === 1 ? showMeasure(ring[0], ms[0]) : ring.map((f, i) => `${f.name} ${showMeasure(f, ms[i])}`).join(', '));
514
533
  const callSites = (ring) => ring.flatMap((f, from) => sitesOf(f, ring.map(g => g.name)).map(s => ({ ...s, from })));
515
- function sitesOf(fn, names) {
534
+ function sitesOf(fn, names, leaves = []) {
516
535
  const out = [], yesX = { op: 'bool', c: yes.y };
517
536
  const at = (sh, name) => { let t = sh.get(name); while (t && t.op === 'var' && sh.has(t.name))
518
537
  t = sh.get(t.name); return t; };
@@ -550,7 +569,12 @@ function sitesOf(fn, names) {
550
569
  return;
551
570
  }
552
571
  };
553
- const goX = (x, w) => {
572
+ const goX = (x, w0) => {
573
+ // (off the body's spine, a leaf: its value, on its path)
574
+ const branch = x.op === 'if' || x.op === 'match' || x.op === 'natmatch';
575
+ if (w0.spine && !branch)
576
+ leaves.push({ value: x, wrap: w0.wrap, shape: w0.shape, vars: w0.vars });
577
+ const w = w0.spine && !branch ? { ...w0, spine: false } : w0, off = { ...w, spine: false };
554
578
  switch (x.op) {
555
579
  case 'var':
556
580
  case 'nat': return;
@@ -590,15 +614,15 @@ function sitesOf(fn, names) {
590
614
  case 'call':
591
615
  x.args.forEach(a => goX(a, w));
592
616
  if (names.includes(x.fn))
593
- out.push({ to: names.indexOf(x.fn), args: x.args, ...w });
617
+ out.push({ to: names.indexOf(x.fn), args: x.args, wrap: w.wrap, shape: w.shape, vars: w.vars });
594
618
  return;
595
619
  case 'if':
596
- goY(x.c, w);
620
+ goY(x.c, off);
597
621
  goX(x.then, { ...w, wrap: y => w.wrap({ op: 'or', xs: [{ op: 'not', x: x.c }, y] }) });
598
622
  goX(x.else, { ...w, wrap: y => w.wrap({ op: 'or', xs: [x.c, y] }) });
599
623
  return;
600
624
  case 'match': {
601
- goX(x.of, w);
625
+ goX(x.of, off);
602
626
  const d = dataNamed(x.data), v = x.of.op === 'var' ? x.of.name : undefined, had = v ? at(w.shape, v) : undefined;
603
627
  x.cases.forEach((c, j) => {
604
628
  if (v && had?.op === 'ctor') {
@@ -609,7 +633,7 @@ function sitesOf(fn, names) {
609
633
  }
610
634
  if (v && !had) {
611
635
  const fields = c.binds.map((b, i) => ({ name: b, sort: fieldSort(d.ctors[j].fields[i]) }));
612
- goX(c.body, { wrap: w.wrap, shape: new Map([...w.shape, [v, { op: 'ctor', data: x.data, ctor: j, args: c.binds.map(b => ({ op: 'var', name: b })) }]]), vars: [...w.vars, ...fields] });
636
+ goX(c.body, { wrap: w.wrap, shape: new Map([...w.shape, [v, { op: 'ctor', data: x.data, ctor: j, args: c.binds.map(b => ({ op: 'var', name: b })) }]]), vars: [...w.vars, ...fields], spine: w.spine });
613
637
  return;
614
638
  }
615
639
  goX(c.body, { ...w, wrap: y => w.wrap({ op: 'holds', x: { op: 'match', data: x.data, of: x.of, cases: x.cases.map((c2, i) => ({ binds: c2.binds, body: i === j ? { op: 'bool', c: y } : yesX })) } }) });
@@ -617,11 +641,11 @@ function sitesOf(fn, names) {
617
641
  return;
618
642
  }
619
643
  case 'natmatch': {
620
- goX(x.of, w);
644
+ goX(x.of, off);
621
645
  const v = x.of.op === 'var' ? x.of.name : undefined;
622
646
  if (v && !at(w.shape, v)) {
623
647
  goX(x.zero, { ...w, shape: new Map([...w.shape, [v, { op: 'nat', value: 0 }]]) });
624
- goX(x.succ, { wrap: w.wrap, shape: new Map([...w.shape, [v, { op: 'add', a: { op: 'var', name: x.pred }, b: { op: 'nat', value: 1 } }]]), vars: [...w.vars, { name: x.pred, sort: 'nat' }] });
648
+ goX(x.succ, { wrap: w.wrap, shape: new Map([...w.shape, [v, { op: 'add', a: { op: 'var', name: x.pred }, b: { op: 'nat', value: 1 } }]]), vars: [...w.vars, { name: x.pred, sort: 'nat' }], spine: w.spine });
625
649
  return;
626
650
  }
627
651
  goX(x.zero, { ...w, wrap: y => w.wrap({ op: 'holds', x: { op: 'natmatch', of: x.of, zero: { op: 'bool', c: y }, pred: x.pred, succ: yesX } }) });
@@ -630,7 +654,7 @@ function sitesOf(fn, names) {
630
654
  }
631
655
  }
632
656
  };
633
- goX(fn.body(), { wrap: y => y, shape: new Map(), vars: fn.params.map(q => ({ name: `${fn.name}.${q.name}`, sort: q.sort })) });
657
+ goX(fn.body(), { wrap: y => y, shape: new Map(), vars: fn.params.map(q => ({ name: `${fn.name}.${q.name}`, sort: q.sort })), spine: true });
634
658
  return out;
635
659
  }
636
660
  // A term (or a law) with the site's shape put in: each matched variable its constructor's value.
@@ -639,15 +663,100 @@ const shapedBy = (s) => {
639
663
  return go;
640
664
  };
641
665
  const ownArgs = (f) => f.params.map(q => ({ op: 'var', name: `${f.name}.${q.name}` }));
666
+ // The decrease a call makes: the callee's measure at its arguments below the caller's at its parameters (`own`),
667
+ // lexicographically (Data.lean's `lexLt`).
668
+ function lowerY(ring, ms, from, to, args, own) {
669
+ const fn = ring[from], g = ring[to];
670
+ const ints = ms[to].comps.map((c, j) => readsInt(g, c) || readsInt(fn, ms[from].comps[j]));
671
+ return lexY(ms[to].comps.map(c => measureX(g, c, args)), ms[from].comps.map(c => measureX(fn, c, own)), ints);
672
+ }
642
673
  // The obligation of a call: under its path, the callee's measure at its arguments below the caller's at its parameters,
643
- // a law over the path's variables (the parameters not matched, the fields of the cases taken). `i`: the call's place
644
- // among its caller's.
645
- function obligation(ring, ms, s, i) {
646
- const fn = ring[s.from], to = ring[s.to];
647
- const ints = ms[s.to].comps.map((c, j) => readsInt(to, c) || readsInt(fn, ms[s.from].comps[j]));
648
- const holds = shapedBy(s)(s.wrap(lexY(ms[s.to].comps.map(c => measureX(to, c, s.args)), ms[s.from].comps.map(c => measureX(fn, c, ownArgs(fn))), ints)));
674
+ // a law over the path's variables (the parameters not matched, the fields of the cases taken), each call of the ring in
675
+ // it read as a value (`lifted`). `i`: the call's place among its caller's.
676
+ function obligation(ring, ms, s, i, inv) {
677
+ const fn = ring[s.from], to = ring[s.to], shaped = shapedBy(s), vars = s.vars.filter(v => !s.shape.has(v.name));
678
+ const holds = lifted(ring, ms, inv, s.from, shaped(ownArgs(fn)), shaped(s.wrap(lowerY(ring, ms, s.from, s.to, s.args, ownArgs(fn)))), vars);
649
679
  const name = ring.length === 1 ? `${fn.name}'s call ${i + 1} lowers ${showMeasure(fn, ms[0])}` : `${fn.name}'s call ${i + 1}, of ${to.name}, lowers ${showMeasure(to, ms[s.to])} below ${showMeasure(fn, ms[s.from])}`;
650
- return { name, vars: s.vars.filter(v => !s.shape.has(v.name)), holds, params: [...new Set(paramsIn(holds))] };
680
+ return { name, vars, holds, params: [...new Set(paramsIn(holds))] };
681
+ }
682
+ // A function's value, in its invariant.
683
+ export const valueVar = (f) => `${f.name}#value`;
684
+ // An invariant at arguments and a value: its parameters and value put in at once.
685
+ function invAt(f, y, args, r) {
686
+ const m = new Map([...f.params.map((q, i) => [`${f.name}.${q.name}`, args[i]]), [valueVar(f), r]]);
687
+ const go = (t) => (Array.isArray(t) ? t.map(go) : t && typeof t === 'object' ? (t.op === 'var' && m.has(t.name) ? m.get(t.name) : Object.fromEntries(Object.entries(t).map(([key, v]) => [key, go(v)]))) : t);
688
+ return go(y);
689
+ }
690
+ // An invariant reads its function's parameters and value alone, binds nothing (no match) and calls no function of the
691
+ // ring: each instance of it is then the same law at those values.
692
+ function checkInv(ring, inv) {
693
+ ring.forEach((f, i) => {
694
+ const y = inv[i];
695
+ if (!y)
696
+ return;
697
+ const own = new Set([...f.params.map(q => `${f.name}.${q.name}`), valueVar(f)]);
698
+ walk(y, o => {
699
+ if ((o.op === 'var' && !own.has(o.name)) || o.op === 'match' || o.op === 'natmatch' || o.op === 'apply' || (o.op === 'call' && ring.some(g => g.name === o.fn)))
700
+ throw new Error(`${f.name}: an invariant reads its parameters and value alone`);
701
+ });
702
+ });
703
+ }
704
+ // Each call of the ring in a law read as a value: a new variable (pushed on `vars`) under its hypothesis, put at the
705
+ // law's top, or at the condition (`bool`) of the case of a match that encloses the call (where the case's fields are
706
+ // bound), one variable for a call written twice at one place. A call under a case with no condition between (no place for
707
+ // its hypothesis where its fields are bound) is refused. `own`: the caller's parameters, as the law reads them.
708
+ function lifted(ring, ms, inv, from, own, y, vars) {
709
+ const names = ring.map(f => f.name), taken = new Set();
710
+ walk([y, own], o => { if (o.op === 'var')
711
+ taken.add(o.name); });
712
+ const level = (z) => {
713
+ const hyps = [], seen = new Map();
714
+ const go = (t, bound) => {
715
+ if (Array.isArray(t))
716
+ return t.map(u => go(u, bound));
717
+ if (!t || typeof t !== 'object')
718
+ return t;
719
+ const o = t;
720
+ if (o.op === 'bool')
721
+ return { op: 'bool', c: level(o.c) };
722
+ if (o.op === 'match')
723
+ return { ...o, of: go(o.of, bound), cases: o.cases.map(c => ({ binds: c.binds, body: go(c.body, true) })) };
724
+ if (o.op === 'natmatch')
725
+ return { ...o, of: go(o.of, bound), zero: go(o.zero, true), succ: go(o.succ, true) };
726
+ if (o.op === 'call' && names.includes(o.fn)) {
727
+ if (bound)
728
+ throw new NestedRefusal(`a call to ${ring.length > 1 ? 'its ring' : 'itself'} is nested in a case of a match within another's argument or condition (nested recursion isn't taken there)`);
729
+ const to = names.indexOf(o.fn), args = o.args.map(a => go(a, false)), key = JSON.stringify([o.fn, args]);
730
+ let r = seen.get(key);
731
+ if (!r) {
732
+ const v = { name: `${ring[from].name}#r${vars.length}`, sort: ring[to].ret };
733
+ // (a name no variable of the law has: the function's name is letters and digits, a field's binding ends in digits)
734
+ if (vars.some(w => w.name === v.name) || taken.has(v.name))
735
+ throw new Error(`${v.name}: a variable of the law already`);
736
+ vars.push(v);
737
+ r = { op: 'var', name: v.name };
738
+ seen.set(key, r);
739
+ const i = inv[to];
740
+ if (i)
741
+ hyps.push({ op: 'or', xs: [{ op: 'not', x: lowerY(ring, ms, from, to, args, own) }, invAt(ring[to], i, args, r)] });
742
+ }
743
+ return r;
744
+ }
745
+ return Object.fromEntries(Object.entries(o).map(([key, v]) => [key, go(v, bound)]));
746
+ };
747
+ const body = go(z, false);
748
+ return hyps.length ? { op: 'or', xs: [...hyps.map(h => ({ op: 'not', x: h })), body] } : body;
749
+ };
750
+ return level(y);
751
+ }
752
+ class NestedRefusal extends Error {
753
+ }
754
+ // A value the body ends at keeps its function's invariant: under the leaf's path, the invariant at the parameters and the
755
+ // leaf's value, each call of the ring in it read as a value. `i`: the leaf's place among its function's.
756
+ function keeps(ring, ms, inv, from, l, i) {
757
+ const fn = ring[from], shaped = shapedBy(l), vars = l.vars.filter(v => !l.shape.has(v.name));
758
+ const holds = lifted(ring, ms, inv, from, shaped(ownArgs(fn)), shaped(l.wrap(invAt(fn, inv[from], ownArgs(fn), l.value))), vars);
759
+ return { name: `${fn.name}'s value ${i + 1} keeps ${showY(inv[from])}`, vars, holds, params: [...new Set(paramsIn(holds))] };
651
760
  }
652
761
  let tracing;
653
762
  const featOf = (f, vs) => f.params.map((p, i) => sizeOfValue(p.sort, vs[i]));
@@ -721,7 +830,8 @@ const pathSamples = (vars, params, cond, n = 240, seed = 19) => {
721
830
  // Size laws about the functions a law reads (not the ring's): for each, S(g(y…)) + a ≤ Σ S(yᵢ) + b over one or two of
722
831
  // its arguments, the bound the values give (an equation where they give one difference), 2·g(n) ≤ n + b for a natural
723
832
  // of one natural, those its values refute dropped; each a lemma for proveData to prove by induction and use.
724
- function sizeLaws(l, ring) {
833
+ // `lower`: where the values give an equation, its lower half too (a guard at a call reads it: 3 items on, the length is 3).
834
+ function sizeLaws(l, ring, lower = false) {
725
835
  const seen = new Set(), helpers = [];
726
836
  walk(l.holds, o => { if (o.op === 'call' && !ring.includes(o.fn) && !seen.has(o.fn)) {
727
837
  seen.add(o.fn);
@@ -729,25 +839,325 @@ function sizeLaws(l, ring) {
729
839
  if (sized(g.ret))
730
840
  helpers.push(g);
731
841
  } });
732
- const out = [];
842
+ const out = [], rings = new Set();
733
843
  const nat = (n) => ({ op: 'nat', value: n }), add = (a, b) => (b.op === 'nat' && b.value === 0 ? a : { op: 'add', a, b });
734
- for (const g of helpers.slice(0, 4)) {
735
- const vars = g.params.map((q, i) => ({ name: `${q.name}${i}`, sort: q.sort }));
736
- if (!vars.some(v => sized(v.sort)))
737
- continue;
844
+ // (a function of one value that halves it, evens or odds of a list, half of a natural: twice its size is bounded too)
845
+ const boundsOf = (g, vars) => {
738
846
  const call = { op: 'call', fn: g.name, args: vars.map(v => ({ op: 'var', name: v.name })) }, envs = samples(vars, [], 160, 23);
739
- const twice = g.ret === 'nat' && vars.length === 1 && vars[0].sort === 'nat' ? upperBounds(sizeBounds(call, g.ret, vars, envs, 2), 1).filter(b => b.lo !== b.hi) : [];
740
- for (const b of [...upperBounds(sizeBounds(call, g.ret, vars, envs)), ...twice].filter(b => b.of.every(i => sized(vars[i].sort)))) {
847
+ const twice = vars.length === 1 && sized(vars[0].sort) ? upperBounds(sizeBounds(call, g.ret, vars, envs, 2), 1).filter(b => b.lo !== b.hi) : [];
848
+ // (twice the size's first: it implies the plain bound where it holds, and a halving's decrease reads it alone)
849
+ return [...twice, ...upperBounds(sizeBounds(call, g.ret, vars, envs))].filter(b => b.of.every(i => sized(vars[i].sort))).flatMap((b) => {
741
850
  const lhs0 = b.coef === 1 ? sizeX(g.ret, call) : { op: 'mul', k: b.coef, a: sizeX(g.ret, call) };
742
851
  const sum = b.of.map(i => sizeX(vars[i].sort, { op: 'var', name: vars[i].name })).reduce((a, c) => ({ op: 'add', a, b: c }));
852
+ // (an upper bound is what a decrease reads: an equation's other half is a proof's cost for nothing, but where a
853
+ // guard at a call reads it, `lower`)
743
854
  const lhs = add(lhs0, nat(Math.max(0, -b.hi))), rhs = add(sum, nat(Math.max(0, b.hi)));
744
- // (an upper bound is what a decrease reads: an equation's other half is a proof's cost for nothing)
745
- const holds = { op: '<=', a: lhs, b: rhs };
855
+ return [{ op: '<=', a: lhs, b: rhs }, ...(lower && b.lo === b.hi ? [{ op: '<=', a: rhs, b: lhs }] : [])];
856
+ });
857
+ };
858
+ for (const g of helpers.slice(0, 4)) {
859
+ const vars = g.params.map((q, i) => ({ name: `${q.name}${i}`, sort: q.sort }));
860
+ if (!vars.some(v => sized(v.sort)))
861
+ continue;
862
+ // Functions that call each other over the same parameters (evens and odds): their bounds at once, one law, each
863
+ // bound the induction step of another's (evens(y :: t) = y :: odds(t)).
864
+ const ring = g.ring.length > 1 ? g.ring.map(fnOf).filter(h => sized(h.ret) && h.params.length === g.params.length && h.params.every((q, i) => q.sort === g.params[i].sort)) : [g];
865
+ if (ring.length > 1) {
866
+ if (rings.has(g.ring.join()))
867
+ continue;
868
+ rings.add(g.ring.join());
869
+ const all = ring.map(h => boundsOf(h, vars));
870
+ // (those of twice the size one law, the plain bounds another: either alone is an induction's; a halving's first)
871
+ for (const twice of [true, false]) {
872
+ const ys = all.flatMap(bs => bs.filter(b => (b.op === '<=' && JSON.stringify(b.a).includes('"op":"mul"')) === twice));
873
+ if (ys.length) {
874
+ const holds = ys.length === 1 ? ys[0] : { op: 'and', xs: ys };
875
+ out.push({ name: `size law: ${showY(holds)}`, vars, holds, params: [] });
876
+ }
877
+ }
878
+ continue;
879
+ }
880
+ for (const holds of boundsOf(g, vars))
746
881
  out.push({ name: `size law: ${showY(holds)}`, vars, holds, params: [] });
882
+ }
883
+ return out;
884
+ }
885
+ const natK = (n) => ({ op: 'nat', value: n }), plusK = (a, n) => (n ? { op: 'add', a, b: natK(n) } : a);
886
+ const allY = (ys) => (ys.length === 1 ? ys[0] : { op: 'and', xs: ys });
887
+ const atomY = (ps, a, ts) => ('size' in a ? { op: '<=', a: natK(a.c), b: sizeX(ps[a.size].sort, ts[a.size]) }
888
+ : 'diff' in a ? { op: '<=', a: plusK(sizeX(ps[a.diff[0]].sort, ts[a.diff[0]]), a.d), b: sizeX(ps[a.diff[1]].sort, ts[a.diff[1]]) }
889
+ : { op: 'holds', x: { op: 'call', fn: a.reach, args: ts } });
890
+ // For each leaf of a structural function's body that calls it no more (delete's `tail` where the item is found), the
891
+ // predicate that its run ends there: the body's choices kept, that leaf true, the others false, a leaf that recurs the
892
+ // predicate at its calls' arguments. Each is a function defined for it, structural as the function is.
893
+ const madeReaches = new Map();
894
+ function reaches(g) {
895
+ const had = madeReaches.get(g.name);
896
+ if (had)
897
+ return had;
898
+ const out = [];
899
+ madeReaches.set(g.name, out);
900
+ try {
901
+ if (g.ring.length !== 1 || g.decreases === undefined)
902
+ return out;
903
+ }
904
+ catch {
905
+ return out;
906
+ }
907
+ const leaves = [], collect = (x) => { if (x.op === 'if') {
908
+ collect(x.then);
909
+ collect(x.else);
910
+ }
911
+ else if (x.op === 'match')
912
+ x.cases.forEach(c => collect(c.body));
913
+ else if (x.op === 'natmatch') {
914
+ collect(x.zero);
915
+ collect(x.succ);
916
+ }
917
+ else
918
+ leaves.push(x); };
919
+ collect(g.body());
920
+ const recurs = (x) => { const cs = []; walk(x, o => { if (o.op === 'call' && o.fn === g.name)
921
+ cs.push(o.args); }); return cs; };
922
+ const ends = leaves.filter(x => !recurs(x).length);
923
+ if (ends.length > 4 || ends.length === leaves.length || leaves.some(x => recurs(x).some(as => as.some(a => recurs(a).length))))
924
+ return out;
925
+ // (a condition, as the surface writes one: a match's cases conditions, an if (c ∧ a) ∨ (¬c ∧ b))
926
+ for (const end of ends) {
927
+ const name = `reach_${g.name}_${ends.indexOf(end)}`;
928
+ if (fns.has(name))
929
+ continue;
930
+ const ren = new Map(g.params.map(q => [`${g.name}.${q.name}`, { op: 'var', name: `${name}.${q.name}` }]));
931
+ const go = (x) => {
932
+ if (x.op === 'if')
933
+ return { op: 'or', xs: [{ op: 'and', xs: [x.c, go(x.then)] }, { op: 'and', xs: [{ op: 'not', x: x.c }, go(x.else)] }] };
934
+ if (x.op === 'match')
935
+ return { op: 'holds', x: { ...x, cases: x.cases.map(c => ({ ...c, body: { op: 'bool', c: go(c.body) } })) } };
936
+ if (x.op === 'natmatch')
937
+ return { op: 'holds', x: { ...x, zero: { op: 'bool', c: go(x.zero) }, succ: { op: 'bool', c: go(x.succ) } } };
938
+ if (x === end)
939
+ return yes.y;
940
+ const cs = recurs(x).map(as => ({ op: 'holds', x: { op: 'call', fn: name, args: as } }));
941
+ return !cs.length ? no.y : cs.length === 1 ? cs[0] : { op: 'or', xs: cs };
942
+ };
943
+ const body = substXs({ op: 'bool', c: go(g.body()) }, ren);
944
+ define(name, Object.fromEntries(g.params.map(q => [q.name, q.sort])), boolean, () => new Bool(body.c));
945
+ out.push(name);
946
+ }
947
+ return out;
948
+ }
949
+ // A predicate's call at constructors unfolded once (delete's run on x :: xs reaches its end: m = x, or its run on xs
950
+ // does), the step a guard at a constructor's value is proven by.
951
+ function stepped(y) {
952
+ if (y.op !== 'holds' || y.x.op !== 'call' || !y.x.args.some(a => a.op === 'ctor'))
953
+ return y;
954
+ const f = fnOf(y.x.fn), args = y.x.args;
955
+ const go = (x) => (x.op === 'bool' && x.c.op === 'holds' ? go(x.c.x) : x.op === 'match' && x.of.op === 'ctor' ? go(substXs(x.cases[x.of.ctor].body, new Map(x.cases[x.of.ctor].binds.map((b, i) => [b, x.of.args[i]])))) : x.op === 'if' ? { ...x, then: go(x.then), else: go(x.else) } : x);
956
+ // (as a condition: a choice its sides' conditions under its own, a side true or false read so)
957
+ const T = JSON.stringify(yes.y), F = JSON.stringify(no.y);
958
+ const cy = (x) => {
959
+ if (x.op === 'bool')
960
+ return x.c;
961
+ if (x.op !== 'if')
962
+ return { op: 'holds', x };
963
+ const a = cy(x.then), b = cy(x.else), [ta, tb] = [JSON.stringify(a), JSON.stringify(b)];
964
+ return ta === T ? (tb === F ? x.c : { op: 'or', xs: [x.c, b] }) : ta === F ? (tb === T ? { op: 'not', x: x.c } : { op: 'and', xs: [{ op: 'not', x: x.c }, b] })
965
+ : tb === T ? { op: 'or', xs: [{ op: 'not', x: x.c }, a] } : tb === F ? { op: 'and', xs: [x.c, a] } : { op: 'or', xs: [{ op: 'and', xs: [x.c, a] }, { op: 'and', xs: [{ op: 'not', x: x.c }, b] }] };
966
+ };
967
+ return cy(go(substXs(f.body(), new Map(f.params.map((q, i) => [`${f.name}.${q.name}`, args[i]])))));
968
+ }
969
+ // `lower`: of a guard at a call, guard ⇒ c ≤ S(g(y…)), the least size the values give under it above the least without
970
+ // (from 2 on, half of a natural is at least 1).
971
+ function guardedLaws(l, s, ring, lower = false) {
972
+ const cond = shapedBy(s)(s.wrap(no.y)), site = pathSamples(l.vars, l.params, e => !evalY(cond, e.env, e.params));
973
+ if (site.length < 12)
974
+ return [];
975
+ // (a lower bound of the calls a guard bounds below: those on the larger side of a comparison)
976
+ const larger = [];
977
+ if (lower)
978
+ walk(l.holds, o => { if (o.op === '<=' || o.op === '<')
979
+ larger.push(o.b); });
980
+ // (each call at its depth among the helpers' calls: an inner call's guarded law is what an outer guard reads, so inner
981
+ // first, and only an outermost call's group is the decrease's)
982
+ const calls = new Map();
983
+ const visit = (t, depth) => {
984
+ if (!t || typeof t !== 'object')
985
+ return;
986
+ if (Array.isArray(t)) {
987
+ t.forEach(u => visit(u, depth));
988
+ return;
989
+ }
990
+ const o = t;
991
+ if (o.op === 'call' && !ring.includes(o.fn)) {
992
+ const g = fnOf(o.fn);
993
+ if (sized(g.ret) && g.params.some(q => sized(q.sort)) && !calls.has(JSON.stringify(o)))
994
+ calls.set(JSON.stringify(o), { g, args: o.args, depth });
995
+ o.args.forEach(a => visit(a, depth + 1));
996
+ return;
997
+ }
998
+ Object.values(o).forEach(v => visit(v, depth));
999
+ };
1000
+ visit(lower ? larger : l.holds, 0);
1001
+ const out = [];
1002
+ const lawOf = (name, vars, holds) => ({ name, vars, holds, params: [...new Set(paramsIn(holds))] });
1003
+ const tries = (f) => { try {
1004
+ return f();
1005
+ }
1006
+ catch {
1007
+ return false;
1008
+ } };
1009
+ for (const { g, args, depth } of [...calls.values()].slice(0, 4).sort((a, b) => b.depth - a.depth)) {
1010
+ const ix = g.params.flatMap((q, i) => (sized(q.sort) ? [i] : []));
1011
+ const sz = site.flatMap(e => { try {
1012
+ return [args.map((a, i) => (ix.includes(i) ? sizeOfValue(g.params[i].sort, evalX(a, e.env, e.params)) : 0))];
1013
+ }
1014
+ catch {
1015
+ return [];
1016
+ } });
1017
+ if (sz.length < 12)
1018
+ continue;
1019
+ const atoms = [];
1020
+ for (const i of ix) {
1021
+ const c = Math.min(...sz.map(r => r[i]));
1022
+ if (c > (g.params[i].sort === 'nat' ? 0 : 1))
1023
+ atoms.push({ size: i, c });
1024
+ }
1025
+ for (const i of ix)
1026
+ for (const j of ix) {
1027
+ const d = i === j ? 0 : Math.min(...sz.map(r => r[j] - r[i]));
1028
+ if (d >= 1)
1029
+ atoms.push({ diff: [i, j], d });
1030
+ }
1031
+ for (const p of reaches(g))
1032
+ if (site.every(e => tries(() => evalX({ op: 'call', fn: p, args }, e.env, e.params) === 1)))
1033
+ atoms.push({ reach: p });
1034
+ if (!atoms.length)
1035
+ continue;
1036
+ const vars = g.params.map((q, i) => ({ name: `${q.name}${i}`, sort: q.sort })), vs = vars.map(v => ({ op: 'var', name: v.name }));
1037
+ const call = { op: 'call', fn: g.name, args: vs }, pool = pathSamples(vars, [], () => true, 800, 29);
1038
+ const within = (as) => { const ys = allY(as.map(a => atomY(g.params, a, vs))); return pool.filter(e => tries(() => evalY(ys, e.env, e.params))); };
1039
+ const tight = (as) => sizeBounds(call, g.ret, vars, within(as));
1040
+ const least = (es) => { const ns = es.flatMap(e => { try {
1041
+ return [sizeOfValue(g.ret, evalX(call, e.env, e.params))];
1042
+ }
1043
+ catch {
1044
+ return [];
1045
+ } }); return ns.length < 12 ? -1 : Math.min(...ns); };
1046
+ const lawOfGuard = (guard, bound) => {
1047
+ const gy = allY(guard.map(a => atomY(g.params, a, vs))), at = guard.map(a => atomY(g.params, a, args)), step = at.map(stepped), shaped = shapedBy(s);
1048
+ // (the guard at the call first, its step before it, then the guarded law: a group's last is the guarded law)
1049
+ out.push({ outer: depth === 0, laws: [...(JSON.stringify(step) !== JSON.stringify(at) ? [lawOf(`${l.name}: ${showY(allY(step))}`, l.vars, shaped(s.wrap(allY(step))))] : []),
1050
+ lawOf(`${l.name}: ${showY(allY(at))}`, l.vars, shaped(s.wrap(allY(at)))),
1051
+ lawOf(`size law under ${showY(gy)}: ${showY(bound)}`, vars, { op: 'or', xs: [{ op: 'not', x: gy }, bound] })] });
1052
+ };
1053
+ if (lower) {
1054
+ const c = least(within(atoms));
1055
+ if (c <= least(pool))
1056
+ continue;
1057
+ let guard = atoms;
1058
+ for (const a of [...atoms].reverse()) {
1059
+ const fewer = guard.filter(x => x !== a);
1060
+ if (fewer.length && least(within(fewer)) >= c)
1061
+ guard = fewer;
1062
+ }
1063
+ lawOfGuard(guard, { op: '<=', a: natK(c), b: sizeX(g.ret, call) });
1064
+ continue;
1065
+ }
1066
+ const base = sizeBounds(call, g.ret, vars, pool), under = tight(atoms);
1067
+ if (!under.length || !base.length)
1068
+ continue;
1069
+ // (of the bounds a size law states without the guard, the one over the fewest arguments the guard lowers most)
1070
+ const n = under.map((_, i) => i).filter(i => base[i].hi <= 2 && under[i].hi < base[i].hi && under[i].of.every(j => sized(vars[j].sort))).sort((a, b) => under[a].of.length - under[b].of.length || (under[a].hi - base[a].hi) - (under[b].hi - base[b].hi))[0];
1071
+ if (n === undefined)
1072
+ continue;
1073
+ let guard = atoms;
1074
+ // (a reach dropped first, then a difference, then a size: the guard at the call is then a size's, by arithmetic)
1075
+ for (const a of [...atoms].reverse()) {
1076
+ const fewer = guard.filter(x => x !== a), b = fewer.length ? tight(fewer) : [];
1077
+ if (b.length && b[n].hi <= under[n].hi)
1078
+ guard = fewer;
747
1079
  }
1080
+ const hi = under[n].hi, sum = under[n].of.map(i => sizeX(vars[i].sort, vs[i])).reduce((a, c) => ({ op: 'add', a, b: c }));
1081
+ lawOfGuard(guard, { op: '<=', a: plusK(sizeX(g.ret, call), Math.max(0, -hi)), b: plusK(sum, Math.max(0, hi)) });
748
1082
  }
749
1083
  return out;
750
1084
  }
1085
+ // An obligation through lemmas proven in order, each above those before (a guarded size law reads the size law it
1086
+ // strengthens, the guard at the call its step at a constructor), in groups (the size laws, then each call's guarded law
1087
+ // and its guard), the obligation tried above them after each group, without conjectures.
1088
+ function throughLemmas(l, groups, until) {
1089
+ const p = programOf([l, ...groups.flatMap(g => g.laws)]), fs = factsOf(p), proven = [];
1090
+ const ctx = () => ({ p, fs, base: [...proven], level: Math.max(0, ...proven.flatMap(q => q.nodes.map(n => (n.rank[0]?.op === 'const' ? n.rank[0].value : 0)))) });
1091
+ const prove = (c, guardAt) => {
1092
+ // (a guard at the call: by its step and the definitions unfolded, no induction; then alone, above none of the
1093
+ // lemmas, whose instances are its proof's cost where it reads none; then above them)
1094
+ // (the lemmas' uses alone first, no definition unfolded, then at one unfolding)
1095
+ const quick = guardAt && !refute(c, 200) ? proveWith(p, fs, c, proven, ctx().level + 1, { induction: false }, Math.min(until, clock() + 1500), 1500, [0, 1]) : undefined;
1096
+ const alone = quick?.out || !guardAt ? quick : searchIn(c, { lemmas: false, samples: 200 }, Math.min(until, clock() + 1500), { ...ctx(), base: [] });
1097
+ const r = alone?.out ? alone : searchIn(c, { lemmas: false, samples: 200 }, Math.min(until, clock() + 3000), ctx());
1098
+ if (dataTrace)
1099
+ console.error(`[data] through ${c.name}: ${r.out ? 'proven' : 'not proven'}`);
1100
+ if (r.out)
1101
+ proven.push(r.out);
1102
+ return !!r.out;
1103
+ };
1104
+ const decrease = () => {
1105
+ // (first the lemmas' uses alone, no definition unfolded, then at one unfolding: the guarded law at the call and its
1106
+ // guard there are the decrease; then the search without conjectures)
1107
+ const r = proveWith(p, fs, l, proven, ctx().level + 1, { induction: false }, Math.min(until, clock() + 3000), 3000, [0, 1]);
1108
+ if (r.out && r.verdict) {
1109
+ const nodes = r.out.nodes, seen = new Set(), todo = [nodes.indexOf(r.out.spec)];
1110
+ while (todo.length) {
1111
+ const k2 = todo.pop();
1112
+ if (seen.has(k2))
1113
+ continue;
1114
+ seen.add(k2);
1115
+ for (const u of nodes[k2].uses)
1116
+ todo.push(u.node);
1117
+ }
1118
+ return { law: l.name, proven: true, checked: true, proof: r.verdict, lemmas: proven.filter(q => seen.has(nodes.findIndex(n => n.name === q.spec.name))).map(q => q.law.name), scheme: r.scheme, tried: r.tried, ms: 0 };
1119
+ }
1120
+ for (const opts of [{ lemmas: false, induction: false }, { lemmas: false }]) {
1121
+ if (clock() > until)
1122
+ return undefined;
1123
+ const v = searchIn(l, opts, Math.min(until, clock() + 4000), ctx()).verdict;
1124
+ if (v.proven && v.checked)
1125
+ return v;
1126
+ if (v.counterexample)
1127
+ return undefined;
1128
+ }
1129
+ return undefined;
1130
+ };
1131
+ // (a group's lemma not proven is tried once more after the groups after it: a guard at one call may read the guarded
1132
+ // law another's group proves, half a length below the length from 2 items on)
1133
+ const left = [];
1134
+ for (const { laws, then } of groups) {
1135
+ const failed = [];
1136
+ for (const [j, c] of laws.entries()) {
1137
+ if (clock() > until)
1138
+ return undefined;
1139
+ if (!prove(c, j < laws.length - 1))
1140
+ failed.push(c);
1141
+ }
1142
+ if (failed.length) {
1143
+ left.push({ failed, laws, then });
1144
+ continue;
1145
+ }
1146
+ if (!then || !proven.length)
1147
+ continue;
1148
+ const v = decrease();
1149
+ if (v)
1150
+ return v;
1151
+ }
1152
+ for (const { failed, laws, then } of left) {
1153
+ if (!failed.every(c => clock() < until && prove(c, laws.indexOf(c) < laws.length - 1)) || !then)
1154
+ continue;
1155
+ const v = decrease();
1156
+ if (v)
1157
+ return v;
1158
+ }
1159
+ return undefined;
1160
+ }
751
1161
  // The calls' relation (core/relation.ts's form): a location per function of the ring, its parameters' sizes the state
752
1162
  // (`s<i>_<k>`), a path per call: the caller's parameters' sizes and the callee's arguments' (`a<k>`, the turn's
753
1163
  // inputs) bounded by the sizes of the path's variables (`v<j>`) where its values give a bound (`sizeBounds`).
@@ -791,7 +1201,7 @@ function callRelation(ring, sites) {
791
1201
  }
792
1202
  function candidates(ring, edges, sites, until) {
793
1203
  if (ring.some(f => f.stated))
794
- return [ring.map(f => f.stated ?? { comps: [{ coef: f.params.map(() => 0), c: 0 }] })];
1204
+ return [padded(ring, ring.map(f => f.stated ?? { comps: [{ coef: f.params.map(() => 0), c: 0 }] }))];
795
1205
  const out = [];
796
1206
  if (ring.length === 1) {
797
1207
  const fn = ring[0], ix = fn.params.flatMap((p, i) => (measurable(p.sort) ? [i] : []));
@@ -816,16 +1226,7 @@ function candidates(ring, edges, sites, until) {
816
1226
  }
817
1227
  // The LP's rank over the runs (coefficients and constants), a node per function, where the runs give edges; for a ring,
818
1228
  // after the relation's.
819
- const fromRuns = () => {
820
- if (!edges.length)
821
- return undefined;
822
- const vars = ring.map((f, i) => f.params.flatMap((q, j) => (measurable(q.sort) ? [`p${i}_${j}`] : [])));
823
- const env = (i, xs) => Object.fromEntries(vars[i].map(x => [x, xs[Number(x.split('_')[1])]]));
824
- const r = ranksOfCalls(vars, edges.flatMap(e => [{ node: e.from, env: env(e.from, e.s) }, { node: e.to, env: env(e.to, e.t) }]), edges.map(e => ({ from: e.from, to: e.to, s: env(e.from, e.s), t: env(e.to, e.t) })));
825
- if (r.left || !r.comps.length)
826
- return undefined;
827
- return ring.map((f, i) => ({ comps: r.comps.map(c => ({ coef: f.params.map((_, j) => c[i].coef[`p${i}_${j}`] ?? 0), c: c[i].c })) }));
828
- };
1229
+ const fromRuns = () => runsRank(ring, edges, edges);
829
1230
  // The relation's rank: per location (each function), its components' forms over the function's parameters' sizes.
830
1231
  const fromRelation = () => {
831
1232
  const rel = callRelation(ring, sites);
@@ -844,6 +1245,9 @@ function candidates(ring, edges, sites, until) {
844
1245
  const runs = ring.length === 1 ? fromRuns() : undefined;
845
1246
  if (runs)
846
1247
  out.push(runs);
1248
+ // (a ring's first: a size across it, the rest after it, below)
1249
+ if (ring.length > 1)
1250
+ out.push(...ringFolds(ring, edges));
847
1251
  const rel = fromRelation();
848
1252
  if (rel)
849
1253
  out.push(rel);
@@ -871,37 +1275,97 @@ function foldMeasures(fn, edges) {
871
1275
  if (!edges.length)
872
1276
  return out;
873
1277
  for (const [i, q] of fn.params.entries()) {
874
- const d = q.sort;
875
- if (!(d instanceof Data) || d.group.length > 1 || d.abstract)
876
- continue;
877
- // each field's choices: of the datatype 1 or 2, of another datatype 0 or 1, else 0
878
- const fields = d.ctors.flatMap((c, j) => c.fields.map((f, k) => ({ j, k, sort: fieldSort(f) })));
879
- const choices = fields.map(f => (f.sort === d ? [1, 2] : f.sort instanceof Data ? [0, 1] : [0]));
880
- if (choices.reduce((n, c) => n * c.length, 1) > 64)
1278
+ const wt = q.sort instanceof Data ? weightings(q.sort) : undefined;
1279
+ if (!wt)
881
1280
  continue;
882
- let combos = [[]];
883
- for (const c of choices)
884
- combos = combos.flatMap(a => c.map(w => [...a, w]));
885
- // (the plain size is tried before: its weights are 1 on the datatype's fields, 0 on the others')
886
- const size = fields.map(f => (f.sort === d ? 1 : 0));
887
- combos = combos.filter(ws => ws.some((w, n) => w !== size[n])).sort((a, b) => a.reduce((x, y) => x + y, 0) - b.reduce((x, y) => x + y, 0));
888
- const weight = (ws) => { const at = new Map(fields.map((f, n) => [`${f.j}.${f.k}`, ws[n]])); const go = (v) => { const o = v; return 1 + d.ctors[o.c].fields.reduce((t, f, k) => { const w = at.get(`${o.c}.${k}`), fs = fieldSort(f); return t + (!w ? 0 : fs === d ? w * go(o.f[k]) : fs instanceof Data ? w * sizeOf(fs, o.f[k]) : 0); }, 0); }; return go; };
889
- for (const ws of combos) {
890
- const w = weight(ws);
1281
+ for (const ws of wt.combos) {
1282
+ const w = wt.weight(ws);
891
1283
  if (!edges.every(e => w(e.tv[i]) < w(e.sv[i])))
892
1284
  continue;
893
- out.push({ comps: [{ coef: fn.params.map(() => 0), c: 0, fold: { fn: foldFn(d, fields, ws), of: i } }] });
1285
+ const made = foldFn(q.sort, wt.fields, ws);
1286
+ if (!made)
1287
+ continue;
1288
+ out.push({ comps: [{ coef: fn.params.map(() => 0), c: 0, fold: { fn: made, of: i } }] });
894
1289
  if (out.length >= 2)
895
1290
  return out;
896
1291
  }
897
1292
  }
898
1293
  return out;
899
1294
  }
900
- // The fold of those weights, defined once.
1295
+ // A datatype's weightings (one datatype, not a group, not abstract): each field's choices, of the datatype 1 or 2, of
1296
+ // another datatype 0 or 1, else 0; every combination but the plain size's (tried before: 1 on the datatype's fields, 0 on
1297
+ // the others'), the lightest first, and the fold of each at a value.
1298
+ function weightings(d) {
1299
+ if (d.group.length > 1 || d.abstract)
1300
+ return undefined;
1301
+ const fields = d.ctors.flatMap((c, j) => c.fields.map((f, k) => ({ j, k, sort: fieldSort(f) })));
1302
+ const choices = fields.map(f => (f.sort === d ? [1, 2] : f.sort instanceof Data ? [0, 1] : [0]));
1303
+ if (choices.reduce((n, c) => n * c.length, 1) > 64)
1304
+ return undefined;
1305
+ let combos = [[]];
1306
+ for (const c of choices)
1307
+ combos = combos.flatMap(a => c.map(w => [...a, w]));
1308
+ const size = fields.map(f => (f.sort === d ? 1 : 0));
1309
+ combos = combos.filter(ws => ws.some((w, n) => w !== size[n])).sort((a, b) => a.reduce((x, y) => x + y, 0) - b.reduce((x, y) => x + y, 0));
1310
+ const weight = (ws) => { const at = new Map(fields.map((f, n) => [`${f.j}.${f.k}`, ws[n]])); const go = (v) => { const o = v; return 1 + d.ctors[o.c].fields.reduce((t, f, k) => { const w = at.get(`${o.c}.${k}`), fs = fieldSort(f); return t + (!w ? 0 : fs === d ? w * go(o.f[k]) : fs instanceof Data ? w * sizeOf(fs, o.f[k]) : 0); }, 0); }; return go; };
1311
+ return { fields, combos, weight, size };
1312
+ }
1313
+ // The LP's rank over the runs (core/cycles.ts's ranksOfCalls): a node per function of the ring, each its own coefficients
1314
+ // of its parameters' sizes and constant per component, every call of `edges` lowered (`points`: the calls whose ends the
1315
+ // rank is at least 0 at).
1316
+ function runsRank(ring, edges, points) {
1317
+ if (!edges.length)
1318
+ return undefined;
1319
+ const vars = ring.map((f, i) => f.params.flatMap((q, j) => (measurable(q.sort) ? [`p${i}_${j}`] : [])));
1320
+ const env = (i, xs) => Object.fromEntries(vars[i].map(x => [x, xs[Number(x.split('_')[1])]]));
1321
+ const r = ranksOfCalls(vars, points.flatMap(e => [{ node: e.from, env: env(e.from, e.s) }, { node: e.to, env: env(e.to, e.t) }]), edges.map(e => ({ from: e.from, to: e.to, s: env(e.from, e.s), t: env(e.to, e.t) })));
1322
+ if (r.left || !r.comps.length)
1323
+ return undefined;
1324
+ return ring.map((f, i) => ({ comps: r.comps.map(c => ({ coef: f.params.map((_, j) => c[i].coef[`p${i}_${j}`] ?? 0), c: c[i].c })) }));
1325
+ }
1326
+ // A size across a ring first, the rest after it: one weighting of a datatype, its fold at each function's first parameter
1327
+ // of it (0 at a function with none) the first component, which no call of the runs raises and some lower; the calls it
1328
+ // leaves equal ranked after it by the LP (`runsRank`). The plain size first (a Stooge sort's ring: the size, then a phase
1329
+ // the LP fits, the sort above its thirds' from 3 items on and below them under 3), then the weightings, the lightest first
1330
+ // (a formula's models through a ring of three, `Not` weighing its formula twice: ¬(p ∧ q) to p ∧ ¬q, no size falling).
1331
+ // The first two the runs don't contradict, by every datatype the ring's parameters have.
1332
+ function ringFolds(ring, edges) {
1333
+ const out = [];
1334
+ if (!edges.length)
1335
+ return out;
1336
+ const ds = [...new Set(ring.flatMap(f => f.params.map(q => q.sort)))].filter((s) => s instanceof Data);
1337
+ for (const d of ds) {
1338
+ const wt = weightings(d);
1339
+ if (!wt)
1340
+ continue;
1341
+ const at = ring.map(f => f.params.findIndex(q => q.sort === d));
1342
+ for (const ws of [wt.size, ...wt.combos]) {
1343
+ const w = wt.weight(ws), val = (i, vs) => (at[i] < 0 ? 0 : w(vs[at[i]])), plain = ws === wt.size;
1344
+ const ts = edges.map(e => [val(e.to, e.tv), val(e.from, e.sv)]);
1345
+ if (ts.some(([a, b]) => a > b) || !ts.some(([a, b]) => a < b))
1346
+ continue;
1347
+ const rest = edges.filter((_, n) => ts[n][0] === ts[n][1]), tail = rest.length ? runsRank(ring, rest, edges) : ring.map(() => ({ comps: [] }));
1348
+ if (!tail)
1349
+ continue;
1350
+ const made = plain ? '' : foldFn(d, wt.fields, ws);
1351
+ if (made === undefined)
1352
+ continue;
1353
+ const first = (f, i) => (plain ? { coef: f.params.map((_, j) => (j === at[i] ? 1 : 0)), c: 0 } : { coef: f.params.map(() => 0), c: 0, ...(at[i] >= 0 ? { fold: { fn: made, of: at[i] } } : {}) });
1354
+ out.push(ring.map((f, i) => ({ comps: [first(f, i), ...tail[i].comps] })));
1355
+ if (out.length >= 2)
1356
+ return out;
1357
+ }
1358
+ }
1359
+ return out;
1360
+ }
1361
+ // The fold of those weights, defined once; none where its name is a function this didn't define (a user's own
1362
+ // `foldList_12`, of another sort, never read as the fold).
1363
+ // (by identity: a fold this defined, then a user's own of its name defined over it, is the user's, never read as the fold)
1364
+ const madeFolds = new Map();
901
1365
  function foldFn(d, fields, ws) {
902
1366
  const name = `fold${d.name}_${ws.join('')}`;
903
1367
  if (fns.has(name))
904
- return name;
1368
+ return madeFolds.get(name) === fns.get(name) ? name : undefined;
905
1369
  const at = new Map(fields.map((f, n) => [`${f.j}.${f.k}`, ws[n]]));
906
1370
  const self = define(name, { x: d }, natural, ({ x }) => x.match(Object.fromEntries(d.ctors.map((c, j) => [c.name, (fs) => c.fields.reduce((t, f, k) => {
907
1371
  const w = at.get(`${j}.${k}`), s2 = fieldSort(f);
@@ -910,6 +1374,7 @@ function foldFn(d, fields, ws) {
910
1374
  const part = s2 === d ? self(fs[f.name]) : fs[f.name].size();
911
1375
  return w === 1 ? t.plus(part) : t.plus(part.times(w));
912
1376
  }, new Nat({ op: 'nat', value: 1 }))]))));
1377
+ madeFolds.set(name, self.fn);
913
1378
  return name;
914
1379
  }
915
1380
  // An obligation as one node of a cyclic proof (no use, no models): its conclusion, each definition it reads unfolded
@@ -920,11 +1385,7 @@ function directly(law, ms) {
920
1385
  varSorts = new Map(law.vars.flatMap(v => (v.sort instanceof Data ? [[v.name, v.sort]] : [])));
921
1386
  const until = clock() + ms;
922
1387
  // (and at each value of a datatype the conclusion builds: a fold reads its fields' sizes, size(x :: xs) = 1 + size(xs))
923
- const ctors = new Set(p.datas.flatMap(d => d.ctors.flatMap((c, j) => (c.fields.length ? [ctorMap(d, j)] : []))));
924
- const built = new Map();
925
- walk(concl, o => { if (o.op === 'get' && ctors.has(o.map))
926
- built.set(tid(o), o); });
927
- const insts = instancesOf(p, fs, { roots: [concl], others: [], depth: 1, shapesAt: [...[...varSorts.keys()].map(ev), ...built.values()], etaAt: [], models: modelsFor(p, law, 16, 3), until });
1388
+ const insts = instancesOf(p, fs, { roots: [concl], others: [], depth: 1, shapesAt: [...[...varSorts.keys()].map(ev), ...builtIn(p, concl)], etaAt: [], models: modelsFor(p, law, 16, 3), until });
928
1389
  if (clock() > until)
929
1390
  return undefined;
930
1391
  const was = pairedKeys.skip;
@@ -937,14 +1398,46 @@ function directly(law, ms) {
937
1398
  pairedKeys.skip = was;
938
1399
  }
939
1400
  }
940
- // Each call's obligation under measures given, proven (`obligations`, each function's) or the first that isn't (`failed`).
941
- function proveMeasures(ring, sites, ms, until) {
942
- const names = ring.map(f => f.name), text = ringText(ring, ms);
1401
+ // The values of a datatype a term builds by its constructors (each of fields), each once.
1402
+ function builtIn(p, t) {
1403
+ const ctors = new Set(p.datas.flatMap(d => d.ctors.flatMap((c, j) => (c.fields.length ? [ctorMap(d, j)] : []))));
1404
+ const built = new Map();
1405
+ walk(t, o => { if (o.op === 'get' && ctors.has(o.map))
1406
+ built.set(tid(o), o); });
1407
+ return [...built.values()];
1408
+ }
1409
+ // Each call's obligation under measures given, proven (`obligations`, each function's) or the first that isn't (`failed`);
1410
+ // with an invariant (`inv`, nested recursion), each value each body ends at keeping its function's after them.
1411
+ function proveMeasures(ring, sites, ms0, until, inv = ring.map(() => undefined)) {
1412
+ // (every measure of one length, at least one component: Data.lean's lexLt compares tuples of one length)
1413
+ const ms = padded(ring, ms0);
1414
+ if (!ms[0].comps.length || ms.some(m => m.comps.length !== ms[0].comps.length))
1415
+ throw new Error(`${ring.map(f => f.name).join(', ')}: measures of one length`);
1416
+ // (a fold a measure reads is a function taken before, never one of the ring: checkMeasures' measures are given)
1417
+ if (ms.some(m => m.comps.some(c => c.fold && ring.some(f => f.name === c.fold.fn))))
1418
+ throw new Error(`${ring.map(f => f.name).join(', ')}: a measure reads the ring`);
1419
+ const was = inTermination.on;
1420
+ inTermination.on = true;
1421
+ try {
1422
+ return proveMeasuresIn(ring, sites, ms, until, inv);
1423
+ }
1424
+ finally {
1425
+ inTermination.on = was;
1426
+ }
1427
+ }
1428
+ function proveMeasuresIn(ring, sites, ms, until0, inv) {
1429
+ // (a call whose path gives guarded size laws: its proofs' time beside the measure's, `guardedMs` more for each)
1430
+ let until = until0;
1431
+ const names = ring.map(f => f.name), text = ringText(ring, ms) + invText(ring, inv);
1432
+ checkInv(ring, inv);
943
1433
  const nth = sites.map((s, i) => sites.slice(0, i).filter(r => r.from === s.from).length);
944
1434
  const obligations = ring.map(() => []);
945
- for (const [i, site] of sites.entries()) {
946
- const law = obligation(ring, ms, site, nth[i]), call = `${ring.length > 1 ? `${names[site.from]}'s ` : ''}call ${nth[i] + 1}`;
947
- // (no call of the ring in it: refused before)
1435
+ const leaves = ring.map((f, i) => { const ls = []; if (inv[i])
1436
+ sitesOf(f, names, ls); return ls; });
1437
+ const laws = [...sites.map((site, i) => ({ from: site.from, site, law: obligation(ring, ms, site, nth[i], inv), call: `${ring.length > 1 ? `${names[site.from]}'s ` : ''}call ${nth[i] + 1}`, what: 'lower it' })),
1438
+ ...leaves.flatMap((ls, from) => ls.map((l, i) => ({ from, law: keeps(ring, ms, inv, from, l, i), call: `${names[from]}'s value ${i + 1}`, what: 'keep its invariant' })))];
1439
+ for (const { from, law, call, what, site } of laws) {
1440
+ // (no call of the ring in it: each read as a value)
948
1441
  walk(law.holds, o => { if (o.op === 'call' && names.includes(o.fn))
949
1442
  throw new Error(`${law.name} reads the ring`); });
950
1443
  // First one node, the definitions unfolded once (most calls lower the measure by their cases alone); then, where its
@@ -954,10 +1447,10 @@ function proveMeasures(ring, sites, ms, until) {
954
1447
  // else, or then, the definitions unfolded alone.
955
1448
  const left = () => Math.max(1, until - clock()), cex = refute(law, 200);
956
1449
  if (cex)
957
- return { failed: `${text}: its ${call} doesn't lower it at ${JSON.stringify(cex)}` };
1450
+ return { failed: `${text}: its ${call} doesn't ${what} at ${JSON.stringify(cex)}` };
958
1451
  const direct = directly(law, Math.min(2000, left()));
959
1452
  if (direct) {
960
- obligations[site.from].push({ law, proof: direct, lemmas: [] });
1453
+ obligations[from].push({ law, proof: direct, lemmas: [] });
961
1454
  continue;
962
1455
  }
963
1456
  // (the size laws first, each proven once and used, within 60% of the time left; then proveData without conjectured
@@ -967,39 +1460,90 @@ function proveMeasures(ring, sites, ms, until) {
967
1460
  if (dataTrace && lemmas.length)
968
1461
  console.error(`[data] ${law.name}: ${lemmas.map(c => c.name).join('; ')}`);
969
1462
  let v = lemmas.length ? proveData(law, { lemmas, lemmasFirst: true, ms: Math.min(8000, 0.6 * left()) }) : undefined;
1463
+ // (then, where the call's path gives a guarded size law: it, its guard at the call and the size laws, proven in order)
1464
+ const guarded = v?.proven || v?.counterexample || !site ? [] : guardedLaws(law, site, names);
1465
+ if (guarded.length) {
1466
+ // (at most `guardedMs` more for a ring's every measure tried: a refusal isn't slowed past it)
1467
+ const more = Math.min(guardedLeft.ms, Math.max(0, clock() + guardedMs.ms - until));
1468
+ guardedLeft.ms -= more;
1469
+ until += more;
1470
+ // (each guard at the call after the guarded laws its arguments' sizes read there: half of a length from 2 items on)
1471
+ const groups = [{ laws: sizeLaws(law, names, true), then: false }, ...guarded.flatMap(g => [...guardedLaws(g.laws.at(-2), site, names, true).map(h => ({ laws: h.laws, then: false })), { laws: g.laws, then: g.outer }])];
1472
+ if (dataTrace)
1473
+ console.error(`[data] ${law.name}: ${groups.flatMap(q => q.laws).map(c => c.name).join('; ')}`);
1474
+ const g = throughLemmas(law, groups, until);
1475
+ if (g) {
1476
+ obligations[from].push({ law, proof: g.proof, scheme: g.scheme, lemmas: g.lemmas, lemmaLaws: groups.flatMap(q => q.laws).filter(c => g.lemmas.includes(c.name)) });
1477
+ continue;
1478
+ }
1479
+ }
970
1480
  if (!v?.proven && !v?.counterexample && clock() < until)
971
1481
  v = proveData(law, { ms: Math.min(12_000, left()), lemmas: false });
972
1482
  if (!v?.proven && !v?.counterexample && clock() < until)
973
1483
  v = proveData(law, { induction: false, ms: Math.min(4000, left()) });
974
1484
  if (!v || !(v.proven && v.checked))
975
- return { failed: `${text}: its ${call} ${v?.counterexample ? `doesn't lower it at ${JSON.stringify(v.counterexample)}` : 'not proven to lower it'}` };
1485
+ return { failed: `${text}: its ${call} ${v?.counterexample ? `doesn't ${what} at ${JSON.stringify(v.counterexample)}` : `not proven to ${what}`}` };
976
1486
  const used = v;
977
- obligations[site.from].push({ law, proof: used.proof, scheme: used.scheme, lemmas: used.lemmas, lemmaLaws: lemmas.filter(c => used.lemmas.includes(c.name)) });
1487
+ obligations[from].push({ law, proof: used.proof, scheme: used.scheme, lemmas: used.lemmas, lemmaLaws: lemmas.filter(c => used.lemmas.includes(c.name)) });
978
1488
  }
979
1489
  return { obligations };
980
1490
  }
981
- // A ring's calls, refused where one is nested in another's argument or condition (its obligation would read a function
982
- // being taken).
983
- function ringSites(ring, why) {
984
- const names = ring.map(f => f.name), sites = callSites(ring);
985
- for (const st of sites) {
986
- let nested = false;
987
- walk([st.args, st.wrap(no.y)], o => { if (o.op === 'call' && names.includes(o.fn))
988
- nested = true; });
989
- if (nested)
990
- throw new Error(`${why}, and a call to ${ring.length > 1 ? 'its ring' : 'itself'} is nested in the argument or the condition of another (nested recursion isn't taken)`);
991
- }
992
- return sites;
993
- }
1491
+ const invText = (ring, inv) => (inv.some(y => y) ? `, keeping ${ring.flatMap((f, i) => (inv[i] ? [showY(inv[i]).replaceAll(valueVar(f), `${f.name}(…)`)] : [])).join(' and ')}` : '');
1492
+ // A ring's calls.
1493
+ const ringSites = (ring) => callSites(ring);
994
1494
  // Measures given to a ring (or a function) checked as `termination` checks the one it takes: each call's obligation
995
1495
  // proven by the kernel, within the counted budget; nothing is taken (core/conformance.ts: tampered measures refused).
996
- export function checkMeasures(fns, ms, budget = terminationMs.ms) {
1496
+ // (a call nested in another's argument read under the invariants given, `inv`, each function's over its parameters and
1497
+ // `valueVar`; none: the decrease must hold whatever the call's value)
1498
+ export function checkMeasures(fns, ms, budget = terminationMs.ms, inv) {
997
1499
  return counted(dataRate, () => {
998
- const r = proveMeasures(fns, ringSites(fns, fns.map(f => f.name).join(', ')), padded(fns, ms), clock() + budget);
1500
+ const had = guardedLeft.ms;
1501
+ guardedLeft.ms = guardedMs.ms;
1502
+ let r;
1503
+ try {
1504
+ r = proveMeasures(fns, ringSites(fns), padded(fns, ms), clock() + budget, inv);
1505
+ }
1506
+ finally {
1507
+ guardedLeft.ms = had;
1508
+ }
999
1509
  return 'failed' in r ? { proven: false, why: r.failed } : { proven: true, obligations: r.obligations };
1000
1510
  });
1001
1511
  }
1512
+ // Invariants to try for a ring with a call nested in another's argument or condition (the search's: one is taken only
1513
+ // where the kernel proves each body keeps it): none first (each decrease whatever the nested calls' values), then, of each
1514
+ // function whose value has a size, that size against one argument's as its values give them (an equation where they
1515
+ // give one difference, else the least and the greatest: the argument with the narrowest range), both bounds, then the
1516
+ // upper alone, then the lower alone.
1517
+ function invariantsOf(ring) {
1518
+ const none = ring.map(() => undefined);
1519
+ const per = ring.map(f => {
1520
+ if (!sized(f.ret))
1521
+ return undefined;
1522
+ const vars = f.params.map(q => ({ name: `${f.name}.${q.name}`, sort: q.sort })), call = { op: 'call', fn: f.name, args: vars.map(v => ({ op: 'var', name: v.name })) };
1523
+ const bs = bounded(() => sizeBounds(call, f.ret, vars, samples(vars, [], 160, 31))).filter(b => b.of.length === 1 && sized(vars[b.of[0]].sort)).sort((a, b) => a.hi - a.lo - (b.hi - b.lo));
1524
+ const b = bs[0];
1525
+ if (!b)
1526
+ return undefined;
1527
+ const nat = (n) => ({ op: 'nat', value: n }), add = (x, n) => (n ? { op: 'add', a: x, b: nat(n) } : x);
1528
+ const r = sizeX(f.ret, { op: 'var', name: valueVar(f) }), v = sizeX(vars[b.of[0]].sort, { op: 'var', name: vars[b.of[0]].name });
1529
+ // lo ≤ S(value) − S(arg) ≤ hi
1530
+ const lower = { op: '<=', a: add(v, Math.max(0, b.lo)), b: add(r, Math.max(0, -b.lo)) }, upper = { op: '<=', a: add(r, Math.max(0, -b.hi)), b: add(v, Math.max(0, b.hi)) };
1531
+ return b.lo === b.hi ? { both: { op: '=', a: add(r, Math.max(0, -b.lo)), b: add(v, Math.max(0, b.lo)) }, lower: undefined, upper: undefined } : { both: { op: 'and', xs: [lower, upper] }, lower, upper };
1532
+ });
1533
+ const out = [none, per.map(p => p?.both), per.map(p => p?.upper ?? p?.both), per.map(p => p?.lower ?? p?.both)];
1534
+ return out.filter((inv, i) => (i === 0 || inv.some(y => y)) && out.findIndex(o => JSON.stringify(o) === JSON.stringify(inv)) === i);
1535
+ }
1002
1536
  // The ring's measures and each call's proof, or a refusal with the measures tried. A ring of one is a function.
1537
+ // (a ring's termination within another's: the outer's guarded time kept)
1538
+ function terminationKept(ring, why) {
1539
+ const had = guardedLeft.ms;
1540
+ try {
1541
+ return termination(ring, why);
1542
+ }
1543
+ finally {
1544
+ guardedLeft.ms = had;
1545
+ }
1546
+ }
1003
1547
  function termination(ring, why) {
1004
1548
  return counted(dataRate, () => {
1005
1549
  const names = ring.map(f => f.name);
@@ -1008,39 +1552,60 @@ function termination(ring, why) {
1008
1552
  const t0 = performance.now();
1009
1553
  if (!ring.some(f => f.params.some(p => measurable(p.sort))))
1010
1554
  throw new Error(`${why}, and ${ring.length === 1 ? 'it has' : 'its ring has'} no parameter a measure reads (a natural or a datatype value)`);
1011
- const sites = ringSites(ring, why);
1555
+ const sites = ringSites(ring);
1556
+ // (a call of the ring in another's argument or condition: nested recursion, with invariants to try)
1557
+ const nested = sites.some(st => { let n = false; walk([st.args, st.wrap(no.y)], o => { if (o.op === 'call' && names.includes(o.fn))
1558
+ n = true; }); return n; });
1012
1559
  if (dataTrace)
1013
- console.error(`[data] ${sites.length} calls`);
1560
+ console.error(`[data] ${sites.length} calls${nested ? ', nested' : ''}`);
1014
1561
  const edges = runEdges(ring), until = clock() + terminationMs.ms * ring.length, tried = [], seen = new Set();
1562
+ guardedLeft.ms = guardedMs.ms * ring.length;
1563
+ const invs = nested ? invariantsOf(ring) : [ring.map(() => undefined)];
1015
1564
  if (dataTrace)
1016
1565
  console.error(`[data] its runs: ${edges.length} calls at ${Math.round(performance.now() - t0)} ms`);
1017
- for (const ms of candidates(ring, edges, sites, until)) {
1018
- const text = ringText(ring, ms);
1019
- if (dataTrace)
1020
- console.error(`[data] ${text} at ${Math.round(performance.now() - t0)} ms`);
1021
- if (clock() > until) {
1022
- tried.push('out of time');
1023
- break;
1024
- }
1025
- const bad = edges.find(e => !lowers(ms, e));
1026
- if (seen.has(text))
1027
- continue;
1028
- seen.add(text);
1029
- if (bad) {
1030
- if (ring.some(f => f.stated) || !tried.length)
1031
- tried.push(`${text}: a call of its runs doesn't lower it (from ${JSON.stringify(bad.s)} to ${JSON.stringify(bad.t)}, the parameters' sizes${ring.length > 1 ? `, ${names[bad.from]} to ${names[bad.to]}` : ''})`);
1032
- continue;
1566
+ try {
1567
+ // (a nested call's arguments read the ring itself, whose values the candidates' samples compute: within the bounds)
1568
+ for (const ms of nested ? bounded(() => candidates(ring, edges, sites, until)) : candidates(ring, edges, sites, until)) {
1569
+ const text = ringText(ring, ms);
1570
+ if (dataTrace)
1571
+ console.error(`[data] ${text} at ${Math.round(performance.now() - t0)} ms`);
1572
+ if (clock() > until) {
1573
+ tried.push('out of time');
1574
+ break;
1575
+ }
1576
+ const bad = edges.find(e => !lowers(ms, e));
1577
+ if (seen.has(text))
1578
+ continue;
1579
+ seen.add(text);
1580
+ if (bad) {
1581
+ if (ring.some(f => f.stated) || !tried.length)
1582
+ tried.push(`${text}: a call of its runs doesn't lower it (from ${JSON.stringify(bad.s)} to ${JSON.stringify(bad.t)}, the parameters' sizes${ring.length > 1 ? `, ${names[bad.from]} to ${names[bad.to]}` : ''})`);
1583
+ continue;
1584
+ }
1585
+ for (const inv of invs) {
1586
+ if (clock() > until)
1587
+ break;
1588
+ const r = proveMeasures(ring, sites, ms, until, inv);
1589
+ if ('obligations' in r)
1590
+ return ring.map((f, i) => ({ measure: ms[i], text: showMeasure(f, ms[i]), ...(inv[i] ? { invariant: inv[i] } : {}), obligations: r.obligations[i], ms: Math.round(performance.now() - t0) }));
1591
+ tried.push(r.failed);
1592
+ }
1033
1593
  }
1034
- const r = proveMeasures(ring, sites, ms, until);
1035
- if ('obligations' in r)
1036
- return ring.map((f, i) => ({ measure: ms[i], text: showMeasure(f, ms[i]), obligations: r.obligations[i], ms: Math.round(performance.now() - t0) }));
1037
- tried.push(r.failed);
1594
+ }
1595
+ catch (e) {
1596
+ if (e instanceof NestedRefusal)
1597
+ throw new Error(`${why}, and ${e.message}`);
1598
+ throw e;
1038
1599
  }
1039
1600
  throw new Error(`${why}, and no measure is proven to fall at every call${ring.length > 1 ? ' within the ring' : ''}${tried.length ? ` (${tried.slice(0, 3).join('; ')})` : ' (no measure found to try)'}`);
1040
1601
  });
1041
1602
  }
1042
1603
  export function law(name, vars, holds) {
1043
1604
  const vs = Object.entries(vars).map(([n, s]) => ({ name: n, sort: s }));
1605
+ // (as a parameter's: never a name the encoding makes, f.p, field#k, f#value, x$)
1606
+ for (const v of vs)
1607
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(v.name))
1608
+ throw new Error(`${name}: the variable ${v.name}'s name is letters and digits`);
1044
1609
  const y = holds(Object.fromEntries(vs.map(v => [v.name, wrap(v.sort, { op: 'var', name: v.name })]))).y;
1045
1610
  equalityOnly(name, y);
1046
1611
  return { name, vars: vs, holds: y, params: [...new Set(paramsIn(y))] };
@@ -1160,7 +1725,7 @@ export const showValue = (d, v) => {
1160
1725
  const c = d.ctors[v.c];
1161
1726
  return c.fields.length ? `${c.name}(${c.fields.map((f, i) => showValue(fieldSort(f), v.f[i])).join(', ')})` : c.name;
1162
1727
  };
1163
- export const rng = (seed) => () => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed / 2147483648; };
1728
+ export const rng = (seed) => () => (seed = lcg(seed)) / 2147483648; // (machine.ts's lcg)
1164
1729
  // `full`: a value that fills its size (a constructor with a field of the group, unless the size is spent, or at 1 in 8),
1165
1730
  // where the plain draw mostly stops at a leaf (a list of length 0 or 1, most often).
1166
1731
  export function randomValue(s, rand, size, natMax = 5, full = false) {
@@ -1278,6 +1843,10 @@ export function programOf(laws, extra = []) {
1278
1843
  ints = true;
1279
1844
  if (ints)
1280
1845
  divs.add(2);
1846
+ // (a function parameter is a map of its own name, as a function is: never one of theirs, which their equations fix)
1847
+ for (const q of ps)
1848
+ if (fs.has(q))
1849
+ throw new Error(`${q}: a function parameter named as a function the law reads`);
1281
1850
  return { datas, fns: order, params: [...ps], divisors: [...divs].sort((a, b) => a - b), ints };
1282
1851
  }
1283
1852
  const dataOf = (p, name) => p.datas.find(d => d.name === name);
@@ -1813,9 +2382,16 @@ function unfoldAt(f) {
1813
2382
  return f.params[f.decreases].sort instanceof Data ? [f.decreases] : [];
1814
2383
  if (!f.measure)
1815
2384
  return [];
1816
- const out = new Set();
1817
- walk(f.body(), o => { if (o.op === 'match' && o.of.op === 'var') {
1818
- const i = f.params.findIndex(q => `${f.name}.${q.name}` === o.of.name);
2385
+ const out = new Set(), at = (o) => f.params.findIndex(q => o.op === 'var' && `${f.name}.${q.name}` === o.name);
2386
+ // (outside a termination's proofs, the parameter the body matches first only: a merge at a built second list and an
2387
+ // undecided first is no decided case, and its recursion at the first's tail unfolds again, a chain to the cap)
2388
+ const body = f.body();
2389
+ if (!inTermination.on && body.op === 'match') {
2390
+ const i = at(body.of);
2391
+ return i >= 0 && f.params[i].sort instanceof Data ? [i] : [];
2392
+ }
2393
+ walk(body, o => { if (o.op === 'match') {
2394
+ const i = at(o.of);
1819
2395
  if (i >= 0 && f.params[i].sort instanceof Data)
1820
2396
  out.add(i);
1821
2397
  } });
@@ -1857,6 +2433,11 @@ function schemes(p, l) {
1857
2433
  const formal = new Map(f.params.map((q, i) => [`${f.name}.${q.name}`, isVar(args[i]) ? ev(args[i].name) : closed(args[i]) ? encX(p, args[i], new Map()) : undefined]));
1858
2434
  let relaxed = false;
1859
2435
  const uses = [];
2436
+ // (the functions of f's ring the law reads at f's arguments too, evens beside odds: a call of one is a use, as f's
2437
+ // own, mutual induction on the conjunction the law is)
2438
+ const alongside = new Set();
2439
+ walk(l.holds, o2 => { if (o2.op === 'call' && o2.fn !== f.name && f.ring.includes(o2.fn) && fnOf(o2.fn).params.length === args.length && JSON.stringify(o2.args) === JSON.stringify(args))
2440
+ alongside.add(o2.fn); });
1860
2441
  // (`through`: the functions of f's ring whose bodies are read in place of their calls, once each: evens through
1861
2442
  // odds, which call each other, is recursion of evens at the tail's tail)
1862
2443
  const go = (x, env, guard, through = new Set()) => {
@@ -1867,7 +2448,7 @@ function schemes(p, l) {
1867
2448
  return;
1868
2449
  }
1869
2450
  const t = x;
1870
- if (t.op === 'call' && t.fn !== f.name && f.ring.includes(t.fn) && !through.has(t.fn)) {
2451
+ if (t.op === 'call' && t.fn !== f.name && f.ring.includes(t.fn) && !through.has(t.fn) && !alongside.has(t.fn)) {
1871
2452
  const g = fnOf(t.fn);
1872
2453
  go(t.args, env, guard, through);
1873
2454
  go(g.body(), new Map([...env, ...g.params.map((q, i) => [`${g.name}.${q.name}`, encX(p, t.args[i], env)])]), guard, new Set([...through, t.fn]));
@@ -1904,7 +2485,7 @@ function schemes(p, l) {
1904
2485
  go(w.b, env, [...guard, { op: 'not', x: c }], through);
1905
2486
  return;
1906
2487
  }
1907
- if (t.op === 'call' && t.fn === f.name) {
2488
+ if (t.op === 'call' && (t.fn === f.name || alongside.has(t.fn))) {
1908
2489
  const subst = {};
1909
2490
  let ok = true;
1910
2491
  t.args.forEach((a, i) => {
@@ -2061,21 +2642,33 @@ function instancesOf(p, fs, w) {
2061
2642
  inst(`fn ${f.name}`, as);
2062
2643
  ctors(note(reads(holdsAt(`fn ${f.name}`, as))));
2063
2644
  }
2645
+ const unfoldOnce = (r) => {
2646
+ const f = fnOfMap(r.map), as = f && argsOf(r.key, f.params.length), rid = sid(r);
2647
+ if (!f || !as || unfolded.has(rid))
2648
+ return [];
2649
+ unfolded.add(rid);
2650
+ inst(`fn ${f.name}`, as);
2651
+ const body = reads(holdsAt(`fn ${f.name}`, as));
2652
+ ctors(note(body));
2653
+ return body;
2654
+ };
2064
2655
  for (let round = 0; round < w.depth && frontier.length; round++) {
2065
2656
  const next = [];
2066
- for (const r of frontier) {
2067
- const f = fnOfMap(r.map), as = f && argsOf(r.key, f.params.length), rid = sid(r);
2068
- if (!f || !as || unfolded.has(rid))
2069
- continue;
2070
- unfolded.add(rid);
2071
- inst(`fn ${f.name}`, as);
2072
- const body = reads(holdsAt(`fn ${f.name}`, as));
2073
- ctors(note(body));
2074
- for (const b of body)
2657
+ for (const r of frontier)
2658
+ for (const b of unfoldOnce(r))
2075
2659
  next.push(b);
2076
- }
2077
2660
  frontier = next;
2078
2661
  }
2662
+ // (at one unfolding, where the goal reads a function that looks two ahead (a match on a field of the value it matches:
2663
+ // ordered, reading the tail's head), a call both an unfolded body and a use's conclusion read, once more:
2664
+ // insert(y, tail xs), where insert(y, xs)'s body and the hypothesis at the tail meet, its constructor what ordered
2665
+ // reads at insert(y, xs)'s tail)
2666
+ if (w.depth === 1 && reads(w.roots).some(r => { const f = fnOfMap(r.map); return !!f && looksAhead(f); })) {
2667
+ const theirs = new Set(reads(w.others).map(r => sid(r)));
2668
+ for (const r of frontier)
2669
+ if (theirs.has(sid(r)))
2670
+ unfoldOnce(r);
2671
+ }
2079
2672
  // Euclid's fact at every key a remainder or quotient is read at (a read the facts bring is read too).
2080
2673
  const ariths = () => {
2081
2674
  for (let pass = 0; pass < 2; pass++)
@@ -2246,11 +2839,29 @@ function instancesOf(p, fs, w) {
2246
2839
  }
2247
2840
  return { find, terms, adj, truthOf };
2248
2841
  };
2842
+ // A value's eta at the constructor of fields a model gives it (its fact's side there), if one.
2843
+ const etaAt = (d, v, model) => {
2844
+ let j;
2845
+ try {
2846
+ j = model.m.evalE(get(tagMap(d.name), v), model.env);
2847
+ }
2848
+ catch {
2849
+ return [];
2850
+ }
2851
+ if (!d.ctors[j]?.fields.length || !fs.at.has(`eta ${d.name}`))
2852
+ return [];
2853
+ const parts = (c) => (c.op === 'and' ? c.xs.flatMap(parts) : [c]);
2854
+ for (const c of parts(holdsAt(`eta ${d.name}`, [v])))
2855
+ if (c.op === 'or' && c.xs.length === 2 && c.xs[0].op === 'not' && c.xs[0].x.op === '=' && c.xs[0].x.b.op === 'const' && c.xs[0].x.b.value === j && c.xs[1].op === '=')
2856
+ return [c.xs[1].b];
2857
+ return [];
2858
+ };
2249
2859
  // A function read whose decreasing argument a model's classes make a constructor's value (the argument itself, or a
2250
2860
  // term of its class) unfolds there too: where the definition's match is decided. Each such instance stands for the
2251
2861
  // reads it was unfolded for (`reached` keeps it in a case where it is one of them).
2252
2862
  if (w.depth >= 1) {
2253
2863
  let extra = 0;
2864
+ const viaBody = new Set();
2254
2865
  for (const model of w.models.length ? w.models : [undefined]) {
2255
2866
  if (late())
2256
2867
  break;
@@ -2266,7 +2877,7 @@ function instancesOf(p, fs, w) {
2266
2877
  }
2267
2878
  for (const r of [...all]) {
2268
2879
  const f = fnOfMap(r.map);
2269
- if (!f)
2880
+ if (!f || viaBody.has(sid(r)))
2270
2881
  continue;
2271
2882
  const as = argsOf(r.key, f.params.length);
2272
2883
  if (!as)
@@ -2274,7 +2885,11 @@ function instancesOf(p, fs, w) {
2274
2885
  for (const di of unfoldAt(f)) {
2275
2886
  const own = as[di], d = f.params[di].sort, root = cl.find(tid(own));
2276
2887
  const built = (t) => (t.op === 'get' && d.ctors.some((c, j) => c.fields.length && t.map === ctorMap(d, j))) || (t.op === 'const' && t.value < d.nullary);
2277
- const cands = built(own) ? [own] : [...cl.terms.values()].filter(t => built(t) && cl.find(tid(t)) === root);
2888
+ const cands0 = built(own) ? [own] : [...cl.terms.values()].filter(t => built(t) && cl.find(tid(t)) === root);
2889
+ // (where none is built, the value an induction descends on, of its class, at the constructor this model gives
2890
+ // it, eta's: count(x, xs) at xs's head and tail where xs is a cons, read through count(x, tail(y :: xs)))
2891
+ // (not where the read is unfolded at the value as it stands already: ordered(xs) itself)
2892
+ const via = cands0.length || !model || inTermination.on || done.has(sigOf(f.name, as)) ? undefined : w.shapesAt.find(v => cl.find(tid(v)) === root), cands = via ? etaAt(d, via, model) : cands0;
2278
2893
  for (const t of cands) {
2279
2894
  const as2 = as.map((a, i) => (i === di ? t : a)), rid = sid({ map: f.name, key: keyOf(as2) }), key2 = sid([fs.at.get(`fn ${f.name}`), as2]);
2280
2895
  const anchor = { read: tid(get(f.name, r.key)), arg: own, value: t }, had = anchoredAt.get(key2) ?? [];
@@ -2287,9 +2902,19 @@ function instancesOf(p, fs, w) {
2287
2902
  done.add(sigOf(f.name, as2));
2288
2903
  if (dataTrace)
2289
2904
  console.error(`[data] unfold ${f.name} at ${brief(as2, 160)} for ${brief(r.key, 80)}`);
2905
+ if (via) {
2906
+ inst(`eta ${d.name}`, [via]);
2907
+ ctors(note(reads(holdsAt(`eta ${d.name}`, [via]))));
2908
+ }
2290
2909
  inst(`fn ${f.name}`, as2);
2291
2910
  note([{ map: f.name, key: keyOf(as2) }]);
2292
- ctors(note(reads(holdsAt(`fn ${f.name}`, as2))));
2911
+ const body = note(reads(holdsAt(`fn ${f.name}`, as2)));
2912
+ ctors(body);
2913
+ // (an eta's unfolding is one step: the reads its body makes unfold no further, a merge's recursion on the
2914
+ // other list at the same constructor would chain to the cap)
2915
+ if (via)
2916
+ for (const b of body)
2917
+ viaBody.add(sid(b));
2293
2918
  }
2294
2919
  }
2295
2920
  }
@@ -2513,6 +3138,34 @@ function instancesOf(p, fs, w) {
2513
3138
  lap(`congruences, ${insts.length} instances, ${w.models.length} models`);
2514
3139
  return insts;
2515
3140
  }
3141
+ // Whether a function looks two ahead: its body matches a field of a value it matched, of the same datatype (ordered's
3142
+ // tail, then its head; not a pair in a list's head).
3143
+ const looksAhead = (f) => {
3144
+ let yes = false;
3145
+ const go = (x, fields) => {
3146
+ if (yes || !x || typeof x !== 'object')
3147
+ return;
3148
+ if (Array.isArray(x)) {
3149
+ x.forEach(y => go(y, fields));
3150
+ return;
3151
+ }
3152
+ const t = x;
3153
+ if (t.op === 'match') {
3154
+ if (t.of.op === 'var' && fields.get(t.of.name) === t.data) {
3155
+ yes = true;
3156
+ return;
3157
+ }
3158
+ go(t.of, fields);
3159
+ for (const c of t.cases)
3160
+ go(c.body, new Map([...fields, ...c.binds.map(b => [b, t.data])]));
3161
+ return;
3162
+ }
3163
+ for (const v of Object.values(t))
3164
+ go(v, fields);
3165
+ };
3166
+ go(f.body(), new Map());
3167
+ return yes;
3168
+ };
2516
3169
  let varSorts = new Map();
2517
3170
  // A term's id, once per object: equal exactly when the terms' texts (JSON.stringify) are, a leaf's id its text. A key's
2518
3171
  // pairing reads its arguments again ((a + b)·(a + b) + b), so a nested read's text grows exponentially with its depth
@@ -2740,13 +3393,16 @@ function matches(pattern, vars, t, s) {
2740
3393
  }
2741
3394
  return out;
2742
3395
  }
2743
- function casesOf(p, unfolded, vars, models) {
3396
+ function casesOf(p, fs0, unfolded, vars, models) {
2744
3397
  // (a read of an unknown function at an abstract value's code, or at its fields, is plain too: p(x) of a filter by p)
2745
3398
  const plain = (e) => (e.op === 'var' ? vars.has(e.name) : e.op === 'const' ? true : e.op === 'get' ? (p.datas.some(d => e.map.startsWith(`${d.name}.`)) && !p.datas.some(d => d.ctors.some((c, j) => c.fields.length > 0 && e.map === ctorMap(d, j))) || p.params.includes(e.map) || codecs.has(e.map)) && plain(e.key)
2746
3399
  : e.op === 'add' || e.op === 'sub' || e.op === 'min' || e.op === 'max' ? plain(e.a) && plain(e.b) : e.op === 'mul' ? plain(e.a) : false);
2747
- const plainC = (c) => readsVar(c) && (c.op === '<' || c.op === '<=' || c.op === '=' ? plain(c.a) && plain(c.b) : c.op === 'not' ? plainC(c.x) : c.op === 'and' || c.op === 'or' ? c.xs.every(plainC) : false);
3400
+ // (and a predicate of the program's at plain values: the guard the code reads, a user's ≤ on naturals, in place of the
3401
+ // tags of fields its unfolding would split on; the merge's size law over Peano naturals)
3402
+ const guard = (e, b) => e.op === 'get' && b.op === 'const' && b.value === 1 && p.fns.some(f => f.name === e.map && f.ret === 'bool') && (argsOf(e.key, fs0.arity.get(e.map) ?? 1) ?? []).every(plain);
3403
+ const plainC = (c) => readsVar(c) && (c.op === '<' || c.op === '<=' || c.op === '=' ? (plain(c.a) && plain(c.b)) || (c.op === '=' && guard(c.a, c.b)) : c.op === 'not' ? plainC(c.x) : c.op === 'and' || c.op === 'or' ? c.xs.every(plainC) : false);
2748
3404
  // The functions' facts the goal unfolds.
2749
- const roots = unfolded;
3405
+ const roots = unfolded, preds = new Set();
2750
3406
  const sigs = models.map(({ m, env }) => {
2751
3407
  const out = new Map();
2752
3408
  const truthOf = (c) => { try {
@@ -2773,6 +3429,8 @@ function casesOf(p, unfolded, vars, models) {
2773
3429
  const key = sid(o.c);
2774
3430
  if (!out.has(key))
2775
3431
  out.set(key, { c: o.c, t: v });
3432
+ if (o.c.op === '=' && guard(o.c.a, o.c.b))
3433
+ preds.add(key);
2776
3434
  }
2777
3435
  go(v ? o.then : o.else);
2778
3436
  return;
@@ -2789,7 +3447,8 @@ function casesOf(p, unfolded, vars, models) {
2789
3447
  for (const key of sigs[i].keys())
2790
3448
  if (!decided.has(key))
2791
3449
  count.set(key, (count.get(key) ?? 0) + 1);
2792
- const pick = [...count.entries()].sort((a2, b2) => b2[1] - a2[1])[0];
3450
+ // (as many models one way as another: a guard of the program's predicates first, the split the code makes)
3451
+ const pick = [...count.entries()].sort((a2, b2) => b2[1] - a2[1] || Number(preds.has(b2[0])) - Number(preds.has(a2[0])))[0];
2793
3452
  if (!pick || depth >= 4)
2794
3453
  return [{ lits, models: ms.length ? ms.map(i => models[i]) : undefined }];
2795
3454
  const key = pick[0], c = ms.map(i => sigs[i].get(key)).find(x => x).c;
@@ -2816,17 +3475,23 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2816
3475
  // A few models for the instances; the whole pool for the cases (a rare case gets its own models from it).
2817
3476
  const few = (ms) => ms.slice(0, 16);
2818
3477
  const specs = [], where = new Map();
3478
+ // (each lemma's nodes placed first, then their uses read through the places: a node's use of one after it, a case's,
3479
+ // is placed too where the lemma was proven above none of the others)
2819
3480
  for (const lm of lemmas) {
2820
- const local = new Map();
3481
+ const local = new Map(), fresh = [];
2821
3482
  lm.nodes.forEach((n, i) => {
2822
3483
  if (where.has(n.name)) {
2823
3484
  local.set(i, where.get(n.name));
2824
3485
  return;
2825
3486
  }
2826
- local.set(i, specs.length);
2827
- where.set(n.name, specs.length);
2828
- specs.push({ ...n, uses: n.uses.map(u => ({ ...u, node: local.get(u.node) ?? u.node })) });
3487
+ local.set(i, specs.length + fresh.length);
3488
+ where.set(n.name, specs.length + fresh.length);
3489
+ fresh.push(i);
2829
3490
  });
3491
+ for (const i of fresh) {
3492
+ const n = lm.nodes[i];
3493
+ specs.push({ ...n, uses: n.uses.map(u => ({ ...u, node: local.get(u.node) ?? u.node })) });
3494
+ }
2830
3495
  }
2831
3496
  // The scheme's nodes: the law's, then each companion's (a mutual induction), each its own models. A use of member i
2832
3497
  // reads node -1 - i until the nodes are placed.
@@ -2850,7 +3515,10 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2850
3515
  const first = (ms) => (prem ? [...ms.filter(held), ...ms.filter(x => !held(x))] : ms);
2851
3516
  const models = first(mb.pool).slice(0, 24), concl = concls[mi], name = mi === 0 ? title : `${title}, at ${mb.on.d.name}`;
2852
3517
  const ih = mb.uses.map(u => ({ node: -1 - (u.member ?? mi), subst: u.subst, guard: u.guard }));
2853
- const shapesAt = mb.rank ? rankShapes(mb.shapes ?? [], mb.rank, mb.uses) : mb.on && mb.on.d !== 'nat' ? [ev(mb.on.v)] : [];
3518
+ // (a termination's obligation without induction: at its variables and the values its call's path builds, as
3519
+ // `directly`'s, x :: y :: zs's size at least 3)
3520
+ const shapesAt0 = mb.rank ? rankShapes(mb.shapes ?? [], mb.rank, mb.uses) : mb.on && mb.on.d !== 'nat' ? [ev(mb.on.v)] : [];
3521
+ const shapesAt = !scheme && inTermination.on ? [...[...varSorts.keys()].map(ev), ...builtIn(p, concl)] : shapesAt0;
2854
3522
  const ihConcls = ih.map(useConcl);
2855
3523
  // Uses of the lemmas, where a lemma's largest read matches a read of this goal (unfolded), its key up to the
2856
3524
  // equalities the unfolded definitions give (any branch); twice over, the uses' own conclusions read the second time.
@@ -2899,8 +3567,8 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2899
3567
  // hypothesis at x :: xss, its definition decided there; a fusion chain's last links', drop(v + 1 + w + x, y :: z))
2900
3568
  const rankReads = mb.rank && JSON.stringify(mb.rank).includes('"op":"get"') && mb.rank.some(e => { let yes = false; walk(e, o => { if (o.op === 'get' && p.fns.some(f => f.name === o.map))
2901
3569
  yes = true; }); return yes; }) ? [mb.rank, mb.uses.map(u => mb.rank.map(e => substE(e, { vars: u.subst, maps: {}, flags: {} })))] : [];
2902
- const instsFor = (ms, us, every = false, hyps) => instancesOf(p, fs, { roots: [concl], others: us.map(useConcl), once: [rankReads, rankReads.length ? us.map(useConcl) : []], decided: us.filter(u => chained.has(u)).map(useConcl), depth, shapesAt, etaAt: [...shapesAt, ...valuesCompared(p, mb.law), ...tagged(hyps)], models: ms, every, until: t0 + attemptMs.ms, hyps });
2903
- const cases = scheme ? casesOf(p, pre.filter(q => fs.facts[q.fact].name.startsWith('fn ')).map(q => holdsAt(fs, q)), new Set(mb.law.vars.map(v => v.name)), mb.pool) : [];
3570
+ const instsFor = (ms, us, every = false, hyps) => instancesOf(p, fs, { roots: [concl], others: us.map(useConcl), once: [rankReads, rankReads.length ? us.map(useConcl) : []], decided: us.filter(u => chained.has(u)).map(useConcl), depth, shapesAt, etaAt: [...shapesAt0, ...valuesCompared(p, mb.law), ...tagged(hyps)], models: ms, every, until: t0 + attemptMs.ms, hyps });
3571
+ const cases = scheme ? casesOf(p, fs, pre.filter(q => fs.facts[q.fact].name.startsWith('fn ')).map(q => holdsAt(fs, q)), new Set(mb.law.vars.map(v => v.name)), mb.pool) : [];
2904
3572
  if (cases.length <= 1) {
2905
3573
  // One node: four uses of a lemma, twelve in all, the best first (as lemmaUsesFor ranks them).
2906
3574
  const one = capUses(uses, 12);
@@ -2951,12 +3619,39 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2951
3619
  const was = pairedKeys.skip;
2952
3620
  pairedKeys.skip = true;
2953
3621
  try {
3622
+ // Within a termination's proof (its obligations and their size laws), first without the shapes at a field's value
3623
+ // (a field of a variable, of a field, of a function's value): each is a split on that value's constructor that a
3624
+ // size's descent rarely reads, and a node with a few of them grows past its time (hmerge's size law: past 20 s with
3625
+ // them, 0.8 s without). Then the nodes as built. (Elsewhere the nodes as built alone: a law's proof often reads them,
3626
+ // length of append's at one vCPU past its 5 s with this pass first.)
3627
+ const lean = !inTermination.on ? specs : specs.map((n, i) => (i < base ? n : { ...n, insts: n.insts.filter(q => !(fs.facts[q.fact].name.startsWith('shape ') && fieldValue(q.at[0]))) }));
3628
+ if (lean.some((n, i) => n.insts.length < specs[i].insts.length)) {
3629
+ // (nine tenths for a law about naturals alone, a size law's or a decrease's, which reads no value's constructor)
3630
+ const v = withDeadline(clock() + (t0 + attemptMs.ms - clock()) * (aboutNaturals(l) ? 0.9 : 0.25), () => proveCyclic(fs.facts, lean));
3631
+ if (dataTrace)
3632
+ console.error(`[data] without the fields' shapes: ${v.proven ? 'proven' : `${v.goal}: ${v.stuck}`}`);
3633
+ if (v.proven && v.checked)
3634
+ return { verdict: v, specs: lean, main: base };
3635
+ }
2954
3636
  return { verdict: withDeadline(t0 + attemptMs.ms, () => proveCyclic(fs.facts, specs)), specs, main: base };
2955
3637
  }
2956
3638
  finally {
2957
3639
  pairedKeys.skip = was;
2958
3640
  }
2959
3641
  }
3642
+ // Whether a termination's obligations are being proven (core/data.ts's proveMeasures).
3643
+ const inTermination = { on: false };
3644
+ // A field's value: a read of a constructor's field map (`D.ctor.field`).
3645
+ const fieldValue = (e) => e?.op === 'get' && e.map.split('.').length === 3;
3646
+ // A law that compares naturals alone (sizes, a function's natural values): no equation of values of a datatype, no
3647
+ // constructor test.
3648
+ const aboutNaturals = (l) => {
3649
+ const isData = (x) => (x.op === 'ctor' ? true : x.op === 'call' ? fnOf(x.fn).ret instanceof Data : x.op === 'var' ? l.vars.some(v => v.name === x.name && v.sort instanceof Data) : x.op === 'if' ? isData(x.then) : x.op === 'match' ? x.cases.some(c => isData(c.body)) : false);
3650
+ let yes = true;
3651
+ walk(l.holds, o => { if (o.op === 'is' || (o.op === '=' && (isData(o.a) || isData(o.b))))
3652
+ yes = false; });
3653
+ return yes;
3654
+ };
2960
3655
  export const attemptMs = { ms: 8000 };
2961
3656
  // A datatype search's budgets count work, not wall time (kernel/prove.ts's `counted`: the solver's rows and each node's),
2962
3657
  // 300 units a millisecond: a search finds the same proof on any machine, at any load. On Modal (2 vCPU) the corpus's
@@ -3416,9 +4111,11 @@ function caseJoins(fs, from, insts, hyps, ms) {
3416
4111
  return c => { const es = all(c); return es.length > 0 && es.every(([a, b]) => { const lb = leaf(b); return classOf(a) !== undefined && lb !== undefined && classOf(lb) !== undefined; }); };
3417
4112
  }
3418
4113
  const holdsAt = (fs, q) => { const f = fs.facts[q.fact]; return substShared(f.holds, Object.fromEntries(f.keys.map((key, i) => [key, q.at[i]]))); };
3419
- // The models a search compares terms in: random values of the law's variables.
4114
+ // The models a search compares terms in: n distinct random values of the law's variables (of 20n draws at most; with
4115
+ // params, every draw): 240 draws held some 70 (a leaf, an empty list again and again).
3420
4116
  function modelsFor(p, l, n, seed) {
3421
- return samples(l.vars, p.params, n, seed).map(s => {
4117
+ const seen = new Set(), fresh = (s) => p.params.length > 0 || (k => !seen.has(k) && !!seen.add(k))(JSON.stringify(l.vars.map(v => s.env.get(v.name))));
4118
+ return samples(l.vars, p.params, p.params.length ? n : 20 * n, seed).filter(fresh).slice(0, n).map(s => {
3422
4119
  const m = new Model(p, s.params);
3423
4120
  const env = Object.fromEntries(l.vars.map(v => [v.name, m.code(v.sort, s.env.get(v.name))]));
3424
4121
  return { m, env };
@@ -3750,10 +4447,13 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
3750
4447
  for (const margs of argSets(mk.params, true).filter(reads))
3751
4448
  for (const pargs of argSets(pr.params.filter((_, i) => i !== di))) {
3752
4449
  const pAt = (x) => { const as = [...pargs]; as.splice(di, 0, x); return { op: 'holds', x: { op: 'call', fn: pr.name, args: as } }; };
3753
- const premise = pAt({ op: 'var', name: dvar }), conclusion = pAt({ op: 'call', fn: mk.name, args: margs });
4450
+ const premise0 = pAt({ op: 'var', name: dvar }), conclusion = pAt({ op: 'call', fn: mk.name, args: margs });
3754
4451
  const conds = [undefined, ...nats.flatMap(a2 => nats.filter(b2 => b2 !== a2).flatMap(b2 => [{ op: '<', a: { op: 'var', name: a2 }, b: { op: 'var', name: b2 } }, { op: '<=', a: { op: 'var', name: a2 }, b: { op: 'var', name: b2 } }]))];
3755
- for (const c of conds) {
3756
- const hyp = c ? { op: 'and', xs: [premise, c] } : premise;
4452
+ // (the premise at each argument of the datatype, where one alone isn't enough: a merge of two ordered lists)
4453
+ const both = margs.filter(a2 => a2.op === 'var' && a2.name !== dvar && sortOfVar.get(a2.name) === mk.ret).map(pAt);
4454
+ for (const c of [...conds, ...(both.length ? [undefined] : [])].map((c2, i) => ({ c: c2, premise: i < conds.length ? premise0 : { op: 'and', xs: [premise0, ...both] } }))) {
4455
+ const { premise } = c;
4456
+ const hyp = c.c ? { op: 'and', xs: [premise, c.c] } : premise;
3757
4457
  const { t: cy, vs } = canon({ op: 'or', xs: [{ op: 'not', x: hyp }, conclusion] });
3758
4458
  const y = cy, text = JSON.stringify(y);
3759
4459
  if (seen.has(text) || text === lawText)
@@ -4333,10 +5033,12 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4333
5033
  return two;
4334
5034
  }
4335
5035
  // The steps the law's inductions leave (lemma calculation), then the conjectures from the values.
4336
- const tc = performance.now(), calc = Array.isArray(opts.lemmas) ? [] : calculated(p, l, 2, 6);
5036
+ // (a conjecture that is the law at some of its values, or the law said as an equation with a constant, p(x) = true,
5037
+ // is proven only by proving the law: none is tried)
5038
+ const tc = performance.now(), calc = Array.isArray(opts.lemmas) ? [] : calculated(p, l, 2, 6).filter(c => !lawAgain(l, c));
4337
5039
  if (dataTrace)
4338
5040
  console.error(`[data] ${l.name}: ${calc.length} calculated in ${Math.round(performance.now() - tc)} ms`);
4339
- const cands = Array.isArray(opts.lemmas) ? opts.lemmas : [...calc, ...conjectures(p, l)];
5041
+ const cands = Array.isArray(opts.lemmas) ? opts.lemmas : [...calc, ...conjectures(p, l).filter(c => !lawAgain(l, c))];
4340
5042
  if (dataTrace)
4341
5043
  for (const c of calc)
4342
5044
  console.error(`[data] calculated ${c.name.slice(0, 200)}`);
@@ -4358,7 +5060,20 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4358
5060
  // Those the goal matches first, of those the ones of the law's shape (an implication for an implication) first, then
4359
5061
  // the fusions.
4360
5062
  const implication = (y) => y.op === 'or' && y.xs.length === 2 && y.xs[0].op === 'not';
4361
- const score = (c, hit) => (hit ? 4 : 0) + (implication(c.holds) === implication(l.holds) ? 2 : 0) + (fusion(c.holds) ? 1 : 0);
5063
+ // (and of those, the ones that take an observer, a function to a natural or a Bool the law reads at its top or that
5064
+ // one's definition reaches, through a function returning a datatype, one of the two not the law's: count through
5065
+ // insert, ordered through merge, a search tree's allBelow through its insertion; the law's step reads them where an
5066
+ // induction unfolds the law's functions)
5067
+ const fnsIn = (y) => { const out = new Set(); walk(y, o => { if (o.op === 'call')
5068
+ out.add(o.fn); }); return out; };
5069
+ const inLaw = fnsIn(l.holds), lawY = implication(l.holds) ? l.holds.xs[1] : l.holds;
5070
+ const observers = new Set([...(lawY.op === '=' ? [lawY.a, lawY.b] : lawY.op === 'holds' ? [lawY.x] : [])].flatMap(x => (x.op === 'call' && !(fnOf(x.fn).ret instanceof Data) ? [x.fn] : [])));
5071
+ for (const f of [...observers])
5072
+ for (const g of fnsIn(fnOf(f).body()))
5073
+ if (!(fnOf(g).ret instanceof Data))
5074
+ observers.add(g);
5075
+ const under = (c) => { const fs2 = [...fnsIn(c.holds)], obs = fs2.filter(f => observers.has(f)), makers = fs2.filter(f => fnOf(f).ret instanceof Data); return obs.length > 0 && makers.length > 0 && [...obs, ...makers].some(f => !inLaw.has(f)); };
5076
+ const score = (c, hit) => (hit ? 8 : 0) + (under(c) ? 4 : 0) + (implication(c.holds) === implication(l.holds) ? 2 : 0) + (fusion(c.holds) ? 1 : 0);
4362
5077
  if (dataTrace)
4363
5078
  console.error(`[data] ${l.name}: ${cands.length} conjectures at ${Math.round(clock())} of ${Math.round(until)}${cands.map(c => `\n[data] conjecture ${c.name.slice(0, 160)}`).join('')}`);
4364
5079
  // (the calculated steps first, in their order: each before the one it was calculated from)
@@ -4378,7 +5093,9 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4378
5093
  const lemmaPass = (which, most, end, cap, depths) => {
4379
5094
  // (`extra`: the calculated steps' attempts and the second ones, at most `most`, beside the conjectures' 3·most)
4380
5095
  let n = 0, since = 0, tries = 0, extra = 0;
4381
- const again = (how) => ok(proveWith(p2, fs2, l, proven, level(), opts, until, cap, depths, how), proven, p2);
5096
+ // (a termination's obligation, its lemmas given: first without induction at no unfolding (the lemma's use and the
5097
+ // constructors' sizes: toList's call on a merge, 1032 instances at one unfolding and past its time), then at one)
5098
+ const again = (how) => (opts.lemmasFirst ? ok(proveWith(p2, fs2, l, proven, level(), { ...opts, induction: false }, until, cap, [0, 1]), proven, p2) : undefined) ?? ok(proveWith(p2, fs2, l, proven, level(), opts, until, cap, depths, how), proven, p2);
4382
5099
  // A conjecture of this pass that failed is tried once more after a lemma is proven (HipSpec's loop: bind over an
4383
5100
  // append needs ++ associative, proven after it); first those, then the next of the ranking.
4384
5101
  const queue = ranked.filter(r => (which === 'hits') === r.hit), retry = [], retried = new Set();
@@ -4473,7 +5190,7 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4473
5190
  // Lemmas first (a call's decrease from size laws): those the goal reads, the others, each proven and the law tried
4474
5191
  // again after it; then the law with every lemma proven, at two unfoldings.
4475
5192
  if (opts.lemmasFirst && Array.isArray(opts.lemmas))
4476
- steps.splice(0, steps.length, () => lemmaPass('hits', 8, share(0.6), 6000, [1]), () => lemmaPass('others', 8, share(0.8), 6000, [1, 2]), () => ok(proveWith(p2, fs2, l, proven, level(), opts, until, 12000, [1, 2], 'first'), proven, p2));
5193
+ steps.splice(0, steps.length, () => lemmaPass('hits', 8, share(0.8), 6000, [1]), () => lemmaPass('others', 8, share(0.8), 6000, [1, 2]), () => ok(proveWith(p2, fs2, l, proven, level(), opts, until, 12000, [1, 2], 'first'), proven, p2));
4477
5194
  for (const [i, step] of steps.entries()) {
4478
5195
  if (clock() > until)
4479
5196
  break;
@@ -4485,6 +5202,31 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4485
5202
  }
4486
5203
  return done({ proven: false, checked: false, lemmas: [], tried, ...stuckOf(first?.last) });
4487
5204
  }
5205
+ // Whether a conjecture is the law again: the law at some values of its variables (count(0, sort(xs)) = count(0, xs)),
5206
+ // either way round, or a Bool law said as an equation with a side that is true at every value (ordered(sort(xs)) =
5207
+ // ordered([])).
5208
+ function lawAgain(l, c) {
5209
+ const free = new Set(l.vars.map(v => v.name)), at = (pat, t) => matchX(pat, t, free, new Map());
5210
+ const y = c.holds, ly = l.holds;
5211
+ if (at(ly, y))
5212
+ return true;
5213
+ if (y.op !== '=')
5214
+ return false;
5215
+ // (a law of two Bool values equal, read as the two implications: p(a) = p(b))
5216
+ const held = (z) => (z.op === 'holds' ? z.x : undefined);
5217
+ const half = ly.op === 'and' && ly.xs.length === 2 && ly.xs[0].op === 'or' && ly.xs[0].xs.length === 2 && ly.xs[0].xs[0].op === 'not' ? [held(ly.xs[0].xs[0].x), held(ly.xs[0].xs[1])] : undefined;
5218
+ const sides = ly.op === '=' ? [ly.a, ly.b] : half?.every(Boolean) ? half : undefined;
5219
+ if (sides && (at(sides, [y.a, y.b]) || at(sides, [y.b, y.a])))
5220
+ return true;
5221
+ const truth = (x) => { if (JSON.stringify(x).includes('"op":"var"'))
5222
+ return undefined; try {
5223
+ return evalX(x, new Map(), {});
5224
+ }
5225
+ catch {
5226
+ return undefined;
5227
+ } };
5228
+ return ly.op === 'holds' && [[y.a, y.b], [y.b, y.a]].some(([t, k2]) => truth(k2) === 1 && at(ly.x, t));
5229
+ }
4488
5230
  // A fusion: an equation one side of which nests a call of the program's functions in another's argument, the other side
4489
5231
  // calls on its variables alone (length(x ++ y) = length(x) + length(y), drop(n + m, xs) = drop(n, drop(m, xs)),
4490
5232
  // rev(xs ++ [x]) = x :: rev(xs)): the rewrite that takes a composition the goal reads apart. Its proof unfolds both