gdp-wired 0.26.0 → 0.28.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 (44) hide show
  1. package/dist/core/accel.d.ts +24 -0
  2. package/dist/core/accel.js +557 -207
  3. package/dist/core/bmc.d.ts +4 -1
  4. package/dist/core/bmc.js +18 -15
  5. package/dist/core/cycles.d.ts +2 -0
  6. package/dist/core/cycles.js +1 -1
  7. package/dist/core/cyclic.js +17 -10
  8. package/dist/core/data.d.ts +1 -0
  9. package/dist/core/data.js +73 -18
  10. package/dist/core/discover.js +64 -25
  11. package/dist/core/dsl.js +108 -18
  12. package/dist/core/extract-check.d.ts +52 -2
  13. package/dist/core/extract-check.js +155 -104
  14. package/dist/core/extract-read.d.ts +25 -0
  15. package/dist/core/extract-read.js +55 -14
  16. package/dist/core/extract-shapes.js +94 -18
  17. package/dist/core/extract-xstate.js +16 -3
  18. package/dist/core/extract.d.ts +1 -0
  19. package/dist/core/extract.js +16 -8
  20. package/dist/core/fresh.d.ts +9 -0
  21. package/dist/core/fresh.js +91 -0
  22. package/dist/core/infer.d.ts +1 -0
  23. package/dist/core/infer.js +64 -46
  24. package/dist/core/live.d.ts +15 -0
  25. package/dist/core/live.js +317 -0
  26. package/dist/core/machine.js +0 -1
  27. package/dist/core/nonterm.d.ts +3 -1
  28. package/dist/core/nonterm.js +103 -25
  29. package/dist/core/solver.d.ts +21 -0
  30. package/dist/core/solver.js +8 -0
  31. package/dist/core/translate.js +69 -19
  32. package/dist/kernel/cdcl.js +212 -78
  33. package/dist/kernel/kernel.d.ts +17 -1
  34. package/dist/kernel/kernel.js +158 -2
  35. package/dist/kernel/prove.d.ts +30 -4
  36. package/dist/kernel/prove.js +119 -25
  37. package/dist/kernel/reader.d.ts +74 -5
  38. package/dist/kernel/reader.js +531 -75
  39. package/dist/kernel/simplex.d.ts +26 -1
  40. package/dist/kernel/simplex.js +148 -14
  41. package/dist/lean-kernel/emit.d.ts +15 -3
  42. package/dist/lean-kernel/emit.js +144 -12
  43. package/dist/lean-kernel/library.js +1 -1
  44. package/package.json +2 -2
@@ -12,9 +12,11 @@ export type BmcOptions = {
12
12
  from?: number;
13
13
  depth?: number;
14
14
  progress?: (depth: number, outcome: 'refuted' | 'sat' | 'unknown', ms: number) => void;
15
+ steps?: boolean;
16
+ full?: boolean;
15
17
  };
16
18
  export declare function bmcFits(m: Machine, laws: Law[]): boolean;
