gdp-wired 0.44.0 → 0.46.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 (133) hide show
  1. package/README.md +58 -7
  2. package/dist/core/bitsets.d.ts +2 -0
  3. package/dist/core/bitsets.js +23 -0
  4. package/dist/core/bmc.js +6 -2
  5. package/dist/core/c/reader.d.ts +9 -1
  6. package/dist/core/c/reader.js +445 -38
  7. package/dist/core/calendar.d.ts +29 -0
  8. package/dist/core/calendar.js +82 -0
  9. package/dist/core/check.js +3 -2
  10. package/dist/core/cli.d.ts +4 -0
  11. package/dist/core/cli.js +335 -39
  12. package/dist/core/compose.js +3 -1
  13. package/dist/core/counts.d.ts +5 -2
  14. package/dist/core/counts.js +335 -88
  15. package/dist/core/cycles.js +8 -1
  16. package/dist/core/cyclic.d.ts +1 -0
  17. package/dist/core/cyclic.js +13 -7
  18. package/dist/core/data-synth.d.ts +3 -0
  19. package/dist/core/data-synth.js +252 -0
  20. package/dist/core/data.d.ts +8 -2
  21. package/dist/core/data.js +1113 -172
  22. package/dist/core/discover.js +3 -1
  23. package/dist/core/draft.d.ts +19 -0
  24. package/dist/core/draft.js +53 -0
  25. package/dist/core/dsl.d.ts +39 -3
  26. package/dist/core/dsl.js +250 -31
  27. package/dist/core/effect-prims.js +2 -2
  28. package/dist/core/effect.d.ts +1 -4
  29. package/dist/core/effect.js +1 -15
  30. package/dist/core/ex/reader.exs +17 -1
  31. package/dist/core/exists.d.ts +16 -1
  32. package/dist/core/exists.js +447 -50
  33. package/dist/core/extract-c.d.ts +2 -0
  34. package/dist/core/extract-c.js +185 -31
  35. package/dist/core/extract-check.d.ts +7 -0
  36. package/dist/core/extract-check.js +115 -3
  37. package/dist/core/extract-ex.js +3 -3
  38. package/dist/core/extract-go-check.d.ts +1 -1
  39. package/dist/core/extract-go-check.js +21 -13
  40. package/dist/core/extract-go.d.ts +1 -0
  41. package/dist/core/extract-go.js +58 -9
  42. package/dist/core/extract-ir.d.ts +1 -0
  43. package/dist/core/extract-ir.js +15 -0
  44. package/dist/core/extract-jvm.d.ts +1 -1
  45. package/dist/core/extract-jvm.js +65 -14
  46. package/dist/core/extract-orm.d.ts +12 -0
  47. package/dist/core/extract-orm.js +244 -0
  48. package/dist/core/extract-print.js +23 -1
  49. package/dist/core/extract-py.d.ts +1 -0
  50. package/dist/core/extract-py.js +4 -4
  51. package/dist/core/extract-rb.js +3 -3
  52. package/dist/core/extract-read.d.ts +25 -0
  53. package/dist/core/extract-read.js +60 -5
  54. package/dist/core/extract-rs.js +22 -20
  55. package/dist/core/extract-shapes.js +22 -0
  56. package/dist/core/extract-sol.d.ts +10 -1
  57. package/dist/core/extract-sol.js +89 -30
  58. package/dist/core/extract-step.d.ts +201 -4
  59. package/dist/core/extract-step.js +1514 -111
  60. package/dist/core/extract-swift.js +24 -13
  61. package/dist/core/extract.d.ts +9 -0
  62. package/dist/core/extract.js +88 -7
  63. package/dist/core/fiber-run.d.ts +5 -0
  64. package/dist/core/fiber-run.js +18 -0
  65. package/dist/core/fresh.d.ts +2 -2
  66. package/dist/core/fresh.js +7 -3
  67. package/dist/core/go/reader.go +7 -1
  68. package/dist/core/infer.d.ts +4 -1
  69. package/dist/core/infer.js +1020 -246
  70. package/dist/core/jvm/JavaReader.java +33 -8
  71. package/dist/core/jvm/Jvm.java +20 -1
  72. package/dist/core/jvm/KtReader.java +59 -6
  73. package/dist/core/laws.d.ts +10 -3
  74. package/dist/core/laws.js +193 -14
  75. package/dist/core/machine.d.ts +16 -3
  76. package/dist/core/machine.js +212 -28
  77. package/dist/core/nonterm.js +14 -1
  78. package/dist/core/orm/harness.js +61 -0
  79. package/dist/core/orm-fixtures/schema.prisma +5 -0
  80. package/dist/core/py/harness.py +260 -21
  81. package/dist/core/py/reader.py +278 -39
  82. package/dist/core/rb/reader.rb +52 -5
  83. package/dist/core/reader-fixtures/README.md +28 -0
  84. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  85. package/dist/core/reader-fixtures/go-685506.go +14 -0
  86. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  87. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  88. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  89. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  90. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  91. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  92. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  93. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  94. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  95. package/dist/core/relation.d.ts +1 -1
  96. package/dist/core/relation.js +29 -2
  97. package/dist/core/relational.js +4 -2
  98. package/dist/core/rs/src/main.rs +18 -2
  99. package/dist/core/sample-cache.d.ts +8 -0
  100. package/dist/core/sample-cache.js +46 -0
  101. package/dist/core/security.d.ts +38 -0
  102. package/dist/core/security.js +88 -0
  103. package/dist/core/sol/harness.py +63 -7
  104. package/dist/core/sol-concrete.d.ts +23 -0
  105. package/dist/core/sol-concrete.js +195 -0
  106. package/dist/core/solver.js +8 -5
  107. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  108. package/dist/core/system.d.ts +62 -1
  109. package/dist/core/system.js +263 -4
  110. package/dist/core/transfer.js +39 -9
  111. package/dist/core/translate.js +39 -10
  112. package/dist/core/watch.js +51 -6
  113. package/dist/interchange/check.js +10 -10
  114. package/dist/interchange/format.d.ts +4 -0
  115. package/dist/interchange/format.js +24 -6
  116. package/dist/kernel/cdcl.d.ts +5 -0
  117. package/dist/kernel/cdcl.js +88 -10
  118. package/dist/kernel/epr.js +141 -29
  119. package/dist/kernel/kernel.d.ts +31 -1
  120. package/dist/kernel/kernel.js +391 -101
  121. package/dist/kernel/model-sequence.d.ts +3 -0
  122. package/dist/kernel/model-sequence.js +34 -0
  123. package/dist/kernel/prove.d.ts +30 -1
  124. package/dist/kernel/prove.js +481 -71
  125. package/dist/kernel/reader.d.ts +3 -0
  126. package/dist/kernel/reader.js +101 -14
  127. package/dist/kernel/share.d.ts +1 -0
  128. package/dist/kernel/share.js +27 -0
  129. package/dist/lean-kernel/emit.d.ts +9 -3
  130. package/dist/lean-kernel/emit.js +200 -66
  131. package/dist/lean-kernel/lean-terms.js +5 -0
  132. package/dist/lean-kernel/library.js +10 -10
  133. package/package.json +7 -2
package/dist/core/data.js CHANGED
@@ -26,13 +26,14 @@
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, lcgFloat } 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";
33
33
  import { env, work } from "./solver.js";
34
34
  import { rankOfPaths, ranksOfCalls, showC } from "./cycles.js";
35
35
  import { proveThrough, transferPlan } from "./transfer.js";
36
+ import { synthesizedLemmas, synthesizedObserver } from "./data-synth.js";
36
37
  // --- sorts and the AST ------------------------------------------------------------------------------------------------
37
38
  export const self = { self: true };
38
39
  export const natural = 'nat';
@@ -192,6 +193,15 @@ export class Data {
192
193
  if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name))
193
194
  throw new Error(`${name}: a datatype's name is letters and digits`);
194
195
  const all = Object.entries(decl).map(([c, fs]) => ({ name: c, fields: Object.entries(fs).map(([f, s]) => ({ name: f, sort: s })) }));
196
+ // (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
197
+ // members, constructor or toString included, nor tag or size; each name letters and digits, so no map is another's)
198
+ for (const c of all) {
199
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(c.name) || c.name in this || ['ctors', 'tag', 'size'].includes(c.name))
200
+ 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(', ')}, ...)`);
201
+ for (const f of c.fields)
202
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(f.name))
203
+ throw new Error(`${name}.${c.name}.${f.name}: a field's name is letters and digits`);
204
+ }
195
205
  for (const c of all)
196
206
  for (const f of c.fields)
197
207
  if (isDataField(f.sort) && !group.includes(f.sort.data) && !declared.has(f.sort.data))
@@ -303,6 +313,11 @@ export function define(name, params, ret, body, opts = {}) {
303
313
  if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name))
304
314
  throw new Error(`${name}: a function's name is letters and digits`);
305
315
  const ps = Object.entries(params).map(([n, s]) => ({ name: n, sort: s }));
316
+ // (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
317
+ // none of them)
318
+ for (const q of ps)
319
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(q.name))
320
+ throw new Error(`${name}(${q.name}): a parameter's name is letters and digits`);
306
321
  const stated = opts.measure && measureOf(name, ps, opts.measure);
307
322
  let built, rec, failed;
308
323
  // The recursion, checked once (a refusal kept and given again).
@@ -337,7 +352,11 @@ export function define(name, params, ret, body, opts = {}) {
337
352
  return Object.assign(call, { fn });
338
353
  }
339
354
  // 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 });
355
+ export const fnParam = (name) => {
356
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name))
357
+ throw new Error(`${name}: a function parameter's name is letters and digits`);
358
+ return Object.assign((x) => new Nat({ op: 'apply', param: name, arg: natX(x) }), { param: name });
359
+ };
341
360
  const paramsIn = (t) => { const out = []; walk(t, o => { if (o.op === 'apply')
342
361
  out.push(o.param); }); return out; };
343
362
  // Each object once, in walk's order (a term shared within another is visited where walk first reaches it).
@@ -436,14 +455,15 @@ function recursion(fn) {
436
455
  if (!got) {
437
456
  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
457
  // (each of the ring given its own measure and proofs: Data.lean's wf_fix_unique_ring)
439
- const ts = termination(members, why);
458
+ const ts = terminationKept(members, why);
440
459
  members.forEach((f, a) => { f.rec = { ring: names, measure: ts[a].measure, termination: ts[a] }; });
441
460
  return { ring: names, measure: ts[0].measure, termination: ts[0] };
442
461
  }
443
462
  members.forEach((f, a) => { f.rec = { decreases: got[a], ring: names }; });
444
463
  return { decreases: got[0], ring: names };
445
464
  }
446
- export const terminationMs = { ms: 10_000 };
465
+ export const terminationMs = { ms: 10_000 }, guardedMs = { ms: 12_000 };
466
+ const guardedLeft = { ms: 0 };
447
467
  // (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
468
  // the integers, its value the same, compare/chc-adt's naturals written as Int)
449
469
  const measurable = (s) => s === 'nat' || s === 'int' || s instanceof Data;
@@ -512,7 +532,7 @@ const padded = (ring, ms) => {
512
532
  };
513
533
  const ringText = (ring, ms) => (ring.length === 1 ? showMeasure(ring[0], ms[0]) : ring.map((f, i) => `${f.name} ${showMeasure(f, ms[i])}`).join(', '));
514
534
  const callSites = (ring) => ring.flatMap((f, from) => sitesOf(f, ring.map(g => g.name)).map(s => ({ ...s, from })));
