gdp-wired 0.27.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.
@@ -29,6 +29,10 @@ export type Accelerated = {
29
29
  cycle: number[];
30
30
  locs: number[];
31
31
  targets: Target[];
32
+ cases?: {
33
+ pins: [string, number][];
34
+ cond: C;
35
+ }[];
32
36
  };
33
37
  export type AccelOptions = {
34
38
  now: () => number;
@@ -42,6 +46,7 @@ export type AccelOptions = {
42
46
  io?: StemIO;
43
47
  };
44
48
  export declare function accelerated(l: Loop, opts: AccelOptions): Generator<Accelerated>;
49
+ export declare const relationBuilt: (l: Loop) => boolean;
45
50
  type Env = Record<string, number>;
46
51
  export type StemIO = {
47
52
  start: (params: Env) => Env;
@@ -211,18 +211,18 @@ const implied = (rows, a) => solve([...rows, plus(times(a, -1), konst(1))].map(l
211
211
  // the relation's cycles, then those of its cases where a state value that a product reads with a turn's input is fixed
212
212
  // (`fixedCases`), which have 30% of the time where there are any.
213
213
  export function* accelerated(l, opts) {
214
- const rel = relOf(l), fixed = fixedCases(l), { now } = opts;
214
+ const rel = relOf(l), fixed = fixedCases(l), { now } = opts, t0 = now();
215
215
  if (rel)
216
- yield* cyclesOf(l, rel, fixed.length ? { ...opts, until: now() + (opts.until - now()) * 0.7 } : opts, []);
216
+ yield* cyclesOf(l, rel, fixed.length ? { ...opts, get until() { return t0 + (opts.until - t0) * 0.7; } } : opts, []);
217
217
  for (const f of fixed) {
218
218
  if (now() > opts.until)
219
219
  return;
220
- yield* cyclesOf(l, f.rel, { now, until: opts.until, ...(opts.maxLen ? { maxLen: opts.maxLen } : {}) }, f.pins);
220
+ yield* cyclesOf(l, f.rel, { now, get until() { return opts.until; }, ...(opts.maxLen ? { maxLen: opts.maxLen } : {}) }, f.pins);
221
221
  }
222
222
  }
223
223
  // (`pins`: rows every part of the set keeps, the fixed values of a case)
224
224
  function* cyclesOf(l, rel, opts, pins) {
225
- const { now, until } = opts, maxLen = opts.maxLen ?? 6;
225
+ const { now } = opts, maxLen = opts.maxLen ?? 6;
226
226
  const S = rel.state, P = new Set(rel.params), Sset = new Set(S), NP = rel.paths.length;
227
227
  const natState = S.filter(x => !rel.ints.has(x));
228
228
  // Each path's inputs as terms of the state before it (a few choices each, the first the likeliest).
@@ -232,7 +232,8 @@ function* cyclesOf(l, rel, opts, pins) {
232
232
  // The cycles: closed walks of paths (a location may come twice: two turns at one location, taken in turn), each once
233
233
  // (its least rotation), with at most `maxLen` choices among a location's paths (a chain of locations with one path out,
234
234
  // as a translated program's straight-line code, is free) and at most 64 turns; the shortest first.
235
- const enumerate = (ids) => {
235
+ // (`fewest`: the fewest choices a walk makes, so a deeper search finds only walks the first didn't)
236
+ const enumerate = (ids, fewest = 0, upTo = maxLen, cap = opts.maxCycles ?? 400) => {
236
237
  let cycles = [];
237
238
  // (those with an inner loop counted out apart, at most 60, after the rest)
238
239
  const counted = [];
@@ -241,7 +242,6 @@ function* cyclesOf(l, rel, opts, pins) {
241
242
  const f = from(i);
242
243
  byFrom.set(f, [...(byFrom.get(f) ?? []), i]);
243
244
  }
244
- const cap = opts.maxCycles ?? 400;
245
245
  const least = (seq) => seq.every((_, r) => r === 0 || cmp(seq, [...seq.slice(r), ...seq.slice(0, r)]) < 0);
246
246
  // (a turn costs 1 at a location of more than one path, 0 else; each location's least cost back to the cycle's start,
247
247
  // so a walk that can't come back within the budget is cut)
@@ -288,15 +288,15 @@ function* cyclesOf(l, rel, opts, pins) {
288
288
  const open = (sigma, i, k) => (i >= NP ? stepTurn(rel, natState, { inner: loops[i - NP] }, sigma) : turn(rel, natState, i, sigma, symbolic(rel.paths[i], k, Sset, P), k));
289
289
  const id0 = Object.fromEntries(S.map(x => [x, { [x]: 1 }]));
290
290
  let nodes = 20_000;
291
- for (let budget = 0; budget <= maxLen && cycles.length < cap && nodes > 0; budget++) {
292
- for (let i = 0; i < NP && cycles.length < cap && nodes > 0 && now() < until; i++) {
291
+ for (let budget = fewest; budget <= upTo && cycles.length < cap && nodes > 0; budget++) {
292
+ for (let i = 0; i < NP && cycles.length < cap && nodes > 0 && now() < opts.until; i++) {
293
293
  const s0 = from(i);
294
294
  if (!backs.has(s0))
295
295
  backs.set(s0, back(s0));
296
296
  const d = backs.get(s0);
297
297
  // (`inner`: the self-loop just taken as many times as its rows allow, not taken again at once)
298
298
  const walk = (seq, at, cost, sigma, rows, inner) => {
299
- if (--nodes < 0 || cycles.length >= cap || now() > until)
299
+ if (--nodes < 0 || cycles.length >= cap || now() > opts.until)
300
300
  return;
301
301
  if (at === s0 && cost === budget && least(seq) && sat(rows)) {
302
302
  if (!seq.some((x, q) => q > 0 && x === seq[q - 1] && to(x) === from(x) && x < NP))
@@ -353,7 +353,7 @@ function* cyclesOf(l, rel, opts, pins) {
353
353
  rel.paths.forEach((_, i) => { byLoc.set(from(i), [...(byLoc.get(from(i)) ?? []), i]); });
354
354
  let budget = 20_000;
355
355
  for (const r of opts.runs) {
356
- if (now() > until || budget <= 0)
356
+ if (now() > opts.until || budget <= 0)
357
357
  break;
358
358
  let st = opts.io.start(r.params);
359
359
  const seq = [];
@@ -423,13 +423,13 @@ function* cyclesOf(l, rel, opts, pins) {
423
423
  sets.push(...lookahead(rel, seq.map((pi, j) => stepOf(pi, firsts[j])), natState, Sset, P));
424
424
  }
425
425
  for (const ins of sets) {
426
- if (now() > until)
426
+ if (now() > opts.until)
427
427
  return;
428
428
  const key = `${seq.join(',')}|${JSON.stringify(ins)}`;
429
429
  if (tried.has(key))
430
430
  continue;
431
431
  tried.add(key);
432
- const out = candidate(rel, seq.map((pi, j) => stepOf(pi, ins[j])), natState, l, () => now() > until, pins);
432
+ const out = candidate(rel, seq.map((pi, j) => stepOf(pi, ins[j])), natState, l, () => now() > opts.until, pins);
433
433
  if (out)
434
434
  yield { ...out, cycle: seq, locs: seq.map(from) };
435
435
  }
@@ -438,13 +438,13 @@ function* cyclesOf(l, rel, opts, pins) {
438
438
  };
439
439
  // The relation's cycles, then the cycles with an inner loop taken to its end, then the lookahead's choices on the first
440
440
  yield* tryAll(cycles, 'no');
441
- if (now() > until)
441
+ if (now() > opts.until)
442
442
  return;
443
443
  // The inner loops: a self-loop or a cycle of two turns at a location whose turn, with its inputs' choices, is a
444
444
  // translation with a metering function (core/accel.ts's `accelerate`), taken to its end as one step of a walk; each
445
445
  // named NP + k among the paths.
446
446
  let tries = 2000;
447
- for (let i = 0; i < NP && loops.length < 40 && tries > 0 && now() < until; i++) {
447
+ for (let i = 0; i < NP && loops.length < 40 && tries > 0 && now() < opts.until; i++) {
448
448
  const at = rel.loc ? rel.from[i] : 0;
449
449
  if (readsPi(rel.paths[i]))
450
450
  continue;
@@ -466,9 +466,14 @@ function* cyclesOf(l, rel, opts, pins) {
466
466
  }
467
467
  if (loops.length)
468
468
  yield* tryAll(enumerate(NP + loops.length).filter(c => c.some(i => i >= NP)), 'yes');
469
- if (now() < until)
469
+ if (now() < opts.until)
470
470
  yield* tryAll(cycles, 'only');
471
+ // Deeper, in the time left: walks of up to 16 choices, at most 5,000 of them (hqr's cycle of 25 turns makes 16), each
472
+ // tried with its first inputs.
473
+ if (now() < opts.until && maxLen < DEEP)
474
+ yield* tryAll(enumerate(NP, maxLen + 1, DEEP, 5000), 'no');
471
475
  }
476
+ const DEEP = 16;
472
477
  // The choices one input at a time of a turn's that the rest of the cycle bounds: the cycle from that turn on (its other
473
478
  // inputs as chosen), the bounds its rows put on the input, as terms of the state at that turn (x ≤ u gives x), the
474
479
  // first three that leave the rows satisfiable; at most 12.
@@ -510,6 +515,9 @@ function pathAt(rel, among, st, input) {
510
515
  const raws = new WeakMap(), rels = new WeakMap();
511
516
  const rawOf = (l) => { if (!raws.has(l))
512
517
  raws.set(l, relationOf(l)); return raws.get(l); };
518
+ // The loop's relation and its cases with a value fixed, built (once a loop): a caller may build them before the search,
519
+ // and not count the time against it.
520
+ export const relationBuilt = (l) => { relOf(l); fixedCases(l); return !!rels.get(l); };
513
521
  function relOf(l) {
514
522
  if (!rels.has(l))
515
523
  rels.set(l, kept(l, rawOf(l)));
@@ -1021,7 +1029,7 @@ function candidate(rel, steps, natState, l, late, pins) {
1021
1029
  e = { op: 'if', c: conds[j], then: vals[j], else: e };
1022
1030
  wit[n] = e;
1023
1031
  }
1024
- return { set, wit, targets: parts.map(p => ({ loc: p.loc, rows: p.rows })) };
1032
+ return { set, wit, targets: parts.map(p => ({ loc: p.loc, rows: p.rows })), ...(rel.loc ? { cases: parts.map((p, j) => ({ pins: [[rel.loc, p.loc]], cond: full[j] })) } : {}) };
1025
1033
  }
1026
1034
  const cmp = (a, b) => { for (let i = 0; i < a.length; i++)
1027
1035
  if (a[i] !== b[i])
@@ -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));
@@ -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) {
package/dist/core/dsl.js CHANGED
@@ -18,7 +18,7 @@
18
18
  import { argsKey, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, withArithmetic } from "./machine.js";
19
19
  import { allowed, keysOf, requestEnv, watch } from "./watch.js";
20
20
  import { someHolds, substVars } from "./exists.js";
21
- import { check, checkRecur, foldObligations, loopObligations } from "../kernel/kernel.js";
21
+ import { check, checkRecur, foldObligations, loopObligations, substC } from "../kernel/kernel.js";
22
22
  import { certLoop, clock, counted, factsFor, fullRate, grow, proveLaws, proveLiveness, proveStepLaws, usualProof, withDeadline } from "../kernel/prove.js";
23
23
  import { certCyclic, certOn, crossCyclic, cyclicOn, foldNodes, proveCyclic, quietly, recurNodes, translatedProof, uncovered } from "./cyclic.js";
24
24
  import { discover } from "./discover.js";
@@ -27,6 +27,8 @@ import { findBoundedRun } from "./bmc.js";
27
27
  import { conjunction, proveKInduction } from "./kind.js";
28
28
  import { cycleLemmas, findLeadsTo, findRank } from "./cycles.js";
29
29
  import { findNeverEnds } from "./nonterm.js";
30
+ import { leadsByTerms } from "./live.js";
31
+ import { freshLaws } from "./fresh.js";
30
32
  // --- terms and conditions -------------------------------------------------------------------------------------------
31
33
  const naturalConst = (v) => {
32
34
  if (!Number.isSafeInteger(v) || v < 0)
@@ -2660,9 +2662,27 @@ const refuteBudget = { trials: 60, depth: 6, bound: 3 };
2660
2662
  const shownRequest = (input) => Object.fromEntries(Object.entries(input).map(([n, x]) => [n, typeof x === 'number' ? x : Object.fromEntries(x)]));
2661
2663
  // The search's own runs, before it looks for what the laws need: deeper and wider, from another seed.
2662
2664
  const deeperBudget = { trials: 600, depth: 24, bound: 8, seed: 29 };
2665
+ const conjuncts = (c) => (!c ? [] : c.op === 'and' ? c.xs.flatMap(conjuncts) : [c]);
2666
+ function guidesOf(m) {
2667
+ const isInput = (e) => e.op === 'var' && m.inputs.includes(e.name);
2668
+ const free = (e) => !namesIn(e).some(n => m.inputs.includes(n));
2669
+ return conjuncts(m.assume).flatMap(c => {
2670
+ if (c.op !== '=' && c.op !== '<=' && c.op !== '<')
2671
+ return [];
2672
+ const [x, t, up] = isInput(c.a) && free(c.b) && c.op === '=' ? [c.a, c.b, false] : isInput(c.b) && free(c.a) ? [c.b, c.a, c.op !== '='] : [undefined, undefined, false];
2673
+ if (!x || !t)
2674
+ return [];
2675
+ return [(env, st, rand, bound) => { try {
2676
+ return [x.name, evalE(t, env, st, m) + (up ? (c.op === '<' ? 1 : 0) + rand(bound + 1) : 0)];
2677
+ }
2678
+ catch {
2679
+ return undefined;
2680
+ } }];
2681
+ });
2682
+ }
2663
2683
  function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2664
2684
  const m = r.machine;
2665
- const run = interpret(m), rand = seeded(budget.seed ?? 13), bound = budget.bound, shown = shownRequest;
2685
+ const run = interpret(m), rand = seeded(budget.seed ?? 13), bound = budget.bound, shown = shownRequest, guides = budget.mixed ? guidesOf(m) : [];
2666
2686
  // (Division by a constant is a function too, its facts Euclid's, which its JavaScript meets: not checked.)
2667
2687
  const facts = (m.facts ?? []).filter(f => !isArithmetic(f.name.slice(0, f.name.indexOf(':'))));
2668
2688
  const holds = (f, params) => {
@@ -2683,7 +2703,13 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2683
2703
  && facts.filter(readsParams).every(f => holds(f, params));
2684
2704
  try {
2685
2705
  for (let trial = 0; trial < budget.trials; trial++) {
2706
+ // (`mixed`: the trials in turn at bounds 1 to 4, every fourth near)
2707
+ const bound = budget.mixed ? 1 + trial % 4 : budget.bound, guided = guides, near = budget.mixed && trial % 4 ? undefined : budget.near;
2686
2708
  const params = r.randomParams(rand, bound);
2709
+ if (near)
2710
+ for (const p of m.params)
2711
+ if (near[p] !== undefined && rand(2))
2712
+ params[p] = near[p];
2687
2713
  if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m) || !factsHold(params))
2688
2714
  continue;
2689
2715
  const watching = [...laws, ...stepLaws].map(w => ({ w, on: watch(m, run, w, params, bound) }));
@@ -2696,6 +2722,15 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2696
2722
  return broken(w, '@start', st);
2697
2723
  for (let d = 0, tries = 0; d < budget.depth && tries < 40; tries++) {
2698
2724
  const input = r.randomInput(rand, bound, params);
2725
+ if (near)
2726
+ for (const x of m.inputs)
2727
+ if (near[x] !== undefined && typeof input[x] === 'number' && rand(2))
2728
+ input[x] = near[x];
2729
+ for (const g of guided) {
2730
+ const set = g({ ...params, ...st.scalars }, st, rand, bound);
2731
+ if (set && typeof input[set[0]] === 'number')
2732
+ input[set[0]] = set[1];
2733
+ }
2699
2734
  if (!allowed(m, run, params, st, input))
2700
2735
  continue;
2701
2736
  d++;
@@ -2714,7 +2749,7 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2714
2749
  // variable of a kind is drawn as its kind draws (33 yes/nos drawn from 0..7 almost never make a lawful state).
2715
2750
  const steps1 = stepLaws.filter(sl => (sl.steps ?? 1) === 1), given = withKinds(r, laws);
2716
2751
  const wide = Object.keys(m.state).length + m.inputs.length >= 32, lawsHere = wide ? given : [], kinded = wide ? r.kindsOfState() : [];
2717
- for (let trial = 0; !m.history && (steps1.length || lawsHere.length) && trial < budget.trials * 4; trial++) {
2752
+ for (let trial = 0; budget.states !== false && !m.history && (steps1.length || lawsHere.length) && trial < budget.trials * 4; trial++) {
2718
2753
  const params = r.randomParams(rand, bound);
2719
2754
  if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m) || !factsHold(params))
2720
2755
  continue;
@@ -2763,21 +2798,52 @@ export function proveRule(r, laws, opts = {}) {
2763
2798
  export function proveSteps(r, laws, stepLaws, opts = {}) {
2764
2799
  noting(r, laws, stepLaws);
2765
2800
  const refuted = refuteByRuns(r, laws, stepLaws);
2801
+ // (a step law broken from a state the laws allow, with no run to it: the laws may need an invariant there, or the run
2802
+ // be further than these runs go; the search goes on from it, as from the kernel's)
2766
2803
  if (refuted)
2767
- return refutedVerdict(refuted);
2804
+ return refuted.run ? refutedVerdict(refuted) : searched(r, laws, stepLaws, refutedVerdict(refuted), opts);
2768
2805
  const out = proveStepLaws(r.machine, withKinds(r, laws), stepLaws);
2769
2806
  const v = verdictOf(out);
2770
2807
  return searched(r, laws, stepLaws, v, opts);
2771
2808
  }
2809
+ // The one-step laws as laws the bounded runs read (core/bmc.ts takes laws alone): a ghost per step law, set once a step
2810
+ // it is about breaks it (`then` read with each primed name the step's update), and the law that it is never set. Only a
2811
+ // machine bmc takes (no maps, no history) and a step law over no key; the ghost changes no run of the machine.
2812
+ function stepGhosts(m, stepLaws) {
2813
+ const plain = stepLaws.filter(sl => (sl.steps ?? 1) === 1 && !sl.forall && !sl.keys?.length);
2814
+ if (!plain.length || Object.keys(m.maps ?? {}).length || m.history || m.inputMaps?.length)
2815
+ return undefined;
2816
+ const flags = Object.fromEntries(Object.keys(m.step.flags ?? {}).map(f => [f, { op: 'flag', name: f }]));
2817
+ const after = { vars: Object.fromEntries(Object.keys(m.state).map(n => [`${n}'`, m.step.state?.[n] ?? { op: 'var', name: n }])), maps: {}, flags };
2818
+ const ghosts = {}, out = [];
2819
+ for (const [i, sl] of plain.entries()) {
2820
+ const name = `broken$${i}`, whens = sl.when === undefined ? [] : Array.isArray(sl.when) ? sl.when : [sl.when];
2821
+ if (name in m.state)
2822
+ return undefined;
2823
+ ghosts[name] = { op: 'if', c: { op: 'and', xs: [...whens, { op: 'not', x: substC(sl.then, after) }] }, then: { op: 'const', value: 1 }, else: { op: 'var', name } };
2824
+ out.push({ name: sl.name, holds: { op: '<=', a: { op: 'var', name }, b: { op: 'const', value: 0 } } });
2825
+ }
2826
+ // (as core/compose.ts's `ghost`: each starts at 0, nothing of the machine reads it)
2827
+ try {
2828
+ return { machine: { ...m, state: { ...m.state, ...Object.fromEntries(Object.keys(ghosts).map(n => [n, { op: 'const', value: 0 }])) }, step: { ...m.step, state: { ...m.step.state, ...ghosts } } }, laws: out };
2829
+ }
2830
+ catch {
2831
+ return undefined;
2832
+ }
2833
+ }
2772
2834
  // The search, where the prover alone didn't prove the laws and nothing refuted them: the lemmas first where the rule has
2773
2835
  // recurrences or carried lists (the rule made again with them), then invariants over what it then is. The verdict is the
2774
2836
  // prover's on the laws with what was found; when nothing is found, the prover's own (with why).
2775
2837
  function searched(r, laws, stepLaws, v, opts) {
2776
2838
  if ((v.proven && v.checked) || opts.search === false || v.run || v.stuck === 'sat' && !/@step|@\d+ steps/.test(v.goal ?? ''))
2777
2839
  return v;
2778
- const deeper = refuteByRuns(r, laws, stepLaws, deeperBudget);
2779
- if (deeper?.run)
2780
- return refutedVerdict(deeper);
2840
+ // The deeper runs; then runs over small values (keys that meet, small params), whose requests meet their
2841
+ // assumption's equalities and clocks, or near the counterexample the verdict ends at.
2842
+ for (const b of [deeperBudget, { ...deeperBudget, bound: 1, seed: 31, states: false }, { ...deeperBudget, trials: 1200, seed: 41, states: false, mixed: true, ...(v.witness ? { near: v.witness } : {}) }]) {
2843
+ const deeper = refuteByRuns(r, laws, stepLaws, b);
2844
+ if (deeper?.run)
2845
+ return refutedVerdict(deeper);
2846
+ }
2781
2847
  const until = clock() + (typeof opts.search === 'object' && opts.search.ms !== undefined ? opts.search.ms : 10_000);
2782
2848
  // Bounded runs (core/bmc.ts): a law broken k steps from the start, a model of the kernel's k-step goal, the run taken
2783
2849
  // by the interpreter. The shallow depths first, within a fortieth of the search's budget (at most 250 ms, counted in
@@ -2786,7 +2852,10 @@ function searched(r, laws, stepLaws, v, opts) {
2786
2852
  // shallow depths.
2787
2853
  const total = until - clock(), tail = Math.min(1000, total / 10);
2788
2854
  let reached = 0;
2789
- const bounded = (ms, from) => counted(fullRate, () => findBoundedRun(r.machine, laws, { ms, from, steps: true, progress: k => { reached = k; } }), true);
2855
+ const ghosted = stepGhosts(r.machine, stepLaws);
2856
+ // (with the step laws' ghosts, a wall stop too, at the budget: their goals cost the cost model more than its clock
2857
+ // counts, a wide rule's past twice its wall time)
2858
+ const bounded = (ms, from) => counted(fullRate, () => findBoundedRun(ghosted?.machine ?? r.machine, [...laws, ...(ghosted?.laws ?? [])], { ms, from, steps: true, ...(ghosted ? { wall: performance.now() + ms } : {}), progress: k => { reached = k; } }), true);
2790
2859
  const refutedBy = (b) => refutedVerdict({ goal: `${b.law} @step (a run of ${b.depth} steps from the start)`, witness: b.witness, run: { params: b.params, trace: b.trace.map(shownRequest) } });
2791
2860
  const shallow = bounded(Math.min(250, total / 40), 1);
2792
2861
  if (shallow)
@@ -2815,26 +2884,46 @@ function searched(r, laws, stepLaws, v, opts) {
2815
2884
  if (c.proven && c.checked)
2816
2885
  return { proven: true, checked: true, found: { ...(lemmas ? { lemmas } : {}), facts: c.found.map(f => f.text) } };
2817
2886
  }
2887
+ // Laws about the ids a counter hands out (core/fresh.ts), within a tenth of what is left: the laws with them, then
2888
+ // the invariant search with them given.
2889
+ let fresh = [];
2890
+ if (Object.keys(rule.machine.maps ?? {}).length && until - clock() - tail > 1000) {
2891
+ const fm = rule.machine, share = (until - clock() - tail) / 10;
2892
+ fresh = withDeadline(clock() + share, () => freshLaws(fm, rule.kindLaws(), { params: (rand, bound) => rule.randomParams(rand, bound), input: (rand, bound, ps) => rule.randomInput(rand, bound, ps) }, { ms: share }));
2893
+ if (fresh.length) {
2894
+ const given = [...withKinds(rule, laws), ...fresh.map(f => f.law)], out = withDeadline(clock() + share, () => (stepLaws.length ? proveStepLaws(fm, given, stepLaws) : proveLaws(fm, given)));
2895
+ if (out.proven && out.checked)
2896
+ return { proven: true, checked: true, found: { laws: fresh, ...(lemmas ? { lemmas } : {}) } };
2897
+ }
2898
+ }
2818
2899
  const ms = until - clock() - tail;
2819
2900
  if (ms < 500)
2820
2901
  return v;
2821
- const inf = inferLaws(rule, laws, stepLaws, { ms, ...(rule === r ? { first: v } : {}) });
2902
+ const inf = inferLaws(rule, [...fresh.map(f => f.law), ...laws], stepLaws, { ms, ...(rule === r && !fresh.length ? { first: v } : {}) });
2822
2903
  if (!(inf.proven && inf.checked)) {
2823
- const deep = bounded(Math.max(0, until - clock()), Math.max(1, reached));
2904
+ // (a step law's ghost: at most 10 s of it, as its goals cost more than the laws')
2905
+ const deep = bounded(Math.max(0, Math.min(until - clock(), ghosted && !laws.length ? 10_000 : Infinity)), Math.max(1, reached));
2824
2906
  if (deep)
2825
2907
  return refutedBy(deep);
2826
2908
  return { ...v, why: [v.why, `the search found nothing that proves it in ${Math.round(inf.stats.ms)} ms`].filter(Boolean).join('; ') };
2827
2909
  }
2828
2910
  const { found, stats: _stats, ...verdict } = inf;
2829
2911
  void _stats;
2830
- return { ...verdict, found: { laws: found, ...(lemmas ? { lemmas } : {}) } };
2912
+ return { ...verdict, found: { laws: [...fresh, ...found], ...(lemmas ? { lemmas } : {}) } };
2831
2913
  }
2832
2914
  export function proveLeadsTo(r, laws, l, opts = {}) {
2833
2915
  noting(r, laws, l);
2834
2916
  if (laws.some(law => law.some?.length))
2835
2917
  throw new Error(`${r.machine.name}: a law with "there exists" goes to proveRule or proveSteps; a liveness takes plain laws (the ones its proof printed, Verdict.witnesses)`);
2836
2918
  if (Array.isArray(l.rank) && !l.rank.length) {
2837
- const f = findLeadsTo(r.machine, withKinds(r, laws), l, { params: (rand, bound) => r.randomParams(rand, bound), input: (rand, bound, ps) => r.randomInput(rand, bound, ps) }, opts);
2919
+ const until = clock() + (opts.ms ?? 10_000), draws = { params: (rand, bound) => r.randomParams(rand, bound), input: (rand, bound, ps) => r.randomInput(rand, bound, ps) };
2920
+ let f = findLeadsTo(r.machine, withKinds(r, laws), l, { ...draws, rule: r }, opts);
2921
+ // Where the rank fitted to the runs isn't the one: a rank of the rule's own terms (core/live.ts), in the time left.
2922
+ if (!(f.proven && f.checked) && until - clock() > 500) {
2923
+ const g = leadsByTerms(r.machine, withKinds(r, laws), l, { ...draws, rule: r, state: (rand, bound) => Object.assign({}, ...r.kindsOfState().map(([n, kd]) => kd.random(n, rand, bound))) }, { ms: until - clock() });
2924
+ if (g.proven && g.checked)
2925
+ f = g;
2926
+ }
2838
2927
  return { proven: f.proven, checked: f.checked, ...(f.goal ? { goal: f.goal, stuck: f.stuck } : {}), ...(f.witness ? { witness: f.witness } : {}), ...(f.why ? { why: f.why } : {}),
2839
2928
  ...(f.found ? { found: { rank: f.found.rank, ...(f.laws?.length ? { laws: f.laws.map((law, i) => ({ law, text: f.found.laws[i] ?? law.name })) } : {}) } } : {}) };
2840
2929
  }