17
- export declare const bmcRate = 250;
19
+ export declare const bmcRate = 250, workRate = 250;
18
20
  export declare function bmcGoal(m: Machine, laws: Law[], k: number): {
19
21
  name: string;
20
22
  hyps: C[];
@@ -54,4 +56,5 @@ export type BoundedSearch = {
54
56
  };
55
57
  export declare function boundedSearch(m: Machine, laws: Law[], opts: Omit<BmcOptions, 'ms' | 'wall'> & {
56
58
  forcedMs: number;
59
+ forcedSteps?: number;
57
60
  }): BoundedSearch | undefined;
package/dist/core/bmc.js CHANGED
@@ -19,11 +19,11 @@
19
19
  // that run breaks no law (a read of a pair the relaxation doesn't keep), the goal itself is asked at that depth. A
20
20
  // relaxed goal refuted is the goal refuted.
21
21
  //
22
- // The budget is read off prove.ts's clock inside `counted` (the kernel's work, bmcRate units a millisecond), so the
22
+ // The budget is read off prove.ts's clock inside `counted` (the cost model's work, bmcRate units a millisecond), so the
23
23
  // search is the same on any machine; a wall-clock stop beside it (`wall`) is for callers under a wall-clock limit.
24
24
  import { evalC, evalE, interpret, isArithmetic, loadJs, numbersOf } from "./machine.js";
25
25
  import { stepLawObligations, substC, substE } from "../kernel/kernel.js";
26
- import { clock, counted } from "../kernel/prove.js";
26
+ import { clock, counted, fullRate } from "../kernel/prove.js";
27
27
  import { REFUTED, cdclSession, growCdcl } from "../kernel/cdcl.js";
28
28
  import { allowed } from "./watch.js";
29
29
  import { isF as isFalse, isT as isTrue, simpC, simpE } from "./nonterm.js";
@@ -41,14 +41,15 @@ export function bmcFits(m, laws) {
41
41
  return false;
42
42
  return laws.every(l => !l.forall && !l.some?.length);
43
43
  }
44
- // The counted clock's rate here, units of the kernel's work a millisecond: the median of what Modal's 2-vCPU containers
45
- // did on the k-step goals of CHC-COMP's unsat LIA-Lin tasks, the stage alone (runs/bmc2/only-mine3: 1,215 depths past
46
- // 200 ms, 252 units a ms at the median, 383 at the 90th percentile; 168 at the median before reader.ts kept its clean
47
- // values and the goals were reduced, runs/bmc2/only-base1). The CDCL search counts its rows, which a goal of many atoms
48
- // and few rows a node keeps low, so a caller under a wall-clock limit gives a wall stop too.
49
- export const bmcRate = 250;
44
+ // The counted clock's rate here: the cost model's (kernel/prove.ts's fullWork, about a Modal 2-vCPU container's
45
+ // milliseconds at the median query), which counts what the incremental search does at a node; work.n's rows a node,
46
+ // read whole no more, ran the counted clock about four times past wall time on the unsat tasks' k-step goals. The
47
+ // resumable search (compare/chc/kind.ts's second CPU) reads it, so a slice takes about the wall time it is given;
48
+ // findBoundedRun keeps work.n's (`full` to read the model's), as its callers' budgets were set against it (core/
49
+ // nonterm.ts's bounded runs from a closed set: on that clock s1.t2's recurrent set past the ITS track's 60 s).
50
+ export const bmcRate = fullRate, workRate = 250;
50
51
  // A forced run's share of the budget, and its steps at most (a derivation checkDerivation replays step by step).
51
- const forcedShare = 0.3, forcedSteps = 1_000_000;
52
+ const forcedShare = 0.3, forcedSteps = 1_000_000, forcedRate = 1_000;
52
53
  // GDP_BMC_RELAX=0: no relaxed goal first; GDP_BMC_INC=0: each depth's goal a search of its own (for comparing).
53
54
  const useRelax = env.GDP_BMC_RELAX !== '0', useInc = env.GDP_BMC_INC !== '0', useTidy = env.GDP_BMC_TIDY !== '0';
54
55
  // The goal of depth k: a run of k steps from the start whose last state breaks a law.
@@ -564,16 +565,17 @@ function unrolled(m, laws) {
564
565
  return { next, again, defs };
565
566
  }
566
567
  export function findBoundedRun(m, laws, opts) {
567
- // A forced run first, within forcedShare of the budget (as wall time: it is the compiled rule's, not the kernel's).
568
- const now = performance.now(), end = Math.min(opts.wall ?? Infinity, now + opts.ms);
569
- const out = boundedSearch(m, laws, { ...opts, forcedMs: forcedShare * (end - now) })?.run(opts.ms, opts.wall);
568
+ // A forced run first, within forcedShare of the budget (as wall time: it is the compiled rule's, not the kernel's;
569
+ // with `steps` and no wall stop, in its steps instead).
570
+ const now = performance.now(), end = Math.min(opts.wall ?? Infinity, now + opts.ms), steps = opts.steps && opts.wall === undefined;
571
+ const out = boundedSearch(m, laws, { ...opts, full: opts.full ?? false, forcedMs: steps ? Infinity : forcedShare * (end - now), ...(steps ? { forcedSteps: Math.min(forcedSteps, Math.round(forcedShare * forcedRate * opts.ms)) } : {}) })?.run(opts.ms, opts.wall);
570
572
  return typeof out === 'object' ? out : undefined;
571
573
  }
572
574
  export function boundedSearch(m, laws, opts) {
573
575
  if (!laws.length || !bmcFits(m, laws))
574
576
  return undefined;
575
577
  const last = Math.min(64, opts.depth ?? 64);
576
- const forced = forcedRunner(m, laws, { steps: forcedSteps });
578
+ const forced = forcedRunner(m, laws, { steps: opts.forcedSteps ?? forcedSteps });
577
579
  let forcedLeft = forced === undefined ? 0 : opts.forcedMs, over = false, again = false;
578
580
  let inc, made = false, k = opts.from ?? 1;
579
581
  const run = (ms, wall) => {
@@ -591,7 +593,8 @@ export function boundedSearch(m, laws, opts) {
591
593
  else if (wall !== undefined && performance.now() >= wall)
592
594
  return 'paused';
593
595
  }
594
- return counted(bmcRate, () => {
596
+ const full = opts.full ?? true;
597
+ return counted(full ? bmcRate : workRate, () => {
595
598
  const until = clock() + ms;
596
599
  const late = () => clock() >= until || (wall !== undefined && performance.now() >= wall);
597
600
  if (!made) {
@@ -669,7 +672,7 @@ export function boundedSearch(m, laws, opts) {
669
672
  return done(typeof got === 'string' ? 'over' : got);
670
673
  }
671
674
  return done('over');
672
- });
675
+ }, full);
673
676
  };
674
677
  return { run, depth: () => k };
675
678
  }
@@ -4,6 +4,7 @@ import type { Liveness, Loop, Tree } from '../kernel/kernel.js';
4
4
  import { type Cyclic, type Fact } from '../kernel/cyclic.js';
5
5
  import { type NodeSpec } from './cyclic.js';
6
6
  import { type Lin } from './solver.js';
7
+ import { inferLaws } from './infer.js';
7
8
  import { type Relation } from './relation.js';
8
9
  import type { StepLaw } from '../kernel/kernel.js';
9
10
  export type Claim = {
@@ -109,6 +110,7 @@ export declare function findRank(l: Loop, laws?: Law[], opts?: {
109
110
  export type Sampler = {
110
111
  params: (rand: (n: number) => number, bound: number) => Record<string, number>;
111
112
  input: (rand: (n: number) => number, bound: number, ps: Record<string, number>) => Request;
113
+ rule?: Parameters<typeof inferLaws>[0];
112
114
  };
113
115
  export type LeadsVerdict = {
114
116
  proven: boolean;
@@ -1876,7 +1876,7 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
1876
1876
  return { proven: true, checked: true, rank, laws: [], found: { rank: text, laws: [] } };
1877
1877
  const ms = until - clock();
1878
1878
  if (ms > 300) {
1879
- const { stay, cover, helps } = livenessParts(m, lv), inf = inferLaws(m, laws, [stay, cover, ...helps], { ms });
1879
+ const { stay, cover, helps } = livenessParts(m, lv), inf = inferLaws(sample.rule ?? m, laws, [stay, cover, ...helps], { ms });
1880
1880
  const kept = inf.found.filter(f => !f.law.forall && !f.law.keys?.length), more = kept.map(f => f.law);
1881
1881
  if (inf.proven && more.length) {
1882
1882
  const again = withDeadline(until + 5000, () => proveLiveness(m, [...laws, ...more], lv));
@@ -56,7 +56,7 @@
56
56
  import { atMost as le, get, n as k, plus as add, same as eq, walk, x as v } from "./machine.js";
57
57
  import { assumed, boundOf, foldObligations, livenessParts, loopLiveness, loopMachine, loopObligations, obligations, stepLawObligations, substC, substE, witnessesOf } from "../kernel/kernel.js";
58
58
  import { baseHyps, descentGoal, instHyps, mainGoal, premiseGoal, refuseCyclic } from "../kernel/cyclic.js";
59
- import { cellProducts, clock, grow, profile, usedHyps, widen, withDeadline, withinDeadline } from "../kernel/prove.js";
59
+ import { cellProducts, clock, counted, fullRate, grow, profile, usedHyps, widen, withDeadline, withinDeadline } from "../kernel/prove.js";
60
60
  import { carry, decide, readsFirst, renamer, translate, tstats } from "./translate.js";
61
61
  import { env } from "./solver.js";
62
62
  const less1 = (a) => ({ op: 'sub', a, b: k(1) });
@@ -952,15 +952,22 @@ export function machineNodes(given, laws, instances, usual, st = tstats()) {
952
952
  }
953
953
  }
954
954
  function translateMade(facts, all, made, st, until) {
955
- for (const x of made) {
956
- const whole = mainGoal(facts, all, all[x.node]);
957
- const tree = timedKind('translate', 0, () => withProducts(() => decide(whole, x.decide ?? [], wp => readsFirst(whole, x.reads ?? [], x.ren, (p, swaps) => translate(x.g, whole, x.tree, x.ren, st, until, new Map(), p, swaps), st, until, wp), st, until)));
958
- if (!tree)
959
- return { specs: [], why: `${all[x.node].name}: not translated` };
960
- all[x.node] = { ...all[x.node], main: tree };
961
- }
962
- return { specs: sliced(all) };
955
+ return counting(until, end => {
956
+ for (const x of made) {
957
+ const whole = mainGoal(facts, all, all[x.node]);
958
+ const tree = timedKind('translate', 0, () => withProducts(() => decide(whole, x.decide ?? [], wp => readsFirst(whole, x.reads ?? [], x.ren, (p, swaps) => translate(x.g, whole, x.tree, x.ren, st, end, new Map(), p, swaps), st, end, wp), st, end)));
959
+ if (!tree)
960
+ return { specs: [], why: `${all[x.node].name}: not translated` };
961
+ all[x.node] = { ...all[x.node], main: tree };
962
+ }
963
+ return { specs: sliced(all) };
964
+ });
963
965
  }
966
+ // A translation on the cost model's clock (kernel/prove.ts's `counted` with `full`): its budget the time from now to
967
+ // `until`, counted, translate.ts counting each leaf's rows as it reads them, so a large tree's translation stops at its
968
+ // budget on any machine. (On wall time alone it ran past it: the bound was read only where a leaf was grown again, and
969
+ // ledger/tigerbeetle/transfers' 21,108 leaves took 92.7 s, the law then past the real-world corpus's 150 s.)
970
+ const counting = (until, f) => { const ms = Math.max(0, until - clock()); return counted(fullRate, () => f(clock() + ms), true); };
964
971
  // The terms (not a read, a variable or a constant) of a conclusion that a node's facts read too, largest first; none
965
972
  // inside a product (a product of a term's linear form is no linear form).
966
973
  function shared(facts, a, concl) {
@@ -1183,7 +1190,7 @@ export function allowTranslated(given, laws, inst, p, usual, facts, lawNodes, na
1183
1190
  insts: closeHyps.length ? cl : [], uses: [{ node: lawNodes.length, subst: {}, guard: yes }], carry: true };
1184
1191
  const all = [...lawNodes, terms, allowed], whole = mainGoal(facts, all, terms), until = withinDeadline(clock() + 10_000);
1185
1192
  const ren = renamer({ s: now, cells: Object.fromEntries(mapNames.map(map => [map, { to: `${map}@`, at: t }])) });
1186
- const tree = timedKind('translate', 0, () => withProducts(() => decide(whole, closeFacts.length ? [le(t, T)] : [], wp => translate(g, whole, usual.tree, ren, st, until, new Map(), wp), st, until)));
1193
+ const tree = counting(until, end => timedKind('translate', 0, () => withProducts(() => decide(whole, closeFacts.length ? [le(t, T)] : [], wp => translate(g, whole, usual.tree, ren, st, end, new Map(), wp), st, end))));
1187
1194
  if (!tree)
1188
1195
  return { specs: [], why: `${terms.name}: not translated` };
1189
1196
  return { specs: sliced([{ ...terms, main: tree }, allowed]) };
@@ -435,6 +435,7 @@ export declare const lemmaCaps: {
435
435
  perCase: number;
436
436
  spare: number;
437
437
  joined: number;
438
+ self: number;
438
439
  };
439
440
  export declare function conjectures(p: Program, l: DataLaw, max?: number, maxSize?: number): DataLaw[];
440
441
  export declare function calculated(p: Program, l: DataLaw, depth?: number, max?: number): DataLaw[];
package/dist/core/data.js CHANGED
@@ -1702,8 +1702,13 @@ function unfoldAt(f) {
1702
1702
  }
1703
1703
  // The inductions the search tries for a law (its schemes), for tests.
1704
1704
  export const schemesOf = (p, l) => schemes(p, l);
1705
+ const readsName = (x, name) => { let yes = false; walk(x, o => { if (o.op === 'var' && o.name === name)
1706
+ yes = true; }); return yes; };
1705
1707
  function schemes(p, l) {
1706
- const out = [], seen = new Set(), halves = [];
1708
+ const out = [], seen = new Set(), halves = [], peano = [];
1709
+ const inDecreasing = (name) => { let yes = false; walk(l.holds, o => { if (o.op !== 'call')
1710
+ return; const f = fnOf(o.fn), a = f.decreases === undefined ? undefined : o.args[f.decreases]; if (a && a.op !== 'var' && readsName(a, name))
1711
+ yes = true; }); return yes; };
1707
1712
  const add = (s) => { const id = JSON.stringify(s.uses); if (!seen.has(id)) {
1708
1713
  seen.add(id);
1709
1714
  out.push(s);
@@ -1813,6 +1818,13 @@ function schemes(p, l) {
1813
1818
  // Structural induction on each variable of a datatype, the others fixed; mutual where its fields reach another of its
1814
1819
  // group (the law and its companions), plain where they reach none or no companion is found.
1815
1820
  for (const v of l.vars) {
1821
+ // (a natural's: v − 1 where v isn't 0, Peano's, where no call of the law recurs on it and a call's decreasing argument
1822
+ // is a term that reads it: even(x + x); placed last)
1823
+ if (v.sort === 'nat') {
1824
+ if (!out.some(sc => sc.on?.v === v.name) && !halves.some(sc => sc.on?.v === v.name) && inDecreasing(v.name))
1825
+ peano.push({ name: `structure of ${v.name}`, on: { v: v.name, d: 'nat' }, uses: [{ subst: { [v.name]: { op: 'sub', a: ev(v.name), b: k(1) } }, guard: { op: 'not', x: eqC(ev(v.name), k(0)) } }] });
1826
+ continue;
1827
+ }
1816
1828
  if (!(v.sort instanceof Data))
1817
1829
  continue;
1818
1830
  const d = v.sort, x = ev(v.name), mut = mutualScheme(l, v.name, d);
@@ -1851,6 +1863,9 @@ function schemes(p, l) {
1851
1863
  if (out.length > before)
1852
1864
  merged++;
1853
1865
  }
1866
+ // (Peano's after the others, and merged with none)
1867
+ for (const sc of peano)
1868
+ add(sc);
1854
1869
  return out;
1855
1870
  }
1856
1871
  function instancesOf(p, fs, w) {
@@ -2678,7 +2693,17 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2678
2693
  const useConcl = (u) => substC(u.node < 0 ? concls[-1 - u.node] : specs[u.node].concl, { vars: u.subst, maps: {}, flags: {} });
2679
2694
  const plans = [];
2680
2695
  for (const [mi, mb] of members.entries()) {
2681
- const models = mb.pool.slice(0, 24), concl = concls[mi], name = mi === 0 ? title : `${title}, at ${mb.on.d.name}`;
2696
+ // (an implication's instances from the models where its premise holds first, the node's and each case's, as only they
2697
+ // say anything of its conclusion: x ⊆ y makes y's intersection with x's tail that tail; its cases from them all)
2698
+ const prem = mb.law.holds.op === 'or' && mb.law.holds.xs.length === 2 && mb.law.holds.xs[0].op === 'not' ? encY(p, mb.law.holds.xs[0].x, new Map()) : undefined;
2699
+ const held = ({ m, env }) => { try {
2700
+ return m.evalC(prem, env);
2701
+ }
2702
+ catch {
2703
+ return false;
2704
+ } };
2705
+ const first = (ms) => (prem ? [...ms.filter(held), ...ms.filter(x => !held(x))] : ms);
2706
+ const models = first(mb.pool).slice(0, 24), concl = concls[mi], name = mi === 0 ? title : `${title}, at ${mb.on.d.name}`;
2682
2707
  const ih = mb.uses.map(u => ({ node: -1 - (u.member ?? mi), subst: u.subst, guard: u.guard }));
2683
2708
  const shapesAt = mb.rank ? rankShapes(mb.shapes ?? [], mb.rank, mb.uses) : mb.on && mb.on.d !== 'nat' ? [ev(mb.on.v)] : [];
2684
2709
  const ihConcls = ih.map(useConcl);
@@ -2686,13 +2711,45 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2686
2711
  // equalities the unfolded definitions give (any branch); twice over, the uses' own conclusions read the second time.
2687
2712
  const pre = instancesOf(p, fs, { roots: [concl], others: ihConcls, depth, shapesAt, etaAt: [], models: [], until: t0 + attemptMs.ms });
2688
2713
  const spare = [], lemmaUses = lemmaUsesFor(p, fs, lemmaNodes, [concl, ihConcls], pre, models, spare);
2689
- const uses = [...ih, ...lemmaUses];
2714
+ // The hypothesis at other values of the variables the step leaves (generalised: qrev's accumulator, drop's list at
2715
+ // a zip's other list): each use of the scheme a lemma whose descended variables are fixed and the others matched to
2716
+ // the goal's reads, its descent the scheme's own (the rank reads only the variable descended on).
2717
+ const free = (u, m) => (mb.rank || !members[m].on || !(members[m].on.v in u.subst) ? [] : members[m].law.vars.filter(v => !(v.name in u.subst)));
2718
+ const selfAt = mb.uses.flatMap(u => { const m = u.member ?? mi, vs = free(u, m); return vs.length ? [{ law: { ...members[m].law, vars: vs }, node: -1 - m, concl: concls[m], pat: substC(concls[m], { vars: u.subst, maps: {}, flags: {} }), fixed: u.subst, guard: u.guard }] : []; });
2719
+ // (each other variable at a value made of the goal's values by a datatype's constructors and fields and arithmetic,
2720
+ // one of them a datatype's: tail ys beside n − 1, head x :: acc; not a function's value or another variable, which
2721
+ // the classes of every branch may join to it; of arithmetic alone, one)
2722
+ const shape = (t) => { if (t.op === 'var' || t.op === 'const')
2723
+ return 'no'; let ok = true, built = false, reads = false; walk(t, o => { if (o.op === 'var')
2724
+ reads = true; if (o.op === 'get') {
2725
+ if (p.fns.some(f => f.name === o.map))
2726
+ ok = false;
2727
+ else if (p.datas.some(d => o.map.startsWith(`${d.name}.`)))
2728
+ built = true;
2729
+ } }); return !ok || !reads ? 'no' : built ? 'data' : 'nat'; };
2730
+ const shaped = (u, fixed) => { const ks = Object.entries(u.subst).filter(([x]) => !(x in fixed)).map(([, t]) => shape(t)); return ks.includes('no') ? 'no' : ks.includes('data') ? 'data' : 'nat'; };
2731
+ const own = new Set(ih.map(u => sid([u.node, u.subst]))), found = selfAt.length ? lemmaUsesFor(p, fs, selfAt, [concl, ihConcls], pre, models).filter(u => !own.has(sid([u.node, u.subst]))).map(u => ({ u, k: shaped(u, selfAt.find(a => a.node === u.node && Object.keys(a.fixed).every(y => sid(a.fixed[y]) === sid(u.subst[y])))?.fixed ?? {}) })) : [];
2732
+ // (those with a datatype's value first; one of arithmetic alone: take n (xs ++ ys)'s n − 1 beside xs's tail)
2733
+ const selfUses = [...found.filter(f => f.k === 'data'), ...found.filter(f => f.k === 'nat').slice(0, 1)].map(f => f.u).slice(0, lemmaCaps.self);
2734
+ if (dataTrace)
2735
+ for (const u of selfUses)
2736
+ console.error(`[data] hypothesis use at ${Object.entries(u.subst).map(([x, t]) => `${x} := ${brief(t, 80)}`).join('; ')}`);
2737
+ const uses = [...ih, ...selfUses, ...lemmaUses];
2690
2738
  if (dataTrace)
2691
2739
  for (const u of lemmaUses)
2692
2740
  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('; ')}`);
2693
2741
  // The lemmas' conclusions are unfolded like the law's (they are what the goal reads, said another way); the cycle's
2694
2742
  // own uses only from depth 3.
2695
- 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 });
2743
+ // (eta also at each value a case's conditions say is a constructor of no field: [x]'s tail is nil, and so the value
2744
+ // nil; at one they say is of fields, its fields' reads would grow the case)
2745
+ const tagged = (hyps) => { const out = new Map(); for (const h of hyps ?? []) {
2746
+ if (h.op !== '=' || h.a.op !== 'get' || h.b.op !== 'const' || h.a.key.op === 'var')
2747
+ continue;
2748
+ const t = h.a, d = p.datas.find(d2 => t.map === tagMap(d2.name)), j = h.b.value;
2749
+ if (d && d.ctors[j] && !d.ctors[j].fields.length)
2750
+ out.set(sid(t.key), t.key);
2751
+ } return [...out.values()]; };
2752
+ const instsFor = (ms, us, every = false, hyps) => instancesOf(p, fs, { roots: [concl], others: us.map(useConcl), depth, shapesAt, etaAt: [...shapesAt, ...valuesCompared(p, mb.law), ...tagged(hyps)], models: ms, every, until: t0 + attemptMs.ms, hyps });
2696
2753
  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) : [];
2697
2754
  if (cases.length <= 1) {
2698
2755
  // One node: four uses of a lemma, twelve in all, the best first (as lemmaUsesFor ranks them).
@@ -2721,7 +2778,7 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2721
2778
  const fit = [...uses, ...spare].filter(u => holdsIn(u.guard) && applies(u)), kept = capUses(fit.filter(u => uses.includes(u)));
2722
2779
  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;
2723
2780
  const us = [...kept, ...capUses(joins ? rest.filter(u => joins(useConcl(u))) : [], lemmaCaps.joined)];
2724
- const ms = few(c.models ?? c.near ?? models);
2781
+ const ms = few(first(c.models ?? c.near ?? models));
2725
2782
  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 });
2726
2783
  }
2727
2784
  plans.push(plan);
@@ -2894,9 +2951,6 @@ function congruence(fs, onUnion) {
2894
2951
  };
2895
2952
  return { find, union, cell, cells, congruent };
2896
2953
  }
2897
- // The uses of lemmas a goal's reads match: each lemma's largest reads (those inside no other) matched against the goal's
2898
- // reads of the same map at keys equal, by the instances' equations (every branch), to the read's key.
2899
- // `hits`: the lemmas (their nodes) with any use at all, gathered there (and no uses made): whether a goal reads each.
2900
2954
  function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
2901
2955
  const terms = new Map(), { find, union, cell, congruent } = congruence(fs, x => terms.set(tid(x), x));
2902
2956
  const leaves = (e) => (e.op === 'if' ? [...leaves(e.then), ...leaves(e.else)] : [e]);
@@ -2928,7 +2982,7 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
2928
2982
  if (round > 0 && out.some(u => u.node === lm.node))
2929
2983
  continue;
2930
2984
  const vars = new Set(lm.law.vars.map(v => v.name)), sides = [];
2931
- walk(encY(p, lm.law.holds, new Map()), o => { if (o.op === 'get')
2985
+ walk(lm.pat ?? encY(p, lm.law.holds, new Map()), o => { if (o.op === 'get')
2932
2986
  sides.push(o); });
2933
2987
  const tops0 = sides.filter(a => !sides.some(b => b !== a && JSON.stringify(b).includes(JSON.stringify(a))));
2934
2988
  // (a read of a function where the lemma has one: a size law about a filter is used at the filter's reads, not at
@@ -2936,9 +2990,10 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
2936
2990
  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))
2937
2991
  yes = true; }); return yes; };
2938
2992
  const tops = tops0.some(callsFn) ? tops0.filter(callsFn) : tops0;
2939
- // (a constructor matched by its fields only for a lemma no read matches as it stands: the uses would multiply)
2993
+ // (a constructor matched by its fields only for a lemma no read matches as it stands, the uses would multiply; always
2994
+ // for the hypothesis, whose step names a value by its fields: y :: zs at the tail of a cons)
2940
2995
  for (const byFields of [false, true]) {
2941
- if (byFields && cands.some(c => c.use.node === lm.node))
2996
+ if (byFields && !lm.fixed && cands.some(c => c.use.node === lm.node))
2942
2997
  break;
2943
2998
  fieldMatch.on = byFields;
2944
2999
  for (const top of tops) {
@@ -2992,23 +3047,23 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
2992
3047
  } }).length : 1;
2993
3048
  if (!score)
2994
3049
  continue;
2995
- const k2 = sid([lm.node, sub]);
3050
+ const k2 = sid([lm.node, lm.fixed ?? {}, sub]);
2996
3051
  if (seen.has(k2))
2997
3052
  continue;
2998
3053
  seen.add(k2);
2999
- const names = Object.keys(sub).sort();
3000
- const fp = models.length ? JSON.stringify([lm.node, models.map(({ m, env }) => names.map(x => { try {
3054
+ const names = Object.keys(sub).sort(), full = lm.fixed ? { ...lm.fixed, ...Object.fromEntries(Object.entries(sub).filter(([x, t]) => !(t.op === 'var' && t.name === x))) } : sub;
3055
+ const fp = models.length ? JSON.stringify([lm.node, lm.fixed ? sid(lm.fixed) : '', models.map(({ m, env }) => names.map(x => { try {
3001
3056
  return m.evalE(sub[x], env);
3002
3057
  }
3003
3058
  catch {
3004
3059
  return -1;
3005
3060
  } }))]) : k2;
3006
- const use = { node: lm.node, subst: sub, guard: yesC };
3061
+ const use = { node: lm.node, subst: full, guard: lm.guard ?? yesC };
3007
3062
  if (hits) {
3008
3063
  hits.add(lm.node);
3009
3064
  break;
3010
3065
  }
3011
- cands.push({ use, at: { goal: t, lemma: substE(top, { vars: sub, maps: {}, flags: {} }) }, score, fp, size: textLength([lm.node, sub]) });
3066
+ cands.push({ use, at: { goal: t, lemma: substE(top, { vars: sub, maps: {}, flags: {} }) }, score, fp, size: textLength([lm.node, sub]), concl: lm.concl });
3012
3067
  }
3013
3068
  }
3014
3069
  }
@@ -3031,7 +3086,7 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
3031
3086
  continue;
3032
3087
  take(c);
3033
3088
  first.add(c);
3034
- fresh.push(substC(lemmas.find(lm => lm.node === c.use.node).concl, { vars: c.use.subst, maps: {}, flags: {} }));
3089
+ fresh.push(substC(c.concl, { vars: c.use.subst, maps: {}, flags: {} }));
3035
3090
  }
3036
3091
  const rest = cands.filter(c => !first.has(c)).sort((a, b) => b.score - a.score || a.size - b.size);
3037
3092
  for (const c of rest) {
@@ -3060,7 +3115,7 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
3060
3115
  // How many uses of lemmas a goal gets: the candidates kept (`perLemma` of each lemma, `total`), and of those a case node
3061
3116
  // keeps (`perCase` of each lemma, those its models meet); past the node's, `spare` kept for its cases, of which a case
3062
3117
  // takes `joined` more (those its own rewriting passes through).
3063
- export const lemmaCaps = { perLemma: 8, total: 24, perCase: 4, spare: 96, joined: 2 };
3118
+ export const lemmaCaps = { perLemma: 8, total: 24, perCase: 4, spare: 96, joined: 2, self: 4 };
3064
3119
  // A node's uses: the scheme's (the cycle's, read at nodes not yet placed) all, `perCase` of each lemma, `total` lemma
3065
3120
  // uses in all, in the order given.
3066
3121
  function capUses(uses, total = Infinity) {
@@ -13,7 +13,8 @@
13
13
  import { quietly } from "./cyclic.js";
14
14
  import { any, atMost, compileFunction, evalC, evalE, n, plus, prod, same, seeded, times, x } from "./machine.js";
15
15
  import { Unproven, lit, proveFold, proveSteps, recur, recurOf } from "./dsl.js";
16
- import { gcd } from "./solver.js";
16
+ import { gcd, plus as addLin } from "./solver.js";
17
+ import { closedForm as fit, nfold, polyOf } from "./accel.js";
17
18
  const valueOf = (t) => (typeof t === 'number' ? t : t.val);
18
19
  const evalLin = (l, at) => Object.entries(l).reduce((s, [a, c]) => s + c * (a === '1' ? 1 : at[a]), 0);
19
20
  const holds = (c, at) => { const v = evalLin(c.lin, at); return c.rel === '=' ? v === 0 : v <= 0; };
@@ -85,34 +86,72 @@ function linearCands(target, forms, samples, show) {
85
86
  const dedupe = (cs) => [...new Map(cs.map(c => [c.name, c])).values()];
86
87
  // A statement whose coefficients are naturals a term can hold (a fit to values near 2^53 can make one that isn't).
87
88
  const exact = (c) => Object.values(c.lin).every(Number.isSafeInteger);
88
- // A polynomial in x of degree 3 at most, exact over the rationals, as d·f = a·x·x·x + b·x·x + c·x + e with whole
89
- // numbers: fitted to four points (Newton's differences), kept when every sample meets it.
90
- function closedForm(samples, show) {
89
+ // A polynomial in x of degree 2 or 3, exact over the rationals, as d·f = a·x·x·x + b·x·x + c·x + e with whole numbers,
90
+ // from core/accel.ts's closed forms: the recurrence's own where its step is affine in f and a polynomial in x (the
91
+ // engine on f and the powers of x, a triangular system), else the values' (the engine on the numbers: the shortest
92
+ // recurrence they all meet); kept when every sample meets it.
93
+ function closedForm(samples, show, rec) {
91
94
  const at = new Map();
92
95
  for (const s of samples) {
93
96
  if (at.has(s.x) && at.get(s.x) !== s.f)
94
97
  return [];
95
98
  at.set(s.x, s.f);
96
99
  }
97
- if (![0, 1, 2].every(x => at.has(x)))
100
+ const seq = [];
101
+ while (at.has(seq.length))
102
+ seq.push({ 1: at.get(seq.length) });
103
+ const p = (() => {
104
+ const next = rec && powers(rec.next), zero = rec?.zero.op === 'const' ? rec.zero.value : undefined;
105
+ const f = next && zero !== undefined ? nfold({ prev: 1 }, { x: { x: 1, 1: 1 }, xx: { xx: 1, x: 2, 1: 1 }, xxx: { xxx: 1, xx: 3, x: 3, 1: 1 }, prev: next }) : undefined;
106
+ const start = (c) => ({ 1: (c['1'] ?? 0) + (c.prev ?? 0) * zero });
107
+ if (f)
108
+ return { terms: f.terms.map(t => ({ ...t, c: start(t.c) })), den: f.den };
109
+ return seq.length >= 3 ? fit(seq, false) : undefined;
110
+ })();
111
+ const cs = p && polyOf(p);
112
+ if (!cs || cs.length < 3 || cs.length > 4)
98
113
  return [];
99
- const [f0, f1, f2] = [at.get(0), at.get(1), at.get(2)];
100
- const keep = (lin) => {
101
- const g = Object.values(lin).reduce((p, q) => gcd(p, Math.abs(q)), 0);
102
- const c = { name: '', rel: '=', lin: Object.fromEntries(Object.entries(lin).map(([a, k]) => [a, k / g]).filter(([, k]) => k !== 0)) };
103
- c.name = nameOf(c, show, 'f');
104
- return exact(c) && samples.every(s => holds(c, s)) ? [c] : [];
105
- };
106
- // f = a x² + b x + c: c = f0, a = (f2 - 2 f1 + f0) / 2, b = f1 - f0 - a; times 2 to keep whole numbers.
107
- const A = f2 - 2 * f1 + f0, B = 2 * (f1 - f0) - A, C = 2 * f0;
108
- const square = A === 0 ? [] : keep({ f: 2, xx: -A, x: -B, 1: -C });
109
- if (square.length || !at.has(3))
110
- return square;
111
- // f = Δ0 + Δ1·x + Δ2·x(x − 1)/2 + Δ3·x(x − 1)(x − 2)/6, times 6: x³ by Δ3, x² by 3Δ2 − 3Δ3, x by 6Δ1 − 3Δ2 + 2Δ3.
112
- const d1 = f1 - f0, d2 = f2 - 2 * f1 + f0, d3 = at.get(3) - 3 * f2 + 3 * f1 - f0;
113
- if (d3 === 0)
114
- return []; // degree 2 at most: above, or linear (the bounds find it)
115
- return keep({ f: 6, xxx: -d3, xx: -(3 * d2 - 3 * d3), x: -(6 * d1 - 3 * d2 + 2 * d3), 1: -6 * f0 });
114
+ // Σ c_k·C(x, k) / den, times 6·den: C(x, 2)·6 = 3·x·x − 3·x, C(x, 3)·6 = x·x·x − 3·x·x + 2·x
115
+ const [c0, c1, c2, c3] = [0, 1, 2, 3].map(k => cs[k]?.['1'] ?? 0);
116
+ const lin = { f: 6 * p.den, xxx: -c3, xx: -(3 * c2 - 3 * c3), x: -(6 * c1 - 3 * c2 + 2 * c3), 1: -6 * c0 };
117
+ const g = Object.values(lin).reduce((a, b) => gcd(a, Math.abs(b)), 0);
118
+ const c = { name: '', rel: '=', lin: Object.fromEntries(Object.entries(lin).map(([a, k]) => [a, k / g]).filter(([, k]) => k !== 0)) };
119
+ c.name = nameOf(c, show, 'f');
120
+ return exact(c) && samples.every(s => holds(c, s)) ? [c] : [];
121
+ }
122
+ // A step as a form over prev and the powers of x up to x·x·x (x, xx, xxx), or undefined where it isn't one.
123
+ function powers(e) {
124
+ switch (e.op) {
125
+ case 'var': return e.name === 'x' || e.name === 'prev' ? { [e.name]: 1 } : undefined;
126
+ case 'const': return { 1: e.value };
127
+ case 'add': {
128
+ const a = powers(e.a), b = powers(e.b);
129
+ return a && b && addLin(a, b);
130
+ }
131
+ case 'mul': {
132
+ const a = powers(e.a);
133
+ return a && Object.fromEntries(Object.entries(a).map(([k, c]) => [k, c * e.k]));
134
+ }
135
+ case 'prod': {
136
+ const a = powers(e.a), b = powers(e.b);
137
+ if (!a || !b)
138
+ return undefined;
139
+ let o = {};
140
+ for (const [u, c] of Object.entries(a))
141
+ for (const [w, d] of Object.entries(b)) {
142
+ if (u !== '1' && w !== '1' && (u === 'prev' || w === 'prev' || u.length + w.length > 3))
143
+ return undefined;
144
+ const m = u === '1' ? w : w === '1' ? u : 'x'.repeat(u.length + w.length);
145
+ o = addLin(o, { [m]: c * d });
146
+ }
147
+ return o;
148
+ }
149
+ case 'sub':
150
+ case 'min':
151
+ case 'max':
152
+ case 'if':
153
+ case 'get': return undefined;
154
+ }
116
155
  }
117
156
  // The law a goal is of (the kernel names each goal after its law: '<law> @step').
118
157
  const lawOfGoal = (goal) => goal.replace(/ @(start|step|step law|\d+ steps|leaf|node)$/, '');
@@ -145,7 +184,7 @@ function recurSamples(d, args) {
145
184
  return out;
146
185
  }
147
186
  // Lemmas about every x and f(x), and laws between two points, that every value meets.
148
- function recurCands(samples, args) {
187
+ function recurCands(samples, args, rec) {
149
188
  const slopes = new Set();
150
189
  const byArgs = new Map();
151
190
  for (const s of samples) {
@@ -162,7 +201,7 @@ function recurCands(samples, args) {
162
201
  const sorted = [...slopes].sort((a, b) => a - b), picked = [...new Set([...sorted.slice(0, 3), ...sorted.slice(-1)])];
163
202
  const xs = [{}, ...picked.map(s => ({ x: s }))];
164
203
  const forms = xs.flatMap(fx => [fx, ...args.map(a => ({ ...fx, [a]: 1 }))]);
165
- const lemmas = [...linearCands('f', forms, samples, showRecur), ...(args.length ? [] : closedForm(samples, showRecur))];
204
+ const lemmas = [...linearCands('f', forms, samples, showRecur), ...(args.length ? [] : closedForm(samples, showRecur, rec))];
166
205
  const pairs = [];
167
206
  for (const run of byArgs.values())
168
207
  for (const a of run)
@@ -284,7 +323,7 @@ function discoverSearch(r, laws, stepLaws, first) {
284
323
  // fitted exactly) first with it alone: it decides the function, and the bounds beside it, which the closed form
285
324
  // implies only through products, are slow to prove by induction; the rest where the laws aren't proven with it.
286
325
  const cands = new Map(fns.flatMap(([n, d]) => { const src = recurOf(d); if (!src)
287
- return []; const args = [...(src.def.args ?? [])]; return [[n, recurCands(recurSamples(d, args), args)]]; }));
326
+ return []; const args = [...(src.def.args ?? [])]; return [[n, recurCands(recurSamples(d, args), args, d.recur)]]; }));
288
327
  const exact = (c) => c.rel === '=' && ('xx' in c.lin || 'xxx' in c.lin);
289
328
  const makeFns = (closedOnly) => {
290
329
  const out = {};