gdp-wired 0.23.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/README.md +12 -2
- package/dist/core/accel.d.ts +44 -0
- package/dist/core/accel.js +720 -0
- package/dist/core/bmc.d.ts +13 -2
- package/dist/core/bmc.js +390 -18
- package/dist/core/cycles.d.ts +23 -0
- package/dist/core/cycles.js +527 -146
- package/dist/core/data.d.ts +17 -0
- package/dist/core/data.js +1177 -213
- package/dist/core/discover.js +8 -3
- package/dist/core/dsl.d.ts +7 -2
- package/dist/core/dsl.js +47 -9
- package/dist/core/extract-check.d.ts +77 -0
- package/dist/core/extract-check.js +785 -0
- package/dist/core/extract-ir.d.ts +139 -0
- package/dist/core/extract-ir.js +198 -0
- package/dist/core/extract-print.d.ts +30 -0
- package/dist/core/extract-print.js +426 -0
- package/dist/core/extract-read.d.ts +298 -0
- package/dist/core/extract-read.js +1298 -0
- package/dist/core/extract-shapes.d.ts +13 -0
- package/dist/core/extract-shapes.js +993 -0
- package/dist/core/extract-xstate.d.ts +34 -0
- package/dist/core/extract-xstate.js +320 -0
- package/dist/core/extract.d.ts +31 -0
- package/dist/core/extract.js +249 -0
- package/dist/core/infer.d.ts +1 -0
- package/dist/core/infer.js +298 -28
- package/dist/core/kind.d.ts +30 -0
- package/dist/core/kind.js +81 -0
- package/dist/core/nonterm.d.ts +4 -1
- package/dist/core/nonterm.js +98 -2
- package/dist/core/relation.js +82 -7
- package/dist/core/transfer.js +1 -1
- package/dist/core/xstate.d.ts +6 -0
- package/dist/core/xstate.js +70 -12
- package/dist/kernel/cdcl.d.ts +15 -0
- package/dist/kernel/cdcl.js +331 -244
- package/dist/kernel/kernel.d.ts +15 -0
- package/dist/kernel/kernel.js +32 -0
- package/dist/kernel/prove.js +20 -7
- package/dist/kernel/reader.d.ts +14 -0
- package/dist/kernel/reader.js +102 -14
- package/dist/lean-kernel/emit.d.ts +28 -1
- package/dist/lean-kernel/emit.js +56 -15
- package/dist/lean-kernel/library.js +2 -1
- package/package.json +12 -3
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 {
|
|
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 };
|
|
@@ -405,15 +405,15 @@ function recursion(fn) {
|
|
|
405
405
|
}
|
|
406
406
|
return undefined;
|
|
407
407
|
};
|
|
408
|
-
const got =
|
|
408
|
+
const got = members.some(f => f.stated) ? undefined : choose(0, []);
|
|
409
|
+
const names = members.map(f => f.name);
|
|
409
410
|
if (!got) {
|
|
410
|
-
const why = `${fn.name}: not structural recursion (no parameter whose field every recursive call passes${members.length > 1 ? `, in its ring ${
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
return { ring:
|
|
411
|
+
const why = `${fn.name}: not structural recursion (no parameter whose field every recursive call passes${members.length > 1 ? `, in its ring ${names.join(', ')}` : ''}${members.some(f => f.stated) ? '; a measure is given' : ''})`;
|
|
412
|
+
// (each of the ring given its own measure and proofs: Data.lean's wf_fix_unique_ring)
|
|
413
|
+
const ts = termination(members, why);
|
|
414
|
+
members.forEach((f, a) => { f.rec = { ring: names, measure: ts[a].measure, termination: ts[a] }; });
|
|
415
|
+
return { ring: names, measure: ts[0].measure, termination: ts[0] };
|
|
415
416
|
}
|
|
416
|
-
const names = members.map(f => f.name);
|
|
417
417
|
members.forEach((f, a) => { f.rec = { decreases: got[a], ring: names }; });
|
|
418
418
|
return { decreases: got[0], ring: names };
|
|
419
419
|
}
|
|
@@ -449,7 +449,14 @@ export function measureX(f, c, args) {
|
|
|
449
449
|
return neg.length ? { op: 'sub', a: sum(pos), b: sum(neg) } : sum(pos);
|
|
450
450
|
}
|
|
451
451
|
const lexY = (as, bs) => (as.length === 1 ? { op: '<', a: as[0], b: bs[0] } : { op: 'or', xs: [{ op: '<', a: as[0], b: bs[0] }, { op: 'and', xs: [{ op: '=', a: as[0], b: bs[0] }, lexY(as.slice(1), bs.slice(1))] }] });
|
|
452
|
-
|
|
452
|
+
// The measures of a ring, each padded to the longest with components 0 (Data.lean's `lexLt` compares tuples of one length).
|
|
453
|
+
const padded = (ring, ms) => {
|
|
454
|
+
const w = Math.max(...ms.map(m => m.comps.length));
|
|
455
|
+
return ms.map((m, i) => ({ comps: [...m.comps, ...Array.from({ length: w - m.comps.length }, () => ({ coef: ring[i].params.map(() => 0), c: 0 }))] }));
|
|
456
|
+
};
|
|
457
|
+
const ringText = (ring, ms) => (ring.length === 1 ? showMeasure(ring[0], ms[0]) : ring.map((f, i) => `${f.name} ${showMeasure(f, ms[i])}`).join(', '));
|
|
458
|
+
const callSites = (ring) => ring.flatMap((f, from) => sitesOf(f, ring.map(g => g.name)).map(s => ({ ...s, from })));
|
|
459
|
+
function sitesOf(fn, names) {
|
|
453
460
|
const out = [], yesX = { op: 'bool', c: yes.y };
|
|
454
461
|
const at = (sh, name) => { let t = sh.get(name); while (t && t.op === 'var' && sh.has(t.name))
|
|
455
462
|
t = sh.get(t.name); return t; };
|
|
@@ -517,8 +524,8 @@ function callSites(fn) {
|
|
|
517
524
|
return;
|
|
518
525
|
case 'call':
|
|
519
526
|
x.args.forEach(a => goX(a, w));
|
|
520
|
-
if (x.fn
|
|
521
|
-
out.push({ args: x.args, ...w });
|
|
527
|
+
if (names.includes(x.fn))
|
|
528
|
+
out.push({ to: names.indexOf(x.fn), args: x.args, ...w });
|
|
522
529
|
return;
|
|
523
530
|
case 'if':
|
|
524
531
|
goY(x.c, w);
|
|
@@ -561,25 +568,30 @@ function callSites(fn) {
|
|
|
561
568
|
goX(fn.body(), { wrap: y => y, shape: new Map(), vars: fn.params.map(q => ({ name: `${fn.name}.${q.name}`, sort: q.sort })) });
|
|
562
569
|
return out;
|
|
563
570
|
}
|
|
564
|
-
//
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
+
// A term (or a law) with the site's shape put in: each matched variable its constructor's value.
|
|
572
|
+
const shapedBy = (s) => {
|
|
573
|
+
const go = (t) => (Array.isArray(t) ? t.map(go) : t && typeof t === 'object' ? (t.op === 'var' && s.shape.has(t.name) ? go(s.shape.get(t.name)) : Object.fromEntries(Object.entries(t).map(([key, v]) => [key, go(v)]))) : t);
|
|
574
|
+
return go;
|
|
575
|
+
};
|
|
576
|
+
const ownArgs = (f) => f.params.map(q => ({ op: 'var', name: `${f.name}.${q.name}` }));
|
|
577
|
+
// The obligation of a call: under its path, the callee's measure at its arguments below the caller's at its parameters,
|
|
578
|
+
// a law over the path's variables (the parameters not matched, the fields of the cases taken). `i`: the call's place
|
|
579
|
+
// among its caller's.
|
|
580
|
+
function obligation(ring, ms, s, i) {
|
|
581
|
+
const fn = ring[s.from], to = ring[s.to];
|
|
582
|
+
const holds = shapedBy(s)(s.wrap(lexY(ms[s.to].comps.map(c => measureX(to, c, s.args)), ms[s.from].comps.map(c => measureX(fn, c, ownArgs(fn))))));
|
|
583
|
+
const name = ring.length === 1 ? `${fn.name}'s call ${i + 1} lowers ${showMeasure(fn, ms[0])}` : `${fn.name}'s call ${i + 1}, of ${to.name}, lowers ${showMeasure(to, ms[s.to])} below ${showMeasure(fn, ms[s.from])}`;
|
|
584
|
+
return { name, vars: s.vars.filter(v => !s.shape.has(v.name)), holds, params: [...new Set(paramsIn(holds))] };
|
|
571
585
|
}
|
|
572
|
-
// The calls the function's runs make, each from its parameters' sizes to its arguments' (random arguments, up to 2,000
|
|
573
|
-
// calls a run: a run past that is cut, its calls kept).
|
|
574
586
|
let tracing;
|
|
575
|
-
|
|
587
|
+
const featOf = (f, vs) => f.params.map((p, i) => (p.sort === 'nat' ? vs[i] : p.sort instanceof Data ? sizeOf(p.sort, vs[i]) : 0));
|
|
588
|
+
function runEdges(ring) {
|
|
576
589
|
const rand = rng(17), edges = new Map();
|
|
577
|
-
const feat = (vs) => fn.params.map((p, i) => (p.sort === 'nat' ? vs[i] : p.sort instanceof Data ? sizeOf(p.sort, vs[i]) : 0));
|
|
578
590
|
const tables = new Map();
|
|
579
591
|
const params = new Proxy({}, { get: (_, key) => tables.get(key) ?? (tables.set(key, randomFn(rand)), tables.get(key)) });
|
|
580
|
-
for (let i = 0; i < 120 && edges.size < 400; i++) {
|
|
581
|
-
const vals = fn.params.map(p => randomValue(p.sort, rand, 1 + (i % 7)));
|
|
582
|
-
tracing = {
|
|
592
|
+
for (let i = 0; i < 120 * ring.length && edges.size < 400 * ring.length; i++) {
|
|
593
|
+
const fn = ring[i % ring.length], vals = fn.params.map(p => randomValue(p.sort, rand, 1 + (Math.floor(i / ring.length) % 7)));
|
|
594
|
+
tracing = { fns: new Map(ring.map((g, j) => [g.name, j])), stack: [], fuel: 2000, edge: (a, b) => { const e = { from: a.at, to: b.at, s: featOf(ring[a.at], a.vals), t: featOf(ring[b.at], b.vals) }; edges.set(JSON.stringify(e), e); } };
|
|
583
595
|
try {
|
|
584
596
|
evalX({ op: 'call', fn: fn.name, args: vals.map((_, j) => ({ op: 'var', name: `$a${j}` })) }, new Map(vals.map((v, j) => [`$a${j}`, v])), params);
|
|
585
597
|
}
|
|
@@ -591,45 +603,190 @@ function runEdges(fn) {
|
|
|
591
603
|
return [...edges.values()];
|
|
592
604
|
}
|
|
593
605
|
const valueOf = (c, xs) => Math.max(0, c.coef.reduce((a, k, i) => a + k * xs[i], c.c));
|
|
594
|
-
const lowers = (
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
606
|
+
const lowers = (ms, e) => {
|
|
607
|
+
const a = ms[e.to], b = ms[e.from];
|
|
608
|
+
for (const [j, c] of a.comps.entries()) {
|
|
609
|
+
const x = valueOf(c, e.t), y = valueOf(b.comps[j], e.s);
|
|
610
|
+
if (x < y)
|
|
598
611
|
return true;
|
|
599
|
-
if (
|
|
612
|
+
if (x > y)
|
|
600
613
|
return false;
|
|
601
614
|
}
|
|
602
615
|
return false;
|
|
603
616
|
};
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
617
|
+
const sizeOfValue = (s, v) => (s === 'nat' ? v : s instanceof Data ? sizeOf(s, v) : 0);
|
|
618
|
+
function sizeBounds(t, sort, vars, envs, coef = 1) {
|
|
619
|
+
const ms = vars.flatMap((v, i) => (measurable(v.sort) ? [i] : [])), at = [];
|
|
620
|
+
for (const s of envs) {
|
|
621
|
+
try {
|
|
622
|
+
at.push({ t: coef * sizeOfValue(sort, evalX(t, s.env, s.params)), v: vars.map(v => sizeOfValue(v.sort, s.env.get(v.name))) });
|
|
623
|
+
}
|
|
624
|
+
catch { /* past the bounds */ }
|
|
625
|
+
}
|
|
626
|
+
if (at.length < 12)
|
|
627
|
+
return [];
|
|
628
|
+
const sets = [...ms.map(i => [i]), ...ms.flatMap((i, a) => ms.slice(a + 1).map(j => [i, j]))];
|
|
629
|
+
return sets.map(of => { const d = at.map(p => p.t - of.reduce((s, i) => s + p.v[i], 0)); return { of, lo: Math.min(...d), hi: Math.max(...d), coef }; });
|
|
630
|
+
}
|
|
631
|
+
// The upper bounds worth stating: an equation where there is one (its fewest variables), else each set's whose bound is
|
|
632
|
+
// small, none another of fewer variables implies (each size is at least 0).
|
|
633
|
+
const upperBounds = (bs, most = 3) => {
|
|
634
|
+
const exact = bs.filter(b => b.lo === b.hi).sort((a, b) => a.of.length - b.of.length);
|
|
635
|
+
if (exact.length)
|
|
636
|
+
return [exact[0]];
|
|
637
|
+
const ok = bs.filter(b => b.hi <= 2).sort((a, b) => a.of.length - b.of.length || a.hi - b.hi);
|
|
638
|
+
return ok.filter(b => !ok.some(c => c !== b && c.of.length < b.of.length && c.of.every(i => b.of.includes(i)) && c.hi <= b.hi)).slice(0, most);
|
|
639
|
+
};
|
|
640
|
+
// The values of a law's variables where its path holds (`cond`: false where it doesn't).
|
|
641
|
+
// (naturals up to 40: a guard n ≥ 12 is met)
|
|
642
|
+
const pathSamples = (vars, params, cond, n = 240, seed = 19) => {
|
|
643
|
+
const rand = rng(seed), out = [];
|
|
644
|
+
for (let i = 0; i < n; i++) {
|
|
645
|
+
const s = { env: new Map(vars.map(v => [v.name, randomValue(v.sort, rand, 1 + (i % 7), i % 2 ? 40 : 5)])), params: Object.fromEntries(params.map(p => [p, randomFn(rand)])) };
|
|
646
|
+
try {
|
|
647
|
+
if (cond(s))
|
|
648
|
+
out.push(s);
|
|
649
|
+
}
|
|
650
|
+
catch { /* past the bounds */ }
|
|
651
|
+
}
|
|
652
|
+
return out;
|
|
653
|
+
};
|
|
654
|
+
// Size laws about the functions a law reads (not the ring's): for each, S(g(y…)) + a ≤ Σ S(yᵢ) + b over one or two of
|
|
655
|
+
// its arguments, the bound the values give (an equation where they give one difference), 2·g(n) ≤ n + b for a natural
|
|
656
|
+
// of one natural, those its values refute dropped; each a lemma for proveData to prove by induction and use.
|
|
657
|
+
function sizeLaws(l, ring) {
|
|
658
|
+
const seen = new Set(), helpers = [];
|
|
659
|
+
walk(l.holds, o => { if (o.op === 'call' && !ring.includes(o.fn) && !seen.has(o.fn)) {
|
|
660
|
+
seen.add(o.fn);
|
|
661
|
+
const g = fnOf(o.fn);
|
|
662
|
+
if (measurable(g.ret))
|
|
663
|
+
helpers.push(g);
|
|
664
|
+
} });
|
|
665
|
+
const out = [];
|
|
666
|
+
const nat = (n) => ({ op: 'nat', value: n }), add = (a, b) => (b.op === 'nat' && b.value === 0 ? a : { op: 'add', a, b });
|
|
667
|
+
for (const g of helpers.slice(0, 4)) {
|
|
668
|
+
const vars = g.params.map((q, i) => ({ name: `${q.name}${i}`, sort: q.sort }));
|
|
669
|
+
if (!vars.some(v => measurable(v.sort)))
|
|
670
|
+
continue;
|
|
671
|
+
const call = { op: 'call', fn: g.name, args: vars.map(v => ({ op: 'var', name: v.name })) }, envs = samples(vars, [], 160, 23);
|
|
672
|
+
const twice = g.ret === 'nat' && vars.length === 1 && vars[0].sort === 'nat' ? upperBounds(sizeBounds(call, g.ret, vars, envs, 2), 1).filter(b => b.lo !== b.hi) : [];
|
|
673
|
+
for (const b of [...upperBounds(sizeBounds(call, g.ret, vars, envs)), ...twice]) {
|
|
674
|
+
const lhs0 = b.coef === 1 ? sizeX(g.ret, call) : { op: 'mul', k: b.coef, a: sizeX(g.ret, call) };
|
|
675
|
+
const sum = b.of.map(i => sizeX(vars[i].sort, { op: 'var', name: vars[i].name })).reduce((a, c) => ({ op: 'add', a, b: c }));
|
|
676
|
+
const lhs = add(lhs0, nat(Math.max(0, -b.hi))), rhs = add(sum, nat(Math.max(0, b.hi)));
|
|
677
|
+
// (an upper bound is what a decrease reads: an equation's other half is a proof's cost for nothing)
|
|
678
|
+
const holds = { op: '<=', a: lhs, b: rhs };
|
|
679
|
+
out.push({ name: `size law: ${showY(holds)}`, vars, holds, params: [] });
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
return out;
|
|
683
|
+
}
|
|
684
|
+
// The calls' relation (core/relation.ts's form): a location per function of the ring, its parameters' sizes the state
|
|
685
|
+
// (`s<i>_<k>`), a path per call: the caller's parameters' sizes and the callee's arguments' (`a<k>`, the turn's
|
|
686
|
+
// inputs) bounded by the sizes of the path's variables (`v<j>`) where its values give a bound (`sizeBounds`).
|
|
687
|
+
function callRelation(ring, sites) {
|
|
688
|
+
const slot = (i, k) => `s${i}_${k}`;
|
|
689
|
+
const state = ring.flatMap((f, i) => f.params.flatMap((q, k) => (measurable(q.sort) ? [slot(i, k)] : [])));
|
|
690
|
+
const paths = [], nats = new Set(state), from = [], to = [];
|
|
691
|
+
for (const s of sites) {
|
|
692
|
+
const caller = ring[s.from], callee = ring[s.to], shaped = shapedBy(s);
|
|
693
|
+
const vars = s.vars.filter(v => !s.shape.has(v.name)), names = vars.map((_, j) => `v${j}`);
|
|
694
|
+
const cond = shaped(s.wrap(no.y));
|
|
695
|
+
const envs = pathSamples(vars, [...new Set(paramsIn([cond, s.args]))], sm => !evalY(cond, sm.env, sm.params));
|
|
696
|
+
if (envs.length < 12)
|
|
697
|
+
continue;
|
|
698
|
+
const rows = vars.flatMap((v, j) => (v.sort instanceof Data ? [{ [names[j]]: -1, 1: 1 }] : []));
|
|
699
|
+
const bounded = (x, t, sort) => {
|
|
700
|
+
const bs = sizeBounds(shaped(t), sort, vars, envs), exact = bs.filter(b => b.lo === b.hi).sort((a, b) => a.of.length - b.of.length)[0];
|
|
701
|
+
const lin = (b, c) => { const o = { [x]: 1 }; for (const i of b.of)
|
|
702
|
+
o[names[i]] = (o[names[i]] ?? 0) - 1; if (c)
|
|
703
|
+
o['1'] = -c; return o; };
|
|
704
|
+
if (exact) {
|
|
705
|
+
rows.push(lin(exact, exact.hi), Object.fromEntries(Object.entries(lin(exact, exact.hi)).map(([y, c]) => [y, -c])));
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
for (const b of upperBounds(bs))
|
|
709
|
+
rows.push(lin(b, b.hi));
|
|
710
|
+
};
|
|
711
|
+
caller.params.forEach((q, k) => { if (measurable(q.sort))
|
|
712
|
+
bounded(slot(s.from, k), ownArgs(caller)[k], q.sort); });
|
|
713
|
+
const post = {};
|
|
714
|
+
callee.params.forEach((q, k) => { if (!measurable(q.sort))
|
|
715
|
+
return; const a = `a${k}`; nats.add(a); bounded(a, s.args[k], q.sort); post[slot(s.to, k)] = { [a]: 1 }; });
|
|
716
|
+
names.forEach(x => nats.add(x));
|
|
717
|
+
paths.push({ rows, pins: { $fn: s.from }, post });
|
|
718
|
+
from.push(s.from);
|
|
719
|
+
to.push(s.to);
|
|
720
|
+
}
|
|
721
|
+
if (!paths.length)
|
|
722
|
+
return undefined;
|
|
723
|
+
return { paths, ints: new Map(), nats: [...nats], state, params: [], loc: '$fn', from, to, exact: false };
|
|
724
|
+
}
|
|
725
|
+
function candidates(ring, edges, sites, until) {
|
|
726
|
+
if (ring.some(f => f.stated))
|
|
727
|
+
return [ring.map(f => f.stated ?? { comps: [{ coef: f.params.map(() => 0), c: 0 }] })];
|
|
728
|
+
const out = [];
|
|
729
|
+
if (ring.length === 1) {
|
|
730
|
+
const fn = ring[0], ix = fn.params.flatMap((p, i) => (measurable(p.sort) ? [i] : []));
|
|
731
|
+
const one = (i) => ({ coef: fn.params.map((_, j) => (j === i ? 1 : 0)), c: 0 }), sum = (is) => ({ coef: fn.params.map((_, j) => (is.includes(j) ? 1 : 0)), c: 0 });
|
|
732
|
+
const ms = ix.map(i => ({ comps: [one(i)] }));
|
|
618
733
|
for (const i of ix)
|
|
619
734
|
for (const j of ix)
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
735
|
+
if (i !== j)
|
|
736
|
+
ms.push({ comps: [one(i), one(j)] });
|
|
737
|
+
for (const [a, i] of ix.entries())
|
|
738
|
+
for (const j of ix.slice(a + 1))
|
|
739
|
+
ms.push({ comps: [sum([i, j])] });
|
|
740
|
+
if (ix.length <= 4)
|
|
741
|
+
for (const i of ix)
|
|
742
|
+
for (const j of ix)
|
|
743
|
+
for (const k2 of ix)
|
|
744
|
+
if (i !== j && j !== k2 && i !== k2)
|
|
745
|
+
ms.push({ comps: [one(i), one(j), one(k2)] });
|
|
746
|
+
if (ix.length > 2)
|
|
747
|
+
ms.push({ comps: [sum(ix)] });
|
|
748
|
+
out.push(...ms.map(m => [m]));
|
|
631
749
|
}
|
|
632
|
-
|
|
750
|
+
// The LP's rank over the runs (coefficients and constants), a node per function, where the runs give edges; for a ring,
|
|
751
|
+
// after the relation's.
|
|
752
|
+
const fromRuns = () => {
|
|
753
|
+
if (!edges.length)
|
|
754
|
+
return undefined;
|
|
755
|
+
const vars = ring.map((f, i) => f.params.flatMap((q, j) => (measurable(q.sort) ? [`p${i}_${j}`] : [])));
|
|
756
|
+
const env = (i, xs) => Object.fromEntries(vars[i].map(x => [x, xs[Number(x.split('_')[1])]]));
|
|
757
|
+
const r = ranksOfCalls(vars, edges.flatMap(e => [{ node: e.from, env: env(e.from, e.s) }, { node: e.to, env: env(e.to, e.t) }]), edges.map(e => ({ from: e.from, to: e.to, s: env(e.from, e.s), t: env(e.to, e.t) })));
|
|
758
|
+
if (r.left || !r.comps.length)
|
|
759
|
+
return undefined;
|
|
760
|
+
return ring.map((f, i) => ({ comps: r.comps.map(c => ({ coef: f.params.map((_, j) => c[i].coef[`p${i}_${j}`] ?? 0), c: c[i].c })) }));
|
|
761
|
+
};
|
|
762
|
+
// The relation's rank: per location (each function), its components' forms over the function's parameters' sizes.
|
|
763
|
+
const fromRelation = () => {
|
|
764
|
+
const rel = callRelation(ring, sites);
|
|
765
|
+
if (!rel)
|
|
766
|
+
return undefined;
|
|
767
|
+
const r = rankOfPaths(ring.map(f => f.name).join(', '), rel, Math.min(until, clock() + 2000));
|
|
768
|
+
if (!('forms' in r) || !r.forms.length)
|
|
769
|
+
return undefined;
|
|
770
|
+
const ms = ring.map((f, i) => {
|
|
771
|
+
const n = r.values.indexOf(i);
|
|
772
|
+
return n < 0 ? { comps: r.forms.map(() => ({ coef: f.params.map(() => 0), c: 0 })) } : { comps: r.forms.map(col => ({ coef: f.params.map((_, k) => col[n][`s${i}_${k}`] ?? 0), c: col[n]['1'] ?? 0 })) };
|
|
773
|
+
});
|
|
774
|
+
// (a form that reads another function's parameters isn't a measure of this one's)
|
|
775
|
+
return r.forms.every(col => col.every((l, n) => Object.keys(l).every(x => x === '1' || x.startsWith(`s${r.values[n]}_`)))) ? ms : undefined;
|
|
776
|
+
};
|
|
777
|
+
const runs = ring.length === 1 ? fromRuns() : undefined;
|
|
778
|
+
if (runs)
|
|
779
|
+
out.push(runs);
|
|
780
|
+
const rel = fromRelation();
|
|
781
|
+
if (rel)
|
|
782
|
+
out.push(rel);
|
|
783
|
+
const runs2 = ring.length > 1 ? fromRuns() : undefined;
|
|
784
|
+
if (runs2)
|
|
785
|
+
out.push(runs2);
|
|
786
|
+
// (a ring's last: each function the sum of its parameters' sizes)
|
|
787
|
+
if (ring.length > 1)
|
|
788
|
+
out.push(ring.map(f => ({ comps: [{ coef: f.params.map(q => (measurable(q.sort) ? 1 : 0)), c: 0 }] })));
|
|
789
|
+
return out.map(ms => padded(ring, ms));
|
|
633
790
|
}
|
|
634
791
|
// An obligation as one node of a cyclic proof (no use, no models): its conclusion, each definition it reads unfolded
|
|
635
792
|
// once, the constructors' facts at the values built, the shape at each size it reads and at its variables of a
|
|
@@ -651,70 +808,104 @@ function directly(law, ms) {
|
|
|
651
808
|
pairedKeys.skip = was;
|
|
652
809
|
}
|
|
653
810
|
}
|
|
654
|
-
|
|
811
|
+
// Each call's obligation under measures given, proven (`obligations`, each function's) or the first that isn't (`failed`).
|
|
812
|
+
function proveMeasures(ring, sites, ms, until) {
|
|
813
|
+
const names = ring.map(f => f.name), text = ringText(ring, ms);
|
|
814
|
+
const nth = sites.map((s, i) => sites.slice(0, i).filter(r => r.from === s.from).length);
|
|
815
|
+
const obligations = ring.map(() => []);
|
|
816
|
+
for (const [i, site] of sites.entries()) {
|
|
817
|
+
const law = obligation(ring, ms, site, nth[i]), call = `${ring.length > 1 ? `${names[site.from]}'s ` : ''}call ${nth[i] + 1}`;
|
|
818
|
+
// (no call of the ring in it: refused before)
|
|
819
|
+
walk(law.holds, o => { if (o.op === 'call' && names.includes(o.fn))
|
|
820
|
+
throw new Error(`${law.name} reads the ring`); });
|
|
821
|
+
// First one node, the definitions unfolded once (most calls lower the measure by their cases alone); then, where its
|
|
822
|
+
// call is on a function of the argument, size laws about those functions proven by induction and used; else, or
|
|
823
|
+
// then, proveData: by induction where the obligation has a scheme (a call on a filter of the tail: the filter's own
|
|
824
|
+
// recursion), else, or then, the definitions unfolded alone.
|
|
825
|
+
const left = () => Math.max(1, until - clock()), cex = refute(law, 200);
|
|
826
|
+
if (cex)
|
|
827
|
+
return { failed: `${text}: its ${call} doesn't lower it at ${JSON.stringify(cex)}` };
|
|
828
|
+
const direct = directly(law, Math.min(2000, left()));
|
|
829
|
+
if (direct) {
|
|
830
|
+
obligations[site.from].push({ law, proof: direct, lemmas: [] });
|
|
831
|
+
continue;
|
|
832
|
+
}
|
|
833
|
+
// (the size laws first, each proven once and used, within 60% of the time left; then proveData without conjectured
|
|
834
|
+
// lemmas, whose making isn't counted in the budget: by induction, then the definitions unfolded alone)
|
|
835
|
+
const inductive = schemes(programOf([law]), law).length > 0, lemmas = sizeLaws(law, names);
|
|
836
|
+
if (dataTrace && lemmas.length)
|
|
837
|
+
console.error(`[data] ${law.name}: ${lemmas.map(c => c.name).join('; ')}`);
|
|
838
|
+
let v = lemmas.length ? proveData(law, { lemmas, lemmasFirst: true, ms: Math.min(8000, 0.6 * left()) }) : undefined;
|
|
839
|
+
if (!v?.proven && !v?.counterexample && inductive && clock() < until)
|
|
840
|
+
v = proveData(law, { ms: Math.min(12_000, left()), lemmas: false });
|
|
841
|
+
if (!v?.proven && !v?.counterexample && clock() < until)
|
|
842
|
+
v = proveData(law, { induction: false, ms: Math.min(4000, left()) });
|
|
843
|
+
if (!v || !(v.proven && v.checked))
|
|
844
|
+
return { failed: `${text}: its ${call} ${v?.counterexample ? `doesn't lower it at ${JSON.stringify(v.counterexample)}` : 'not proven to lower it'}` };
|
|
845
|
+
const used = v;
|
|
846
|
+
obligations[site.from].push({ law, proof: used.proof, scheme: used.scheme, lemmas: used.lemmas, lemmaLaws: lemmas.filter(c => used.lemmas.includes(c.name)) });
|
|
847
|
+
}
|
|
848
|
+
return { obligations };
|
|
849
|
+
}
|
|
850
|
+
// A ring's calls, refused where one is nested in another's argument or condition (its obligation would read a function
|
|
851
|
+
// being taken).
|
|
852
|
+
function ringSites(ring, why) {
|
|
853
|
+
const names = ring.map(f => f.name), sites = callSites(ring);
|
|
854
|
+
for (const st of sites) {
|
|
855
|
+
let nested = false;
|
|
856
|
+
walk([st.args, st.wrap(no.y)], o => { if (o.op === 'call' && names.includes(o.fn))
|
|
857
|
+
nested = true; });
|
|
858
|
+
if (nested)
|
|
859
|
+
throw new Error(`${why}, and a call to ${ring.length > 1 ? 'its ring' : 'itself'} is nested in the argument or the condition of another (nested recursion isn't taken)`);
|
|
860
|
+
}
|
|
861
|
+
return sites;
|
|
862
|
+
}
|
|
863
|
+
// Measures given to a ring (or a function) checked as `termination` checks the one it takes: each call's obligation
|
|
864
|
+
// proven by the kernel, within the counted budget; nothing is taken (core/conformance.ts: tampered measures refused).
|
|
865
|
+
export function checkMeasures(fns, ms, budget = terminationMs.ms) {
|
|
866
|
+
return counted(dataRate, () => {
|
|
867
|
+
const r = proveMeasures(fns, ringSites(fns, fns.map(f => f.name).join(', ')), padded(fns, ms), clock() + budget);
|
|
868
|
+
return 'failed' in r ? { proven: false, why: r.failed } : { proven: true, obligations: r.obligations };
|
|
869
|
+
});
|
|
870
|
+
}
|
|
871
|
+
// The ring's measures and each call's proof, or a refusal with the measures tried. A ring of one is a function.
|
|
872
|
+
function termination(ring, why) {
|
|
655
873
|
return counted(dataRate, () => {
|
|
874
|
+
const names = ring.map(f => f.name);
|
|
656
875
|
if (dataTrace)
|
|
657
|
-
console.error(`[data] termination of ${
|
|
658
|
-
const t0 = performance.now()
|
|
659
|
-
if (!
|
|
660
|
-
throw new Error(`${why}, and it has no parameter a measure reads (a natural or a datatype value)`);
|
|
876
|
+
console.error(`[data] termination of ${names.join(', ')}`);
|
|
877
|
+
const t0 = performance.now();
|
|
878
|
+
if (!ring.some(f => f.params.some(p => measurable(p.sort))))
|
|
879
|
+
throw new Error(`${why}, and ${ring.length === 1 ? 'it has' : 'its ring has'} no parameter a measure reads (a natural or a datatype value)`);
|
|
880
|
+
const sites = ringSites(ring, why);
|
|
661
881
|
if (dataTrace)
|
|
662
882
|
console.error(`[data] ${sites.length} calls`);
|
|
663
|
-
const edges = runEdges(
|
|
883
|
+
const edges = runEdges(ring), until = clock() + terminationMs.ms * ring.length, tried = [], seen = new Set();
|
|
664
884
|
if (dataTrace)
|
|
665
885
|
console.error(`[data] its runs: ${edges.length} calls at ${Math.round(performance.now() - t0)} ms`);
|
|
666
|
-
for (const
|
|
886
|
+
for (const ms of candidates(ring, edges, sites, until)) {
|
|
887
|
+
const text = ringText(ring, ms);
|
|
667
888
|
if (dataTrace)
|
|
668
|
-
console.error(`[data] ${
|
|
889
|
+
console.error(`[data] ${text} at ${Math.round(performance.now() - t0)} ms`);
|
|
669
890
|
if (clock() > until) {
|
|
670
891
|
tried.push('out of time');
|
|
671
892
|
break;
|
|
672
893
|
}
|
|
673
|
-
const
|
|
894
|
+
const bad = edges.find(e => !lowers(ms, e));
|
|
674
895
|
if (seen.has(text))
|
|
675
896
|
continue;
|
|
676
897
|
seen.add(text);
|
|
677
898
|
if (bad) {
|
|
678
|
-
if (
|
|
679
|
-
tried.push(`${text}: a call of its runs doesn't lower it (from ${JSON.stringify(bad.s)} to ${JSON.stringify(bad.t)}, the parameters' sizes)`);
|
|
899
|
+
if (ring.some(f => f.stated) || !tried.length)
|
|
900
|
+
tried.push(`${text}: a call of its runs doesn't lower it (from ${JSON.stringify(bad.s)} to ${JSON.stringify(bad.t)}, the parameters' sizes${ring.length > 1 ? `, ${names[bad.from]} to ${names[bad.to]}` : ''})`);
|
|
680
901
|
continue;
|
|
681
902
|
}
|
|
682
|
-
const
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
// A call nested in its own argument or condition: the obligation would read the function being taken.
|
|
687
|
-
if (programOf([law]).fns.some(g => g.name === fn.name))
|
|
688
|
-
throw new Error(`${why}, and a call to itself is nested in the argument or the condition of another (nested recursion isn't taken)`);
|
|
689
|
-
// First one node, the definitions unfolded once (most calls lower the measure by their cases alone); else
|
|
690
|
-
// proveData: by induction where the obligation has a scheme (a call on a filter of the tail: the filter's own
|
|
691
|
-
// recursion), else, or then, the definitions unfolded alone.
|
|
692
|
-
const left = () => Math.max(1, until - clock()), cex = refute(law, 200);
|
|
693
|
-
if (cex) {
|
|
694
|
-
failed = `${text}: its call ${i + 1} doesn't lower it at ${JSON.stringify(cex)}`;
|
|
695
|
-
break;
|
|
696
|
-
}
|
|
697
|
-
const direct = directly(law, Math.min(2000, left()));
|
|
698
|
-
if (direct) {
|
|
699
|
-
obligations.push({ law, proof: direct, lemmas: [] });
|
|
700
|
-
continue;
|
|
701
|
-
}
|
|
702
|
-
const inductive = schemes(programOf([law]), law).length > 0;
|
|
703
|
-
// (no conjectured lemmas: their making isn't counted in the budget, and a call's decrease mostly needs none)
|
|
704
|
-
let v = proveData(law, inductive ? { ms: Math.min(12_000, left()), lemmas: false } : { induction: false, ms: Math.min(4000, left()) });
|
|
705
|
-
if (inductive && !(v.proven && v.checked) && !v.counterexample && clock() < until)
|
|
706
|
-
v = proveData(law, { induction: false, ms: Math.min(4000, left()) });
|
|
707
|
-
if (!(v.proven && v.checked)) {
|
|
708
|
-
failed = `${text}: its call ${i + 1} ${v.counterexample ? `doesn't lower it at ${JSON.stringify(v.counterexample)}` : 'not proven to lower it'}`;
|
|
709
|
-
break;
|
|
710
|
-
}
|
|
711
|
-
obligations.push({ law, proof: v.proof, scheme: v.scheme, lemmas: v.lemmas });
|
|
712
|
-
}
|
|
713
|
-
if (!failed)
|
|
714
|
-
return { measure: m, text, obligations, ms: Math.round(performance.now() - t0) };
|
|
715
|
-
tried.push(failed);
|
|
903
|
+
const r = proveMeasures(ring, sites, ms, until);
|
|
904
|
+
if ('obligations' in r)
|
|
905
|
+
return ring.map((f, i) => ({ measure: ms[i], text: showMeasure(f, ms[i]), obligations: r.obligations[i], ms: Math.round(performance.now() - t0) }));
|
|
906
|
+
tried.push(r.failed);
|
|
716
907
|
}
|
|
717
|
-
throw new Error(`${why}, and no measure is proven to fall at every call${tried.length ? ` (${tried.slice(0, 3).join('; ')})` : ''}`);
|
|
908
|
+
throw new Error(`${why}, and no measure is proven to fall at every call${ring.length > 1 ? ' within the ring' : ''}${tried.length ? ` (${tried.slice(0, 3).join('; ')})` : ' (no measure found to try)'}`);
|
|
718
909
|
});
|
|
719
910
|
}
|
|
720
911
|
export function law(name, vars, holds) {
|
|
@@ -794,16 +985,17 @@ export function evalX(x, env, params, d = 0) {
|
|
|
794
985
|
if (d >= evalBounds.depth || ++evalCalls > evalBounds.calls)
|
|
795
986
|
throw new EvalLimit(`${f.name}: past the evaluation's bounds`);
|
|
796
987
|
}
|
|
797
|
-
|
|
988
|
+
const at = tracing?.fns.get(f.name);
|
|
989
|
+
if (at === undefined)
|
|
798
990
|
return evalX(body, e2, params, d + 1);
|
|
799
|
-
// A run of a
|
|
991
|
+
// A run of a ring whose termination is being proven: each call within it recorded, the run cut past its fuel.
|
|
800
992
|
const t = tracing;
|
|
801
993
|
if (--t.fuel < 0)
|
|
802
994
|
throw new RangeError('out of fuel');
|
|
803
|
-
const top = t.stack.at(-1);
|
|
995
|
+
const top = t.stack.at(-1), frame = { at, vals };
|
|
804
996
|
if (top)
|
|
805
|
-
t.edge(top,
|
|
806
|
-
t.stack.push(
|
|
997
|
+
t.edge(top, frame);
|
|
998
|
+
t.stack.push(frame);
|
|
807
999
|
try {
|
|
808
1000
|
return evalX(body, e2, params, d + 1);
|
|
809
1001
|
}
|
|
@@ -1502,7 +1694,7 @@ function unfoldAt(f) {
|
|
|
1502
1694
|
// The inductions the search tries for a law (its schemes), for tests.
|
|
1503
1695
|
export const schemesOf = (p, l) => schemes(p, l);
|
|
1504
1696
|
function schemes(p, l) {
|
|
1505
|
-
const out = [], seen = new Set();
|
|
1697
|
+
const out = [], seen = new Set(), halves = [];
|
|
1506
1698
|
const add = (s) => { const id = JSON.stringify(s.uses); if (!seen.has(id)) {
|
|
1507
1699
|
seen.add(id);
|
|
1508
1700
|
out.push(s);
|
|
@@ -1521,36 +1713,51 @@ function schemes(p, l) {
|
|
|
1521
1713
|
if (!m && (at.op !== 'var' || !l.vars.some(v => v.name === at.name)))
|
|
1522
1714
|
return;
|
|
1523
1715
|
const d = f.params[f.decreases ?? 0].sort;
|
|
1524
|
-
const
|
|
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;
|
|
1525
1724
|
const uses = [];
|
|
1526
|
-
|
|
1725
|
+
// (`through`: the functions of f's ring whose bodies are read in place of their calls, once each: evens through
|
|
1726
|
+
// odds, which call each other, is recursion of evens at the tail's tail)
|
|
1727
|
+
const go = (x, env, guard, through = new Set()) => {
|
|
1527
1728
|
if (!x || typeof x !== 'object')
|
|
1528
1729
|
return;
|
|
1529
1730
|
if (Array.isArray(x)) {
|
|
1530
|
-
x.forEach(y => go(y, env, guard));
|
|
1731
|
+
x.forEach(y => go(y, env, guard, through));
|
|
1531
1732
|
return;
|
|
1532
1733
|
}
|
|
1533
1734
|
const t = x;
|
|
1735
|
+
if (t.op === 'call' && t.fn !== f.name && f.ring.includes(t.fn) && !through.has(t.fn)) {
|
|
1736
|
+
const g = fnOf(t.fn);
|
|
1737
|
+
go(t.args, env, guard, through);
|
|
1738
|
+
go(g.body(), new Map([...env, ...g.params.map((q, i) => [`${g.name}.${q.name}`, encX(p, t.args[i], env)])]), guard, new Set([...through, t.fn]));
|
|
1739
|
+
return;
|
|
1740
|
+
}
|
|
1534
1741
|
if (t.op === 'match') {
|
|
1535
|
-
go(t.of, env, guard);
|
|
1742
|
+
go(t.of, env, guard, through);
|
|
1536
1743
|
const dd = dataOf(p, t.data), of = encX(p, t.of, env);
|
|
1537
|
-
t.cases.forEach((c, j) => { const e2 = new Map(env); c.binds.forEach((b, i) => e2.set(b, get(fieldMap(dd, j, i), of))); go(c.body, e2, [...guard, eqC(get(tagMap(dd.name), of), k(j))]); });
|
|
1744
|
+
t.cases.forEach((c, j) => { const e2 = new Map(env); c.binds.forEach((b, i) => e2.set(b, get(fieldMap(dd, j, i), of))); go(c.body, e2, [...guard, eqC(get(tagMap(dd.name), of), k(j))], through); });
|
|
1538
1745
|
return;
|
|
1539
1746
|
}
|
|
1540
1747
|
if (t.op === 'natmatch') {
|
|
1541
|
-
go(t.of, env, guard);
|
|
1748
|
+
go(t.of, env, guard, through);
|
|
1542
1749
|
const of = encX(p, t.of, env), e2 = new Map(env);
|
|
1543
|
-
go(t.zero, env, [...guard, eqC(of, k(0))]);
|
|
1750
|
+
go(t.zero, env, [...guard, eqC(of, k(0))], through);
|
|
1544
1751
|
e2.set(t.pred, { op: 'sub', a: of, b: k(1) });
|
|
1545
|
-
go(t.succ, e2, [...guard, { op: 'not', x: eqC(of, k(0)) }]);
|
|
1752
|
+
go(t.succ, e2, [...guard, { op: 'not', x: eqC(of, k(0)) }], through);
|
|
1546
1753
|
return;
|
|
1547
1754
|
}
|
|
1548
1755
|
// (a well-founded call's descent may need its if's condition: x − y below x where y ≤ x)
|
|
1549
1756
|
if (m && t.op === 'if') {
|
|
1550
1757
|
const c = encY(p, t.c, env);
|
|
1551
|
-
go(t.c, env, guard);
|
|
1552
|
-
go(t.then, env, [...guard, c]);
|
|
1553
|
-
go(t.else, env, [...guard, { op: 'not', x: c }]);
|
|
1758
|
+
go(t.c, env, guard, through);
|
|
1759
|
+
go(t.then, env, [...guard, c], through);
|
|
1760
|
+
go(t.else, env, [...guard, { op: 'not', x: c }], through);
|
|
1554
1761
|
return;
|
|
1555
1762
|
}
|
|
1556
1763
|
if (t.op === 'call' && t.fn === f.name) {
|
|
@@ -1559,7 +1766,12 @@ function schemes(p, l) {
|
|
|
1559
1766
|
t.args.forEach((a, i) => {
|
|
1560
1767
|
const lv = args[i];
|
|
1561
1768
|
if (lv.op !== 'var' || !l.vars.some(v => v.name === lv.name)) {
|
|
1562
|
-
|
|
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
|
+
}
|
|
1563
1775
|
return;
|
|
1564
1776
|
}
|
|
1565
1777
|
const e = encX(p, a, env);
|
|
@@ -1570,14 +1782,18 @@ function schemes(p, l) {
|
|
|
1570
1782
|
uses.push({ subst, guard: andC(yesC, ...guard) });
|
|
1571
1783
|
}
|
|
1572
1784
|
for (const v of Object.values(t))
|
|
1573
|
-
go(v, env, guard);
|
|
1785
|
+
go(v, env, guard, through);
|
|
1574
1786
|
};
|
|
1575
1787
|
const env = new Map([...formal].flatMap(([key, e]) => (e ? [[key, e]] : [])));
|
|
1576
1788
|
go(f.body(), env, []);
|
|
1577
1789
|
if (!uses.length)
|
|
1578
1790
|
return;
|
|
1579
1791
|
if (!m) {
|
|
1580
|
-
|
|
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);
|
|
1581
1797
|
return;
|
|
1582
1798
|
}
|
|
1583
1799
|
// Well-founded: ranked by the measure at the law's arguments; the law's variables it reads named.
|
|
@@ -1597,6 +1813,35 @@ function schemes(p, l) {
|
|
|
1597
1813
|
}
|
|
1598
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)) }] : []))) });
|
|
1599
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
|
+
}
|
|
1600
1845
|
return out;
|
|
1601
1846
|
}
|
|
1602
1847
|
function instancesOf(p, fs, w) {
|
|
@@ -1679,12 +1924,17 @@ function instancesOf(p, fs, w) {
|
|
|
1679
1924
|
};
|
|
1680
1925
|
ariths();
|
|
1681
1926
|
lap(`unfolded, ${insts.length} instances, ${all.length} reads`);
|
|
1682
|
-
|
|
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) => {
|
|
1683
1933
|
const parent = new Map(), terms = new Map(), adj = new Map();
|
|
1684
1934
|
const find = (x) => { let r = x; while (parent.has(r))
|
|
1685
1935
|
r = parent.get(r); return r; };
|
|
1686
1936
|
const linked = new Set();
|
|
1687
|
-
const edge = (x, y, cong) => {
|
|
1937
|
+
const edge = (x, y, cong, twin) => {
|
|
1688
1938
|
const a2 = tid(x), b2 = tid(y);
|
|
1689
1939
|
terms.set(a2, x);
|
|
1690
1940
|
terms.set(b2, y);
|
|
@@ -1697,8 +1947,8 @@ function instancesOf(p, fs, w) {
|
|
|
1697
1947
|
linked.add(a2 < b2 ? `${a2}|${b2}` : `${b2}|${a2}`);
|
|
1698
1948
|
if (merged)
|
|
1699
1949
|
parent.set(find(a2), find(b2));
|
|
1700
|
-
(adj.get(a2) ?? adj.set(a2, []).get(a2)).push({ to: b2, cong });
|
|
1701
|
-
(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 });
|
|
1702
1952
|
return merged;
|
|
1703
1953
|
};
|
|
1704
1954
|
const truthOf = (c) => { if (!model)
|
|
@@ -1740,6 +1990,9 @@ function instancesOf(p, fs, w) {
|
|
|
1740
1990
|
active(holdsAt(fs.facts[q.fact].name, q.at));
|
|
1741
1991
|
for (const c of w.others)
|
|
1742
1992
|
active(c);
|
|
1993
|
+
for (const c of w.hyps ?? [])
|
|
1994
|
+
if (c.op === '=')
|
|
1995
|
+
edge(c.a, c.b);
|
|
1743
1996
|
const cells = new Map();
|
|
1744
1997
|
for (const r of all) {
|
|
1745
1998
|
const n = fs.arity.get(r.map), as = n ? argsOf(r.key, n) : undefined;
|
|
@@ -1749,10 +2002,22 @@ function instancesOf(p, fs, w) {
|
|
|
1749
2002
|
// Arguments equal by arithmetic alone, one class: (n + 1) ∸ 1 and n (a successor's predecessor, where a definition
|
|
1750
2003
|
// on the naturals is unfolded at n + 1), so their reads meet by congruence. The kernel proves the equality itself.
|
|
1751
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)));
|
|
1752
2017
|
for (const list of cells.values())
|
|
1753
2018
|
for (const x of list)
|
|
1754
2019
|
for (const t of x.as) {
|
|
1755
|
-
const f = linearForm(t);
|
|
2020
|
+
const f = linearForm(t, at, known);
|
|
1756
2021
|
if (f === undefined)
|
|
1757
2022
|
continue;
|
|
1758
2023
|
const had = byForm.get(f);
|
|
@@ -1761,6 +2026,40 @@ function instancesOf(p, fs, w) {
|
|
|
1761
2026
|
else if (tid(had) !== tid(t))
|
|
1762
2027
|
edge(had, t);
|
|
1763
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
|
+
}
|
|
1764
2063
|
for (let changed = true; changed && !late();) {
|
|
1765
2064
|
changed = false;
|
|
1766
2065
|
for (const [map, list] of cells) {
|
|
@@ -1859,6 +2158,28 @@ function instancesOf(p, fs, w) {
|
|
|
1859
2158
|
for (const d of p.datas)
|
|
1860
2159
|
if (r.map === sizeMap(d.name))
|
|
1861
2160
|
shape(r.key, d);
|
|
2161
|
+
// Where it does, the sizes those shapes read in turn (a field's, a value built's), `depth` rounds: size(x) is 1 plus
|
|
2162
|
+
// its tail's, and the tail's size is its own shape's (a size law of a recursion two fields deep).
|
|
2163
|
+
{
|
|
2164
|
+
const sizeOf = (r) => p.datas.find(d => r.map === sizeMap(d.name));
|
|
2165
|
+
let todo = reads([w.roots, w.others]).filter(r => sizeOf(r)).map(r => r.key);
|
|
2166
|
+
const shaped = new Set(todo.map(t => sid(t)));
|
|
2167
|
+
for (let round = 0; round < w.depth && todo.length; round++) {
|
|
2168
|
+
const next = [];
|
|
2169
|
+
for (const t of todo) {
|
|
2170
|
+
const d = sizeOf({ map: (reads([w.roots, w.others]).find(r => sid(r.key) === sid(t) && sizeOf(r)) ?? { map: '' }).map }) ?? dataOfTerm(t);
|
|
2171
|
+
if (!d)
|
|
2172
|
+
continue;
|
|
2173
|
+
for (const r of reads(holdsAt(`shape ${d.name}`, [t])))
|
|
2174
|
+
if (sizeOf(r) && !shaped.has(sid(r.key))) {
|
|
2175
|
+
shaped.add(sid(r.key));
|
|
2176
|
+
shape(r.key, sizeOf(r));
|
|
2177
|
+
next.push(r.key);
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
todo = next;
|
|
2181
|
+
}
|
|
2182
|
+
}
|
|
1862
2183
|
if (w.depth >= 2)
|
|
1863
2184
|
for (const r of [...all])
|
|
1864
2185
|
for (const d of p.datas)
|
|
@@ -1886,7 +2207,7 @@ function instancesOf(p, fs, w) {
|
|
|
1886
2207
|
for (const model of w.models) {
|
|
1887
2208
|
if (late())
|
|
1888
2209
|
break;
|
|
1889
|
-
const { find, adj, truthOf } = closure(model);
|
|
2210
|
+
const { find, adj, truthOf } = closure(model, true);
|
|
1890
2211
|
const counted = new Set(), explained = new Set();
|
|
1891
2212
|
const explain = (a2, b2) => {
|
|
1892
2213
|
const key = a2 < b2 ? `${a2}|${b2}` : `${b2}|${a2}`;
|
|
@@ -1897,7 +2218,8 @@ function instancesOf(p, fs, w) {
|
|
|
1897
2218
|
// A path through no constant first: two terms the model gives one value aren't equal for that alone (each needs
|
|
1898
2219
|
// its own facts), and a congruence between them is what the proof can use; else one through a constant.
|
|
1899
2220
|
const isConst = (x) => x !== a2 && x !== b2 && x.startsWith('{"op":"const"');
|
|
1900
|
-
|
|
2221
|
+
// (and through no twins, where the facts give a path)
|
|
2222
|
+
for (const [avoid, noTwin] of [[true, true], [false, true], [false, false]]) {
|
|
1901
2223
|
if (back.has(b2))
|
|
1902
2224
|
break;
|
|
1903
2225
|
back.clear();
|
|
@@ -1909,7 +2231,7 @@ function instancesOf(p, fs, w) {
|
|
|
1909
2231
|
if (avoid && isConst(x))
|
|
1910
2232
|
continue;
|
|
1911
2233
|
for (const e of adj.get(x) ?? [])
|
|
1912
|
-
if (!back.has(e.to)) {
|
|
2234
|
+
if (!back.has(e.to) && !(noTwin && e.twin)) {
|
|
1913
2235
|
back.set(e.to, { from: x, cong: e.cong });
|
|
1914
2236
|
queue.push(e.to);
|
|
1915
2237
|
}
|
|
@@ -2058,12 +2380,18 @@ const sid = (t) => {
|
|
|
2058
2380
|
const tid = (t) => sid(t);
|
|
2059
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
|
|
2060
2382
|
// truncated difference by a constant only where the constant is at most the term's (x + 1 ∸ 1 is x); else undefined.
|
|
2061
|
-
|
|
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) {
|
|
2062
2387
|
const go = (t) => {
|
|
2063
2388
|
switch (t.op) {
|
|
2064
2389
|
case 'const': return { cs: new Map(), c: t.value };
|
|
2065
2390
|
case 'var':
|
|
2066
|
-
case 'get':
|
|
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
|
+
}
|
|
2067
2395
|
case 'add': {
|
|
2068
2396
|
const a = go(t.a), b = go(t.b);
|
|
2069
2397
|
if (!a || !b)
|
|
@@ -2079,7 +2407,17 @@ function linearForm(e) {
|
|
|
2079
2407
|
}
|
|
2080
2408
|
case 'sub': {
|
|
2081
2409
|
const a = go(t.a);
|
|
2082
|
-
|
|
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 };
|
|
2083
2421
|
}
|
|
2084
2422
|
case 'if':
|
|
2085
2423
|
case 'min':
|
|
@@ -2189,6 +2527,9 @@ function valuesCompared(p, l) {
|
|
|
2189
2527
|
}
|
|
2190
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
|
|
2191
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 };
|
|
2192
2533
|
function matches(pattern, vars, t, s) {
|
|
2193
2534
|
if (pattern.op === 'var' && vars.has(pattern.name)) {
|
|
2194
2535
|
const had = s[pattern.name];
|
|
@@ -2196,6 +2537,19 @@ function matches(pattern, vars, t, s) {
|
|
|
2196
2537
|
return sid(had) === sid(t) ? s : undefined;
|
|
2197
2538
|
return { ...s, [pattern.name]: t };
|
|
2198
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
|
+
}
|
|
2199
2553
|
if (pattern.op !== t.op)
|
|
2200
2554
|
return undefined;
|
|
2201
2555
|
const po = pattern, to = t;
|
|
@@ -2218,7 +2572,8 @@ function matches(pattern, vars, t, s) {
|
|
|
2218
2572
|
return out;
|
|
2219
2573
|
}
|
|
2220
2574
|
function casesOf(p, unfolded, vars, models) {
|
|
2221
|
-
|
|
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)
|
|
2222
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);
|
|
2223
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);
|
|
2224
2579
|
// The functions' facts the goal unfolds.
|
|
@@ -2284,6 +2639,8 @@ function casesOf(p, unfolded, vars, models) {
|
|
|
2284
2639
|
const dataTrace = !!globalThis.process?.env?.DATA_TRACE;
|
|
2285
2640
|
// Debugging: every congruence a model's closure makes, not only those explanations use.
|
|
2286
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;
|
|
2287
2644
|
function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
|
|
2288
2645
|
const t0 = clock();
|
|
2289
2646
|
anchoredAt.clear();
|
|
@@ -2319,14 +2676,14 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
|
|
|
2319
2676
|
// Uses of the lemmas, where a lemma's largest read matches a read of this goal (unfolded), its key up to the
|
|
2320
2677
|
// equalities the unfolded definitions give (any branch); twice over, the uses' own conclusions read the second time.
|
|
2321
2678
|
const pre = instancesOf(p, fs, { roots: [concl], others: ihConcls, depth, shapesAt, etaAt: [], models: [], until: t0 + attemptMs.ms });
|
|
2322
|
-
const lemmaUses = lemmaUsesFor(p, fs, lemmaNodes, [concl, ihConcls], pre, models);
|
|
2679
|
+
const spare = [], lemmaUses = lemmaUsesFor(p, fs, lemmaNodes, [concl, ihConcls], pre, models, spare);
|
|
2323
2680
|
const uses = [...ih, ...lemmaUses];
|
|
2324
2681
|
if (dataTrace)
|
|
2325
2682
|
for (const u of lemmaUses)
|
|
2326
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('; ')}`);
|
|
2327
2684
|
// The lemmas' conclusions are unfolded like the law's (they are what the goal reads, said another way); the cycle's
|
|
2328
2685
|
// own uses only from depth 3.
|
|
2329
|
-
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 });
|
|
2330
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) : [];
|
|
2331
2688
|
if (cases.length <= 1) {
|
|
2332
2689
|
// One node: four uses of a lemma, twelve in all, the best first (as lemmaUsesFor ranks them).
|
|
@@ -2350,9 +2707,13 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
|
|
|
2350
2707
|
catch {
|
|
2351
2708
|
return false;
|
|
2352
2709
|
} }); };
|
|
2353
|
-
|
|
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)];
|
|
2354
2715
|
const ms = few(c.models ?? c.near ?? models);
|
|
2355
|
-
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 });
|
|
2356
2717
|
}
|
|
2357
2718
|
plans.push(plan);
|
|
2358
2719
|
}
|
|
@@ -2497,7 +2858,8 @@ function reached(p, fs, insts, from, ms) {
|
|
|
2497
2858
|
}
|
|
2498
2859
|
// The uses of lemmas a goal's reads match: each lemma's largest reads (those inside no other) matched against the goal's
|
|
2499
2860
|
// reads of the same map at keys equal, by the instances' equations (every branch), to the read's key.
|
|
2500
|
-
|
|
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) {
|
|
2501
2863
|
const id = tid, parent = new Map(), terms = new Map();
|
|
2502
2864
|
const find = (x) => { let r = x; while (parent.has(r))
|
|
2503
2865
|
r = parent.get(r); return r; };
|
|
@@ -2552,70 +2914,95 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
|
|
|
2552
2914
|
const vars = new Set(lm.law.vars.map(v => v.name)), sides = [];
|
|
2553
2915
|
walk(encY(p, lm.law.holds, new Map()), o => { if (o.op === 'get')
|
|
2554
2916
|
sides.push(o); });
|
|
2555
|
-
const
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2586
|
-
let subs = [{}];
|
|
2587
|
-
for (const q of pats.keys()) {
|
|
2588
|
-
const ms = members(args[q]).slice(0, 256);
|
|
2589
|
-
subs = subs.flatMap(sb => ms.flatMap(m => { const r = matchAt(q, m, sb); return r ? [r] : []; })).slice(0, 512);
|
|
2590
|
-
}
|
|
2591
|
-
for (const sub of subs) {
|
|
2592
|
-
if (Object.keys(sub).length !== vars.size)
|
|
2593
|
-
continue;
|
|
2594
|
-
// Where a model gives the lemma's arguments the goal read's (a match through every branch's classes may be none).
|
|
2595
|
-
const there = pats.map(a => substE(a, { vars: sub, maps: {}, flags: {} }));
|
|
2596
|
-
const score = models.length ? models.filter(({ m, env }) => { try {
|
|
2597
|
-
return there.every((a, q) => m.evalE(a, env) === m.evalE(args[q], env));
|
|
2917
|
+
const tops0 = sides.filter(a => !sides.some(b => b !== a && JSON.stringify(b).includes(JSON.stringify(a))));
|
|
2918
|
+
// (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
|
|
2919
|
+
// every size the goal reads)
|
|
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))
|
|
2921
|
+
yes = true; }); return yes; };
|
|
2922
|
+
const tops = tops0.some(callsFn) ? tops0.filter(callsFn) : tops0;
|
|
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);
|
|
2598
2948
|
}
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
if (
|
|
2949
|
+
return out;
|
|
2950
|
+
};
|
|
2951
|
+
for (const t of reads) {
|
|
2952
|
+
if (t.op !== 'get' || t.map !== top.map)
|
|
2603
2953
|
continue;
|
|
2604
|
-
|
|
2605
|
-
if (
|
|
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)
|
|
2606
2960
|
continue;
|
|
2607
|
-
|
|
2608
|
-
const
|
|
2609
|
-
|
|
2610
|
-
|
|
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));
|
|
2611
2973
|
}
|
|
2612
2974
|
catch {
|
|
2613
|
-
return
|
|
2614
|
-
} })
|
|
2615
|
-
|
|
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
|
+
}
|
|
2616
2997
|
}
|
|
2617
2998
|
}
|
|
2618
2999
|
}
|
|
3000
|
+
fieldMatch.on = false;
|
|
3001
|
+
}
|
|
3002
|
+
if (hits) {
|
|
3003
|
+
for (const c of cands)
|
|
3004
|
+
hits.add(c.use.node);
|
|
3005
|
+
return [];
|
|
2619
3006
|
}
|
|
2620
3007
|
// First, as found: four of a lemma, twelve in all (the next round reads their conclusions). Then the rest, best first
|
|
2621
3008
|
// (the most models, then the smallest terms), one of each set of values, up to `perLemma` of a lemma and `total` in
|
|
@@ -2631,9 +3018,18 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
|
|
|
2631
3018
|
fresh.push(substC(lemmas.find(lm => lm.node === c.use.node).concl, { vars: c.use.subst, maps: {}, flags: {} }));
|
|
2632
3019
|
}
|
|
2633
3020
|
const rest = cands.filter(c => !first.has(c)).sort((a, b) => b.score - a.score || a.size - b.size);
|
|
2634
|
-
for (const c of rest)
|
|
2635
|
-
if (
|
|
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)
|
|
2636
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
|
+
}
|
|
2637
3033
|
// The second round: the reads of the first's conclusions, and the goal's again, matched up to the classes those
|
|
2638
3034
|
// conclusions join (assoc's use makes x ++ (y ++ [z]) and (x ++ y) ++ [z] one, where rev of a snoc then matches).
|
|
2639
3035
|
for (const c of fresh)
|
|
@@ -2646,8 +3042,9 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
|
|
|
2646
3042
|
return out;
|
|
2647
3043
|
}
|
|
2648
3044
|
// How many uses of lemmas a goal gets: the candidates kept (`perLemma` of each lemma, `total`), and of those a case node
|
|
2649
|
-
// keeps (`perCase` of each lemma, those its models meet)
|
|
2650
|
-
|
|
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 };
|
|
2651
3048
|
// A node's uses: the scheme's (the cycle's, read at nodes not yet placed) all, `perCase` of each lemma, `total` lemma
|
|
2652
3049
|
// uses in all, in the order given.
|
|
2653
3050
|
function capUses(uses, total = Infinity) {
|
|
@@ -2675,6 +3072,104 @@ function equalities(c) {
|
|
|
2675
3072
|
}
|
|
2676
3073
|
// A lemma use: the goal's read it matched, and the lemma's read there (equal where the use applies).
|
|
2677
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
|
+
}
|
|
2678
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]]))); };
|
|
2679
3174
|
// The models a search compares terms in: random values of the law's variables.
|
|
2680
3175
|
function modelsFor(p, l, n, seed) {
|
|
@@ -2691,7 +3186,8 @@ const settled = new WeakMap();
|
|
|
2691
3186
|
// `without`: 'plain', the law with no induction where no scheme applies; 'cases', no induction, then by the cases of
|
|
2692
3187
|
// each variable (a natural's zero and successor, a datatype's constructors), none of them using the law again; 'first',
|
|
2693
3188
|
// no induction before the schemes (a law that follows from its lemmas by rewriting).
|
|
2694
|
-
|
|
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) {
|
|
2695
3191
|
const models = modelsFor(p, l, 240, opts.seed ?? 3);
|
|
2696
3192
|
let tried = 0, last;
|
|
2697
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: [] }] : []));
|
|
@@ -2702,13 +3198,25 @@ function proveWith(p, fs, l, lemmas, level, opts, until, per, depths, without) {
|
|
|
2702
3198
|
for (const s of ss) {
|
|
2703
3199
|
if (clock() > until)
|
|
2704
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;
|
|
2705
3205
|
const key = JSON.stringify([l.name, s?.name, depth, level, lemmas.map(q => q.spec.name), opts.seed]);
|
|
2706
3206
|
if (done.has(key))
|
|
2707
3207
|
continue;
|
|
2708
3208
|
tried++;
|
|
2709
3209
|
const t1 = clock();
|
|
2710
|
-
|
|
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));
|
|
2711
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}`}`);
|
|
2712
3220
|
if (!(verdict.proven && verdict.checked) && clock() <= t1 + attemptMs.ms)
|
|
2713
3221
|
done.add(key);
|
|
2714
3222
|
if (verdict.proven && verdict.checked)
|
|
@@ -3048,6 +3556,421 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
|
|
|
3048
3556
|
}
|
|
3049
3557
|
return out;
|
|
3050
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
|
+
}
|
|
3051
3974
|
export const showX = (x) => {
|
|
3052
3975
|
switch (x.op) {
|
|
3053
3976
|
case 'var': return x.name.replace(/#\d+$/, '');
|
|
@@ -3163,7 +4086,7 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
3163
4086
|
if (c)
|
|
3164
4087
|
return c;
|
|
3165
4088
|
}
|
|
3166
|
-
const first = phase === 'rest' ? 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);
|
|
3167
4090
|
const one = first && ok(first, base);
|
|
3168
4091
|
if (one)
|
|
3169
4092
|
return one;
|
|
@@ -3180,24 +4103,37 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
3180
4103
|
if (two)
|
|
3181
4104
|
return two;
|
|
3182
4105
|
}
|
|
3183
|
-
|
|
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)}`);
|
|
3184
4114
|
const p2 = ctx ? p : programOf([l, ...cands]), fs2 = ctx ? fs : factsOf(p2);
|
|
3185
4115
|
// Each scheme's goals: the law's, and each companion's (a lemma may be what only a companion's goal reads).
|
|
3186
4116
|
const goalOf = (law, uses, on, concls, shapes) => {
|
|
3187
4117
|
const concl = encY(p2, law.holds, new Map()), ihc = uses.map(u => substC(concls[u.member ?? 0] ?? concl, { vars: u.subst, maps: {}, flags: {} }));
|
|
3188
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: [] }) };
|
|
3189
4119
|
};
|
|
3190
|
-
const goals = schemes(p2, l).flatMap(s => {
|
|
4120
|
+
const goals = schemes(p2, l).filter(s => !s.merged).flatMap(s => {
|
|
3191
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()));
|
|
3192
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));
|
|
3193
4123
|
});
|
|
3194
|
-
|
|
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));
|
|
3195
4129
|
// Those the goal matches first, of those the ones of the law's shape (an implication for an implication) first.
|
|
3196
4130
|
const implication = (y) => y.op === 'or' && y.xs.length === 2 && y.xs[0].op === 'not';
|
|
3197
4131
|
const score = (c, hit) => (hit ? 2 : 0) + (implication(c.holds) === implication(l.holds) ? 1 : 0);
|
|
3198
4132
|
if (dataTrace)
|
|
3199
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('')}`);
|
|
3200
|
-
|
|
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))];
|
|
3201
4137
|
// The lemmas proven: those given (`base`) and those found, each found one a level above the last.
|
|
3202
4138
|
const proven = [...base], failed = new Set(), level = () => lv + 1 + proven.length - base.length;
|
|
3203
4139
|
// A pass of lemmas: of those the goal reads (`hits`) or the others, each proven at one unfolding (8 s of counted work
|
|
@@ -3207,19 +4143,35 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
3207
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.
|
|
3208
4144
|
const refuted = new Set();
|
|
3209
4145
|
const lemmaPass = (which, most, end, cap, depths) => {
|
|
3210
|
-
|
|
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;
|
|
3211
4148
|
const again = (how) => ok(proveWith(p2, fs2, l, proven, level(), opts, until, cap, depths, how), proven, p2);
|
|
3212
|
-
|
|
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;) {
|
|
3213
4153
|
if (n >= most || tries >= 3 * most || clock() > end)
|
|
3214
4154
|
break;
|
|
3215
|
-
if (
|
|
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)
|
|
3216
4164
|
continue;
|
|
3217
|
-
if (refute(c, 200)) {
|
|
4165
|
+
if (!again2 && refute(c, 200)) {
|
|
3218
4166
|
refuted.add(c);
|
|
3219
4167
|
continue;
|
|
3220
4168
|
}
|
|
3221
|
-
|
|
3222
|
-
|
|
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]);
|
|
3223
4175
|
tried += r.tried;
|
|
3224
4176
|
if (!r.out) {
|
|
3225
4177
|
failed.add(c);
|
|
@@ -3229,7 +4181,15 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
3229
4181
|
proven.push(r.out);
|
|
3230
4182
|
n++;
|
|
3231
4183
|
since++;
|
|
3232
|
-
|
|
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;
|
|
3233
4193
|
if (which === 'hits' || implication(c.holds) === implication(l.holds)) {
|
|
3234
4194
|
since = 0;
|
|
3235
4195
|
const r2 = again('first');
|
|
@@ -3277,6 +4237,10 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
3277
4237
|
// No induction: the law by the cases of a variable (or none), its definitions unfolded.
|
|
3278
4238
|
() => ok(proveWith(p, fs, l, base, lv + 1, opts, until, 3000, [1, 2], 'cases'), base),
|
|
3279
4239
|
];
|
|
4240
|
+
// Lemmas first (a call's decrease from size laws): those the goal reads, the others, each proven and the law tried
|
|
4241
|
+
// again after it; then the law with every lemma proven, at two unfoldings.
|
|
4242
|
+
if (opts.lemmasFirst && Array.isArray(opts.lemmas))
|
|
4243
|
+
steps.splice(0, steps.length, () => lemmaPass('hits', 8, share(0.6), 6000, [1]), () => lemmaPass('others', 8, share(0.8), 6000, [1, 2]), () => ok(proveWith(p2, fs2, l, proven, level(), opts, until, 12000, [1, 2], 'first'), proven, p2));
|
|
3280
4244
|
for (const [i, step] of steps.entries()) {
|
|
3281
4245
|
if (clock() > until)
|
|
3282
4246
|
break;
|