515
- function sitesOf(fn, names) {
535
+ function sitesOf(fn, names, leaves = []) {
516
536
  const out = [], yesX = { op: 'bool', c: yes.y };
517
537
  const at = (sh, name) => { let t = sh.get(name); while (t && t.op === 'var' && sh.has(t.name))
518
538
  t = sh.get(t.name); return t; };
@@ -550,7 +570,12 @@ function sitesOf(fn, names) {
550
570
  return;
551
571
  }
552
572
  };
553
- const goX = (x, w) => {
573
+ const goX = (x, w0) => {
574
+ // (off the body's spine, a leaf: its value, on its path)
575
+ const branch = x.op === 'if' || x.op === 'match' || x.op === 'natmatch';
576
+ if (w0.spine && !branch)
577
+ leaves.push({ value: x, wrap: w0.wrap, shape: w0.shape, vars: w0.vars });
578
+ const w = w0.spine && !branch ? { ...w0, spine: false } : w0, off = { ...w, spine: false };
554
579
  switch (x.op) {
555
580
  case 'var':
556
581
  case 'nat': return;
@@ -590,15 +615,15 @@ function sitesOf(fn, names) {
590
615
  case 'call':
591
616
  x.args.forEach(a => goX(a, w));
592
617
  if (names.includes(x.fn))
593
- out.push({ to: names.indexOf(x.fn), args: x.args, ...w });
618
+ out.push({ to: names.indexOf(x.fn), args: x.args, wrap: w.wrap, shape: w.shape, vars: w.vars });
594
619
  return;
595
620
  case 'if':
596
- goY(x.c, w);
621
+ goY(x.c, off);
597
622
  goX(x.then, { ...w, wrap: y => w.wrap({ op: 'or', xs: [{ op: 'not', x: x.c }, y] }) });
598
623
  goX(x.else, { ...w, wrap: y => w.wrap({ op: 'or', xs: [x.c, y] }) });
599
624
  return;
600
625
  case 'match': {
601
- goX(x.of, w);
626
+ goX(x.of, off);
602
627
  const d = dataNamed(x.data), v = x.of.op === 'var' ? x.of.name : undefined, had = v ? at(w.shape, v) : undefined;
603
628
  x.cases.forEach((c, j) => {
604
629
  if (v && had?.op === 'ctor') {
@@ -609,7 +634,7 @@ function sitesOf(fn, names) {
609
634
  }
610
635
  if (v && !had) {
611
636
  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] });
637
+ 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
638
  return;
614
639
  }
615
640
  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 +642,11 @@ function sitesOf(fn, names) {
617
642
  return;
618
643
  }
619
644
  case 'natmatch': {
620
- goX(x.of, w);
645
+ goX(x.of, off);
621
646
  const v = x.of.op === 'var' ? x.of.name : undefined;
622
647
  if (v && !at(w.shape, v)) {
623
648
  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' }] });
649
+ 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
650
  return;
626
651
  }
627
652
  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 +655,7 @@ function sitesOf(fn, names) {
630
655
  }
631
656
  }
632
657
  };
633
- goX(fn.body(), { wrap: y => y, shape: new Map(), vars: fn.params.map(q => ({ name: `${fn.name}.${q.name}`, sort: q.sort })) });
658
+ 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
659
  return out;
635
660
  }
636
661
  // A term (or a law) with the site's shape put in: each matched variable its constructor's value.
@@ -639,15 +664,100 @@ const shapedBy = (s) => {
639
664
  return go;
640
665
  };
641
666
  const ownArgs = (f) => f.params.map(q => ({ op: 'var', name: `${f.name}.${q.name}` }));
667
+ // The decrease a call makes: the callee's measure at its arguments below the caller's at its parameters (`own`),
668
+ // lexicographically (Data.lean's `lexLt`).
669
+ function lowerY(ring, ms, from, to, args, own) {
670
+ const fn = ring[from], g = ring[to];
671
+ const ints = ms[to].comps.map((c, j) => readsInt(g, c) || readsInt(fn, ms[from].comps[j]));
672
+ return lexY(ms[to].comps.map(c => measureX(g, c, args)), ms[from].comps.map(c => measureX(fn, c, own)), ints);
673
+ }
642
674
  // 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)));
675
+ // a law over the path's variables (the parameters not matched, the fields of the cases taken), each call of the ring in
676
+ // it read as a value (`lifted`). `i`: the call's place among its caller's.
677
+ function obligation(ring, ms, s, i, inv) {
678
+ const fn = ring[s.from], to = ring[s.to], shaped = shapedBy(s), vars = s.vars.filter(v => !s.shape.has(v.name));
679
+ 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
680
  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))] };
681
+ return { name, vars, holds, params: [...new Set(paramsIn(holds))] };
682
+ }
683
+ // A function's value, in its invariant.
684
+ export const valueVar = (f) => `${f.name}#value`;
685
+ // An invariant at arguments and a value: its parameters and value put in at once.
686
+ function invAt(f, y, args, r) {
687
+ const m = new Map([...f.params.map((q, i) => [`${f.name}.${q.name}`, args[i]]), [valueVar(f), r]]);
688
+ 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);
689
+ return go(y);
690
+ }
691
+ // An invariant reads its function's parameters and value alone, binds nothing (no match) and calls no function of the
692
+ // ring: each instance of it is then the same law at those values.
693
+ function checkInv(ring, inv) {
694
+ ring.forEach((f, i) => {
695
+ const y = inv[i];
696
+ if (!y)
697
+ return;
698
+ const own = new Set([...f.params.map(q => `${f.name}.${q.name}`), valueVar(f)]);
699
+ walk(y, o => {
700
+ 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)))
701
+ throw new Error(`${f.name}: an invariant reads its parameters and value alone`);
702
+ });
703
+ });
704
+ }
705
+ // Each call of the ring in a law read as a value: a new variable (pushed on `vars`) under its hypothesis, put at the
706
+ // law's top, or at the condition (`bool`) of the case of a match that encloses the call (where the case's fields are
707
+ // bound), one variable for a call written twice at one place. A call under a case with no condition between (no place for
708
+ // its hypothesis where its fields are bound) is refused. `own`: the caller's parameters, as the law reads them.
709
+ function lifted(ring, ms, inv, from, own, y, vars) {
710
+ const names = ring.map(f => f.name), taken = new Set();
711
+ walk([y, own], o => { if (o.op === 'var')
712
+ taken.add(o.name); });
713
+ const level = (z) => {
714
+ const hyps = [], seen = new Map();
715
+ const go = (t, bound) => {
716
+ if (Array.isArray(t))
717
+ return t.map(u => go(u, bound));
718
+ if (!t || typeof t !== 'object')
719
+ return t;
720
+ const o = t;
721
+ if (o.op === 'bool')
722
+ return { op: 'bool', c: level(o.c) };
723
+ if (o.op === 'match')
724
+ return { ...o, of: go(o.of, bound), cases: o.cases.map(c => ({ binds: c.binds, body: go(c.body, true) })) };
725
+ if (o.op === 'natmatch')
726
+ return { ...o, of: go(o.of, bound), zero: go(o.zero, true), succ: go(o.succ, true) };
727
+ if (o.op === 'call' && names.includes(o.fn)) {
728
+ if (bound)
729
+ 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)`);
730
+ const to = names.indexOf(o.fn), args = o.args.map(a => go(a, false)), key = JSON.stringify([o.fn, args]);
731
+ let r = seen.get(key);
732
+ if (!r) {
733
+ const v = { name: `${ring[from].name}#r${vars.length}`, sort: ring[to].ret };
734
+ // (a name no variable of the law has: the function's name is letters and digits, a field's binding ends in digits)
735
+ if (vars.some(w => w.name === v.name) || taken.has(v.name))
736
+ throw new Error(`${v.name}: a variable of the law already`);
737
+ vars.push(v);
738
+ r = { op: 'var', name: v.name };
739
+ seen.set(key, r);
740
+ const i = inv[to];
741
+ if (i)
742
+ hyps.push({ op: 'or', xs: [{ op: 'not', x: lowerY(ring, ms, from, to, args, own) }, invAt(ring[to], i, args, r)] });
743
+ }
744
+ return r;
745
+ }
746
+ return Object.fromEntries(Object.entries(o).map(([key, v]) => [key, go(v, bound)]));
747
+ };
748
+ const body = go(z, false);
749
+ return hyps.length ? { op: 'or', xs: [...hyps.map(h => ({ op: 'not', x: h })), body] } : body;
750
+ };
751
+ return level(y);
752
+ }
753
+ class NestedRefusal extends Error {
754
+ }
755
+ // A value the body ends at keeps its function's invariant: under the leaf's path, the invariant at the parameters and the
756
+ // leaf's value, each call of the ring in it read as a value. `i`: the leaf's place among its function's.
757
+ function keeps(ring, ms, inv, from, l, i) {
758
+ const fn = ring[from], shaped = shapedBy(l), vars = l.vars.filter(v => !l.shape.has(v.name));
759
+ const holds = lifted(ring, ms, inv, from, shaped(ownArgs(fn)), shaped(l.wrap(invAt(fn, inv[from], ownArgs(fn), l.value))), vars);
760
+ return { name: `${fn.name}'s value ${i + 1} keeps ${showY(inv[from])}`, vars, holds, params: [...new Set(paramsIn(holds))] };
651
761
  }
652
762
  let tracing;
653
763
  const featOf = (f, vs) => f.params.map((p, i) => sizeOfValue(p.sort, vs[i]));
@@ -721,7 +831,8 @@ const pathSamples = (vars, params, cond, n = 240, seed = 19) => {
721
831
  // 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
832
  // its arguments, the bound the values give (an equation where they give one difference), 2·g(n) ≤ n + b for a natural
723
833
  // of one natural, those its values refute dropped; each a lemma for proveData to prove by induction and use.
724
- function sizeLaws(l, ring) {
834
+ // `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).
835
+ function sizeLaws(l, ring, lower = false) {
725
836
  const seen = new Set(), helpers = [];
726
837
  walk(l.holds, o => { if (o.op === 'call' && !ring.includes(o.fn) && !seen.has(o.fn)) {
727
838
  seen.add(o.fn);
@@ -729,25 +840,325 @@ function sizeLaws(l, ring) {
729
840
  if (sized(g.ret))
730
841
  helpers.push(g);
731
842
  } });
732
- const out = [];
843
+ const out = [], rings = new Set();
733
844
  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;
845
+ // (a function of one value that halves it, evens or odds of a list, half of a natural: twice its size is bounded too)
846
+ const boundsOf = (g, vars) => {
738
847
  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)))) {
848
+ const twice = vars.length === 1 && sized(vars[0].sort) ? upperBounds(sizeBounds(call, g.ret, vars, envs, 2), 1).filter(b => b.lo !== b.hi) : [];
849
+ // (twice the size's first: it implies the plain bound where it holds, and a halving's decrease reads it alone)
850
+ return [...twice, ...upperBounds(sizeBounds(call, g.ret, vars, envs))].filter(b => b.of.every(i => sized(vars[i].sort))).flatMap((b) => {
741
851
  const lhs0 = b.coef === 1 ? sizeX(g.ret, call) : { op: 'mul', k: b.coef, a: sizeX(g.ret, call) };
742
852
  const sum = b.of.map(i => sizeX(vars[i].sort, { op: 'var', name: vars[i].name })).reduce((a, c) => ({ op: 'add', a, b: c }));
853
+ // (an upper bound is what a decrease reads: an equation's other half is a proof's cost for nothing, but where a
854
+ // guard at a call reads it, `lower`)
743
855
  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 };
856
+ return [{ op: '<=', a: lhs, b: rhs }, ...(lower && b.lo === b.hi ? [{ op: '<=', a: rhs, b: lhs }] : [])];
857
+ });
858
+ };
859
+ for (const g of helpers.slice(0, 4)) {
860
+ const vars = g.params.map((q, i) => ({ name: `${q.name}${i}`, sort: q.sort }));
861
+ if (!vars.some(v => sized(v.sort)))
862
+ continue;
863
+ // Functions that call each other over the same parameters (evens and odds): their bounds at once, one law, each
864
+ // bound the induction step of another's (evens(y :: t) = y :: odds(t)).
865
+ 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];
866
+ if (ring.length > 1) {
867
+ if (rings.has(g.ring.join()))
868
+ continue;
869
+ rings.add(g.ring.join());
870
+ const all = ring.map(h => boundsOf(h, vars));
871
+ // (those of twice the size one law, the plain bounds another: either alone is an induction's; a halving's first)
872
+ for (const twice of [true, false]) {
873
+ const ys = all.flatMap(bs => bs.filter(b => (b.op === '<=' && JSON.stringify(b.a).includes('"op":"mul"')) === twice));
874
+ if (ys.length) {
875
+ const holds = ys.length === 1 ? ys[0] : { op: 'and', xs: ys };
876
+ out.push({ name: `size law: ${showY(holds)}`, vars, holds, params: [] });
877
+ }
878
+ }
879
+ continue;
880
+ }
881
+ for (const holds of boundsOf(g, vars))
746
882
  out.push({ name: `size law: ${showY(holds)}`, vars, holds, params: [] });
