gdp-wired 0.24.0 → 0.25.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.
package/dist/core/data.js CHANGED
@@ -2,7 +2,7 @@ import { substC, substE } from "../kernel/kernel.js";
2
2
  import { proveCyclic } from "./cyclic.js";
3
3
  import { clock, counted, pairedKeys, withDeadline } from "../kernel/prove.js";
4
4
  import { work } from "./solver.js";
5
- import { rankOfPaths, ranksOfCalls } from "./cycles.js";
5
+ import { rankOfPaths, ranksOfCalls, showC } from "./cycles.js";
6
6
  import { proveThrough, transferPlan } from "./transfer.js";
7
7
  // --- sorts and the AST ------------------------------------------------------------------------------------------------
8
8
  export const self = { self: true };
@@ -1694,7 +1694,7 @@ function unfoldAt(f) {
1694
1694
  // The inductions the search tries for a law (its schemes), for tests.
1695
1695
  export const schemesOf = (p, l) => schemes(p, l);
1696
1696
  function schemes(p, l) {
1697
- const out = [], seen = new Set();
1697
+ const out = [], seen = new Set(), halves = [];
1698
1698
  const add = (s) => { const id = JSON.stringify(s.uses); if (!seen.has(id)) {
1699
1699
  seen.add(id);
1700
1700
  out.push(s);
@@ -1713,7 +1713,14 @@ function schemes(p, l) {
1713
1713
  if (!m && (at.op !== 'var' || !l.vars.some(v => v.name === at.name)))
1714
1714
  return;
1715
1715
  const d = f.params[f.decreases ?? 0].sort;
1716
- const formal = new Map(f.params.map((q, i) => [`${f.name}.${q.name}`, args[i].op === 'var' && l.vars.some(v => v.name === args[i].name) ? ev(args[i].name) : undefined]));
1716
+ const isVar = (x) => x.op === 'var' && l.vars.some(v => v.name === x.name);
1717
+ // (an argument that is no variable of the law read as the term it is, where its variables are the law's: its changes
1718
+ // at a recursive call then constrain nothing, the scheme being one half of a merged one, below)
1719
+ const closed = (x) => { let ok = true; walk(x, o => { if (o.op === 'var' && !l.vars.some(v => v.name === o.name))
1720
+ ok = false; if (o.op === 'match' || o.op === 'natmatch' || o.op === 'if')
1721
+ ok = false; }); return ok; };
1722
+ 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]));
1723
+ let relaxed = false;
1717
1724
  const uses = [];
1718
1725
  // (`through`: the functions of f's ring whose bodies are read in place of their calls, once each: evens through
1719
1726
  // odds, which call each other, is recursion of evens at the tail's tail)
@@ -1759,7 +1766,12 @@ function schemes(p, l) {
1759
1766
  t.args.forEach((a, i) => {
1760
1767
  const lv = args[i];
1761
1768
  if (lv.op !== 'var' || !l.vars.some(v => v.name === lv.name)) {
1762
- ok = ok && JSON.stringify(a) === JSON.stringify({ op: 'var', name: `${f.name}.${f.params[i].name}` });
1769
+ if (JSON.stringify(a) !== JSON.stringify({ op: 'var', name: `${f.name}.${f.params[i].name}` })) {
1770
+ if (formal.get(`${f.name}.${f.params[i].name}`))
1771
+ relaxed = true;
1772
+ else
1773
+ ok = false;
1774
+ }
1763
1775
  return;
1764
1776
  }
1765
1777
  const e = encX(p, a, env);
@@ -1777,7 +1789,11 @@ function schemes(p, l) {
1777
1789
  if (!uses.length)
1778
1790
  return;
1779
1791
  if (!m) {
1780
- add({ name: `recursion of ${f.name} on ${at.name}`, on: { v: at.name, d }, uses });
1792
+ const sc = { name: `recursion of ${f.name} on ${at.name}`, on: { v: at.name, d }, uses };
1793
+ if (relaxed)
1794
+ halves.push(sc);
1795
+ else
1796
+ add(sc);
1781
1797
  return;
1782
1798
  }
1783
1799
  // Well-founded: ranked by the measure at the law's arguments; the law's variables it reads named.
@@ -1797,6 +1813,35 @@ function schemes(p, l) {
1797
1813
  }
1798
1814
  add({ name: `structure of ${v.name}`, on: { v: v.name, d }, uses: d.ctors.flatMap((c, j) => c.fields.flatMap((f, i) => (isDataField(f.sort) && f.sort.data === d.name ? [{ subst: { [v.name]: get(fieldMap(d, j, i), x) }, guard: eqC(get(tagMap(d.name), x), k(j)) }] : []))) });
1799
1815
  }
1816
+ // Two schemes merged (Boyer and Moore's): each pair of their uses that agree where both substitute a variable, the two
1817
+ // substitutions at once under both guards (drop n (take m xs): n, m and xs each one smaller where n and m are
1818
+ // successors and xs a cons), ranked by a datatype's variable both descend on, else a natural's. After the others.
1819
+ const plainOnes = [...out.filter(sc => sc.on && !sc.rank && !sc.companions), ...halves];
1820
+ let merged = 0;
1821
+ for (const [i, s1] of plainOnes.entries())
1822
+ for (const s2 of plainOnes.slice(i + 1)) {
1823
+ if (merged >= 4 || s1.on.v === s2.on.v)
1824
+ continue;
1825
+ const uses = [];
1826
+ for (const u1 of s1.uses)
1827
+ for (const u2 of s2.uses) {
1828
+ if (Object.keys(u1.subst).some(x => x in u2.subst && tid(u1.subst[x]) !== tid(u2.subst[x])))
1829
+ continue;
1830
+ const subst = { ...u1.subst, ...u2.subst };
1831
+ if (Object.keys(subst).length <= Math.max(Object.keys(u1.subst).length, Object.keys(u2.subst).length))
1832
+ continue;
1833
+ uses.push({ subst, guard: andC(u1.guard, u2.guard) });
1834
+ }
1835
+ if (!uses.length)
1836
+ continue;
1837
+ const on = [s2.on, s1.on].find(o => o.d !== 'nat' && uses.every(u => o.v in u.subst)) ?? [s2.on, s1.on].find(o => uses.every(u => o.v in u.subst));
1838
+ if (!on)
1839
+ continue;
1840
+ const before = out.length;
1841
+ add({ name: `${s1.name} with ${s2.name}`, on, uses, merged: true });
1842
+ if (out.length > before)
1843
+ merged++;
1844
+ }
1800
1845
  return out;
1801
1846
  }
1802
1847
  function instancesOf(p, fs, w) {
@@ -1879,12 +1924,17 @@ function instancesOf(p, fs, w) {
1879
1924
  };
1880
1925
  ariths();
1881
1926
  lap(`unfolded, ${insts.length} instances, ${all.length} reads`);
1882
- const closure = (model) => {
1927
+ // `twins`: natural arguments of a function equal in every model of a case (its node's), one class too, with the
1928
+ // congruences that reads at them then meet (where the case's arguments agree by arithmetic its facts give: n ∸ len xs
1929
+ // and (n ∸ 1) ∸ len (tail xs), xs a cons); an explanation takes such a step only where the facts give none.
1930
+ const twinValues = new Map();
1931
+ const truncated = (t) => t.op === 'sub' || ((t.op === 'add' || t.op === 'mul') && (truncated(t.a) || (t.op === 'add' && truncated(t.b))));
1932
+ const closure = (model, twins = false) => {
1883
1933
  const parent = new Map(), terms = new Map(), adj = new Map();
1884
1934
  const find = (x) => { let r = x; while (parent.has(r))
1885
1935
  r = parent.get(r); return r; };
1886
1936
  const linked = new Set();
1887
- const edge = (x, y, cong) => {
1937
+ const edge = (x, y, cong, twin) => {
1888
1938
  const a2 = tid(x), b2 = tid(y);
1889
1939
  terms.set(a2, x);
1890
1940
  terms.set(b2, y);
@@ -1897,8 +1947,8 @@ function instancesOf(p, fs, w) {
1897
1947
  linked.add(a2 < b2 ? `${a2}|${b2}` : `${b2}|${a2}`);
1898
1948
  if (merged)
1899
1949
  parent.set(find(a2), find(b2));
1900
- (adj.get(a2) ?? adj.set(a2, []).get(a2)).push({ to: b2, cong });
1901
- (adj.get(b2) ?? adj.set(b2, []).get(b2)).push({ to: a2, cong: cong && { map: cong.map, x: cong.y, y: cong.x } });
1950
+ (adj.get(a2) ?? adj.set(a2, []).get(a2)).push({ to: b2, cong, twin });
1951
+ (adj.get(b2) ?? adj.set(b2, []).get(b2)).push({ to: a2, cong: cong && { map: cong.map, x: cong.y, y: cong.x }, twin });
1902
1952
  return merged;
1903
1953
  };
1904
1954
  const truthOf = (c) => { if (!model)
@@ -1940,6 +1990,9 @@ function instancesOf(p, fs, w) {
1940
1990
  active(holdsAt(fs.facts[q.fact].name, q.at));
1941
1991
  for (const c of w.others)
1942
1992
  active(c);
1993
+ for (const c of w.hyps ?? [])
1994
+ if (c.op === '=')
1995
+ edge(c.a, c.b);
1943
1996
  const cells = new Map();
1944
1997
  for (const r of all) {
1945
1998
  const n = fs.arity.get(r.map), as = n ? argsOf(r.key, n) : undefined;
@@ -1949,10 +2002,22 @@ function instancesOf(p, fs, w) {
1949
2002
  // Arguments equal by arithmetic alone, one class: (n + 1) ∸ 1 and n (a successor's predecessor, where a definition
1950
2003
  // on the naturals is unfolded at n + 1), so their reads meet by congruence. The kernel proves the equality itself.
1951
2004
  const byForm = new Map();
2005
+ const at = model && ((t) => { try {
2006
+ return model.m.evalE(t, model.env);
2007
+ }
2008
+ catch {
2009
+ return undefined;
2010
+ } });
2011
+ // (a read or variable of a constant's class, that constant: n + m ∸ 1 and m ∸ 1 one form where the case has n = 0)
2012
+ const consts = new Map();
2013
+ for (const [key, t] of terms)
2014
+ if (t.op === 'const')
2015
+ consts.set(find(key), t.value);
2016
+ const known = (t) => consts.get(find(tid(t)));
1952
2017
  for (const list of cells.values())
1953
2018
  for (const x of list)
1954
2019
  for (const t of x.as) {
1955
- const f = linearForm(t);
2020
+ const f = linearForm(t, at, known);
1956
2021
  if (f === undefined)
1957
2022
  continue;
1958
2023
  const had = byForm.get(f);
@@ -1961,6 +2026,40 @@ function instancesOf(p, fs, w) {
1961
2026
  else if (tid(had) !== tid(t))
1962
2027
  edge(had, t);
1963
2028
  }
2029
+ if (twins && w.hyps && w.models.length >= 4) {
2030
+ const byValue = new Map();
2031
+ for (const [map, list] of cells) {
2032
+ const f = fnOfMap(map);
2033
+ if (!f)
2034
+ continue;
2035
+ for (const x of list)
2036
+ for (const [i, t] of x.as.entries()) {
2037
+ // (a difference, truncated, the form linear forms leave: n ∸ len xs; not a value the facts give, x for run [] x)
2038
+ if (f.params[i]?.sort !== 'nat' || !truncated(t))
2039
+ continue;
2040
+ const id = tid(t);
2041
+ let vs = twinValues.get(id);
2042
+ // (a value the same in every model is no witness: it is a constant's, or the models' chance)
2043
+ if (vs === undefined) {
2044
+ vs = null;
2045
+ try {
2046
+ const xs = w.models.map(({ m, env }) => m.evalE(t, env));
2047
+ if (new Set(xs).size > 1)
2048
+ vs = JSON.stringify(xs);
2049
+ }
2050
+ catch { /* past the models' bounds */ }
2051
+ twinValues.set(id, vs);
2052
+ }
2053
+ if (vs === null)
2054
+ continue;
2055
+ const had = byValue.get(vs);
2056
+ if (!had)
2057
+ byValue.set(vs, t);
2058
+ else if (tid(had) !== id)
2059
+ edge(had, t, undefined, true);
2060
+ }
2061
+ }
2062
+ }
1964
2063
  for (let changed = true; changed && !late();) {
1965
2064
  changed = false;
1966
2065
  for (const [map, list] of cells) {
@@ -2108,7 +2207,7 @@ function instancesOf(p, fs, w) {
2108
2207
  for (const model of w.models) {
2109
2208
  if (late())
2110
2209
  break;
2111
- const { find, adj, truthOf } = closure(model);
2210
+ const { find, adj, truthOf } = closure(model, true);
2112
2211
  const counted = new Set(), explained = new Set();
2113
2212
  const explain = (a2, b2) => {
2114
2213
  const key = a2 < b2 ? `${a2}|${b2}` : `${b2}|${a2}`;
@@ -2119,7 +2218,8 @@ function instancesOf(p, fs, w) {
2119
2218
  // A path through no constant first: two terms the model gives one value aren't equal for that alone (each needs
2120
2219
  // its own facts), and a congruence between them is what the proof can use; else one through a constant.
2121
2220
  const isConst = (x) => x !== a2 && x !== b2 && x.startsWith('{"op":"const"');
2122
- for (const avoid of [true, false]) {
2221
+ // (and through no twins, where the facts give a path)
2222
+ for (const [avoid, noTwin] of [[true, true], [false, true], [false, false]]) {
2123
2223
  if (back.has(b2))
2124
2224
  break;
2125
2225
  back.clear();
@@ -2131,7 +2231,7 @@ function instancesOf(p, fs, w) {
2131
2231
  if (avoid && isConst(x))
2132
2232
  continue;
2133
2233
  for (const e of adj.get(x) ?? [])
2134
- if (!back.has(e.to)) {
2234
+ if (!back.has(e.to) && !(noTwin && e.twin)) {
2135
2235
  back.set(e.to, { from: x, cong: e.cong });
2136
2236
  queue.push(e.to);
2137
2237
  }
@@ -2280,12 +2380,18 @@ const sid = (t) => {
2280
2380
  const tid = (t) => sid(t);
2281
2381
  // A natural term's linear form (Σ cᵢ·atomᵢ + c, an atom a variable or a read, its text its id), where it is one: a
2282
2382
  // truncated difference by a constant only where the constant is at most the term's (x + 1 ∸ 1 is x); else undefined.
2283
- function linearForm(e) {
2383
+ // `at`: a model's values, where a truncated difference whose left side is at least its right there is their difference
2384
+ // (n + m ∸ 1 and n + (m ∸ 1) one form where m ≥ 1: the kernel proves the equality from the case's own conditions).
2385
+ // `known`: a term's constant value, where the facts give it one.
2386
+ function linearForm(e, at, known) {
2284
2387
  const go = (t) => {
2285
2388
  switch (t.op) {
2286
2389
  case 'const': return { cs: new Map(), c: t.value };
2287
2390
  case 'var':
2288
- case 'get': return { cs: new Map([[tid(t), 1]]), c: 0 };
2391
+ case 'get': {
2392
+ const v = known?.(t);
2393
+ return v !== undefined ? { cs: new Map(), c: v } : { cs: new Map([[tid(t), 1]]), c: 0 };
2394
+ }
2289
2395
  case 'add': {
2290
2396
  const a = go(t.a), b = go(t.b);
2291
2397
  if (!a || !b)
@@ -2301,7 +2407,17 @@ function linearForm(e) {
2301
2407
  }
2302
2408
  case 'sub': {
2303
2409
  const a = go(t.a);
2304
- return a && t.b.op === 'const' && a.c >= t.b.value ? { cs: a.cs, c: a.c - t.b.value } : undefined;
2410
+ if (a && t.b.op === 'const' && a.c >= t.b.value)
2411
+ return { cs: a.cs, c: a.c - t.b.value };
2412
+ if (!a || !at)
2413
+ return undefined;
2414
+ const va = at(t.a), vb = at(t.b), b = va !== undefined && vb !== undefined && va >= vb ? go(t.b) : undefined;
2415
+ if (!b)
2416
+ return undefined;
2417
+ const cs = new Map(a.cs);
2418
+ for (const [x, k2] of b.cs)
2419
+ cs.set(x, (cs.get(x) ?? 0) - k2);
2420
+ return { cs, c: a.c - b.c };
2305
2421
  }
2306
2422
  case 'if':
2307
2423
  case 'min':
@@ -2411,6 +2527,9 @@ function valuesCompared(p, l) {
2411
2527
  }
2412
2528
  // Where a lemma's terms appear in a goal: a substitution of its variables by terms of the goal, for each term of the goal
2413
2529
  // that one of the lemma's sides matches (its variables read anywhere, the rest exactly).
2530
+ // A constructor in the lemma matches any value of its datatype too (`fieldMatch`), by its fields' reads (rev (y ++ [z]) at rev (y ++ x),
2531
+ // z the head of x: where x is no such constructor, a case the use's models then refuse).
2532
+ const fieldMatch = { on: false };
2414
2533
  function matches(pattern, vars, t, s) {
2415
2534
  if (pattern.op === 'var' && vars.has(pattern.name)) {
2416
2535
  const had = s[pattern.name];
@@ -2418,6 +2537,19 @@ function matches(pattern, vars, t, s) {
2418
2537
  return sid(had) === sid(t) ? s : undefined;
2419
2538
  return { ...s, [pattern.name]: t };
2420
2539
  }
2540
+ if (fieldMatch.on && pattern.op === 'get' && (t.op !== 'get' || t.map !== pattern.map)) {
2541
+ const at = pattern.map.indexOf('.'), d = at > 0 ? declared.get(pattern.map.slice(0, at)) : undefined, j = d ? d.ctors.findIndex((c, i) => c.fields.length > 0 && ctorMap(d, i) === pattern.map) : -1;
2542
+ if (d && j >= 0) {
2543
+ const fs2 = argsOf(pattern.key, d.ctors[j].fields.length);
2544
+ let out = s;
2545
+ for (const [i, f] of (fs2 ?? []).entries()) {
2546
+ if (!out)
2547
+ break;
2548
+ out = matches(f, vars, get(fieldMap(d, j, i), t), out);
2549
+ }
2550
+ return fs2 ? out : undefined;
2551
+ }
2552
+ }
2421
2553
  if (pattern.op !== t.op)
2422
2554
  return undefined;
2423
2555
  const po = pattern, to = t;
@@ -2440,7 +2572,8 @@ function matches(pattern, vars, t, s) {
2440
2572
  return out;
2441
2573
  }
2442
2574
  function casesOf(p, unfolded, vars, models) {
2443
- 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))) && plain(e.key)
2575
+ // (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)
2576
+ 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)
2444
2577
  : 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);
2445
2578
  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);
2446
2579
  // The functions' facts the goal unfolds.
@@ -2506,6 +2639,8 @@ function casesOf(p, unfolded, vars, models) {
2506
2639
  const dataTrace = !!globalThis.process?.env?.DATA_TRACE;
2507
2640
  // Debugging: every congruence a model's closure makes, not only those explanations use.
2508
2641
  const allCong = !!globalThis.process?.env?.DATA_ALLCONG;
2642
+ // Debugging: a failed attempt's node whose name the pattern matches, written out (hypotheses, uses, instances).
2643
+ const nodeTrace = globalThis.process?.env?.DATA_NODE;
2509
2644
  function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2510
2645
  const t0 = clock();
2511
2646
  anchoredAt.clear();
@@ -2541,14 +2676,14 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2541
2676
  // Uses of the lemmas, where a lemma's largest read matches a read of this goal (unfolded), its key up to the
2542
2677
  // equalities the unfolded definitions give (any branch); twice over, the uses' own conclusions read the second time.
2543
2678
  const pre = instancesOf(p, fs, { roots: [concl], others: ihConcls, depth, shapesAt, etaAt: [], models: [], until: t0 + attemptMs.ms });
2544
- const lemmaUses = lemmaUsesFor(p, fs, lemmaNodes, [concl, ihConcls], pre, models);
2679
+ const spare = [], lemmaUses = lemmaUsesFor(p, fs, lemmaNodes, [concl, ihConcls], pre, models, spare);
2545
2680
  const uses = [...ih, ...lemmaUses];
2546
2681
  if (dataTrace)
2547
2682
  for (const u of lemmaUses)
2548
2683
  console.error(`[data] lemma use ${specs[u.node].name.slice(0, 40)} at ${Object.entries(u.subst).map(([x, t]) => `${x} := ${brief(t, 80)}`).join('; ')}`);
2549
2684
  // The lemmas' conclusions are unfolded like the law's (they are what the goal reads, said another way); the cycle's
2550
2685
  // own uses only from depth 3.
2551
- const instsFor = (ms, us, every = false) => instancesOf(p, fs, { roots: [concl], others: us.map(useConcl), depth, shapesAt, etaAt: [...shapesAt, ...valuesCompared(p, mb.law)], models: ms, every, until: t0 + attemptMs.ms });
2686
+ const instsFor = (ms, us, every = false, hyps) => instancesOf(p, fs, { roots: [concl], others: us.map(useConcl), depth, shapesAt, etaAt: [...shapesAt, ...valuesCompared(p, mb.law)], models: ms, every, until: t0 + attemptMs.ms, hyps });
2552
2687
  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) : [];
2553
2688
  if (cases.length <= 1) {
2554
2689
  // One node: four uses of a lemma, twelve in all, the best first (as lemmaUsesFor ranks them).
@@ -2572,9 +2707,13 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2572
2707
  catch {
2573
2708
  return false;
2574
2709
  } }); };
2575
- const us = capUses(uses.filter(u => holdsIn(u.guard) && applies(u)));
2710
+ // And ranked within the case: of the uses past the node's caps, those whose sides are both the goal's terms (the
2711
+ // step the case's rewriting joins), `perCase` more of a lemma.
2712
+ const fit = [...uses, ...spare].filter(u => holdsIn(u.guard) && applies(u)), kept = capUses(fit.filter(u => uses.includes(u)));
2713
+ 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;
2714
+ const us = [...kept, ...capUses(joins ? rest.filter(u => joins(useConcl(u))) : [], lemmaCaps.joined)];
2576
2715
  const ms = few(c.models ?? c.near ?? models);
2577
- plan.push({ name: `${name}, case ${i + 1}`, hyps: c.lits, concl, sub: 0, insts: reached(p, fs, instsFor(ms, us), [c.lits, concl, us.map(u => [u.guard, useConcl(u)]), shapesAt], ms), uses: us });
2716
+ 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], ms), uses: us });
2578
2717
  }
2579
2718
  plans.push(plan);
2580
2719
  }
@@ -2719,7 +2858,8 @@ function reached(p, fs, insts, from, ms) {
2719
2858
  }
2720
2859
  // The uses of lemmas a goal's reads match: each lemma's largest reads (those inside no other) matched against the goal's
2721
2860
  // reads of the same map at keys equal, by the instances' equations (every branch), to the read's key.
2722
- function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
2861
+ // `hits`: the lemmas (their nodes) with any use at all, gathered there (and no uses made): whether a goal reads each.
2862
+ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
2723
2863
  const id = tid, parent = new Map(), terms = new Map();
2724
2864
  const find = (x) => { let r = x; while (parent.has(r))
2725
2865
  r = parent.get(r); return r; };
@@ -2780,69 +2920,89 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
2780
2920
  const callsFn = (t) => { let yes = false; walk(t, o => { if (o.op === 'get' && fs.arity.has(o.map) && p.fns.some(f => f.name === o.map))
2781
2921
  yes = true; }); return yes; };
2782
2922
  const tops = tops0.some(callsFn) ? tops0.filter(callsFn) : tops0;
2783
- for (const top of tops) {
2784
- const n = fs.arity.get(top.map) ?? 1, pats = argsOf(top.key, n);
2785
- // A pattern's match at a term alone, once (a match given others' bindings is it, where it agrees with them).
2786
- const alone = pats?.map(() => new Map());
2787
- const matchAt = (q, m, sb) => {
2788
- const memo = alone[q];
2789
- if (!memo.has(m))
2790
- memo.set(m, matches(pats[q], vars, m, {}));
2791
- const r = memo.get(m);
2792
- if (!r)
2793
- return undefined;
2794
- let out = sb;
2795
- for (const [x, v] of Object.entries(r)) {
2796
- const had = sb[x];
2797
- if (had) {
2798
- if (sid(had) !== sid(v))
2799
- return undefined;
2800
- }
2801
- else
2802
- out = out === sb ? { ...sb, [x]: v } : (out[x] = v, out);
2803
- }
2804
- return out;
2805
- };
2806
- for (const t of reads) {
2807
- if (t.op !== 'get' || t.map !== top.map)
2808
- continue;
2809
- // Each argument of the read matched up to its class (a key of several arguments is their pairing).
2810
- const args = argsOf(t.key, n);
2811
- if (!pats || !args)
2812
- continue;
2813
- let subs = [{}];
2814
- for (const q of pats.keys()) {
2815
- const ms = members(args[q]).slice(0, 256);
2816
- subs = subs.flatMap(sb => ms.flatMap(m => { const r = matchAt(q, m, sb); return r ? [r] : []; })).slice(0, 512);
2817
- }
2818
- for (const sub of subs) {
2819
- if (Object.keys(sub).length !== vars.size)
2820
- continue;
2821
- // Where a model gives the lemma's arguments the goal read's (a match through every branch's classes may be none).
2822
- const there = pats.map(a => substE(a, { vars: sub, maps: {}, flags: {} }));
2823
- const score = models.length ? models.filter(({ m, env }) => { try {
2824
- return there.every((a, q) => m.evalE(a, env) === m.evalE(args[q], env));
2923
+ // (a constructor matched by its fields only for a lemma no read matches as it stands: the uses would multiply)
2924
+ for (const byFields of [false, true]) {
2925
+ if (byFields && cands.some(c => c.use.node === lm.node))
2926
+ break;
2927
+ fieldMatch.on = byFields;
2928
+ for (const top of tops) {
2929
+ const n = fs.arity.get(top.map) ?? 1, pats = argsOf(top.key, n);
2930
+ // A pattern's match at a term alone, once (a match given others' bindings is it, where it agrees with them).
2931
+ const alone = pats?.map(() => new Map());
2932
+ const matchAt = (q, m, sb) => {
2933
+ const memo = alone[q];
2934
+ if (!memo.has(m))
2935
+ memo.set(m, matches(pats[q], vars, m, {}));
2936
+ const r = memo.get(m);
2937
+ if (!r)
2938
+ return undefined;
2939
+ let out = sb;
2940
+ for (const [x, v] of Object.entries(r)) {
2941
+ const had = sb[x];
2942
+ if (had) {
2943
+ if (sid(had) !== sid(v))
2944
+ return undefined;
2945
+ }
2946
+ else
2947
+ out = out === sb ? { ...sb, [x]: v } : (out[x] = v, out);
2825
2948
  }
2826
- catch {
2827
- return false;
2828
- } }).length : 1;
2829
- if (!score)
2949
+ return out;
2950
+ };
2951
+ for (const t of reads) {
2952
+ if (t.op !== 'get' || t.map !== top.map)
2830
2953
  continue;
2831
- const k2 = sid([lm.node, sub]);
2832
- if (seen.has(k2))
2954
+ // (one use is all `hits` asks of a lemma)
2955
+ if (hits?.has(lm.node))
2956
+ break;
2957
+ // Each argument of the read matched up to its class (a key of several arguments is their pairing).
2958
+ const args = argsOf(t.key, n);
2959
+ if (!pats || !args)
2833
2960
  continue;
2834
- seen.add(k2);
2835
- const names = Object.keys(sub).sort();
2836
- const fp = models.length ? JSON.stringify([lm.node, models.map(({ m, env }) => names.map(x => { try {
2837
- return m.evalE(sub[x], env);
2961
+ let subs = [{}];
2962
+ for (const q of pats.keys()) {
2963
+ const ms = members(args[q]).slice(0, 256);
2964
+ subs = subs.flatMap(sb => ms.flatMap(m => { const r = matchAt(q, m, sb); return r ? [r] : []; })).slice(0, 512);
2965
+ }
2966
+ for (const sub of subs) {
2967
+ if (Object.keys(sub).length !== vars.size)
2968
+ continue;
2969
+ // Where a model gives the lemma's arguments the goal read's (a match through every branch's classes may be none).
2970
+ const there = pats.map(a => substE(a, { vars: sub, maps: {}, flags: {} }));
2971
+ const score = models.length ? models.filter(({ m, env }) => { try {
2972
+ return there.every((a, q) => m.evalE(a, env) === m.evalE(args[q], env));
2838
2973
  }
2839
2974
  catch {
2840
- return -1;
2841
- } }))]) : k2;
2842
- cands.push({ use: { node: lm.node, subst: sub, guard: yesC }, at: { goal: t, lemma: substE(top, { vars: sub, maps: {}, flags: {} }) }, score, fp, size: textLength([lm.node, sub]) });
2975
+ return false;
2976
+ } }).length : 1;
2977
+ if (!score)
2978
+ continue;
2979
+ const k2 = sid([lm.node, sub]);
2980
+ if (seen.has(k2))
2981
+ continue;
2982
+ seen.add(k2);
2983
+ const names = Object.keys(sub).sort();
2984
+ const fp = models.length ? JSON.stringify([lm.node, models.map(({ m, env }) => names.map(x => { try {
2985
+ return m.evalE(sub[x], env);
2986
+ }
2987
+ catch {
2988
+ return -1;
2989
+ } }))]) : k2;
2990
+ const use = { node: lm.node, subst: sub, guard: yesC };
2991
+ if (hits) {
2992
+ hits.add(lm.node);
2993
+ break;
2994
+ }
2995
+ cands.push({ use, at: { goal: t, lemma: substE(top, { vars: sub, maps: {}, flags: {} }) }, score, fp, size: textLength([lm.node, sub]) });
2996
+ }
2843
2997
  }
2844
2998
  }
2845
2999
  }
3000
+ fieldMatch.on = false;
3001
+ }
3002
+ if (hits) {
3003
+ for (const c of cands)
3004
+ hits.add(c.use.node);
3005
+ return [];
2846
3006
  }
2847
3007
  // First, as found: four of a lemma, twelve in all (the next round reads their conclusions). Then the rest, best first
2848
3008
  // (the most models, then the smallest terms), one of each set of values, up to `perLemma` of a lemma and `total` in
@@ -2858,9 +3018,18 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
2858
3018
  fresh.push(substC(lemmas.find(lm => lm.node === c.use.node).concl, { vars: c.use.subst, maps: {}, flags: {} }));
2859
3019
  }
2860
3020
  const rest = cands.filter(c => !first.has(c)).sort((a, b) => b.score - a.score || a.size - b.size);
2861
- for (const c of rest)
2862
- if (!fps.has(c.fp) && out.length < lemmaCaps.total && out.filter(u => u.node === c.use.node).length < lemmaCaps.perLemma)
3021
+ for (const c of rest) {
3022
+ if (fps.has(c.fp))
3023
+ continue;
3024
+ if (out.length < lemmaCaps.total && out.filter(u => u.node === c.use.node).length < lemmaCaps.perLemma)
2863
3025
  take(c);
3026
+ // (past the node's caps, kept for the cases: one case's models may meet a use the node's rank puts below them)
3027
+ else if (spare && spare.length < lemmaCaps.spare) {
3028
+ fps.add(c.fp);
3029
+ spare.push(c.use);
3030
+ matchedAt.set(c.use, c.at);
3031
+ }
3032
+ }
2864
3033
  // The second round: the reads of the first's conclusions, and the goal's again, matched up to the classes those
2865
3034
  // conclusions join (assoc's use makes x ++ (y ++ [z]) and (x ++ y) ++ [z] one, where rev of a snoc then matches).
2866
3035
  for (const c of fresh)
@@ -2873,8 +3042,9 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
2873
3042
  return out;
2874
3043
  }
2875
3044
  // How many uses of lemmas a goal gets: the candidates kept (`perLemma` of each lemma, `total`), and of those a case node
2876
- // keeps (`perCase` of each lemma, those its models meet).
2877
- export const lemmaCaps = { perLemma: 8, total: 24, perCase: 4 };
3045
+ // keeps (`perCase` of each lemma, those its models meet); past the node's, `spare` kept for its cases, of which a case
3046
+ // takes `joined` more (those its own rewriting passes through).
3047
+ export const lemmaCaps = { perLemma: 8, total: 24, perCase: 4, spare: 96, joined: 2 };
2878
3048
  // A node's uses: the scheme's (the cycle's, read at nodes not yet placed) all, `perCase` of each lemma, `total` lemma
2879
3049
  // uses in all, in the order given.
2880
3050
  function capUses(uses, total = Infinity) {
@@ -2902,6 +3072,104 @@ function equalities(c) {
2902
3072
  }
2903
3073
  // A lemma use: the goal's read it matched, and the lemma's read there (equal where the use applies).
2904
3074
  const matchedAt = new WeakMap();
3075
+ // A case's terms up to the equalities its models take (an if's branch, an implication's conclusion, where all of them
3076
+ // take it; the induction's hypotheses too), closed under congruence: `joins(c)`, whether each side of each equality of
3077
+ // c is one of those terms' classes (a read whose arguments' classes some read of its map has). A lemma use that joins
3078
+ // is a step the case's own rewriting passes through, from one of its terms to another (ripple's fertilisation), where
3079
+ // a use that only matches one of its terms is one its models alone may agree with (app (t, []) for t).
3080
+ function caseJoins(fs, from, insts, hyps, ms) {
3081
+ const parent = new Map();
3082
+ const find = (x) => { let r = x; while (parent.has(r))
3083
+ r = parent.get(r); return r; };
3084
+ const union = (x, y) => { const a = find(tid(x)), b = find(tid(y)); if (a !== b)
3085
+ parent.set(a, b); };
3086
+ const truth = (c) => { let v; for (const { m, env } of ms) {
3087
+ let t;
3088
+ try {
3089
+ t = m.evalC(c, env);
3090
+ }
3091
+ catch {
3092
+ return undefined;
3093
+ }
3094
+ if (v === undefined)
3095
+ v = t;
3096
+ else if (v !== t)
3097
+ return undefined;
3098
+ } return v; };
3099
+ const leaf = (e) => { if (e.op !== 'if')
3100
+ return e; const t = truth(e.c); return t === undefined ? undefined : leaf(t ? e.then : e.else); };
3101
+ const eqs = (c) => {
3102
+ if (c.op === '=') {
3103
+ const b = leaf(c.b);
3104
+ if (b)
3105
+ union(c.a, b);
3106
+ return;
3107
+ }
3108
+ if (c.op === 'and') {
3109
+ c.xs.forEach(eqs);
3110
+ return;
3111
+ }
3112
+ if (c.op === 'or') {
3113
+ const open = c.xs.filter(x => truth(x) !== false);
3114
+ if (open.length === 1)
3115
+ eqs(open[0]);
3116
+ }
3117
+ };
3118
+ for (const q of insts)
3119
+ eqs(holdsAt(fs, q));
3120
+ for (const h of hyps)
3121
+ eqs(h);
3122
+ const cells = new Map(), seen = new Set();
3123
+ walkOnce([from, insts.map(q => holdsAt(fs, q)), hyps], o => { if (o.op !== 'get')
3124
+ return; seen.add(tid(o)); const n = fs.arity.get(o.map), as = n ? argsOf(o.key, n) : undefined; if (as)
3125
+ (cells.get(o.map) ?? cells.set(o.map, []).get(o.map)).push({ key: o.key, as }); });
3126
+ for (let changed = true, rounds = 0; changed && rounds < 8; rounds++) {
3127
+ changed = false;
3128
+ for (const [map, list] of cells) {
3129
+ const bySig = new Map();
3130
+ for (const x of list) {
3131
+ const sig = x.as.map(t => find(tid(t))).join('\u0001'), y = bySig.get(sig), cx = get(map, x.key);
3132
+ if (!y)
3133
+ bySig.set(sig, cx);
3134
+ else if (find(tid(y)) !== find(tid(cx))) {
3135
+ union(y, cx);
3136
+ changed = true;
3137
+ }
3138
+ }
3139
+ }
3140
+ }
3141
+ const bySig = new Map();
3142
+ for (const [map, list] of cells)
3143
+ for (const x of list)
3144
+ bySig.set(`${map}\u0002${x.as.map(t => find(tid(t))).join('\u0001')}`, find(tid(get(map, x.key))));
3145
+ // (once per object: a key's pairing reads its arguments again, so a term's objects are shared deep down)
3146
+ const memo = new WeakMap();
3147
+ const classOf = (t) => {
3148
+ if (t.op !== 'get')
3149
+ return find(tid(t));
3150
+ const had = memo.get(t);
3151
+ if (had !== undefined)
3152
+ return had ?? undefined;
3153
+ const n = fs.arity.get(t.map), as = n ? argsOf(t.key, n) : undefined;
3154
+ let out;
3155
+ if (!as)
3156
+ out = seen.has(tid(t)) ? find(tid(t)) : undefined;
3157
+ else {
3158
+ const cs = [];
3159
+ for (const a of as) {
3160
+ const c = classOf(a);
3161
+ if (c === undefined)
3162
+ break;
3163
+ cs.push(c);
3164
+ }
3165
+ out = cs.length < as.length ? undefined : bySig.get(`${t.map}\u0002${cs.join('\u0001')}`);
3166
+ }
3167
+ memo.set(t, out ?? null);
3168
+ return out;
3169
+ };
3170
+ const all = (c) => (c.op === '=' ? [[c.a, c.b]] : c.op === 'and' ? c.xs.flatMap(all) : []);
3171
+ 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; }); };
3172
+ }
2905
3173
  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]]))); };
2906
3174
  // The models a search compares terms in: random values of the law's variables.
2907
3175
  function modelsFor(p, l, n, seed) {
@@ -2918,7 +3186,8 @@ const settled = new WeakMap();
2918
3186
  // `without`: 'plain', the law with no induction where no scheme applies; 'cases', no induction, then by the cases of
2919
3187
  // each variable (a natural's zero and successor, a datatype's constructors), none of them using the law again; 'first',
2920
3188
  // no induction before the schemes (a law that follows from its lemmas by rewriting).
2921
- function proveWith(p, fs, l, lemmas, level, opts, until, per, depths, without) {
3189
+ // `merge`: the merged schemes too (schemes, below), at one unfolding: the law's first attempts only.
3190
+ function proveWith(p, fs, l, lemmas, level, opts, until, per, depths, without, merge = false) {
2922
3191
  const models = modelsFor(p, l, 240, opts.seed ?? 3);
2923
3192
  let tried = 0, last;
2924
3193
  const cases = l.vars.flatMap((v) => (v.sort === 'nat' || v.sort instanceof Data ? [{ name: `cases of ${v.name}`, on: { v: v.name, d: v.sort }, uses: [] }] : []));
@@ -2929,13 +3198,25 @@ function proveWith(p, fs, l, lemmas, level, opts, until, per, depths, without) {
2929
3198
  for (const s of ss) {
2930
3199
  if (clock() > until)
2931
3200
  return { tried, last };
3201
+ // (a merged scheme at one unfolding only, in the law's first attempts: its cases are each scheme's at once, many at
3202
+ // two, and every proof by one found so far needed no lemma)
3203
+ if (s?.merged && (depth > 1 || !merge))
3204
+ continue;
2932
3205
  const key = JSON.stringify([l.name, s?.name, depth, level, lemmas.map(q => q.spec.name), opts.seed]);
2933
3206
  if (done.has(key))
2934
3207
  continue;
2935
3208
  tried++;
2936
3209
  const t1 = clock();
2937
- const { verdict, specs, main } = (attemptMs.ms = Math.min(per * (opts.patience ?? 1), until - clock()), attempt(p, fs, l, s, depth, lemmas, level, models));
3210
+ // (and within a third of an attempt's time: a merged scheme's proof, where there is one, is short)
3211
+ const { verdict, specs, main } = (attemptMs.ms = Math.min(per * (opts.patience ?? 1) / (s?.merged ? 3 : 1), until - clock()), attempt(p, fs, l, s, depth, lemmas, level, models));
2938
3212
  last = verdict;
3213
+ if (nodeTrace && !verdict.proven && new RegExp(nodeTrace).test(verdict.goal)) {
3214
+ const n = specs.find(x => x.name === verdict.goal);
3215
+ if (n)
3216
+ console.error(`[node] ${n.name}: ${verdict.stuck}\n hyps: ${n.hyps.map(showC).join(' ; ')}\n concl: ${showC(n.concl)}\n uses:\n ${n.uses.map(u => `${specs[u.node]?.name.slice(0, 40)}: ${showC(substC(specs[u.node].concl, { vars: u.subst, maps: {}, flags: {} }))} if ${showC(u.guard)}`).join('\n ')}\n instances:\n ${n.insts.map(q => `${fs.facts[q.fact].name}: ${showC(holdsAt(fs, q))}`).join('\n ')}`);
3217
+ }
3218
+ if (dataTrace)
3219
+ console.error(`[data] -> ${verdict.proven ? (verdict.checked ? 'proven' : `not checked: ${verdict.why}`) : `${verdict.goal}: ${verdict.stuck}`}`);
2939
3220
  if (!(verdict.proven && verdict.checked) && clock() <= t1 + attemptMs.ms)
2940
3221
  done.add(key);
2941
3222
  if (verdict.proven && verdict.checked)
@@ -3275,6 +3556,421 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
3275
3556
  }
3276
3557
  return out;
3277
3558
  }
3559
+ // Lemma calculation (Zeno's, HipSpec's): the step of an induction a law's definitions don't close, said as a lemma.
3560
+ // For each variable a scheme inducts on (a datatype's or a natural's) and each of its recursive constructors, the law
3561
+ // at that constructor of fresh fields, its definitions unfolded where they are decided (`reduceX`), the hypothesis (the
3562
+ // law at each recursive field) used as a rewrite where its side appears (either way, on either side); what is left
3563
+ // unequal is the step's goal, and with its subterms common to both sides each a fresh variable (generalised, as the
3564
+ // step's terms stand for any value of their sort), a conjecture. Those every random value meets are kept, smallest
3565
+ // first; each one's own step is calculated again (`depth`), the deeper ones first: a lemma's proof may need the next
3566
+ // (bind over an append needs ++ associative).
3567
+ export function calculated(p, l, depth = 2, max = 6) {
3568
+ const out = [], seen = new Set([canonText(l.holds, l.vars)]);
3569
+ const go = (law, d) => {
3570
+ if (d <= 0 || out.length >= 3 * max)
3571
+ return;
3572
+ for (const c of stepsOf(p, law)) {
3573
+ // (an equation and its mirror one)
3574
+ const text = canonText(c.holds, c.vars), y = c.holds, mirror = canonText({ op: '=', a: y.b, b: y.a }, c.vars);
3575
+ if (seen.has(text) || seen.has(mirror))
3576
+ continue;
3577
+ seen.add(text);
3578
+ seen.add(mirror);
3579
+ if (refute(c, 200))
3580
+ continue;
3581
+ if (general.has(c))
3582
+ go(c, d - 1);
3583
+ out.push(c);
3584
+ }
3585
+ };
3586
+ go(l, depth);
3587
+ // (the generalised steps first, in their order, then the base cases (a step's proof often needs one: nil's right
3588
+ // identity under length's), then the steps as they stand)
3589
+ return [...out.filter(c => general.has(c)), ...out.filter(c => based.has(c)), ...out.filter(c => !general.has(c) && !based.has(c))].slice(0, max);
3590
+ }
3591
+ // A law's text with its variables named by sort in order of appearance (two laws alike up to their names, one text).
3592
+ function canonText(y, vars) {
3593
+ const count = new Map(), ren = new Map();
3594
+ walk(y, o => { if (o.op === 'var' && !ren.has(o.name)) {
3595
+ const v = vars.find(w => w.name === o.name);
3596
+ if (!v)
3597
+ return;
3598
+ const key = v.sort instanceof Data ? v.sort.name : String(v.sort), i = (count.get(key) ?? 0) + 1;
3599
+ count.set(key, i);
3600
+ ren.set(v.name, `${key}#${i}`);
3601
+ } });
3602
+ return JSON.stringify(y, (_, v) => (v && typeof v === 'object' && v.op === 'var' && ren.has(v.name) ? { op: 'var', name: ren.get(v.name) } : v));
3603
+ }
3604
+ const substXs = (x, sub) => (sub.size ? JSON.parse(JSON.stringify(x), (_, v) => (v && typeof v === 'object' && v.op === 'var' && sub.has(v.name) ? sub.get(v.name) : v)) : x);
3605
+ const sameX = (a, b) => JSON.stringify(a) === JSON.stringify(b);
3606
+ // A term with its definitions unfolded where they are decided: a call whose body, its parameters given, decides its
3607
+ // first choice (the match, natmatch or if at its top, and the ones in the case taken) is that case's term (else the
3608
+ // call stays); a match of a constructor, a natmatch of a constant or of a successor (x + k), an if whose condition the
3609
+ // terms decide, is its case; one undecided inside a term unfolded stays as it is (a non-recursive definition unfolded
3610
+ // into another's, say); sums with their constants gathered. Within `fuel` unfoldings (a definition's recursion on a
3611
+ // value not built stays a call).
3612
+ export function reduceX(x, fuel = { n: 400 }) {
3613
+ // (`top`: the term is a body's choice, where an undecided one fails the unfolding)
3614
+ const red = (t, top = false) => {
3615
+ switch (t.op) {
3616
+ case 'var':
3617
+ case 'nat':
3618
+ case 'int': return t;
3619
+ case 'call': {
3620
+ const args = t.args.map(a => red(a));
3621
+ if (args.some(a => !a))
3622
+ return undefined;
3623
+ const call = { op: 'call', fn: t.fn, args: args };
3624
+ const f = fnNamed(t.fn);
3625
+ if (!f || fuel.n <= 0)
3626
+ return call;
3627
+ fuel.n--;
3628
+ const was = fuel.n;
3629
+ const body = red(substXs(f.body(), new Map(f.params.map((q, i) => [`${f.name}.${q.name}`, args[i]]))), true);
3630
+ if (!body) {
3631
+ fuel.n = was;
3632
+ return call;
3633
+ }
3634
+ return body;
3635
+ }
3636
+ case 'ctor': {
3637
+ const args = t.args.map(a => red(a));
3638
+ return args.some(a => !a) ? undefined : { ...t, args: args };
3639
+ }
3640
+ case 'match': {
3641
+ const of = red(t.of);
3642
+ if (!of)
3643
+ return undefined;
3644
+ if (of.op !== 'ctor')
3645
+ return top ? undefined : alpha({ ...t, of });
3646
+ const c = t.cases[of.ctor];
3647
+ return red(substXs(c.body, new Map(c.binds.map((b, i) => [b, of.args[i]]))), top);
3648
+ }
3649
+ case 'natmatch': {
3650
+ const of = red(t.of);
3651
+ if (!of)
3652
+ return undefined;
3653
+ if (of.op === 'nat')
3654
+ return of.value === 0 ? red(t.zero, top) : red(substXs(t.succ, new Map([[t.pred, { op: 'nat', value: of.value - 1 }]])), top);
3655
+ if (of.op === 'add' && of.b.op === 'nat' && of.b.value >= 1)
3656
+ return red(substXs(t.succ, new Map([[t.pred, of.b.value === 1 ? of.a : { op: 'add', a: of.a, b: { op: 'nat', value: of.b.value - 1 } }]])), top);
3657
+ return top ? undefined : alpha({ ...t, of });
3658
+ }
3659
+ case 'if': {
3660
+ const c = decide(t.c);
3661
+ return c === undefined ? (top ? undefined : alpha(t)) : red(c ? t.then : t.else, top);
3662
+ }
3663
+ case 'bool': {
3664
+ const c = decide(t.c);
3665
+ return c === undefined ? t : { op: 'bool', c: c ? { op: '<=', a: { op: 'nat', value: 0 }, b: { op: 'nat', value: 0 } } : { op: '<', a: { op: 'nat', value: 0 }, b: { op: 'nat', value: 0 } } };
3666
+ }
3667
+ case 'add': {
3668
+ const a = red(t.a), b = red(t.b);
3669
+ if (!a || !b)
3670
+ return undefined;
3671
+ if (a.op === 'nat' && b.op === 'nat')
3672
+ return { op: 'nat', value: a.value + b.value };
3673
+ if (a.op === 'nat' && a.value === 0)
3674
+ return b;
3675
+ if (b.op === 'nat' && b.value === 0)
3676
+ return a;
3677
+ // (constants last: (x + 1) + 1 is x + 2, 1 + x is x + 1)
3678
+ if (a.op === 'nat')
3679
+ return b.op === 'add' && b.b.op === 'nat' ? { op: 'add', a: b.a, b: { op: 'nat', value: b.b.value + a.value } } : { op: 'add', a: b, b: a };
3680
+ if (b.op === 'nat' && a.op === 'add' && a.b.op === 'nat')
3681
+ return { op: 'add', a: a.a, b: { op: 'nat', value: a.b.value + b.value } };
3682
+ return { op: 'add', a, b };
3683
+ }
3684
+ case 'sub':
3685
+ case 'min':
3686
+ case 'max':
3687
+ case 'prod':
3688
+ case 'iadd':
3689
+ case 'isub': {
3690
+ const a = red(t.a), b = red(t.b);
3691
+ if (!a || !b)
3692
+ return undefined;
3693
+ // (x + k ∸ j: a successor's predecessor)
3694
+ if (t.op === 'sub' && b.op === 'nat' && a.op === 'add' && a.b.op === 'nat' && a.b.value >= b.value)
3695
+ return a.b.value === b.value ? a.a : { op: 'add', a: a.a, b: { op: 'nat', value: a.b.value - b.value } };
3696
+ if (t.op === 'sub' && a.op === 'nat' && b.op === 'nat')
3697
+ return { op: 'nat', value: Math.max(0, a.value - b.value) };
3698
+ return { ...t, a, b };
3699
+ }
3700
+ case 'mul':
3701
+ case 'mod':
3702
+ case 'div':
3703
+ case 'ineg':
3704
+ case 'imul':
3705
+ case 'ofnat':
3706
+ case 'imod':
3707
+ case 'idiv': {
3708
+ const a = red(t.a);
3709
+ return a ? { ...t, a } : undefined;
3710
+ }
3711
+ case 'apply': {
3712
+ const arg = red(t.arg);
3713
+ return arg ? { ...t, arg } : undefined;
3714
+ }
3715
+ case 'size': {
3716
+ const of = red(t.of);
3717
+ return of ? { ...t, of } : undefined;
3718
+ }
3719
+ }
3720
+ };
3721
+ // An undecided choice left in a term, its binders named by their depth (two copies of one definition unfolded with
3722
+ // fresh names are then one term).
3723
+ const alpha = (t, level = 0) => {
3724
+ const go = (x, lv) => {
3725
+ if (!x || typeof x !== 'object')
3726
+ return x;
3727
+ if (Array.isArray(x))
3728
+ return x.map(y => go(y, lv));
3729
+ const o = x;
3730
+ if (o.op === 'match')
3731
+ return { ...o, of: go(o.of, lv), cases: o.cases.map(c => { const names = c.binds.map((_, i) => `$${lv}.${i}`); return { binds: names, body: go(substXs(c.body, new Map(c.binds.map((b, i) => [b, { op: 'var', name: names[i] }]))), lv + 1) }; }) };
3732
+ if (o.op === 'natmatch') {
3733
+ const name = `$${lv}.0`;
3734
+ return { ...o, of: go(o.of, lv), zero: go(o.zero, lv), pred: name, succ: go(substXs(o.succ, new Map([[o.pred, { op: 'var', name }]])), lv + 1) };
3735
+ }
3736
+ return Object.fromEntries(Object.entries(o).map(([key, v]) => [key, go(v, lv)]));
3737
+ };
3738
+ return go(t, level);
3739
+ };
3740
+ // A condition the terms decide: constructors told apart or alike field by field, constants compared, a test of a
3741
+ // constructor, a condition's value (bool) read back.
3742
+ const decide = (c) => {
3743
+ switch (c.op) {
3744
+ case 'and': {
3745
+ let all = true;
3746
+ for (const y of c.xs) {
3747
+ const v = decide(y);
3748
+ if (v === false)
3749
+ return false;
3750
+ if (v === undefined)
3751
+ all = undefined;
3752
+ }
3753
+ return all;
3754
+ }
3755
+ case 'or': {
3756
+ let any = false;
3757
+ for (const y of c.xs) {
3758
+ const v = decide(y);
3759
+ if (v === true)
3760
+ return true;
3761
+ if (v === undefined)
3762
+ any = undefined;
3763
+ }
3764
+ return any;
3765
+ }
3766
+ case 'not': {
3767
+ const v = decide(c.x);
3768
+ return v === undefined ? undefined : !v;
3769
+ }
3770
+ case 'is': {
3771
+ const of = red(c.of);
3772
+ return of && of.op === 'ctor' ? of.ctor === c.ctor : undefined;
3773
+ }
3774
+ case 'holds': {
3775
+ const x = red(c.x);
3776
+ return x && x.op === 'bool' ? decide(x.c) : undefined;
3777
+ }
3778
+ case '=':
3779
+ case '<':
3780
+ case '<=': {
3781
+ const a = red(c.a), b = red(c.b);
3782
+ if (!a || !b)
3783
+ return undefined;
3784
+ if (a.op === 'nat' && b.op === 'nat')
3785
+ return c.op === '=' ? a.value === b.value : c.op === '<' ? a.value < b.value : a.value <= b.value;
3786
+ if (c.op === '=' && sameX(a, b))
3787
+ return true;
3788
+ if (c.op === '=' && a.op === 'ctor' && b.op === 'ctor')
3789
+ return a.ctor !== b.ctor ? false : a.args.every((x, i) => sameX(x, b.args[i])) ? true : undefined;
3790
+ return undefined;
3791
+ }
3792
+ case 'i<':
3793
+ case 'i<=': return undefined;
3794
+ }
3795
+ };
3796
+ return red(x) ?? x;
3797
+ }
3798
+ // The steps a law's inductions leave, each as a conjecture (lemma calculation, above).
3799
+ const general = new WeakSet(), based = new WeakSet();
3800
+ function stepsOf(p, l) {
3801
+ if (l.holds.op !== '=')
3802
+ return [];
3803
+ const eq = l.holds, out = [];
3804
+ const sorts = new Map(l.vars.map(v => [v.name, v.sort]));
3805
+ const sortOf = (x) => (x.op === 'var' ? sorts.get(x.name) : x.op === 'call' ? fnNamed(x.fn)?.ret : x.op === 'ctor' ? dataNamed(x.data) : x.op === 'nat' || x.op === 'add' ? 'nat'
3806
+ : x.op === 'match' ? x.cases.map(c => sortOf(c.body)).find(s => s) : x.op === 'natmatch' ? sortOf(x.zero) ?? sortOf(x.succ) : x.op === 'if' ? sortOf(x.then) ?? sortOf(x.else) : undefined);
3807
+ let fresh = 0;
3808
+ const freshVar = (s) => { const name = `${s instanceof Data ? s.name.toLowerCase() : 'n'}_c${++fresh}`; sorts.set(name, s); return { op: 'var', name }; };
3809
+ const has = (x, t) => JSON.stringify(x).includes(JSON.stringify(t));
3810
+ const rewrite = (x, from, to) => { const f = JSON.stringify(from); return JSON.parse(JSON.stringify(x), (_, v) => (v && typeof v === 'object' && v.op && JSON.stringify(v) === f ? to : v)); };
3811
+ // The hypothesis at any values of the law's other variables (`free`): from's instances rewritten to to's, outermost
3812
+ // first (qrev (x, a :: y) to rev x ++ (a :: y), the hypothesis read at y := a :: y). Whether one was.
3813
+ const matchP = (pat, t, free, sub) => {
3814
+ if (pat && typeof pat === 'object' && pat.op === 'var' && free.has(pat.name)) {
3815
+ const n = pat.name, had = sub.get(n);
3816
+ if (had)
3817
+ return sameX(had, t);
3818
+ sub.set(n, t);
3819
+ return true;
3820
+ }
3821
+ if (Array.isArray(pat))
3822
+ return Array.isArray(t) && pat.length === t.length && pat.every((x, i) => matchP(x, t[i], free, sub));
3823
+ if (pat && typeof pat === 'object') {
3824
+ if (!t || typeof t !== 'object' || Array.isArray(t))
3825
+ return false;
3826
+ const po = pat, to = t;
3827
+ return Object.keys(po).length === Object.keys(to).length && Object.keys(po).every(key => matchP(po[key], to[key], free, sub));
3828
+ }
3829
+ return pat === t;
3830
+ };
3831
+ const rewriteP = (x, from, to, free) => {
3832
+ let hit = false;
3833
+ const go = (t) => {
3834
+ if (!t || typeof t !== 'object')
3835
+ return t;
3836
+ if (Array.isArray(t))
3837
+ return t.map(go);
3838
+ const sub = new Map();
3839
+ if (t.op && matchP(from, t, free, sub)) {
3840
+ hit = true;
3841
+ return substXs(to, sub);
3842
+ }
3843
+ return Object.fromEntries(Object.entries(t).map(([key, v]) => [key, go(v)]));
3844
+ };
3845
+ return { x: go(x), hit };
3846
+ };
3847
+ // (the subterms of a term with a call in them, outermost first)
3848
+ const subterms = (x) => { const acc = []; const go = (t) => { if (!t || typeof t !== 'object')
3849
+ return; if (Array.isArray(t)) {
3850
+ t.forEach(go);
3851
+ return;
3852
+ } const o = t; if ((o.op === 'call' || o.op === 'ctor' || o.op === 'add') && JSON.stringify(o).includes('"op":"call"') || o.op === 'match' || o.op === 'natmatch' || o.op === 'if') {
3853
+ acc.push(o);
3854
+ if (o.op === 'match' || o.op === 'natmatch' || o.op === 'if')
3855
+ return;
3856
+ } ; for (const v of Object.values(o))
3857
+ go(v); }; go(x); return acc; };
3858
+ const lawOf = (a, b) => {
3859
+ // (one constructor on both sides: the fields that differ, where one does)
3860
+ for (;;) {
3861
+ if (a.op !== 'ctor' || b.op !== 'ctor' || a.ctor !== b.ctor || a.data !== b.data)
3862
+ break;
3863
+ const differ = a.args.flatMap((x, i) => (sameX(x, b.args[i]) ? [] : [i]));
3864
+ if (differ.length !== 1)
3865
+ break;
3866
+ [a, b] = [a.args[differ[0]], b.args[differ[0]]];
3867
+ }
3868
+ if (sameX(a, b) || !(JSON.stringify([a, b]).includes('"op":"call"')))
3869
+ return undefined;
3870
+ const y = { op: '=', a, b }, vs = [];
3871
+ walk(y, o => { if (o.op === 'var' && !vs.some(v => v.name === o.name)) {
3872
+ const s = sorts.get(o.name);
3873
+ if (s)
3874
+ vs.push({ name: o.name, sort: s });
3875
+ } });
3876
+ if (!vs.length || textLength(y) > 3000)
3877
+ return undefined;
3878
+ return { name: `${showX(a)} = ${showX(b)}`, vars: vs, holds: y, params: [...new Set(paramsIn(y))] };
3879
+ };
3880
+ // The step's goal generalised: each subterm common to both sides (those inside no other common one) a fresh variable.
3881
+ const generalise = (a, b) => {
3882
+ let ga = a, gb = b;
3883
+ for (const t of subterms(a)) {
3884
+ if (!has(ga, t) || !has(gb, t))
3885
+ continue;
3886
+ const s = sortOf(t);
3887
+ if (!s || s === 'bool')
3888
+ continue;
3889
+ const v = freshVar(s);
3890
+ ga = rewrite(ga, t, v);
3891
+ gb = rewrite(gb, t, v);
3892
+ }
3893
+ return [ga, gb];
3894
+ };
3895
+ const bases = [];
3896
+ for (const v of l.vars) {
3897
+ const d = v.sort;
3898
+ const cases = [];
3899
+ // (the base cases too, after every step: rev (y ++ [z]) = z :: rev y, the nil case of rev (x ++ (y ++ [z])))
3900
+ if (d === 'nat') {
3901
+ const m = freshVar('nat');
3902
+ cases.push({ at: { op: 'add', a: m, b: { op: 'nat', value: 1 } }, rec: [m] });
3903
+ bases.push({ v, at: { op: 'nat', value: 0 } });
3904
+ }
3905
+ else if (d instanceof Data && !d.abstract)
3906
+ for (const [j, c] of d.ctors.entries()) {
3907
+ const fields = c.fields.map(f => freshVar(fieldSort(f)));
3908
+ if (!c.fields.some(f => isDataField(f.sort) && f.sort.data === d.name)) {
3909
+ bases.push({ v, at: { op: 'ctor', data: d.name, ctor: j, args: fields } });
3910
+ continue;
3911
+ }
3912
+ cases.push({ at: { op: 'ctor', data: d.name, ctor: j, args: fields }, rec: fields.filter((_, i) => { const f = c.fields[i]; return isDataField(f.sort) && f.sort.data === d.name; }) });
3913
+ }
3914
+ for (const cs of cases) {
3915
+ const at = (x, to) => reduceX(substXs(x, new Map([[v.name, to]])));
3916
+ const a = at(eq.a, cs.at), b = at(eq.b, cs.at);
3917
+ if (sameX(a, b))
3918
+ continue;
3919
+ const ihs = cs.rec.map(r => [at(eq.a, r), at(eq.b, r)]), free = new Set(l.vars.filter(w => w.name !== v.name).map(w => w.name));
3920
+ // (`common`: a rewrite of a variable, kept only where its sides then share a term to generalise)
3921
+ const tries = [];
3922
+ for (const [ia, ib] of ihs)
3923
+ for (const [from, to] of [[ia, ib], [ib, ia]]) {
3924
+ if (from.op === 'var') {
3925
+ // (the hypothesis's side that is a variable, rewritten in a side that doesn't read its other side: x :: t to
3926
+ // x :: rev (rev t), where rev (rev t ++ [x]) = x :: rev (rev t) shares rev t)
3927
+ for (const s1 of [a, b])
3928
+ if (has(s1, from) && !has(s1, to))
3929
+ tries.push(s1 === a ? { x: reduceX(rewrite(a, from, to)), y: b, common: true } : { x: a, y: reduceX(rewrite(b, from, to)), common: true });
3930
+ continue;
3931
+ }
3932
+ if (has(a, from) || has(b, from))
3933
+ tries.push({ x: reduceX(rewrite(a, from, to)), y: reduceX(rewrite(b, from, to)) });
3934
+ // (else the hypothesis at other values of the law's other variables, where they differ: an accumulator's)
3935
+ else if (free.size) {
3936
+ const ra = rewriteP(a, from, to, free), rb = rewriteP(b, from, to, free);
3937
+ if (ra.hit || rb.hit)
3938
+ tries.push({ x: reduceX(ra.x), y: reduceX(rb.x) });
3939
+ }
3940
+ }
3941
+ // (and the step as unfolded, where no rewrite gave one and none closed it)
3942
+ if (tries.some(t => !t.common && sameX(t.x, t.y)))
3943
+ continue;
3944
+ tries.push({ x: a, y: b });
3945
+ const before = out.length;
3946
+ for (const [i, { x, y, common }] of tries.entries()) {
3947
+ if (sameX(x, y) || (i === tries.length - 1 && out.length > before))
3948
+ continue;
3949
+ const [ga, gb] = generalise(x, y), generalised = !sameX(ga, x) || !sameX(gb, y);
3950
+ if (common && !generalised)
3951
+ continue;
3952
+ // (the step as it stands where nothing is common to its sides; only a generalised one's own step is calculated)
3953
+ const c = lawOf(ga, gb);
3954
+ if (c && !out.some(o => canonText(o.holds, o.vars) === canonText(c.holds, c.vars))) {
3955
+ if (generalised)
3956
+ general.add(c);
3957
+ out.push(c);
3958
+ }
3959
+ }
3960
+ }
3961
+ }
3962
+ for (const { v, at } of bases) {
3963
+ const a = reduceX(substXs(eq.a, new Map([[v.name, at]]))), b = reduceX(substXs(eq.b, new Map([[v.name, at]])));
3964
+ if (sameX(a, b))
3965
+ continue;
3966
+ const [ga, gb] = generalise(a, b), c = lawOf(ga, gb);
3967
+ if (c && !out.some(o => canonText(o.holds, o.vars) === canonText(c.holds, c.vars))) {
3968
+ based.add(c);
3969
+ out.push(c);
3970
+ }
3971
+ }
3972
+ return out;
3973
+ }
3278
3974
  export const showX = (x) => {
3279
3975
  switch (x.op) {
3280
3976
  case 'var': return x.name.replace(/#\d+$/, '');
@@ -3390,7 +4086,7 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
3390
4086
  if (c)
3391
4087
  return c;
3392
4088
  }
3393
- const first = phase === 'rest' || (opts.lemmasFirst && Array.isArray(opts.lemmas)) ? undefined : proveWith(p, fs, l, base, lv + 1, opts, until, 6000, [1], 'plain');
4089
+ const first = phase === 'rest' || (opts.lemmasFirst && Array.isArray(opts.lemmas)) ? undefined : proveWith(p, fs, l, base, lv + 1, opts, until, 6000, [1], 'plain', !ctx || ctx.merge === true);
3394
4090
  const one = first && ok(first, base);
3395
4091
  if (one)
3396
4092
  return one;
@@ -3407,24 +4103,37 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
3407
4103
  if (two)
3408
4104
  return two;
3409
4105
  }
3410
- const cands = Array.isArray(opts.lemmas) ? opts.lemmas : conjectures(p, l);
4106
+ // The steps the law's inductions leave (lemma calculation), then the conjectures from the values.
4107
+ const tc = performance.now(), calc = Array.isArray(opts.lemmas) ? [] : calculated(p, l, 2, 6);
4108
+ if (dataTrace)
4109
+ console.error(`[data] ${l.name}: ${calc.length} calculated in ${Math.round(performance.now() - tc)} ms`);
4110
+ const cands = Array.isArray(opts.lemmas) ? opts.lemmas : [...calc, ...conjectures(p, l)];
4111
+ if (dataTrace)
4112
+ for (const c of calc)
4113
+ console.error(`[data] calculated ${c.name.slice(0, 200)}`);
3411
4114
  const p2 = ctx ? p : programOf([l, ...cands]), fs2 = ctx ? fs : factsOf(p2);
3412
4115
  // Each scheme's goals: the law's, and each companion's (a lemma may be what only a companion's goal reads).
3413
4116
  const goalOf = (law, uses, on, concls, shapes) => {
3414
4117
  const concl = encY(p2, law.holds, new Map()), ihc = uses.map(u => substC(concls[u.member ?? 0] ?? concl, { vars: u.subst, maps: {}, flags: {} }));
3415
4118
  return { from: [concl, ihc], insts: instancesOf(p2, fs2, { roots: [concl], others: ihc, depth: 2, shapesAt: shapes ?? (on && on.d !== 'nat' ? [ev(on.v)] : []), etaAt: [], models: [] }) };
3416
4119
  };
3417
- const goals = schemes(p2, l).flatMap(s => {
4120
+ const goals = schemes(p2, l).filter(s => !s.merged).flatMap(s => {
3418
4121
  const all = [{ law: l, uses: s.uses, on: s.on, shapes: s.shapes }, ...(s.companions ?? [])], concls = all.map(m => encY(p2, m.law.holds, new Map()));
3419
4122
  return all.map((m, i) => goalOf(m.law, m.uses.map(u => ({ ...u, member: u.member ?? i })), m.on, concls, 'shapes' in m ? m.shapes : undefined));
3420
4123
  });
3421
- const matchesGoal = (c) => goals.some(g => lemmaUsesFor(p2, fs2, [{ law: c, node: 0, concl: encY(p2, c.holds, new Map()) }], g.from, g.insts).length > 0);
4124
+ // (every conjecture against each goal at once: a lemma's uses are found apart from the others')
4125
+ const goalHits = new Set(), others = cands.slice(calc.length);
4126
+ for (const g of goals)
4127
+ lemmaUsesFor(p2, fs2, others.map((c, i) => ({ law: c, node: i, concl: encY(p2, c.holds, new Map()) })), g.from, g.insts, [], undefined, goalHits);
4128
+ const matchesGoal = (c) => goalHits.has(others.indexOf(c));
3422
4129
  // Those the goal matches first, of those the ones of the law's shape (an implication for an implication) first.
3423
4130
  const implication = (y) => y.op === 'or' && y.xs.length === 2 && y.xs[0].op === 'not';
3424
4131
  const score = (c, hit) => (hit ? 2 : 0) + (implication(c.holds) === implication(l.holds) ? 1 : 0);
3425
4132
  if (dataTrace)
3426
4133
  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('')}`);
3427
- const ranked = cands.map(c => ({ c, hit: matchesGoal(c) })).sort((a, b) => score(b.c, b.hit) - score(a.c, a.hit));
4134
+ // (the calculated steps first, in their order: each before the one it was calculated from)
4135
+ const calcSet = new Set(calc);
4136
+ 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))];
3428
4137
  // The lemmas proven: those given (`base`) and those found, each found one a level above the last.
3429
4138
  const proven = [...base], failed = new Set(), level = () => lv + 1 + proven.length - base.length;
3430
4139
  // A pass of lemmas: of those the goal reads (`hits`) or the others, each proven at one unfolding (8 s of counted work
@@ -3434,19 +4143,35 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
3434
4143
  // rewriting), then by its schemes: after each lemma the goal reads or of the law's shape, else at the end of the pass.
3435
4144
  const refuted = new Set();
3436
4145
  const lemmaPass = (which, most, end, cap, depths) => {
3437
- let n = 0, since = 0, tries = 0;
4146
+ // (`extra`: the calculated steps' attempts and the second ones, at most `most`, beside the conjectures' 3·most)
4147
+ let n = 0, since = 0, tries = 0, extra = 0;
3438
4148
  const again = (how) => ok(proveWith(p2, fs2, l, proven, level(), opts, until, cap, depths, how), proven, p2);
3439
- for (const { c, hit } of ranked) {
4149
+ // A conjecture of this pass that failed is tried once more after a lemma is proven (HipSpec's loop: bind over an
4150
+ // append needs ++ associative, proven after it); first those, then the next of the ranking.
4151
+ const queue = ranked.filter(r => (which === 'hits') === r.hit), retry = [], retried = new Set();
4152
+ for (let i = 0; i < queue.length || retry.length;) {
3440
4153
  if (n >= most || tries >= 3 * most || clock() > end)
3441
4154
  break;
3442
- if ((which === 'hits') !== hit || proven.some(q => q.law === c) || refuted.has(c))
4155
+ if (extra >= most) {
4156
+ retry.length = 0;
4157
+ if (i >= queue.length)
4158
+ break;
4159
+ }
4160
+ const again2 = retry.length > 0, c = again2 ? retry.shift() : queue[i++].c;
4161
+ if (proven.some(q => q.law === c) || refuted.has(c))
4162
+ continue;
4163
+ if (!again2 && calcSet.has(c) && extra >= most)
3443
4164
  continue;
3444
- if (refute(c, 200)) {
4165
+ if (!again2 && refute(c, 200)) {
3445
4166
  refuted.add(c);
3446
4167
  continue;
3447
4168
  }
3448
- tries++;
3449
- const r = proveWith(p2, fs2, c, proven, level(), opts, Math.min(end, clock() + 8000 * (opts.patience ?? 1)), 5000, [1]);
4169
+ if (again2 || calcSet.has(c))
4170
+ extra++;
4171
+ else
4172
+ tries++;
4173
+ // (a calculated step half a conjecture's time: there are few, and one past its time is seldom the one)
4174
+ const r = proveWith(p2, fs2, c, proven, level(), opts, Math.min(end, clock() + (calcSet.has(c) ? 3000 : 8000) * (opts.patience ?? 1)), 5000, [1]);
3450
4175
  tried += r.tried;
3451
4176
  if (!r.out) {
3452
4177
  failed.add(c);
@@ -3456,7 +4181,15 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
3456
4181
  proven.push(r.out);
3457
4182
  n++;
3458
4183
  since++;
3459
- // (as before the passes: again after a lemma the goal reads, or one of the law's shape, an implication for one)
4184
+ for (const q of queue.slice(0, i))
4185
+ if (failed.has(q.c) && !retried.has(q.c)) {
4186
+ retried.add(q.c);
4187
+ retry.push(q.c);
4188
+ }
4189
+ // (as before the passes: again after a lemma the goal reads, or one of the law's shape, an implication for one; a
4190
+ // calculated step's after the last of them, whose proofs read each other)
4191
+ if (calcSet.has(c) && !retry.length && i < queue.length && calcSet.has(queue[i].c))
4192
+ continue;
3460
4193
  if (which === 'hits' || implication(c.holds) === implication(l.holds)) {
3461
4194
  since = 0;
3462
4195
  const r2 = again('first');