883
+ }
884
+ return out;
885
+ }
886
+ const natK = (n) => ({ op: 'nat', value: n }), plusK = (a, n) => (n ? { op: 'add', a, b: natK(n) } : a);
887
+ const allY = (ys) => (ys.length === 1 ? ys[0] : { op: 'and', xs: ys });
888
+ const atomY = (ps, a, ts) => ('size' in a ? { op: '<=', a: natK(a.c), b: sizeX(ps[a.size].sort, ts[a.size]) }
889
+ : '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]]) }
890
+ : { op: 'holds', x: { op: 'call', fn: a.reach, args: ts } });
891
+ // For each leaf of a structural function's body that calls it no more (delete's `tail` where the item is found), the
892
+ // predicate that its run ends there: the body's choices kept, that leaf true, the others false, a leaf that recurs the
893
+ // predicate at its calls' arguments. Each is a function defined for it, structural as the function is.
894
+ const madeReaches = new Map();
895
+ function reaches(g) {
896
+ const had = madeReaches.get(g.name);
897
+ if (had)
898
+ return had;
899
+ const out = [];
900
+ madeReaches.set(g.name, out);
901
+ try {
902
+ if (g.ring.length !== 1 || g.decreases === undefined)
903
+ return out;
904
+ }
905
+ catch {
906
+ return out;
907
+ }
908
+ const leaves = [], collect = (x) => { if (x.op === 'if') {
909
+ collect(x.then);
910
+ collect(x.else);
911
+ }
912
+ else if (x.op === 'match')
913
+ x.cases.forEach(c => collect(c.body));
914
+ else if (x.op === 'natmatch') {
915
+ collect(x.zero);
916
+ collect(x.succ);
917
+ }
918
+ else
919
+ leaves.push(x); };
920
+ collect(g.body());
921
+ const recurs = (x) => { const cs = []; walk(x, o => { if (o.op === 'call' && o.fn === g.name)
922
+ cs.push(o.args); }); return cs; };
923
+ const ends = leaves.filter(x => !recurs(x).length);
924
+ if (ends.length > 4 || ends.length === leaves.length || leaves.some(x => recurs(x).some(as => as.some(a => recurs(a).length))))
925
+ return out;
926
+ // (a condition, as the surface writes one: a match's cases conditions, an if (c ∧ a) ∨ (¬c ∧ b))
927
+ for (const end of ends) {
928
+ const name = `reach_${g.name}_${ends.indexOf(end)}`;
929
+ if (fns.has(name))
930
+ continue;
931
+ const ren = new Map(g.params.map(q => [`${g.name}.${q.name}`, { op: 'var', name: `${name}.${q.name}` }]));
932
+ const go = (x) => {
933
+ if (x.op === 'if')
934
+ return { op: 'or', xs: [{ op: 'and', xs: [x.c, go(x.then)] }, { op: 'and', xs: [{ op: 'not', x: x.c }, go(x.else)] }] };
935
+ if (x.op === 'match')
936
+ return { op: 'holds', x: { ...x, cases: x.cases.map(c => ({ ...c, body: { op: 'bool', c: go(c.body) } })) } };
937
+ if (x.op === 'natmatch')
938
+ return { op: 'holds', x: { ...x, zero: { op: 'bool', c: go(x.zero) }, succ: { op: 'bool', c: go(x.succ) } } };
939
+ if (x === end)
940
+ return yes.y;
941
+ const cs = recurs(x).map(as => ({ op: 'holds', x: { op: 'call', fn: name, args: as } }));
942
+ return !cs.length ? no.y : cs.length === 1 ? cs[0] : { op: 'or', xs: cs };
943
+ };
944
+ const body = substXs({ op: 'bool', c: go(g.body()) }, ren);
945
+ define(name, Object.fromEntries(g.params.map(q => [q.name, q.sort])), boolean, () => new Bool(body.c));
946
+ out.push(name);
947
+ }
948
+ return out;
949
+ }
950
+ // A predicate's call at constructors unfolded once (delete's run on x :: xs reaches its end: m = x, or its run on xs
951
+ // does), the step a guard at a constructor's value is proven by.
952
+ function stepped(y) {
953
+ if (y.op !== 'holds' || y.x.op !== 'call' || !y.x.args.some(a => a.op === 'ctor'))
954
+ return y;
955
+ const f = fnOf(y.x.fn), args = y.x.args;
956
+ 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);
957
+ // (as a condition: a choice its sides' conditions under its own, a side true or false read so)
958
+ const T = JSON.stringify(yes.y), F = JSON.stringify(no.y);
959
+ const cy = (x) => {
960
+ if (x.op === 'bool')
961
+ return x.c;
962
+ if (x.op !== 'if')
963
+ return { op: 'holds', x };
964
+ const a = cy(x.then), b = cy(x.else), [ta, tb] = [JSON.stringify(a), JSON.stringify(b)];
965
+ 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] })
966
+ : 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] }] };
967
+ };
968
+ return cy(go(substXs(f.body(), new Map(f.params.map((q, i) => [`${f.name}.${q.name}`, args[i]])))));
969
+ }
970
+ // `lower`: of a guard at a call, guard ⇒ c ≤ S(g(y…)), the least size the values give under it above the least without
971
+ // (from 2 on, half of a natural is at least 1).
972
+ function guardedLaws(l, s, ring, lower = false) {
973
+ const cond = shapedBy(s)(s.wrap(no.y)), site = pathSamples(l.vars, l.params, e => !evalY(cond, e.env, e.params));
974
+ if (site.length < 12)
975
+ return [];
976
+ // (a lower bound of the calls a guard bounds below: those on the larger side of a comparison)
977
+ const larger = [];
978
+ if (lower)
979
+ walk(l.holds, o => { if (o.op === '<=' || o.op === '<')
980
+ larger.push(o.b); });
981
+ // (each call at its depth among the helpers' calls: an inner call's guarded law is what an outer guard reads, so inner
982
+ // first, and only an outermost call's group is the decrease's)
983
+ const calls = new Map();
984
+ const visit = (t, depth) => {
985
+ if (!t || typeof t !== 'object')
986
+ return;
987
+ if (Array.isArray(t)) {
988
+ t.forEach(u => visit(u, depth));
989
+ return;
747
990
  }
991
+ const o = t;
992
+ if (o.op === 'call' && !ring.includes(o.fn)) {
993
+ const g = fnOf(o.fn);
994
+ if (sized(g.ret) && g.params.some(q => sized(q.sort)) && !calls.has(JSON.stringify(o)))
995
+ calls.set(JSON.stringify(o), { g, args: o.args, depth });
996
+ o.args.forEach(a => visit(a, depth + 1));
997
+ return;
998
+ }
999
+ Object.values(o).forEach(v => visit(v, depth));
1000
+ };
1001
+ visit(lower ? larger : l.holds, 0);
1002
+ const out = [];
1003
+ const lawOf = (name, vars, holds) => ({ name, vars, holds, params: [...new Set(paramsIn(holds))] });
1004
+ const tries = (f) => { try {
1005
+ return f();
1006
+ }
1007
+ catch {
1008
+ return false;
1009
+ } };
1010
+ for (const { g, args, depth } of [...calls.values()].slice(0, 4).sort((a, b) => b.depth - a.depth)) {
1011
+ const ix = g.params.flatMap((q, i) => (sized(q.sort) ? [i] : []));
1012
+ const sz = site.flatMap(e => { try {
1013
+ return [args.map((a, i) => (ix.includes(i) ? sizeOfValue(g.params[i].sort, evalX(a, e.env, e.params)) : 0))];
1014
+ }
1015
+ catch {
1016
+ return [];
1017
+ } });
1018
+ if (sz.length < 12)
1019
+ continue;
1020
+ const atoms = [];
1021
+ for (const i of ix) {
1022
+ const c = Math.min(...sz.map(r => r[i]));
1023
+ if (c > (g.params[i].sort === 'nat' ? 0 : 1))
1024
+ atoms.push({ size: i, c });
1025
+ }
1026
+ for (const i of ix)
1027
+ for (const j of ix) {
1028
+ const d = i === j ? 0 : Math.min(...sz.map(r => r[j] - r[i]));
1029
+ if (d >= 1)
1030
+ atoms.push({ diff: [i, j], d });
1031
+ }
1032
+ for (const p of reaches(g))
1033
+ if (site.every(e => tries(() => evalX({ op: 'call', fn: p, args }, e.env, e.params) === 1)))
1034
+ atoms.push({ reach: p });
1035
+ if (!atoms.length)
1036
+ continue;
1037
+ const vars = g.params.map((q, i) => ({ name: `${q.name}${i}`, sort: q.sort })), vs = vars.map(v => ({ op: 'var', name: v.name }));
1038
+ const call = { op: 'call', fn: g.name, args: vs }, pool = pathSamples(vars, [], () => true, 800, 29);
1039
+ 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))); };
1040
+ const tight = (as) => sizeBounds(call, g.ret, vars, within(as));
1041
+ const least = (es) => { const ns = es.flatMap(e => { try {
1042
+ return [sizeOfValue(g.ret, evalX(call, e.env, e.params))];
1043
+ }
1044
+ catch {
1045
+ return [];
1046
+ } }); return ns.length < 12 ? -1 : Math.min(...ns); };
1047
+ const lawOfGuard = (guard, bound) => {
1048
+ 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);
1049
+ // (the guard at the call first, its step before it, then the guarded law: a group's last is the guarded law)
1050
+ 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))))] : []),
1051
+ lawOf(`${l.name}: ${showY(allY(at))}`, l.vars, shaped(s.wrap(allY(at)))),
1052
+ lawOf(`size law under ${showY(gy)}: ${showY(bound)}`, vars, { op: 'or', xs: [{ op: 'not', x: gy }, bound] })] });
1053
+ };
1054
+ if (lower) {
1055
+ const c = least(within(atoms));
1056
+ if (c <= least(pool))
1057
+ continue;
1058
+ let guard = atoms;
1059
+ for (const a of [...atoms].reverse()) {
1060
+ const fewer = guard.filter(x => x !== a);
1061
+ if (fewer.length && least(within(fewer)) >= c)
1062
+ guard = fewer;
1063
+ }
1064
+ lawOfGuard(guard, { op: '<=', a: natK(c), b: sizeX(g.ret, call) });
1065
+ continue;
1066
+ }
1067
+ const base = sizeBounds(call, g.ret, vars, pool), under = tight(atoms);
1068
+ if (!under.length || !base.length)
1069
+ continue;
1070
+ // (of the bounds a size law states without the guard, the one over the fewest arguments the guard lowers most)
1071
+ 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];
1072
+ if (n === undefined)
1073
+ continue;
1074
+ let guard = atoms;
1075
+ // (a reach dropped first, then a difference, then a size: the guard at the call is then a size's, by arithmetic)
1076
+ for (const a of [...atoms].reverse()) {
1077
+ const fewer = guard.filter(x => x !== a), b = fewer.length ? tight(fewer) : [];
1078
+ if (b.length && b[n].hi <= under[n].hi)
1079
+ guard = fewer;
1080
+ }
1081
+ 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 }));
1082
+ lawOfGuard(guard, { op: '<=', a: plusK(sizeX(g.ret, call), Math.max(0, -hi)), b: plusK(sum, Math.max(0, hi)) });
748
1083
  }
749
1084
  return out;
750
1085
  }
1086
+ // An obligation through lemmas proven in order, each above those before (a guarded size law reads the size law it
1087
+ // strengthens, the guard at the call its step at a constructor), in groups (the size laws, then each call's guarded law
1088
+ // and its guard), the obligation tried above them after each group, without conjectures.
1089
+ function throughLemmas(l, groups, until) {
1090
+ const p = programOf([l, ...groups.flatMap(g => g.laws)]), fs = factsOf(p), proven = [];
1091
+ 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)))) });
1092
+ const prove = (c, guardAt) => {
1093
+ // (a guard at the call: by its step and the definitions unfolded, no induction; then alone, above none of the
1094
+ // lemmas, whose instances are its proof's cost where it reads none; then above them)
1095
+ // (the lemmas' uses alone first, no definition unfolded, then at one unfolding)
1096
+ 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;
1097
+ const alone = quick?.out || !guardAt ? quick : searchIn(c, { lemmas: false, samples: 200 }, Math.min(until, clock() + 1500), { ...ctx(), base: [] });
1098
+ const r = alone?.out ? alone : searchIn(c, { lemmas: false, samples: 200 }, Math.min(until, clock() + 3000), ctx());
1099
+ if (dataTrace)
1100
+ console.error(`[data] through ${c.name}: ${r.out ? 'proven' : 'not proven'}`);
1101
+ if (r.out)
1102
+ proven.push(r.out);
1103
+ return !!r.out;
1104
+ };
1105
+ const decrease = () => {
1106
+ // (first the lemmas' uses alone, no definition unfolded, then at one unfolding: the guarded law at the call and its
1107
+ // guard there are the decrease; then the search without conjectures)
1108
+ const r = proveWith(p, fs, l, proven, ctx().level + 1, { induction: false }, Math.min(until, clock() + 3000), 3000, [0, 1]);
1109
+ if (r.out && r.verdict) {
1110
+ const nodes = r.out.nodes, seen = new Set(), todo = [nodes.indexOf(r.out.spec)];
1111
+ while (todo.length) {
1112
+ const k2 = todo.pop();
1113
+ if (seen.has(k2))
1114
+ continue;
1115
+ seen.add(k2);
1116
+ for (const u of nodes[k2].uses)
1117
+ todo.push(u.node);
1118
+ }
1119
+ 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 };
1120
+ }
1121
+ for (const opts of [{ lemmas: false, induction: false }, { lemmas: false }]) {
1122
+ if (clock() > until)
1123
+ return undefined;
1124
+ const v = searchIn(l, opts, Math.min(until, clock() + 4000), ctx()).verdict;
1125
+ if (v.proven && v.checked)
1126
+ return v;
1127
+ if (v.counterexample)
1128
+ return undefined;
1129
+ }
1130
+ return undefined;
1131
+ };
1132
+ // (a group's lemma not proven is tried once more after the groups after it: a guard at one call may read the guarded
1133
+ // law another's group proves, half a length below the length from 2 items on)
1134
+ const left = [];
1135
+ for (const { laws, then } of groups) {
1136
+ const failed = [];
1137
+ for (const [j, c] of laws.entries()) {
1138
+ if (clock() > until)
1139
+ return undefined;
1140
+ if (!prove(c, j < laws.length - 1))
1141
+ failed.push(c);
1142
+ }
1143
+ if (failed.length) {
1144
+ left.push({ failed, laws, then });
1145
+ continue;
1146
+ }
1147
+ if (!then || !proven.length)
1148
+ continue;
1149
+ const v = decrease();
1150
+ if (v)
1151
+ return v;
1152
+ }
1153
+ for (const { failed, laws, then } of left) {
1154
+ if (!failed.every(c => clock() < until && prove(c, laws.indexOf(c) < laws.length - 1)) || !then)
1155
+ continue;
1156
+ const v = decrease();
1157
+ if (v)
1158
+ return v;
1159
+ }
1160
+ return undefined;
1161
+ }
751
1162
  // The calls' relation (core/relation.ts's form): a location per function of the ring, its parameters' sizes the state
752
1163
  // (`s<i>_<k>`), a path per call: the caller's parameters' sizes and the callee's arguments' (`a<k>`, the turn's
753
1164
  // inputs) bounded by the sizes of the path's variables (`v<j>`) where its values give a bound (`sizeBounds`).
@@ -791,7 +1202,7 @@ function callRelation(ring, sites) {
791
1202
  }
792
1203
  function candidates(ring, edges, sites, until) {
793
1204
  if (ring.some(f => f.stated))
794
- return [ring.map(f => f.stated ?? { comps: [{ coef: f.params.map(() => 0), c: 0 }] })];
1205
+ return [padded(ring, ring.map(f => f.stated ?? { comps: [{ coef: f.params.map(() => 0), c: 0 }] }))];
795
1206
  const out = [];
796
1207
  if (ring.length === 1) {
797
1208
  const fn = ring[0], ix = fn.params.flatMap((p, i) => (measurable(p.sort) ? [i] : []));
@@ -816,16 +1227,7 @@ function candidates(ring, edges, sites, until) {
816
1227
  }
817
1228
  // The LP's rank over the runs (coefficients and constants), a node per function, where the runs give edges; for a ring,
818
1229
  // 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
- };
1230
+ const fromRuns = () => runsRank(ring, edges, edges);
829
1231
  // The relation's rank: per location (each function), its components' forms over the function's parameters' sizes.
830
1232
  const fromRelation = () => {
831
1233
  const rel = callRelation(ring, sites);
@@ -844,6 +1246,9 @@ function candidates(ring, edges, sites, until) {
844
1246
  const runs = ring.length === 1 ? fromRuns() : undefined;
845
1247
  if (runs)
846
1248
  out.push(runs);
1249
+ // (a ring's first: a size across it, the rest after it, below)
1250
+ if (ring.length > 1)
1251
+ out.push(...ringFolds(ring, edges));
847
1252
  const rel = fromRelation();
848
1253
  if (rel)
849
1254
  out.push(rel);
@@ -871,37 +1276,97 @@ function foldMeasures(fn, edges) {
871
1276
  if (!edges.length)
872
1277
  return out;
873
1278
  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)
1279
+ const wt = q.sort instanceof Data ? weightings(q.sort) : undefined;
1280
+ if (!wt)
881
1281
  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);
1282
+ for (const ws of wt.combos) {
1283
+ const w = wt.weight(ws);
891
1284
  if (!edges.every(e => w(e.tv[i]) < w(e.sv[i])))
892
1285
  continue;
893
- out.push({ comps: [{ coef: fn.params.map(() => 0), c: 0, fold: { fn: foldFn(d, fields, ws), of: i } }] });
1286
+ const made = foldFn(q.sort, wt.fields, ws);
1287
+ if (!made)
1288
+ continue;
1289
+ out.push({ comps: [{ coef: fn.params.map(() => 0), c: 0, fold: { fn: made, of: i } }] });
1290
+ if (out.length >= 2)
1291
+ return out;
1292
+ }
1293
+ }
1294
+ return out;
1295
+ }
1296
+ // A datatype's weightings (one datatype, not a group, not abstract): each field's choices, of the datatype 1 or 2, of
1297
+ // another datatype 0 or 1, else 0; every combination but the plain size's (tried before: 1 on the datatype's fields, 0 on
1298
+ // the others'), the lightest first, and the fold of each at a value.
1299
+ function weightings(d) {
1300
+ if (d.group.length > 1 || d.abstract)
1301
+ return undefined;
1302
+ const fields = d.ctors.flatMap((c, j) => c.fields.map((f, k) => ({ j, k, sort: fieldSort(f) })));
1303
+ const choices = fields.map(f => (f.sort === d ? [1, 2] : f.sort instanceof Data ? [0, 1] : [0]));
1304
+ if (choices.reduce((n, c) => n * c.length, 1) > 64)
1305
+ return undefined;
1306
+ let combos = [[]];
1307
+ for (const c of choices)
1308
+ combos = combos.flatMap(a => c.map(w => [...a, w]));
1309
+ const size = fields.map(f => (f.sort === d ? 1 : 0));
1310
+ 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));
1311
+ 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; };
1312
+ return { fields, combos, weight, size };
1313
+ }
1314
+ // The LP's rank over the runs (core/cycles.ts's ranksOfCalls): a node per function of the ring, each its own coefficients
1315
+ // of its parameters' sizes and constant per component, every call of `edges` lowered (`points`: the calls whose ends the
1316
+ // rank is at least 0 at).
1317
+ function runsRank(ring, edges, points) {
1318
+ if (!edges.length)
1319
+ return undefined;
1320
+ const vars = ring.map((f, i) => f.params.flatMap((q, j) => (measurable(q.sort) ? [`p${i}_${j}`] : [])));
1321
+ const env = (i, xs) => Object.fromEntries(vars[i].map(x => [x, xs[Number(x.split('_')[1])]]));
1322
+ 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) })));
1323
+ if (r.left || !r.comps.length)
1324
+ return undefined;
1325
+ 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 })) }));
1326
+ }
1327
+ // A size across a ring first, the rest after it: one weighting of a datatype, its fold at each function's first parameter
1328
+ // of it (0 at a function with none) the first component, which no call of the runs raises and some lower; the calls it
1329
+ // leaves equal ranked after it by the LP (`runsRank`). The plain size first (a Stooge sort's ring: the size, then a phase
1330
+ // the LP fits, the sort above its thirds' from 3 items on and below them under 3), then the weightings, the lightest first
1331
+ // (a formula's models through a ring of three, `Not` weighing its formula twice: ¬(p ∧ q) to p ∧ ¬q, no size falling).
1332
+ // The first two the runs don't contradict, by every datatype the ring's parameters have.
1333
+ function ringFolds(ring, edges) {
1334
+ const out = [];
1335
+ if (!edges.length)
1336
+ return out;
1337
+ const ds = [...new Set(ring.flatMap(f => f.params.map(q => q.sort)))].filter((s) => s instanceof Data);
1338
+ for (const d of ds) {
1339
+ const wt = weightings(d);
1340
+ if (!wt)
1341
+ continue;
1342
+ const at = ring.map(f => f.params.findIndex(q => q.sort === d));
1343
+ for (const ws of [wt.size, ...wt.combos]) {
1344
+ const w = wt.weight(ws), val = (i, vs) => (at[i] < 0 ? 0 : w(vs[at[i]])), plain = ws === wt.size;
1345
+ const ts = edges.map(e => [val(e.to, e.tv), val(e.from, e.sv)]);
1346
+ if (ts.some(([a, b]) => a > b) || !ts.some(([a, b]) => a < b))
1347
+ continue;
1348
+ const rest = edges.filter((_, n) => ts[n][0] === ts[n][1]), tail = rest.length ? runsRank(ring, rest, edges) : ring.map(() => ({ comps: [] }));
1349
+ if (!tail)
1350
+ continue;
1351
+ const made = plain ? '' : foldFn(d, wt.fields, ws);
1352
+ if (made === undefined)
1353
+ continue;
1354
+ 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] } } : {}) });
1355
+ out.push(ring.map((f, i) => ({ comps: [first(f, i), ...tail[i].comps] })));
894
1356
  if (out.length >= 2)
895
1357
  return out;
896
1358
  }
897
1359
  }
898
1360
  return out;
899
1361
  }
900
- // The fold of those weights, defined once.
1362
+ // The fold of those weights, defined once; none where its name is a function this didn't define (a user's own
1363
+ // `foldList_12`, of another sort, never read as the fold).
1364
+ // (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)
1365
+ const madeFolds = new Map();
901
1366
  function foldFn(d, fields, ws) {
902
1367
  const name = `fold${d.name}_${ws.join('')}`;
903
1368
  if (fns.has(name))
904
- return name;
1369
+ return madeFolds.get(name) === fns.get(name) ? name : undefined;
905
1370
  const at = new Map(fields.map((f, n) => [`${f.j}.${f.k}`, ws[n]]));
906
1371
  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
1372
  const w = at.get(`${j}.${k}`), s2 = fieldSort(f);
@@ -910,6 +1375,77 @@ function foldFn(d, fields, ws) {
910
1375
  const part = s2 === d ? self(fs[f.name]) : fs[f.name].size();
911
1376
  return w === 1 ? t.plus(part) : t.plus(part.times(w));
912
1377
  }, new Nat({ op: 'nat', value: 1 }))]))));
1378
+ madeFolds.set(name, self.fn);
1379
+ return name;
1380
+ }
1381
+ // A well-founded function's calls, counted: `f_calls`, of f's parameters, f's body with each choice kept and each value
1382
+ // 1 plus f_calls at the arguments of each call of f it makes (quicksort's: 1 + calls(filter≤ xs) + calls(filter> xs)).
1383
+ // It recurs where f does, at the same arguments under the same choices, so f's measure falls at its calls as at f's: its
1384
+ // termination is proven as any function's, f's measure given. Its use: the rank of f's recursion as an induction (below,
1385
+ // `schemes`), each step's descent one unfolding of it at the case, where f's measure falls only by a lemma (a filter's
1386
+ // size law), which a cyclic proof's descents can't read. None for a ring, or a call of f within f's arguments or choices.
1387
+ const madeCalls = new Map();
1388
+ function callsFn(f) {
1389
+ const name = `${f.name}_calls`;
1390
+ if (fns.has(name))
1391
+ return madeCalls.get(name) === fns.get(name) ? name : undefined;
1392
+ if (f.ring.length !== 1 || f.decreases !== undefined || !f.measure)
1393
+ return undefined;
1394
+ const has = (t) => { let yes = false; walk(t, o => { if (o.op === 'call' && o.fn === f.name)
1395
+ yes = true; }); return yes; };
1396
+ let ok = true;
1397
+ const sum = (xs) => { const ys = xs.filter(x => !(x.op === 'nat' && x.value === 0)); return ys.length ? ys.reduce((a, b) => ({ op: 'add', a, b })) : { op: 'nat', value: 0 }; };
1398
+ const count = (t) => {
1399
+ if (!has(t))
1400
+ return { op: 'nat', value: 0 };
1401
+ if (t.op === 'call' && t.fn === f.name) {
1402
+ if (has(t.args))
1403
+ ok = false;
1404
+ return { op: 'call', fn: name, args: t.args };
1405
+ }
1406
+ if (t.op === 'match') {
1407
+ if (has(t.of))
1408
+ ok = false;
1409
+ return { ...t, cases: t.cases.map(c => ({ binds: c.binds, body: count(c.body) })) };
1410
+ }
1411
+ if (t.op === 'natmatch') {
1412
+ if (has(t.of))
1413
+ ok = false;
1414
+ return { ...t, zero: count(t.zero), succ: count(t.succ) };
1415
+ }
1416
+ if (t.op === 'if') {
1417
+ if (has(t.c))
1418
+ ok = false;
1419
+ return { op: 'if', c: t.c, then: count(t.then), else: count(t.else) };
1420
+ }
1421
+ // (any other term: the calls its parts make, a condition's among them)
1422
+ const parts = [], go = (x) => { if (!x || typeof x !== 'object')
1423
+ return; if (Array.isArray(x)) {
1424
+ x.forEach(go);
1425
+ return;
1426
+ } const o = x; if ('op' in o && ['match', 'natmatch', 'if', 'call', 'var', 'nat', 'int', 'add', 'ctor'].includes(o.op)) {
1427
+ parts.push(count(o));
1428
+ return;
1429
+ } for (const v of Object.values(o))
1430
+ go(v); };
1431
+ for (const v of Object.values(t))
1432
+ go(v);
1433
+ return sum(parts);
1434
+ };
1435
+ const pre = `${f.name}.`;
1436
+ const body = JSON.parse(JSON.stringify(sum([{ op: 'nat', value: 1 }, count(f.body())])), (_, v) => (v && typeof v === 'object' && v.op === 'var' && typeof v.name === 'string' && v.name.startsWith(pre) ? { op: 'var', name: `${name}.${v.name.slice(pre.length)}` } : v));
1437
+ if (!ok)
1438
+ return undefined;
1439
+ const self = define(name, Object.fromEntries(f.params.map(q => [q.name, q.sort])), natural, () => new Nat(body));
1440
+ self.fn.stated = f.measure;
1441
+ madeCalls.set(name, self.fn);
1442
+ try {
1443
+ void self.fn.ring;
1444
+ }
1445
+ catch {
1446
+ madeCalls.delete(name);
1447
+ return undefined;
1448
+ }
913
1449
  return name;
914
1450
  }
915
1451
  // An obligation as one node of a cyclic proof (no use, no models): its conclusion, each definition it reads unfolded
@@ -920,11 +1456,7 @@ function directly(law, ms) {
920
1456
  varSorts = new Map(law.vars.flatMap(v => (v.sort instanceof Data ? [[v.name, v.sort]] : [])));
921
1457
  const until = clock() + ms;
922
1458
  // (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 });
1459
+ 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
1460
  if (clock() > until)
929
1461
  return undefined;
930
1462
  const was = pairedKeys.skip;
@@ -937,14 +1469,46 @@ function directly(law, ms) {
937
1469
  pairedKeys.skip = was;
938
1470
  }
939
1471
  }
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);
1472
+ // The values of a datatype a term builds by its constructors (each of fields), each once.
1473
+ function builtIn(p, t) {
1474
+ const ctors = new Set(p.datas.flatMap(d => d.ctors.flatMap((c, j) => (c.fields.length ? [ctorMap(d, j)] : []))));
1475
+ const built = new Map();
1476
+ walk(t, o => { if (o.op === 'get' && ctors.has(o.map))
1477
+ built.set(tid(o), o); });
1478
+ return [...built.values()];
1479
+ }
1480
+ // Each call's obligation under measures given, proven (`obligations`, each function's) or the first that isn't (`failed`);
1481
+ // with an invariant (`inv`, nested recursion), each value each body ends at keeping its function's after them.
1482
+ function proveMeasures(ring, sites, ms0, until, inv = ring.map(() => undefined)) {
1483
+ // (every measure of one length, at least one component: Data.lean's lexLt compares tuples of one length)
1484
+ const ms = padded(ring, ms0);
1485
+ if (!ms[0].comps.length || ms.some(m => m.comps.length !== ms[0].comps.length))
1486
+ throw new Error(`${ring.map(f => f.name).join(', ')}: measures of one length`);
1487
+ // (a fold a measure reads is a function taken before, never one of the ring: checkMeasures' measures are given)
1488
+ if (ms.some(m => m.comps.some(c => c.fold && ring.some(f => f.name === c.fold.fn))))
1489
+ throw new Error(`${ring.map(f => f.name).join(', ')}: a measure reads the ring`);
1490
+ const was = inTermination.on;
1491
+ inTermination.on = true;
1492
+ try {
1493
+ return proveMeasuresIn(ring, sites, ms, until, inv);
1494
+ }
1495
+ finally {
1496
+ inTermination.on = was;
1497
+ }
1498
+ }
1499
+ function proveMeasuresIn(ring, sites, ms, until0, inv) {
1500
+ // (a call whose path gives guarded size laws: its proofs' time beside the measure's, `guardedMs` more for each)
1501
+ let until = until0;
1502
+ const names = ring.map(f => f.name), text = ringText(ring, ms) + invText(ring, inv);
1503
+ checkInv(ring, inv);
943
1504
  const nth = sites.map((s, i) => sites.slice(0, i).filter(r => r.from === s.from).length);
944
1505
  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)
1506
+ const leaves = ring.map((f, i) => { const ls = []; if (inv[i])
1507
+ sitesOf(f, names, ls); return ls; });
1508
+ 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' })),
1509
+ ...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' })))];
1510
+ for (const { from, law, call, what, site } of laws) {
1511
+ // (no call of the ring in it: each read as a value)
948
1512
  walk(law.holds, o => { if (o.op === 'call' && names.includes(o.fn))
949
1513
  throw new Error(`${law.name} reads the ring`); });
950
1514
  // First one node, the definitions unfolded once (most calls lower the measure by their cases alone); then, where its
@@ -954,10 +1518,10 @@ function proveMeasures(ring, sites, ms, until) {
954
1518
  // else, or then, the definitions unfolded alone.
955
1519
  const left = () => Math.max(1, until - clock()), cex = refute(law, 200);
956
1520
  if (cex)
957
- return { failed: `${text}: its ${call} doesn't lower it at ${JSON.stringify(cex)}` };
1521
+ return { failed: `${text}: its ${call} doesn't ${what} at ${JSON.stringify(cex)}` };
958
1522
  const direct = directly(law, Math.min(2000, left()));
959
1523
  if (direct) {
960
- obligations[site.from].push({ law, proof: direct, lemmas: [] });
1524
+ obligations[from].push({ law, proof: direct, lemmas: [] });
961
1525
  continue;
962
1526
  }
963
1527
  // (the size laws first, each proven once and used, within 60% of the time left; then proveData without conjectured
@@ -967,39 +1531,90 @@ function proveMeasures(ring, sites, ms, until) {
967
1531
  if (dataTrace && lemmas.length)
968
1532
  console.error(`[data] ${law.name}: ${lemmas.map(c => c.name).join('; ')}`);
969
1533
  let v = lemmas.length ? proveData(law, { lemmas, lemmasFirst: true, ms: Math.min(8000, 0.6 * left()) }) : undefined;
1534
+ // (then, where the call's path gives a guarded size law: it, its guard at the call and the size laws, proven in order)
1535
+ const guarded = v?.proven || v?.counterexample || !site ? [] : guardedLaws(law, site, names);
1536
+ if (guarded.length) {
1537
+ // (at most `guardedMs` more for a ring's every measure tried: a refusal isn't slowed past it)
1538
+ const more = Math.min(guardedLeft.ms, Math.max(0, clock() + guardedMs.ms - until));
1539
+ guardedLeft.ms -= more;
1540
+ until += more;
1541
+ // (each guard at the call after the guarded laws its arguments' sizes read there: half of a length from 2 items on)
1542
+ 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 }])];
1543
+ if (dataTrace)
1544
+ console.error(`[data] ${law.name}: ${groups.flatMap(q => q.laws).map(c => c.name).join('; ')}`);
1545
+ const g = throughLemmas(law, groups, until);
1546
+ if (g) {
1547
+ 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)) });
1548
+ continue;
1549
+ }
1550
+ }
970
1551
  if (!v?.proven && !v?.counterexample && clock() < until)
971
1552
  v = proveData(law, { ms: Math.min(12_000, left()), lemmas: false });
972
1553
  if (!v?.proven && !v?.counterexample && clock() < until)
973
1554
  v = proveData(law, { induction: false, ms: Math.min(4000, left()) });
974
1555
  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'}` };
1556
+ return { failed: `${text}: its ${call} ${v?.counterexample ? `doesn't ${what} at ${JSON.stringify(v.counterexample)}` : `not proven to ${what}`}` };
976
1557
  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)) });
1558
+ obligations[from].push({ law, proof: used.proof, scheme: used.scheme, lemmas: used.lemmas, lemmaLaws: lemmas.filter(c => used.lemmas.includes(c.name)) });
978
1559
  }
979
1560
  return { obligations };
980
1561
  }
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
- }
1562
+ 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 ')}` : '');
1563
+ // A ring's calls.
1564
+ const ringSites = (ring) => callSites(ring);
994
1565
  // Measures given to a ring (or a function) checked as `termination` checks the one it takes: each call's obligation
995
1566
  // 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) {
1567
+ // (a call nested in another's argument read under the invariants given, `inv`, each function's over its parameters and
1568
+ // `valueVar`; none: the decrease must hold whatever the call's value)
1569
+ export function checkMeasures(fns, ms, budget = terminationMs.ms, inv) {
997
1570
  return counted(dataRate, () => {
998
- const r = proveMeasures(fns, ringSites(fns, fns.map(f => f.name).join(', ')), padded(fns, ms), clock() + budget);
1571
+ const had = guardedLeft.ms;
1572
+ guardedLeft.ms = guardedMs.ms;
1573
+ let r;
1574
+ try {
1575
+ r = proveMeasures(fns, ringSites(fns), padded(fns, ms), clock() + budget, inv);
1576
+ }
1577
+ finally {
1578
+ guardedLeft.ms = had;
1579
+ }
999
1580
  return 'failed' in r ? { proven: false, why: r.failed } : { proven: true, obligations: r.obligations };
1000
1581
  });
1001
1582
  }
1583
+ // Invariants to try for a ring with a call nested in another's argument or condition (the search's: one is taken only
1584
+ // where the kernel proves each body keeps it): none first (each decrease whatever the nested calls' values), then, of each
1585
+ // function whose value has a size, that size against one argument's as its values give them (an equation where they
1586
+ // give one difference, else the least and the greatest: the argument with the narrowest range), both bounds, then the
1587
+ // upper alone, then the lower alone.
1588
+ function invariantsOf(ring) {
1589
+ const none = ring.map(() => undefined);
1590
+ const per = ring.map(f => {
1591
+ if (!sized(f.ret))
1592
+ return undefined;
1593
+ 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 })) };
1594
+ 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));
1595
+ const b = bs[0];
1596
+ if (!b)
1597
+ return undefined;
1598
+ const nat = (n) => ({ op: 'nat', value: n }), add = (x, n) => (n ? { op: 'add', a: x, b: nat(n) } : x);
1599
+ 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 });
1600
+ // lo ≤ S(value) − S(arg) ≤ hi
1601
+ 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)) };
1602
+ 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 };
1603
+ });
1604
+ const out = [none, per.map(p => p?.both), per.map(p => p?.upper ?? p?.both), per.map(p => p?.lower ?? p?.both)];
1605
+ return out.filter((inv, i) => (i === 0 || inv.some(y => y)) && out.findIndex(o => JSON.stringify(o) === JSON.stringify(inv)) === i);
1606
+ }
1002
1607
  // The ring's measures and each call's proof, or a refusal with the measures tried. A ring of one is a function.
1608
+ // (a ring's termination within another's: the outer's guarded time kept)
1609
+ function terminationKept(ring, why) {
1610
+ const had = guardedLeft.ms;
1611
+ try {
1612
+ return termination(ring, why);
1613
+ }
1614
+ finally {
1615
+ guardedLeft.ms = had;
1616
+ }
1617
+ }
1003
1618
  function termination(ring, why) {
1004
1619
  return counted(dataRate, () => {
1005
1620
  const names = ring.map(f => f.name);
@@ -1008,39 +1623,60 @@ function termination(ring, why) {
1008
1623
  const t0 = performance.now();
1009
1624
  if (!ring.some(f => f.params.some(p => measurable(p.sort))))
1010
1625
  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);
1626
+ const sites = ringSites(ring);
1627
+ // (a call of the ring in another's argument or condition: nested recursion, with invariants to try)
1628
+ const nested = sites.some(st => { let n = false; walk([st.args, st.wrap(no.y)], o => { if (o.op === 'call' && names.includes(o.fn))
1629
+ n = true; }); return n; });
1012
1630
  if (dataTrace)
1013
- console.error(`[data] ${sites.length} calls`);
1631
+ console.error(`[data] ${sites.length} calls${nested ? ', nested' : ''}`);
1014
1632
  const edges = runEdges(ring), until = clock() + terminationMs.ms * ring.length, tried = [], seen = new Set();
1633
+ guardedLeft.ms = guardedMs.ms * ring.length;
1634
+ const invs = nested ? invariantsOf(ring) : [ring.map(() => undefined)];
1015
1635
  if (dataTrace)
1016
1636
  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;
1637
+ try {
1638
+ // (a nested call's arguments read the ring itself, whose values the candidates' samples compute: within the bounds)
1639
+ for (const ms of nested ? bounded(() => candidates(ring, edges, sites, until)) : candidates(ring, edges, sites, until)) {
1640
+ const text = ringText(ring, ms);
1641
+ if (dataTrace)
1642
+ console.error(`[data] ${text} at ${Math.round(performance.now() - t0)} ms`);
1643
+ if (clock() > until) {
1644
+ tried.push('out of time');
1645
+ break;
1646
+ }
1647
+ const bad = edges.find(e => !lowers(ms, e));
1648
+ if (seen.has(text))
1649
+ continue;
1650
+ seen.add(text);
1651
+ if (bad) {
1652
+ if (ring.some(f => f.stated) || !tried.length)
1653
+ 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]}` : ''})`);
1654
+ continue;
1655
+ }
1656
+ for (const inv of invs) {
1657
+ if (clock() > until)
1658
+ break;
1659
+ const r = proveMeasures(ring, sites, ms, until, inv);
1660
+ if ('obligations' in r)
1661
+ 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) }));
1662
+ tried.push(r.failed);
1663
+ }
1033
1664
  }
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);
1665
+ }
1666
+ catch (e) {
1667
+ if (e instanceof NestedRefusal)
1668
+ throw new Error(`${why}, and ${e.message}`);
1669
+ throw e;
1038
1670
  }
1039
1671
  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
1672
  });
1041
1673
  }
1042
1674
  export function law(name, vars, holds) {
1043
1675
  const vs = Object.entries(vars).map(([n, s]) => ({ name: n, sort: s }));
1676
+ // (as a parameter's: never a name the encoding makes, f.p, field#k, f#value, x$)
1677
+ for (const v of vs)
1678
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(v.name))
1679
+ throw new Error(`${name}: the variable ${v.name}'s name is letters and digits`);
1044
1680
  const y = holds(Object.fromEntries(vs.map(v => [v.name, wrap(v.sort, { op: 'var', name: v.name })]))).y;
1045
1681
  equalityOnly(name, y);
1046
1682
  return { name, vars: vs, holds: y, params: [...new Set(paramsIn(y))] };
@@ -1160,7 +1796,7 @@ export const showValue = (d, v) => {
1160
1796
  const c = d.ctors[v.c];
1161
1797
  return c.fields.length ? `${c.name}(${c.fields.map((f, i) => showValue(fieldSort(f), v.f[i])).join(', ')})` : c.name;
1162
1798
  };
1163
- export const rng = (seed) => () => (seed = lcgFloat(seed)) / 2147483648; // (a search's draws: machine.ts's lcgFloat)
1799
+ export const rng = (seed) => () => (seed = lcg(seed)) / 2147483648; // (machine.ts's lcg)
1164
1800
  // `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
1801
  // where the plain draw mostly stops at a leaf (a list of length 0 or 1, most often).
1166
1802
  export function randomValue(s, rand, size, natMax = 5, full = false) {
@@ -1208,7 +1844,9 @@ export const tagMap = (d) => `${d}.tag`, sizeMap = (d) => `${d}.size`;
1208
1844
  export const fieldMap = (d, j, i) => `${d.name}.${d.ctors[j].name}.${d.ctors[j].fields[i].name}`;
1209
1845
  export const ctorMap = (d, j) => `${d.name}.${d.ctors[j].name}`;
1210
1846
  // Everything a law reads: the datatypes, the functions (with those they call), the function parameters.
1211
- export function programOf(laws, extra = []) {
1847
+ // `allowCounters: false` leaves optional call-count ranks for a later search pass;
1848
+ // the original functions and every definition actually included are still admitted normally.
1849
+ export function programOf(laws, extra = [], allowCounters = true) {
1212
1850
  const fs = new Map(), ds = new Map(), ps = new Set();
1213
1851
  // A datatype with those its fields name (its group, those declared before it).
1214
1852
  const addSort = (s) => { if (s instanceof Data && !ds.has(s.name)) {
@@ -1258,6 +1896,15 @@ export function programOf(laws, extra = []) {
1258
1896
  for (const f of fs.values())
1259
1897
  place(f);
1260
1898
  }
1899
+ // (and outside a termination's proofs, the call count of each well-founded function whose measure falls only by a
1900
+ // lemma: its recursion's rank as an induction, `callsFn`)
1901
+ const counters = !allowCounters || inTermination.on ? [] : order.flatMap(f => (f.decreases === undefined && f.termination?.obligations.some(o => o.lemmas.length) ? [callsFn(f)].filter(n => n !== undefined) : []));
1902
+ if (counters.length) {
1903
+ for (const n of counters)
1904
+ visit({ op: 'call', fn: n, args: [] });
1905
+ for (const f of fs.values())
1906
+ place(f);
1907
+ }
1261
1908
  const divs = new Set();
1262
1909
  let ints = false;
1263
1910
  const scan = (t) => walk(t, o => { if (o.op === 'mod' || o.op === 'div' || o.op === 'imod' || o.op === 'idiv')
@@ -1278,6 +1925,10 @@ export function programOf(laws, extra = []) {
1278
1925
  ints = true;
1279
1926
  if (ints)
1280
1927
  divs.add(2);
1928
+ // (a function parameter is a map of its own name, as a function is: never one of theirs, which their equations fix)
1929
+ for (const q of ps)
1930
+ if (fs.has(q))
1931
+ throw new Error(`${q}: a function parameter named as a function the law reads`);
1281
1932
  return { datas, fns: order, params: [...ps], divisors: [...divs].sort((a, b) => a - b), ints };
1282
1933
  }
1283
1934
  const dataOf = (p, name) => p.datas.find(d => d.name === name);
@@ -1627,6 +2278,8 @@ export class Model {
1627
2278
  case 'prod': return this.evalE(e.a, env) * this.evalE(e.b, env);
1628
2279
  case 'if': return this.evalC(e.c, env) ? this.evalE(e.then, env) : this.evalE(e.else, env);
1629
2280
  case 'get': return this.read(e.map, this.evalE(e.key, env));
2281
+ case 'tup': return safe(cpair(this.evalE(e.a, env), this.evalE(e.b, env)));
2282
+ case 'proj': return cun(this.evalE(e.a, env))[e.k];
1630
2283
  }
1631
2284
  }
1632
2285
  evalC(c, env) {
@@ -1656,7 +2309,7 @@ export function unkey(key, n) {
1656
2309
  // A sample whose evaluation passes the bounds (EvalLimit, or the stack) is skipped.
1657
2310
  export function refute(l, n = 400, seed = 7) {
1658
2311
  return bounded(() => {
1659
- for (const s of samples(l.vars, programOf([l]).params, n, seed)) {
2312
+ for (const s of samples(l.vars, programOf([l], [], false).params, n, seed)) {
1660
2313
  let ok;
1661
2314
  try {
1662
2315
  ok = evalY(l.holds, s.env, s.params);
@@ -1813,9 +2466,16 @@ function unfoldAt(f) {
1813
2466
  return f.params[f.decreases].sort instanceof Data ? [f.decreases] : [];
1814
2467
  if (!f.measure)
1815
2468
  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);
2469
+ const out = new Set(), at = (o) => f.params.findIndex(q => o.op === 'var' && `${f.name}.${q.name}` === o.name);
2470
+ // (outside a termination's proofs, the parameter the body matches first only: a merge at a built second list and an
2471
+ // undecided first is no decided case, and its recursion at the first's tail unfolds again, a chain to the cap)
2472
+ const body = f.body();
2473
+ if (!inTermination.on && body.op === 'match') {
2474
+ const i = at(body.of);
2475
+ return i >= 0 && f.params[i].sort instanceof Data ? [i] : [];
2476
+ }
2477
+ walk(body, o => { if (o.op === 'match') {
2478
+ const i = at(o.of);
1819
2479
  if (i >= 0 && f.params[i].sort instanceof Data)
1820
2480
  out.add(i);
1821
2481
  } });
@@ -1857,6 +2517,11 @@ function schemes(p, l) {
1857
2517
  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
2518
  let relaxed = false;
1859
2519
  const uses = [];
2520
+ // (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
2521
+ // own, mutual induction on the conjunction the law is)
2522
+ const alongside = new Set();
2523
+ 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))
2524
+ alongside.add(o2.fn); });
1860
2525
  // (`through`: the functions of f's ring whose bodies are read in place of their calls, once each: evens through
1861
2526
  // odds, which call each other, is recursion of evens at the tail's tail)
1862
2527
  const go = (x, env, guard, through = new Set()) => {
@@ -1867,7 +2532,7 @@ function schemes(p, l) {
1867
2532
  return;
1868
2533
  }
1869
2534
  const t = x;
1870
- if (t.op === 'call' && t.fn !== f.name && f.ring.includes(t.fn) && !through.has(t.fn)) {
2535
+ if (t.op === 'call' && t.fn !== f.name && f.ring.includes(t.fn) && !through.has(t.fn) && !alongside.has(t.fn)) {
1871
2536
  const g = fnOf(t.fn);
1872
2537
  go(t.args, env, guard, through);
1873
2538
  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 +2569,7 @@ function schemes(p, l) {
1904
2569
  go(w.b, env, [...guard, { op: 'not', x: c }], through);
1905
2570
  return;
1906
2571
  }
1907
- if (t.op === 'call' && t.fn === f.name) {
2572
+ if (t.op === 'call' && (t.fn === f.name || alongside.has(t.fn))) {
1908
2573
  const subst = {};
1909
2574
  let ok = true;
1910
2575
  t.args.forEach((a, i) => {
@@ -1942,7 +2607,9 @@ function schemes(p, l) {
1942
2607
  }
1943
2608
  // Well-founded: ranked by the measure at the law's arguments; the law's variables it reads named.
1944
2609
  const read = f.params.flatMap((q, i) => (m.comps.some(c => c.coef[i]) && args[i].op === 'var' && l.vars.some(v => v.name === args[i].name) ? [{ i, v: args[i].name }] : []));
1945
- add({ name: `recursion of ${f.name} on ${read.map(r => r.v).join(', ') || 'its arguments'}`, uses, rank: m.comps.map(c => encX(p, measureX(f, c, args), new Map())),
2610
+ // (ranked by its call count where the program has it: each descent one unfolding of it, `callsFn`)
2611
+ const counter = p.fns.find(g => g.name === `${f.name}_calls` && madeCalls.get(g.name) === g);
2612
+ add({ name: `recursion of ${f.name} on ${read.map(r => r.v).join(', ') || 'its arguments'}`, uses, rank: counter ? [encX(p, { op: 'call', fn: counter.name, args }, new Map())] : m.comps.map(c => encX(p, measureX(f, c, args), new Map())),
1946
2613
  shapes: read.filter(r => f.params[r.i].sort instanceof Data).map(r => ev(r.v)) });
1947
2614
  });
1948
2615
  // Structural induction on each variable of a datatype, the others fixed; mutual where its fields reach another of its
@@ -2005,10 +2672,8 @@ function instancesOf(p, fs, w) {
2005
2672
  console.error(`[data] instances: ${what} at ${Math.round(performance.now() - tt)} ms`); };
2006
2673
  const insts = [], seen = new Set();
2007
2674
  const inst = (fact, at) => { const i = fs.at.get(fact); if (i === undefined)
2008
- return; const id = sid([i, at]); if (!seen.has(id)) {
2009
- seen.add(id);
2010
- insts.push({ fact: i, at });
2011
- } };
2675
+ return undefined; const id = sid([i, at]); if (seen.has(id))
2676
+ return undefined; seen.add(id); const q = { fact: i, at }; insts.push(q); return q; };
2012
2677
  const holdsAt = (fact, at) => { const f = fs.facts[fs.at.get(fact)]; return substShared(f.holds, Object.fromEntries(f.keys.map((key, q) => [key, at[q]]))); };
2013
2678
  // (each read once, where walk first reaches it: a read again adds nothing where these are used)
2014
2679
  const reads = (t) => readsOnce(t).map(o => ({ map: o.map, key: o.key }));
@@ -2061,21 +2726,33 @@ function instancesOf(p, fs, w) {
2061
2726
  inst(`fn ${f.name}`, as);
2062
2727
  ctors(note(reads(holdsAt(`fn ${f.name}`, as))));
2063
2728
  }
2729
+ const unfoldOnce = (r) => {
2730
+ const f = fnOfMap(r.map), as = f && argsOf(r.key, f.params.length), rid = sid(r);
2731
+ if (!f || !as || unfolded.has(rid))
2732
+ return [];
2733
+ unfolded.add(rid);
2734
+ inst(`fn ${f.name}`, as);
2735
+ const body = reads(holdsAt(`fn ${f.name}`, as));
2736
+ ctors(note(body));
2737
+ return body;
2738
+ };
2064
2739
  for (let round = 0; round < w.depth && frontier.length; round++) {
2065
2740
  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)
2741
+ for (const r of frontier)
2742
+ for (const b of unfoldOnce(r))
2075
2743
  next.push(b);
2076
- }
2077
2744
  frontier = next;
2078
2745
  }
2746
+ // (at one unfolding, where the goal reads a function that looks two ahead (a match on a field of the value it matches:
2747
+ // ordered, reading the tail's head), a call both an unfolded body and a use's conclusion read, once more:
2748
+ // insert(y, tail xs), where insert(y, xs)'s body and the hypothesis at the tail meet, its constructor what ordered
2749
+ // reads at insert(y, xs)'s tail)
2750
+ if (w.depth === 1 && reads(w.roots).some(r => { const f = fnOfMap(r.map); return !!f && looksAhead(f); })) {
2751
+ const theirs = new Set(reads(w.others).map(r => sid(r)));
2752
+ for (const r of frontier)
2753
+ if (theirs.has(sid(r)))
2754
+ unfoldOnce(r);
2755
+ }
2079
2756
  // Euclid's fact at every key a remainder or quotient is read at (a read the facts bring is read too).
2080
2757
  const ariths = () => {
2081
2758
  for (let pass = 0; pass < 2; pass++)
@@ -2246,11 +2923,29 @@ function instancesOf(p, fs, w) {
2246
2923
  }
2247
2924
  return { find, terms, adj, truthOf };
2248
2925
  };
2926
+ // A value's eta at the constructor of fields a model gives it (its fact's side there), if one.
2927
+ const etaAt = (d, v, model) => {
2928
+ let j;
2929
+ try {
2930
+ j = model.m.evalE(get(tagMap(d.name), v), model.env);
2931
+ }
2932
+ catch {
2933
+ return [];
2934
+ }
2935
+ if (!d.ctors[j]?.fields.length || !fs.at.has(`eta ${d.name}`))
2936
+ return [];
2937
+ const parts = (c) => (c.op === 'and' ? c.xs.flatMap(parts) : [c]);
2938
+ for (const c of parts(holdsAt(`eta ${d.name}`, [v])))
2939
+ 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 === '=')
2940
+ return [c.xs[1].b];
2941
+ return [];
2942
+ };
2249
2943
  // A function read whose decreasing argument a model's classes make a constructor's value (the argument itself, or a
2250
2944
  // term of its class) unfolds there too: where the definition's match is decided. Each such instance stands for the
2251
2945
  // reads it was unfolded for (`reached` keeps it in a case where it is one of them).
2252
2946
  if (w.depth >= 1) {
2253
2947
  let extra = 0;
2948
+ const viaBody = new Set();
2254
2949
  for (const model of w.models.length ? w.models : [undefined]) {
2255
2950
  if (late())
2256
2951
  break;
@@ -2266,7 +2961,7 @@ function instancesOf(p, fs, w) {
2266
2961
  }
2267
2962
  for (const r of [...all]) {
2268
2963
  const f = fnOfMap(r.map);
2269
- if (!f)
2964
+ if (!f || viaBody.has(sid(r)))
2270
2965
  continue;
2271
2966
  const as = argsOf(r.key, f.params.length);
2272
2967
  if (!as)
@@ -2274,7 +2969,11 @@ function instancesOf(p, fs, w) {
2274
2969
  for (const di of unfoldAt(f)) {
2275
2970
  const own = as[di], d = f.params[di].sort, root = cl.find(tid(own));
2276
2971
  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);
2972
+ const cands0 = built(own) ? [own] : [...cl.terms.values()].filter(t => built(t) && cl.find(tid(t)) === root);
2973
+ // (where none is built, the value an induction descends on, of its class, at the constructor this model gives
2974
+ // it, eta's: count(x, xs) at xs's head and tail where xs is a cons, read through count(x, tail(y :: xs)))
2975
+ // (not where the read is unfolded at the value as it stands already: ordered(xs) itself)
2976
+ 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
2977
  for (const t of cands) {
2279
2978
  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
2979
  const anchor = { read: tid(get(f.name, r.key)), arg: own, value: t }, had = anchoredAt.get(key2) ?? [];
@@ -2287,9 +2986,19 @@ function instancesOf(p, fs, w) {
2287
2986
  done.add(sigOf(f.name, as2));
2288
2987
  if (dataTrace)
2289
2988
  console.error(`[data] unfold ${f.name} at ${brief(as2, 160)} for ${brief(r.key, 80)}`);
2989
+ if (via) {
2990
+ inst(`eta ${d.name}`, [via]);
2991
+ ctors(note(reads(holdsAt(`eta ${d.name}`, [via]))));
2992
+ }
2290
2993
  inst(`fn ${f.name}`, as2);
2291
2994
  note([{ map: f.name, key: keyOf(as2) }]);
2292
- ctors(note(reads(holdsAt(`fn ${f.name}`, as2))));
2995
+ const body = note(reads(holdsAt(`fn ${f.name}`, as2)));
2996
+ ctors(body);
2997
+ // (an eta's unfolding is one step: the reads its body makes unfold no further, a merge's recursion on the
2998
+ // other list at the same constructor would chain to the cap)
2999
+ if (via)
3000
+ for (const b of body)
3001
+ viaBody.add(sid(b));
2293
3002
  }
2294
3003
  }
2295
3004
  }
@@ -2513,6 +3222,34 @@ function instancesOf(p, fs, w) {
2513
3222
  lap(`congruences, ${insts.length} instances, ${w.models.length} models`);
2514
3223
  return insts;
2515
3224
  }
3225
+ // Whether a function looks two ahead: its body matches a field of a value it matched, of the same datatype (ordered's
3226
+ // tail, then its head; not a pair in a list's head).
3227
+ const looksAhead = (f) => {
3228
+ let yes = false;
3229
+ const go = (x, fields) => {
3230
+ if (yes || !x || typeof x !== 'object')
3231
+ return;
3232
+ if (Array.isArray(x)) {
3233
+ x.forEach(y => go(y, fields));
3234
+ return;
3235
+ }
3236
+ const t = x;
3237
+ if (t.op === 'match') {
3238
+ if (t.of.op === 'var' && fields.get(t.of.name) === t.data) {
3239
+ yes = true;
3240
+ return;
3241
+ }
3242
+ go(t.of, fields);
3243
+ for (const c of t.cases)
3244
+ go(c.body, new Map([...fields, ...c.binds.map(b => [b, t.data])]));
3245
+ return;
3246
+ }
3247
+ for (const v of Object.values(t))
3248
+ go(v, fields);
3249
+ };
3250
+ go(f.body(), new Map());
3251
+ return yes;
3252
+ };
2516
3253
  let varSorts = new Map();
2517
3254
  // 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
3255
  // pairing reads its arguments again ((a + b)·(a + b) + b), so a nested read's text grows exponentially with its depth
@@ -2591,7 +3328,9 @@ function linearForm(e, at, known) {
2591
3328
  case 'if':
2592
3329
  case 'min':
2593
3330
  case 'max':
2594
- case 'prod': return undefined;
3331
+ case 'prod':
3332
+ case 'tup':
3333
+ case 'proj': return undefined;
2595
3334
  }
2596
3335
  };
2597
3336
  const f = go(e);
@@ -2615,6 +3354,7 @@ function substShared(c, vars) {
2615
3354
  out = x;
2616
3355
  break;
2617
3356
  case 'mul':
3357
+ case 'proj':
2618
3358
  out = { ...x, a: e(x.a) };
2619
3359
  break;
2620
3360
  case 'if':
@@ -2628,6 +3368,7 @@ function substShared(c, vars) {
2628
3368
  case 'sub':
2629
3369
  case 'min':
2630
3370
  case 'max':
3371
+ case 'tup':
2631
3372
  out = { ...x, a: e(x.a), b: e(x.b) };
2632
3373
  break;
2633
3374
  default: out = substE(x, { vars, maps: {}, flags: {} });
@@ -2740,13 +3481,16 @@ function matches(pattern, vars, t, s) {
2740
3481
  }
2741
3482
  return out;
2742
3483
  }
2743
- function casesOf(p, unfolded, vars, models) {
3484
+ function casesOf(p, fs0, unfolded, vars, models) {
2744
3485
  // (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
3486
  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
3487
  : 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);
3488
+ // (and a predicate of the program's at plain values: the guard the code reads, a user's ≤ on naturals, in place of the
3489
+ // tags of fields its unfolding would split on; the merge's size law over Peano naturals)
3490
+ 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);
3491
+ 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
3492
  // The functions' facts the goal unfolds.
2749
- const roots = unfolded;
3493
+ const roots = unfolded, preds = new Set();
2750
3494
  const sigs = models.map(({ m, env }) => {
2751
3495
  const out = new Map();
2752
3496
  const truthOf = (c) => { try {
@@ -2773,6 +3517,8 @@ function casesOf(p, unfolded, vars, models) {
2773
3517
  const key = sid(o.c);
2774
3518
  if (!out.has(key))
2775
3519
  out.set(key, { c: o.c, t: v });
3520
+ if (o.c.op === '=' && guard(o.c.a, o.c.b))
3521
+ preds.add(key);
2776
3522
  }
2777
3523
  go(v ? o.then : o.else);
2778
3524
  return;
@@ -2789,7 +3535,8 @@ function casesOf(p, unfolded, vars, models) {
2789
3535
  for (const key of sigs[i].keys())
2790
3536
  if (!decided.has(key))
2791
3537
  count.set(key, (count.get(key) ?? 0) + 1);
2792
- const pick = [...count.entries()].sort((a2, b2) => b2[1] - a2[1])[0];
3538
+ // (as many models one way as another: a guard of the program's predicates first, the split the code makes)
3539
+ const pick = [...count.entries()].sort((a2, b2) => b2[1] - a2[1] || Number(preds.has(b2[0])) - Number(preds.has(a2[0])))[0];
2793
3540
  if (!pick || depth >= 4)
2794
3541
  return [{ lits, models: ms.length ? ms.map(i => models[i]) : undefined }];
2795
3542
  const key = pick[0], c = ms.map(i => sigs[i].get(key)).find(x => x).c;
@@ -2816,17 +3563,23 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2816
3563
  // A few models for the instances; the whole pool for the cases (a rare case gets its own models from it).
2817
3564
  const few = (ms) => ms.slice(0, 16);
2818
3565
  const specs = [], where = new Map();
3566
+ // (each lemma's nodes placed first, then their uses read through the places: a node's use of one after it, a case's,
3567
+ // is placed too where the lemma was proven above none of the others)
2819
3568
  for (const lm of lemmas) {
2820
- const local = new Map();
3569
+ const local = new Map(), fresh = [];
2821
3570
  lm.nodes.forEach((n, i) => {
2822
3571
  if (where.has(n.name)) {
2823
3572
  local.set(i, where.get(n.name));
2824
3573
  return;
2825
3574
  }
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 })) });
3575
+ local.set(i, specs.length + fresh.length);
3576
+ where.set(n.name, specs.length + fresh.length);
3577
+ fresh.push(i);
2829
3578
  });
3579
+ for (const i of fresh) {
3580
+ const n = lm.nodes[i];
3581
+ specs.push({ ...n, uses: n.uses.map(u => ({ ...u, node: local.get(u.node) ?? u.node })) });
3582
+ }
2830
3583
  }
2831
3584
  // The scheme's nodes: the law's, then each companion's (a mutual induction), each its own models. A use of member i
2832
3585
  // reads node -1 - i until the nodes are placed.
@@ -2836,6 +3589,7 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2836
3589
  varSorts = new Map(members.flatMap(mb => mb.law.vars.flatMap(v => (v.sort instanceof Data ? [[v.name, v.sort]] : []))));
2837
3590
  const lemmaNodes = lemmas.map(lm => ({ law: lm.law, node: where.get(lm.spec.name), concl: specs[where.get(lm.spec.name)].concl }));
2838
3591
  const useConcl = (u) => substC(u.node < 0 ? concls[-1 - u.node] : specs[u.node].concl, { vars: u.subst, maps: {}, flags: {} });
3592
+ const leaner = new Map();
2839
3593
  const plans = [];
2840
3594
  for (const [mi, mb] of members.entries()) {
2841
3595
  // (an implication's instances from the models where its premise holds first, the node's and each case's, as only they
@@ -2850,7 +3604,10 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2850
3604
  const first = (ms) => (prem ? [...ms.filter(held), ...ms.filter(x => !held(x))] : ms);
2851
3605
  const models = first(mb.pool).slice(0, 24), concl = concls[mi], name = mi === 0 ? title : `${title}, at ${mb.on.d.name}`;
2852
3606
  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)] : [];
3607
+ // (a termination's obligation without induction: at its variables and the values its call's path builds, as
3608
+ // `directly`'s, x :: y :: zs's size at least 3)
3609
+ const shapesAt0 = mb.rank ? rankShapes(mb.shapes ?? [], mb.rank, mb.uses) : mb.on && mb.on.d !== 'nat' ? [ev(mb.on.v)] : [];
3610
+ const shapesAt = !scheme && inTermination.on ? [...[...varSorts.keys()].map(ev), ...builtIn(p, concl)] : shapesAt0;
2854
3611
  const ihConcls = ih.map(useConcl);
2855
3612
  // Uses of the lemmas, where a lemma's largest read matches a read of this goal (unfolded), its key up to the
2856
3613
  // equalities the unfolded definitions give (any branch); twice over, the uses' own conclusions read the second time.
@@ -2899,8 +3656,8 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2899
3656
  // hypothesis at x :: xss, its definition decided there; a fusion chain's last links', drop(v + 1 + w + x, y :: z))
2900
3657
  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
3658
  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) : [];
3659
+ 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 });
3660
+ 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
3661
  if (cases.length <= 1) {
2905
3662
  // One node: four uses of a lemma, twelve in all, the best first (as lemmaUsesFor ranks them).
2906
3663
  const one = capUses(uses, 12);
@@ -2929,7 +3686,19 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2929
3686
  const rest = fit.filter(u => u.node >= 0 && !kept.includes(u)), joins = rest.length && c.models ? caseJoins(fs, [concl, ihConcls], pre, ihConcls, few(c.models)) : undefined;
2930
3687
  const us = [...kept, ...capUses(joins ? rest.filter(u => joins(useConcl(u))) : [], lemmaCaps.joined)];
2931
3688
  const ms = few(first(c.models ?? c.near ?? models));
2932
- plan.push({ name: `${name}, case ${i + 1}`, hyps: c.lits, concl, sub: 0, insts: reached(p, fs, instsFor(ms, us, false, c.lits), [c.lits, concl, us.map(u => [u.guard, useConcl(u)]), shapesAt, rankReads], ms), uses: us });
3689
+ const from = [c.lits, concl, us.map(u => [u.guard, useConcl(u)]), shapesAt, rankReads], insts = reached(p, fs, instsFor(ms, us, false, c.lits), from, ms);
3690
+ // (and leaner: without the shapes and etas at fields' values, and what only they reach)
3691
+ const atField = (q) => /^(shape|eta) /.test(fs.facts[q.fact].name) && fieldValue(q.at[0]);
3692
+ // (and the function reads both the conclusion and a use's conclusion make, which cancel: count(x, xs) in the law and
3693
+ // in its hypothesis at the tail of ys)
3694
+ const fnReads = (t) => new Set(readsOnce(t).filter(r => r.op === 'get' && p.fns.some(f => f.name === r.map)).map(r => sid(r)));
3695
+ const inConcl = fnReads(concl), common = new Set([...fnReads(us.map(useConcl))].filter(x => inConcl.has(x)));
3696
+ const lean = reached(p, fs, insts.filter(q => !atField(q)), from, ms, common);
3697
+ // Structural equalities need their constructor fields; the arithmetic observer
3698
+ // cancellation pass only spends time on scalar laws, never on those equalities.
3699
+ if (insts.some(atField) && !inTermination.on && aboutNaturals(mb.law))
3700
+ leaner.set(`${name}, case ${i + 1}`, lean);
3701
+ plan.push({ name: `${name}, case ${i + 1}`, hyps: c.lits, concl, sub: 0, insts, uses: us });
2933
3702
  }
2934
3703
  plans.push(plan);
2935
3704
  }
@@ -2939,8 +3708,14 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2939
3708
  const mb = members[mi], size = !mb.on ? k(0) : mb.on.d === 'nat' ? ev(mb.on.v) : get(sizeMap(mb.on.d.name), ev(mb.on.v));
2940
3709
  // (level, the measure or the size, 0 or 1), the measure's place padded to the program's widest measure
2941
3710
  const comps = mb.rank ?? [size], mid = [...comps, ...Array.from({ length: rankWidth(p) - comps.length }, () => k(0))];
2942
- for (const { sub, cases, ...n } of plan)
2943
- specs.push({ ...n, rank: [k(level), ...mid, k(sub)], uses: cases ? cases.map((g, i) => ({ node: offsets[mi] + 1 + i, subst: {}, guard: g })) : n.uses.map(u => (u.node < 0 ? { ...u, node: offsets[-1 - u.node] } : u)) });
3711
+ for (const { sub, cases, ...n } of plan) {
3712
+ const spec = { ...n, rank: [k(level), ...mid, k(sub)], uses: cases ? cases.map((g, i) => ({ node: offsets[mi] + 1 + i, subst: {}, guard: g })) : n.uses.map(u => (u.node < 0 ? { ...u, node: offsets[-1 - u.node] } : u)) };
3713
+ // (a case's leaner instances first, within a third of the attempt's time, all of them where those don't prove it:
3714
+ // the kernel's search on each node apart, the other nodes' trees kept. A merge's case node, past 11 s with all of its
3715
+ // 33 instances, is proven in 0.2 s with 8: count x (merge xs ys) = count x xs + count x ys now in 7 s, none in 96)
3716
+ const lean = leaner.get(n.name);
3717
+ specs.push(lean ? { ...spec, insts: lean, within: attemptMs.ms / 3, variants: [{ ...spec, within: attemptMs.ms }] } : spec);
3718
+ }
2944
3719
  }
2945
3720
  const name = title;
2946
3721
  // Each attempt within its own time (a goal past it is left unknown, and the attempt fails).
@@ -2951,12 +3726,39 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2951
3726
  const was = pairedKeys.skip;
2952
3727
  pairedKeys.skip = true;
2953
3728
  try {
3729
+ // Within a termination's proof (its obligations and their size laws), first without the shapes at a field's value
3730
+ // (a field of a variable, of a field, of a function's value): each is a split on that value's constructor that a
3731
+ // 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
3732
+ // them, 0.8 s without). Then the nodes as built. (Elsewhere a case's node is tried leaner first on its own, all of
3733
+ // its instances where that fails: `leaner`, above.)
3734
+ 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]))) }));
3735
+ if (lean.some((n, i) => n.insts.length < specs[i].insts.length)) {
3736
+ // (nine tenths for a law about naturals alone, a size law's or a decrease's, which reads no value's constructor)
3737
+ const v = withDeadline(clock() + (t0 + attemptMs.ms - clock()) * (aboutNaturals(l) ? 0.9 : 0.25), () => proveCyclic(fs.facts, lean));
3738
+ if (dataTrace)
3739
+ console.error(`[data] without the fields' shapes: ${v.proven ? 'proven' : `${v.goal}: ${v.stuck}`}`);
3740
+ if (v.proven && v.checked)
3741
+ return { verdict: v, specs: lean, main: base };
3742
+ }
2954
3743
  return { verdict: withDeadline(t0 + attemptMs.ms, () => proveCyclic(fs.facts, specs)), specs, main: base };
2955
3744
  }
2956
3745
  finally {
2957
3746
  pairedKeys.skip = was;
2958
3747
  }
2959
3748
  }
3749
+ // Whether a termination's obligations are being proven (core/data.ts's proveMeasures).
3750
+ const inTermination = { on: false };
3751
+ // A field's value: a read of a constructor's field map (`D.ctor.field`).
3752
+ const fieldValue = (e) => e?.op === 'get' && e.map.split('.').length === 3;
3753
+ // A law that compares naturals alone (sizes, a function's natural values): no equation of values of a datatype, no
3754
+ // constructor test.
3755
+ const aboutNaturals = (l) => {
3756
+ 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);
3757
+ let yes = true;
3758
+ walk(l.holds, o => { if (o.op === 'is' || (o.op === '=' && (isData(o.a) || isData(o.b))))
3759
+ yes = false; });
3760
+ return yes;
3761
+ };
2960
3762
  export const attemptMs = { ms: 8000 };
2961
3763
  // A datatype search's budgets count work, not wall time (kernel/prove.ts's `counted`: the solver's rows and each node's),
2962
3764
  // 300 units a millisecond: a search finds the same proof on any machine, at any load. On Modal (2 vCPU) the corpus's
@@ -2967,7 +3769,7 @@ const dataRate = 300;
2967
3769
  // through each instance at a read reached (a function's at its call, a constructor's at its cell, a shape or eta at a
2968
3770
  // value whose tag is read), the reads of what it gives where the models take it (an if's taken branch, an implication's
2969
3771
  // conclusion where its premise holds); a congruence where both its reads are reached.
2970
- function reached(p, fs, insts, from, ms) {
3772
+ function reached(p, fs, insts, from, ms, opaque) {
2971
3773
  const reach = new Set(), id = (t) => sid(t), done = new Map();
2972
3774
  // (an object once a model: what it reaches there is the same each time)
2973
3775
  const active = (t, m, env) => {
@@ -3011,7 +3813,8 @@ function reached(p, fs, insts, from, ms) {
3011
3813
  const each = (t) => { for (const { m, env } of ms)
3012
3814
  active(t, m, env); };
3013
3815
  // The conclusion and the uses' are read whole: the goal is where the law fails, which no model is.
3014
- walkOnce(from, o => { if (o.op === 'get')
3816
+ // (`opaque`: reads none is wanted at, unless another instance's reads reach them)
3817
+ walkOnce(from, o => { if (o.op === 'get' && !opaque?.has(sid(o)))
3015
3818
  reach.add(sid(o)); });
3016
3819
  const anchor = (q) => {
3017
3820
  const name = fs.facts[q.fact].name;
@@ -3416,9 +4219,11 @@ function caseJoins(fs, from, insts, hyps, ms) {
3416
4219
  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
4220
  }
3418
4221
  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.
4222
+ // The models a search compares terms in: n distinct random values of the law's variables (of 20n draws at most; with
4223
+ // params, every draw): 240 draws held some 70 (a leaf, an empty list again and again).
3420
4224
  function modelsFor(p, l, n, seed) {
3421
- return samples(l.vars, p.params, n, seed).map(s => {
4225
+ 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))));
4226
+ return samples(l.vars, p.params, p.params.length ? n : 20 * n, seed).filter(fresh).slice(0, n).map(s => {
3422
4227
  const m = new Model(p, s.params);
3423
4228
  const env = Object.fromEntries(l.vars.map(v => [v.name, m.code(v.sort, s.env.get(v.name))]));
3424
4229
  return { m, env };
@@ -3484,6 +4289,8 @@ function proveWith(p, fs, l, lemmas, level, opts, until, per, depths, without, m
3484
4289
  // by every random value, smallest first, each named canonically (its variables in order of appearance), none ground,
3485
4290
  // none the law, none that follows by rewriting with smaller ones; and for each predicate the law reads, that a function
3486
4291
  // returning a datatype keeps it (p(x) implies p(f(x, ...)), under a comparison of two naturals where that is needed).
4292
+ // (the observers distributed over a builder, below: proven together before the law is tried again)
4293
+ const distributed = new WeakSet();
3487
4294
  export function conjectures(p, l, max = 24, maxSize = 6) {
3488
4295
  const sortsOf = (s) => (s instanceof Data ? s.name : s);
3489
4296
  const vars = [...p.datas.flatMap(d => [{ name: `${d.name.toLowerCase()}1`, sort: d }, { name: `${d.name.toLowerCase()}2`, sort: d }]), { name: 'n1', sort: 'nat' }, { name: 'n2', sort: 'nat' }];
@@ -3734,6 +4541,54 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
3734
4541
  if (size(big) > size(small))
3735
4542
  rules.push({ l: big, r: small, vs });
3736
4543
  }
4544
+ // An observer distributed over a function that builds its datatype (past the sizes above: count x (merge xs ys) =
4545
+ // count x xs + count x ys is seven symbols a side): for each function to a natural reading a datatype (`o`) and each
4546
+ // function returning that datatype from values of it (`m`), o(m(a, b, ..)) = o(a) + o(b) + ..; and for two such
4547
+ // functions of one signature, o(m1(v̄)) + o(m2(v̄)) = o(a) + .. (take and drop, evens and odds, a filter and its
4548
+ // complement). Each variable of its own (the sort's first, second, third), kept where the values agree.
4549
+ const pool = new Map([...vars, ...thirds].reduce((acc, v) => acc.set(sortsOf(v.sort), [...(acc.get(sortsOf(v.sort)) ?? []), v.name]), new Map()));
4550
+ const homs = [];
4551
+ const fill = (ps, taken) => { const out2 = []; for (const q of ps) {
4552
+ const s2 = sortsOf(q.sort), i = taken.get(s2) ?? 0, name = pool.get(s2)?.[i];
4553
+ if (!name)
4554
+ return undefined;
4555
+ taken.set(s2, i + 1);
4556
+ out2.push({ op: 'var', name });
4557
+ } return out2; };
4558
+ const sumOf = (xs) => xs.reduce((a2, b2) => ({ op: 'add', a: a2, b: b2 }));
4559
+ for (const o of fnsUsed) {
4560
+ if (o.ret !== 'nat')
4561
+ continue;
4562
+ for (const [oi, oq] of o.params.entries()) {
4563
+ if (!(oq.sort instanceof Data))
4564
+ continue;
4565
+ const d = oq.sort, ms = fnsUsed.filter(m => m !== o && m.ret === d && m.params.some(q => q.sort === d));
4566
+ const obs = (x) => ({ op: 'call', fn: o.name, args: fill(o.params, new Map()).map((y, i) => (i === oi ? x : y)) });
4567
+ for (const [mi, m] of ms.entries())
4568
+ for (const m2 of [undefined, ...ms.slice(mi + 1).filter(q => JSON.stringify(q.params.map(r => sortsOf(r.sort))) === JSON.stringify(m.params.map(r => sortsOf(r.sort))))]) {
4569
+ // (the observer's own variables first, the builder's after: count x (take n xs), n the second natural)
4570
+ const taken = new Map();
4571
+ if (!fill(o.params.filter((_, i) => i !== oi), taken))
4572
+ continue;
4573
+ const args = fill(m.params, taken);
4574
+ if (!args)
4575
+ continue;
4576
+ const parts = m.params.flatMap((q, i) => (q.sort === d ? [obs(args[i])] : []));
4577
+ const lhs = m2 ? { op: 'add', a: obs({ op: 'call', fn: m.name, args }), b: obs({ op: 'call', fn: m2.name, args }) } : obs({ op: 'call', fn: m.name, args });
4578
+ const rhs = sumOf(parts), fl = fp(lhs);
4579
+ if (fl === undefined || fl !== fp(rhs))
4580
+ continue;
4581
+ const { t: ct, vs } = canon([lhs, rhs]), [ca, cb] = ct, y = { op: '=', a: ca, b: cb }, text = JSON.stringify(y);
4582
+ if (seen.has(text) || text === lawText || JSON.stringify({ op: '=', a: cb, b: ca }) === lawText)
4583
+ continue;
4584
+ seen.add(text);
4585
+ const h = lawOf(y, vs, `${showX(ca)} = ${showX(cb)}`);
4586
+ distributed.add(h);
4587
+ homs.push(h);
4588
+ }
4589
+ }
4590
+ }
4591
+ out.unshift(...homs);
3737
4592
  // Predicates kept by a function returning a datatype.
3738
4593
  const preds = p.fns.filter(f => f.ret === 'bool' && used.has(f.name)), makers = p.fns.filter(f => f.ret instanceof Data && used.has(f.name));
3739
4594
  const nats = vars.filter(v => v.sort === 'nat').map(v => v.name);
@@ -3750,10 +4605,13 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
3750
4605
  for (const margs of argSets(mk.params, true).filter(reads))
3751
4606
  for (const pargs of argSets(pr.params.filter((_, i) => i !== di))) {
3752
4607
  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 });
4608
+ const premise0 = pAt({ op: 'var', name: dvar }), conclusion = pAt({ op: 'call', fn: mk.name, args: margs });
3754
4609
  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;
4610
+ // (the premise at each argument of the datatype, where one alone isn't enough: a merge of two ordered lists)
4611
+ const both = margs.filter(a2 => a2.op === 'var' && a2.name !== dvar && sortOfVar.get(a2.name) === mk.ret).map(pAt);
4612
+ for (const c of [...conds, ...(both.length ? [undefined] : [])].map((c2, i) => ({ c: c2, premise: i < conds.length ? premise0 : { op: 'and', xs: [premise0, ...both] } }))) {
4613
+ const { premise } = c;
4614
+ const hyp = c.c ? { op: 'and', xs: [premise, c.c] } : premise;
3757
4615
  const { t: cy, vs } = canon({ op: 'or', xs: [{ op: 'not', x: hyp }, conclusion] });
3758
4616
  const y = cy, text = JSON.stringify(y);
3759
4617
  if (seen.has(text) || text === lawText)
@@ -4279,13 +5137,14 @@ function proveDataCounted(l, opts, until) {
4279
5137
  }
4280
5138
  export function searchIn(l, opts, until, ctx, phase = 'all') {
4281
5139
  const t0 = performance.now(), w0 = work.n;
4282
- const p = ctx?.p ?? programOf([l, ...(Array.isArray(opts.lemmas) ? opts.lemmas : [])]), fs = ctx?.fs ?? factsOf(p);
5140
+ let p = ctx?.p ?? programOf([l, ...(Array.isArray(opts.lemmas) ? opts.lemmas : [])], [], false), fs = ctx?.fs ?? factsOf(p);
4283
5141
  const base = ctx?.base ?? [], lv = ctx?.level ?? 0;
4284
- let out;
5142
+ let out, proofFacts;
5143
+ const contexts = new Map([[p, fs]]);
4285
5144
  const done = (v) => {
4286
5145
  if (dataTrace)
4287
5146
  console.error(`[data] ${l.name}: ${work.n - w0} units of work in ${Math.round(performance.now() - t0)} ms`);
4288
- return { verdict: { law: l.name, ...v, ms: Math.round(performance.now() - t0) }, out };
5147
+ return { verdict: { law: l.name, ...v, ms: Math.round(performance.now() - t0) }, out, facts: proofFacts };
4289
5148
  };
4290
5149
  if (phase !== 'rest') {
4291
5150
  const cex = refute(l, opts.samples ?? 400);
@@ -4308,7 +5167,7 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4308
5167
  }
4309
5168
  return lemmas.filter(q => seen.has(nodes.indexOf(nodes.find(n => n.name === q.spec.name)))).map(q => q.law.name);
4310
5169
  };
4311
- const ok = (r, lemmas, prog = p) => (tried += r.tried, r.out ? (out = r.out, done({ proven: true, checked: true, proof: r.verdict, lemmas: used(r.out, lemmas), scheme: r.scheme, tried, program: prog, node: r.out.nodes.indexOf(r.out.spec) })) : undefined);
5170
+ const ok = (r, lemmas, prog = p) => (tried += r.tried, r.out ? (out = r.out, proofFacts = contexts.get(prog), done({ proven: true, checked: true, proof: r.verdict, lemmas: used(r.out, lemmas), scheme: r.scheme, tried, program: prog, node: r.out.nodes.indexOf(r.out.spec) })) : undefined);
4312
5171
  // A law that calls no function (arithmetic alone: an integer's, a remainder's) has nothing to induct on: its cases.
4313
5172
  if (phase !== 'rest' && opts.induction !== false && !JSON.stringify(l.holds).includes('"op":"call"')) {
4314
5173
  const c = ok(proveWith(p, fs, l, base, lv + 1, opts, until, 3000, [1, 2], 'cases'), base);
@@ -4321,6 +5180,18 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4321
5180
  return one;
4322
5181
  if (phase === 'first')
4323
5182
  return done({ proven: false, checked: false, lemmas: [], tried, ...stuckOf(first.last) });
5183
+ // Call-count ranks are useful only after the law's light first attempt fails.
5184
+ // Admitting them eagerly made even singleton laws re-prove unused recursive
5185
+ // definitions. Extend the vocabulary here, preserving prior proof fact indices.
5186
+ if (opts.induction !== false && !inTermination.on) {
5187
+ const next = programOf([l, ...(Array.isArray(opts.lemmas) ? opts.lemmas : [])], p.fns);
5188
+ if (next.fns.some(f => !p.fns.includes(f))) {
5189
+ const made = factsOf(next), extra = made.facts.filter(f => !fs.at.has(f.name));
5190
+ fs = { facts: [...fs.facts, ...extra], at: new Map([...fs.at, ...extra.map((f, i) => [f.name, fs.facts.length + i])]), arity: made.arity };
5191
+ p = next;
5192
+ contexts.set(p, fs);
5193
+ }
5194
+ }
4324
5195
  const without = opts.lemmas === false || opts.induction === false;
4325
5196
  if (without)
4326
5197
  return ok(proveWith(p, fs, l, base, lv + 1, opts, until, 20000, [2, 3]), base) ?? (opts.induction === false ? undefined : ok(proveWith(p, fs, l, base, lv + 1, opts, until, 3000, [1, 2], 'cases'), base)) ?? done({ proven: false, checked: false, lemmas: [], tried, ...stuckOf(first?.last) });
@@ -4333,14 +5204,28 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4333
5204
  return two;
4334
5205
  }
4335
5206
  // 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);
5207
+ // (a conjecture that is the law at some of its values, or the law said as an equation with a constant, p(x) = true,
5208
+ // is proven only by proving the law: none is tried)
5209
+ const tc = performance.now(), calc = Array.isArray(opts.lemmas) ? [] : calculated(p, l, 2, 6).filter(c => !lawAgain(l, c));
4337
5210
  if (dataTrace)
4338
5211
  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)];
5212
+ const invented = Array.isArray(opts.lemmas) ? [] : synthesizedLemmas(p).filter(c => !lawAgain(l, c));
5213
+ for (const c of invented)
5214
+ distributed.add(c);
5215
+ const cands = Array.isArray(opts.lemmas) ? opts.lemmas : [...calc, ...invented, ...conjectures(p, l).filter(c => !lawAgain(l, c))];
4340
5216
  if (dataTrace)
4341
5217
  for (const c of calc)
4342
5218
  console.error(`[data] calculated ${c.name.slice(0, 200)}`);
4343
- const p2 = ctx ? p : programOf([l, ...cands]), fs2 = ctx ? fs : factsOf(p2);
5219
+ // A transfer context predates invented observer definitions. Extend its vocabulary, retaining
5220
+ // the old fact indices used by its already-proved nodes; new definitions/congruences append.
5221
+ const p2 = ctx && !invented.length ? p : programOf([l, ...cands], ctx ? p.fns : []);
5222
+ const madeFacts = p2 === p ? fs : factsOf(p2);
5223
+ const extraFacts = ctx ? madeFacts.facts.filter(f => !fs.at.has(f.name)) : [];
5224
+ const fs2 = !ctx ? madeFacts : !extraFacts.length ? fs : {
5225
+ facts: [...fs.facts, ...extraFacts],
5226
+ at: new Map([...fs.at, ...extraFacts.map((f, i) => [f.name, fs.facts.length + i])]), arity: madeFacts.arity,
5227
+ };
5228
+ contexts.set(p2, fs2);
4344
5229
  // Each scheme's goals: the law's, and each companion's (a lemma may be what only a companion's goal reads).
4345
5230
  const goalOf = (law, uses, on, concls, shapes) => {
4346
5231
  const concl = encY(p2, law.holds, new Map()), ihc = uses.map(u => substC(concls[u.member ?? 0] ?? concl, { vars: u.subst, maps: {}, flags: {} }));
@@ -4354,16 +5239,37 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4354
5239
  const goalHits = new Set(), others = cands.slice(calc.length);
4355
5240
  for (const g of goals)
4356
5241
  lemmaUsesFor(p2, fs2, others.map((c, i) => ({ law: c, node: i, concl: encY(p2, c.holds, new Map()) })), g.from, g.insts, [], undefined, goalHits);
4357
- const matchesGoal = (c) => goalHits.has(others.indexOf(c));
5242
+ // (an observer distributed over one builder the goal reads, over the others too: count through ++ leaves the counts of
5243
+ // quicksort's two filters, which the filters' complement law then joins)
5244
+ const observer = (c) => { const family = synthesizedObserver(c); if (family)
5245
+ return family; const y = c.holds; let f; walk(y.b, o => { if (!f && o.op === 'call')
5246
+ f = o.fn; }); return f; };
5247
+ const hitObservers = new Set(others.flatMap((c, i) => (goalHits.has(i) && distributed.has(c) ? [observer(c)] : [])));
5248
+ const matchesGoal = (c) => goalHits.has(others.indexOf(c)) || (distributed.has(c) && hitObservers.has(observer(c)));
4358
5249
  // Those the goal matches first, of those the ones of the law's shape (an implication for an implication) first, then
4359
5250
  // the fusions.
4360
5251
  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);
5252
+ // (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
5253
+ // one's definition reaches, through a function returning a datatype, one of the two not the law's: count through
5254
+ // insert, ordered through merge, a search tree's allBelow through its insertion; the law's step reads them where an
5255
+ // induction unfolds the law's functions)
5256
+ const fnsIn = (y) => { const out = new Set(); walk(y, o => { if (o.op === 'call')
5257
+ out.add(o.fn); }); return out; };
5258
+ const inLaw = fnsIn(l.holds), lawY = implication(l.holds) ? l.holds.xs[1] : l.holds;
5259
+ 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] : [])));
5260
+ for (const f of [...observers])
5261
+ for (const g of fnsIn(fnOf(f).body()))
5262
+ if (!(fnOf(g).ret instanceof Data))
5263
+ observers.add(g);
5264
+ 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)); };
5265
+ // Targeted observer families include the premises of their guarded equations; keep
5266
+ // those ahead of undirected enumeration so the whole dependency chain gets a turn.
5267
+ const score = (c, hit) => (synthesizedObserver(c) ? 16 : 0) + (hit ? 8 : 0) + (under(c) ? 4 : 0) + (implication(c.holds) === implication(l.holds) ? 2 : 0) + (fusion(c.holds) ? 1 : 0);
4362
5268
  if (dataTrace)
4363
5269
  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
5270
  // (the calculated steps first, in their order: each before the one it was calculated from)
4365
5271
  const calcSet = new Set(calc);
4366
- const ranked = [...calc.map(c => ({ c, hit: true })), ...cands.slice(calc.length).map(c => ({ c, hit: matchesGoal(c) })).sort((a, b) => score(b.c, b.hit) - score(a.c, a.hit))];
5272
+ const ranked = [...calc.map(c => ({ c, hit: true })), ...cands.slice(calc.length).map(c => ({ c, hit: matchesGoal(c) })).sort((a, b) => score(b.c, b.hit) - score(a.c, a.hit) || +distributed.has(b.c) - +distributed.has(a.c))];
4367
5273
  if (dataTrace)
4368
5274
  for (const r of ranked)
4369
5275
  console.error(`[data] ranked ${r.hit ? "hit" : " "} ${r.c.name.slice(0, 150)}`);
@@ -4378,7 +5284,9 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4378
5284
  const lemmaPass = (which, most, end, cap, depths) => {
4379
5285
  // (`extra`: the calculated steps' attempts and the second ones, at most `most`, beside the conjectures' 3·most)
4380
5286
  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);
5287
+ // (a termination's obligation, its lemmas given: first without induction at no unfolding (the lemma's use and the
5288
+ // constructors' sizes: toList's call on a merge, 1032 instances at one unfolding and past its time), then at one)
5289
+ 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
5290
  // A conjecture of this pass that failed is tried once more after a lemma is proven (HipSpec's loop: bind over an
4383
5291
  // append needs ++ associative, proven after it); first those, then the next of the ranking.
4384
5292
  const queue = ranked.filter(r => (which === 'hits') === r.hit), retry = [], retried = new Set();
@@ -4421,8 +5329,16 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4421
5329
  }
4422
5330
  // (as before the passes: again after a lemma the goal reads, or one of the law's shape, an implication for one; a
4423
5331
  // calculated step's after the last of them, whose proofs read each other)
5332
+ // (and one of an observer distributed over a builder before the next of them: quicksort's count needs both ++'s and
5333
+ // the filters')
4424
5334
  if (calcSet.has(c) && !retry.length && i < queue.length && calcSet.has(queue[i].c))
4425
5335
  continue;
5336
+ if (distributed.has(c) && i < queue.length && distributed.has(queue[i].c)) {
5337
+ for (const q of retry)
5338
+ retried.delete(q);
5339
+ retry.length = 0;
5340
+ continue;
5341
+ }
4426
5342
  if (which === 'hits' || implication(c.holds) === implication(l.holds)) {
4427
5343
  since = 0;
4428
5344
  const r2 = again('first');
@@ -4473,7 +5389,7 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4473
5389
  // Lemmas first (a call's decrease from size laws): those the goal reads, the others, each proven and the law tried
4474
5390
  // again after it; then the law with every lemma proven, at two unfoldings.
4475
5391
  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));
5392
+ 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
5393
  for (const [i, step] of steps.entries()) {
4478
5394
  if (clock() > until)
4479
5395
  break;
@@ -4485,6 +5401,31 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
4485
5401
  }
4486
5402
  return done({ proven: false, checked: false, lemmas: [], tried, ...stuckOf(first?.last) });
4487
5403
  }
5404
+ // Whether a conjecture is the law again: the law at some values of its variables (count(0, sort(xs)) = count(0, xs)),
5405
+ // either way round, or a Bool law said as an equation with a side that is true at every value (ordered(sort(xs)) =
5406
+ // ordered([])).
5407
+ function lawAgain(l, c) {
5408
+ const free = new Set(l.vars.map(v => v.name)), at = (pat, t) => matchX(pat, t, free, new Map());
5409
+ const y = c.holds, ly = l.holds;
5410
+ if (at(ly, y))
5411
+ return true;
5412
+ if (y.op !== '=')
5413
+ return false;
5414
+ // (a law of two Bool values equal, read as the two implications: p(a) = p(b))
5415
+ const held = (z) => (z.op === 'holds' ? z.x : undefined);
5416
+ 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;
5417
+ const sides = ly.op === '=' ? [ly.a, ly.b] : half?.every(Boolean) ? half : undefined;
5418
+ if (sides && (at(sides, [y.a, y.b]) || at(sides, [y.b, y.a])))
5419
+ return true;
5420
+ const truth = (x) => { if (JSON.stringify(x).includes('"op":"var"'))
5421
+ return undefined; try {
5422
+ return evalX(x, new Map(), {});
5423
+ }
5424
+ catch {
5425
+ return undefined;
5426
+ } };
5427
+ return ly.op === 'holds' && [[y.a, y.b], [y.b, y.a]].some(([t, k2]) => truth(k2) === 1 && at(ly.x, t));
5428
+ }
4488
5429
  // A fusion: an equation one side of which nests a call of the program's functions in another's argument, the other side
4489
5430
  // calls on its variables alone (length(x ++ y) = length(x) + length(y), drop(n + m, xs) = drop(n, drop(m, xs)),
4490
5431
  // rev(xs ++ [x]) = x :: rev(xs)): the rewrite that takes a composition the goal reads apart. Its proof unfolds both