gdp-wired 0.22.0 → 0.24.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 +27 -2
- package/dist/core/bmc.d.ts +49 -0
- package/dist/core/bmc.js +509 -0
- package/dist/core/check.d.ts +1 -1
- package/dist/core/check.js +19 -6
- package/dist/core/cycles.d.ts +38 -0
- package/dist/core/cycles.js +531 -43
- package/dist/core/data.d.ts +25 -1
- package/dist/core/data.js +984 -215
- package/dist/core/discover.js +8 -3
- package/dist/core/dsl.d.ts +17 -3
- package/dist/core/dsl.js +81 -15
- 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.js +518 -5
- package/dist/core/kind.d.ts +30 -0
- package/dist/core/kind.js +81 -0
- package/dist/core/nonterm.d.ts +34 -0
- package/dist/core/nonterm.js +610 -0
- package/dist/core/q.d.ts +17 -0
- package/dist/core/q.js +52 -0
- package/dist/core/rationals.d.ts +112 -0
- package/dist/core/rationals.js +281 -0
- package/dist/core/relation.d.ts +28 -0
- package/dist/core/relation.js +483 -0
- package/dist/core/solver.d.ts +5 -2
- package/dist/core/solver.js +65 -20
- package/dist/core/transfer.d.ts +3 -3
- package/dist/core/transfer.js +69 -42
- package/dist/core/xstate.d.ts +6 -0
- package/dist/core/xstate.js +70 -12
- package/dist/kernel/cdcl.d.ts +13 -0
- package/dist/kernel/cdcl.js +307 -236
- package/dist/kernel/kernel.d.ts +106 -0
- package/dist/kernel/kernel.js +342 -0
- package/dist/kernel/prove.js +14 -3
- package/dist/kernel/qprove.d.ts +18 -0
- package/dist/kernel/qprove.js +157 -0
- package/dist/kernel/reader.d.ts +14 -0
- package/dist/kernel/reader.js +102 -14
- package/dist/kernel/simplex.d.ts +4 -0
- package/dist/kernel/simplex.js +38 -11
- package/dist/lean-kernel/emit.d.ts +46 -1
- package/dist/lean-kernel/emit.js +125 -16
- package/dist/lean-kernel/library.js +4 -1
- package/dist/lean-kernel/qlean.d.ts +26 -0
- package/dist/lean-kernel/qlean.js +105 -0
- package/package.json +16 -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 } from "./cycles.js";
|
|
6
6
|
import { proveThrough, transferPlan } from "./transfer.js";
|
|
7
7
|
// --- sorts and the AST ------------------------------------------------------------------------------------------------
|
|
8
8
|
export const self = { self: true };
|
|
@@ -146,6 +146,8 @@ export class Data {
|
|
|
146
146
|
group;
|
|
147
147
|
ctors;
|
|
148
148
|
seq = ++declaredSeq;
|
|
149
|
+
// An abstract sort (`opaque`, below): its values read by equality alone.
|
|
150
|
+
abstract = false;
|
|
149
151
|
constructor(name, decl, group = [name]) {
|
|
150
152
|
this.name = name;
|
|
151
153
|
this.group = group;
|
|
@@ -312,6 +314,28 @@ function walk(t, f) {
|
|
|
312
314
|
for (const v of Object.values(o))
|
|
313
315
|
walk(v, f);
|
|
314
316
|
}
|
|
317
|
+
// Each object once, in walk's order (a term shared within another is visited where walk first reaches it).
|
|
318
|
+
function walkOnce(t, f, seen = new WeakSet()) {
|
|
319
|
+
if (!t || typeof t !== 'object' || seen.has(t))
|
|
320
|
+
return;
|
|
321
|
+
seen.add(t);
|
|
322
|
+
if (Array.isArray(t)) {
|
|
323
|
+
t.forEach(x => walkOnce(x, f, seen));
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
const o = t;
|
|
327
|
+
f(o);
|
|
328
|
+
for (const v of Object.values(o))
|
|
329
|
+
walkOnce(v, f, seen);
|
|
330
|
+
}
|
|
331
|
+
// The reads in a term, each text once, in the order walk first reaches them.
|
|
332
|
+
const readsOnce = (t) => { const out = [], had = new Set(); walkOnce(t, o => { if (o.op === 'get') {
|
|
333
|
+
const k0 = sid(o);
|
|
334
|
+
if (!had.has(k0)) {
|
|
335
|
+
had.add(k0);
|
|
336
|
+
out.push(o);
|
|
337
|
+
}
|
|
338
|
+
} }); return out; };
|
|
315
339
|
// The calls a body makes, each with what its bound names are fields of (a parameter, through matches).
|
|
316
340
|
function callsIn(body) {
|
|
317
341
|
const calls = [];
|
|
@@ -381,15 +405,15 @@ function recursion(fn) {
|
|
|
381
405
|
}
|
|
382
406
|
return undefined;
|
|
383
407
|
};
|
|
384
|
-
const got =
|
|
408
|
+
const got = members.some(f => f.stated) ? undefined : choose(0, []);
|
|
409
|
+
const names = members.map(f => f.name);
|
|
385
410
|
if (!got) {
|
|
386
|
-
const why = `${fn.name}: not structural recursion (no parameter whose field every recursive call passes${members.length > 1 ? `, in its ring ${
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
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] };
|
|
391
416
|
}
|
|
392
|
-
const names = members.map(f => f.name);
|
|
393
417
|
members.forEach((f, a) => { f.rec = { decreases: got[a], ring: names }; });
|
|
394
418
|
return { decreases: got[0], ring: names };
|
|
395
419
|
}
|
|
@@ -425,7 +449,14 @@ export function measureX(f, c, args) {
|
|
|
425
449
|
return neg.length ? { op: 'sub', a: sum(pos), b: sum(neg) } : sum(pos);
|
|
426
450
|
}
|
|
427
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))] }] });
|
|
428
|
-
|
|
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) {
|
|
429
460
|
const out = [], yesX = { op: 'bool', c: yes.y };
|
|
430
461
|
const at = (sh, name) => { let t = sh.get(name); while (t && t.op === 'var' && sh.has(t.name))
|
|
431
462
|
t = sh.get(t.name); return t; };
|
|
@@ -493,8 +524,8 @@ function callSites(fn) {
|
|
|
493
524
|
return;
|
|
494
525
|
case 'call':
|
|
495
526
|
x.args.forEach(a => goX(a, w));
|
|
496
|
-
if (x.fn
|
|
497
|
-
out.push({ args: x.args, ...w });
|
|
527
|
+
if (names.includes(x.fn))
|
|
528
|
+
out.push({ to: names.indexOf(x.fn), args: x.args, ...w });
|
|
498
529
|
return;
|
|
499
530
|
case 'if':
|
|
500
531
|
goY(x.c, w);
|
|
@@ -537,25 +568,30 @@ function callSites(fn) {
|
|
|
537
568
|
goX(fn.body(), { wrap: y => y, shape: new Map(), vars: fn.params.map(q => ({ name: `${fn.name}.${q.name}`, sort: q.sort })) });
|
|
538
569
|
return out;
|
|
539
570
|
}
|
|
540
|
-
//
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
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))] };
|
|
547
585
|
}
|
|
548
|
-
// The calls the function's runs make, each from its parameters' sizes to its arguments' (random arguments, up to 2,000
|
|
549
|
-
// calls a run: a run past that is cut, its calls kept).
|
|
550
586
|
let tracing;
|
|
551
|
-
|
|
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) {
|
|
552
589
|
const rand = rng(17), edges = new Map();
|
|
553
|
-
const feat = (vs) => fn.params.map((p, i) => (p.sort === 'nat' ? vs[i] : p.sort instanceof Data ? sizeOf(p.sort, vs[i]) : 0));
|
|
554
590
|
const tables = new Map();
|
|
555
591
|
const params = new Proxy({}, { get: (_, key) => tables.get(key) ?? (tables.set(key, randomFn(rand)), tables.get(key)) });
|
|
556
|
-
for (let i = 0; i < 120 && edges.size < 400; i++) {
|
|
557
|
-
const vals = fn.params.map(p => randomValue(p.sort, rand, 1 + (i % 7)));
|
|
558
|
-
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); } };
|
|
559
595
|
try {
|
|
560
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);
|
|
561
597
|
}
|
|
@@ -567,46 +603,191 @@ function runEdges(fn) {
|
|
|
567
603
|
return [...edges.values()];
|
|
568
604
|
}
|
|
569
605
|
const valueOf = (c, xs) => Math.max(0, c.coef.reduce((a, k, i) => a + k * xs[i], c.c));
|
|
570
|
-
const lowers = (
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
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)
|
|
574
611
|
return true;
|
|
575
|
-
if (
|
|
612
|
+
if (x > y)
|
|
576
613
|
return false;
|
|
577
614
|
}
|
|
578
615
|
return false;
|
|
579
616
|
};
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
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
|
+
}
|
|
607
681
|
}
|
|
608
682
|
return out;
|
|
609
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)] }));
|
|
733
|
+
for (const i of ix)
|
|
734
|
+
for (const j of ix)
|
|
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]));
|
|
749
|
+
}
|
|
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));
|
|
790
|
+
}
|
|
610
791
|
// An obligation as one node of a cyclic proof (no use, no models): its conclusion, each definition it reads unfolded
|
|
611
792
|
// once, the constructors' facts at the values built, the shape at each size it reads and at its variables of a
|
|
612
793
|
// datatype, the congruences 16 random models' explanations use. The kernel checks it as any cyclic proof; undefined where it isn't proven.
|
|
@@ -627,75 +808,110 @@ function directly(law, ms) {
|
|
|
627
808
|
pairedKeys.skip = was;
|
|
628
809
|
}
|
|
629
810
|
}
|
|
630
|
-
|
|
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) {
|
|
631
873
|
return counted(dataRate, () => {
|
|
874
|
+
const names = ring.map(f => f.name);
|
|
632
875
|
if (dataTrace)
|
|
633
|
-
console.error(`[data] termination of ${
|
|
634
|
-
const t0 = performance.now()
|
|
635
|
-
if (!
|
|
636
|
-
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);
|
|
637
881
|
if (dataTrace)
|
|
638
882
|
console.error(`[data] ${sites.length} calls`);
|
|
639
|
-
const edges = runEdges(
|
|
883
|
+
const edges = runEdges(ring), until = clock() + terminationMs.ms * ring.length, tried = [], seen = new Set();
|
|
640
884
|
if (dataTrace)
|
|
641
885
|
console.error(`[data] its runs: ${edges.length} calls at ${Math.round(performance.now() - t0)} ms`);
|
|
642
|
-
for (const
|
|
886
|
+
for (const ms of candidates(ring, edges, sites, until)) {
|
|
887
|
+
const text = ringText(ring, ms);
|
|
643
888
|
if (dataTrace)
|
|
644
|
-
console.error(`[data] ${
|
|
889
|
+
console.error(`[data] ${text} at ${Math.round(performance.now() - t0)} ms`);
|
|
645
890
|
if (clock() > until) {
|
|
646
891
|
tried.push('out of time');
|
|
647
892
|
break;
|
|
648
893
|
}
|
|
649
|
-
const
|
|
894
|
+
const bad = edges.find(e => !lowers(ms, e));
|
|
650
895
|
if (seen.has(text))
|
|
651
896
|
continue;
|
|
652
897
|
seen.add(text);
|
|
653
898
|
if (bad) {
|
|
654
|
-
if (
|
|
655
|
-
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]}` : ''})`);
|
|
656
901
|
continue;
|
|
657
902
|
}
|
|
658
|
-
const
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
// A call nested in its own argument or condition: the obligation would read the function being taken.
|
|
663
|
-
if (programOf([law]).fns.some(g => g.name === fn.name))
|
|
664
|
-
throw new Error(`${why}, and a call to itself is nested in the argument or the condition of another (nested recursion isn't taken)`);
|
|
665
|
-
// First one node, the definitions unfolded once (most calls lower the measure by their cases alone); else
|
|
666
|
-
// proveData: by induction where the obligation has a scheme (a call on a filter of the tail: the filter's own
|
|
667
|
-
// recursion), else, or then, the definitions unfolded alone.
|
|
668
|
-
const left = () => Math.max(1, until - clock()), cex = refute(law, 200);
|
|
669
|
-
if (cex) {
|
|
670
|
-
failed = `${text}: its call ${i + 1} doesn't lower it at ${JSON.stringify(cex)}`;
|
|
671
|
-
break;
|
|
672
|
-
}
|
|
673
|
-
const direct = directly(law, Math.min(2000, left()));
|
|
674
|
-
if (direct) {
|
|
675
|
-
obligations.push({ law, proof: direct, lemmas: [] });
|
|
676
|
-
continue;
|
|
677
|
-
}
|
|
678
|
-
const inductive = schemes(programOf([law]), law).length > 0;
|
|
679
|
-
// (no conjectured lemmas: their making isn't counted in the budget, and a call's decrease mostly needs none)
|
|
680
|
-
let v = proveData(law, inductive ? { ms: Math.min(12_000, left()), lemmas: false } : { induction: false, ms: Math.min(4000, left()) });
|
|
681
|
-
if (inductive && !(v.proven && v.checked) && !v.counterexample && clock() < until)
|
|
682
|
-
v = proveData(law, { induction: false, ms: Math.min(4000, left()) });
|
|
683
|
-
if (!(v.proven && v.checked)) {
|
|
684
|
-
failed = `${text}: its call ${i + 1} ${v.counterexample ? `doesn't lower it at ${JSON.stringify(v.counterexample)}` : 'not proven to lower it'}`;
|
|
685
|
-
break;
|
|
686
|
-
}
|
|
687
|
-
obligations.push({ law, proof: v.proof, scheme: v.scheme, lemmas: v.lemmas });
|
|
688
|
-
}
|
|
689
|
-
if (!failed)
|
|
690
|
-
return { measure: m, text, obligations, ms: Math.round(performance.now() - t0) };
|
|
691
|
-
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);
|
|
692
907
|
}
|
|
693
|
-
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)'}`);
|
|
694
909
|
});
|
|
695
910
|
}
|
|
696
911
|
export function law(name, vars, holds) {
|
|
697
912
|
const vs = Object.entries(vars).map(([n, s]) => ({ name: n, sort: s }));
|
|
698
913
|
const y = holds(Object.fromEntries(vs.map(v => [v.name, wrap(v.sort, { op: 'var', name: v.name })]))).y;
|
|
914
|
+
equalityOnly(name, y);
|
|
699
915
|
return { name, vars: vs, holds: y, params: [...new Set(paramsIn(y))] };
|
|
700
916
|
}
|
|
701
917
|
const fnOf = (name) => { const f = fns.get(name); if (!f)
|
|
@@ -769,16 +985,17 @@ export function evalX(x, env, params, d = 0) {
|
|
|
769
985
|
if (d >= evalBounds.depth || ++evalCalls > evalBounds.calls)
|
|
770
986
|
throw new EvalLimit(`${f.name}: past the evaluation's bounds`);
|
|
771
987
|
}
|
|
772
|
-
|
|
988
|
+
const at = tracing?.fns.get(f.name);
|
|
989
|
+
if (at === undefined)
|
|
773
990
|
return evalX(body, e2, params, d + 1);
|
|
774
|
-
// 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.
|
|
775
992
|
const t = tracing;
|
|
776
993
|
if (--t.fuel < 0)
|
|
777
994
|
throw new RangeError('out of fuel');
|
|
778
|
-
const top = t.stack.at(-1);
|
|
995
|
+
const top = t.stack.at(-1), frame = { at, vals };
|
|
779
996
|
if (top)
|
|
780
|
-
t.edge(top,
|
|
781
|
-
t.stack.push(
|
|
997
|
+
t.edge(top, frame);
|
|
998
|
+
t.stack.push(frame);
|
|
782
999
|
try {
|
|
783
1000
|
return evalX(body, e2, params, d + 1);
|
|
784
1001
|
}
|
|
@@ -813,20 +1030,27 @@ export const showValue = (d, v) => {
|
|
|
813
1030
|
return c.fields.length ? `${c.name}(${c.fields.map((f, i) => showValue(fieldSort(f), v.f[i])).join(', ')})` : c.name;
|
|
814
1031
|
};
|
|
815
1032
|
export const rng = (seed) => () => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed / 2147483648; };
|
|
816
|
-
|
|
1033
|
+
// `full`: a value that fills its size (a constructor with a field of the group, unless the size is spent, or at 1 in 8),
|
|
1034
|
+
// where the plain draw mostly stops at a leaf (a list of length 0 or 1, most often).
|
|
1035
|
+
export function randomValue(s, rand, size, natMax = 5, full = false) {
|
|
817
1036
|
if (s === 'nat')
|
|
818
1037
|
return Math.floor(rand() * (natMax + 1));
|
|
819
1038
|
if (s === 'bool')
|
|
820
1039
|
return rand() < 0.5 ? 0 : 1;
|
|
821
1040
|
if (s === 'int')
|
|
822
1041
|
return Math.floor(rand() * (2 * natMax + 1)) - natMax;
|
|
1042
|
+
// (an abstract value drawn as a natural is: the same draws, so a law at an abstract sort meets the values it would at
|
|
1043
|
+
// the naturals)
|
|
1044
|
+
if (s.abstract)
|
|
1045
|
+
return { c: 0, f: [Math.floor(rand() * (natMax + 1))] };
|
|
823
1046
|
// The leaves: constructors of no field of the group, or (a datatype with none, a rose tree) those of least height.
|
|
824
1047
|
const base = s.ctors.filter(c => c.fields.every(f => !inGroup(s, f)));
|
|
825
1048
|
const leaves = base.length ? base : s.ctors.filter(c => s.ctorHeight(c) === s.height);
|
|
826
|
-
const
|
|
1049
|
+
const inner = full ? s.ctors.filter(c => !leaves.includes(c)) : [];
|
|
1050
|
+
const pick = size <= 0 || rand() < (full ? 0.125 : 0.25) ? leaves : inner.length ? inner : s.ctors;
|
|
827
1051
|
const c = pick[Math.floor(rand() * pick.length)], j = s.ctors.indexOf(c);
|
|
828
1052
|
const rec = c.fields.filter(f => inGroup(s, f)).length;
|
|
829
|
-
return { c: j, f: c.fields.map(f => randomValue(fieldSort(f), rand, inGroup(s, f) ? Math.floor((size - 1) / Math.max(1, rec)) : Math.min(3, size), natMax)) };
|
|
1053
|
+
return { c: j, f: c.fields.map(f => randomValue(fieldSort(f), rand, inGroup(s, f) ? Math.floor((size - 1) / Math.max(1, rec)) : Math.min(3, size), natMax, full)) };
|
|
830
1054
|
}
|
|
831
1055
|
// A random function of a natural: a table of small values.
|
|
832
1056
|
export const randomFn = (rand, natMax = 5) => { const t = new Map(); return n => { if (!t.has(n))
|
|
@@ -1443,7 +1667,7 @@ function mutualScheme(l, v, d) {
|
|
|
1443
1667
|
return { name: `mutual structure of ${v}`, on: { v, d }, uses: usesOf(d, v), companions: order.slice(1).map(n => { const x = dataNamed(n), a = at.get(n); return { law: a.law, on: { v: a.v, d: x }, uses: usesOf(x, a.v) }; }) };
|
|
1444
1668
|
}
|
|
1445
1669
|
// The width of a program's ranks' middle: its widest measure (1 when every recursion is structural).
|
|
1446
|
-
const rankWidth = (p) => Math.max(1, ...p.fns.map(f => (f.decreases === undefined ? f.measure?.comps.length ?? 1 : 1)));
|
|
1670
|
+
export const rankWidth = (p) => Math.max(1, ...p.fns.map(f => (f.decreases === undefined ? f.measure?.comps.length ?? 1 : 1)));
|
|
1447
1671
|
// Where a well-founded scheme's node wants a datatype's shape: at the values its measure reads, and at those its measure
|
|
1448
1672
|
// reads at each use (a constructor's value a call passes: its size from its fields).
|
|
1449
1673
|
function rankShapes(shapes, rank, uses) {
|
|
@@ -1491,34 +1715,42 @@ function schemes(p, l) {
|
|
|
1491
1715
|
const d = f.params[f.decreases ?? 0].sort;
|
|
1492
1716
|
const formal = new Map(f.params.map((q, i) => [`${f.name}.${q.name}`, args[i].op === 'var' && l.vars.some(v => v.name === args[i].name) ? ev(args[i].name) : undefined]));
|
|
1493
1717
|
const uses = [];
|
|
1494
|
-
|
|
1718
|
+
// (`through`: the functions of f's ring whose bodies are read in place of their calls, once each: evens through
|
|
1719
|
+
// odds, which call each other, is recursion of evens at the tail's tail)
|
|
1720
|
+
const go = (x, env, guard, through = new Set()) => {
|
|
1495
1721
|
if (!x || typeof x !== 'object')
|
|
1496
1722
|
return;
|
|
1497
1723
|
if (Array.isArray(x)) {
|
|
1498
|
-
x.forEach(y => go(y, env, guard));
|
|
1724
|
+
x.forEach(y => go(y, env, guard, through));
|
|
1499
1725
|
return;
|
|
1500
1726
|
}
|
|
1501
1727
|
const t = x;
|
|
1728
|
+
if (t.op === 'call' && t.fn !== f.name && f.ring.includes(t.fn) && !through.has(t.fn)) {
|
|
1729
|
+
const g = fnOf(t.fn);
|
|
1730
|
+
go(t.args, env, guard, through);
|
|
1731
|
+
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]));
|
|
1732
|
+
return;
|
|
1733
|
+
}
|
|
1502
1734
|
if (t.op === 'match') {
|
|
1503
|
-
go(t.of, env, guard);
|
|
1735
|
+
go(t.of, env, guard, through);
|
|
1504
1736
|
const dd = dataOf(p, t.data), of = encX(p, t.of, env);
|
|
1505
|
-
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))]); });
|
|
1737
|
+
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); });
|
|
1506
1738
|
return;
|
|
1507
1739
|
}
|
|
1508
1740
|
if (t.op === 'natmatch') {
|
|
1509
|
-
go(t.of, env, guard);
|
|
1741
|
+
go(t.of, env, guard, through);
|
|
1510
1742
|
const of = encX(p, t.of, env), e2 = new Map(env);
|
|
1511
|
-
go(t.zero, env, [...guard, eqC(of, k(0))]);
|
|
1743
|
+
go(t.zero, env, [...guard, eqC(of, k(0))], through);
|
|
1512
1744
|
e2.set(t.pred, { op: 'sub', a: of, b: k(1) });
|
|
1513
|
-
go(t.succ, e2, [...guard, { op: 'not', x: eqC(of, k(0)) }]);
|
|
1745
|
+
go(t.succ, e2, [...guard, { op: 'not', x: eqC(of, k(0)) }], through);
|
|
1514
1746
|
return;
|
|
1515
1747
|
}
|
|
1516
1748
|
// (a well-founded call's descent may need its if's condition: x − y below x where y ≤ x)
|
|
1517
1749
|
if (m && t.op === 'if') {
|
|
1518
1750
|
const c = encY(p, t.c, env);
|
|
1519
|
-
go(t.c, env, guard);
|
|
1520
|
-
go(t.then, env, [...guard, c]);
|
|
1521
|
-
go(t.else, env, [...guard, { op: 'not', x: c }]);
|
|
1751
|
+
go(t.c, env, guard, through);
|
|
1752
|
+
go(t.then, env, [...guard, c], through);
|
|
1753
|
+
go(t.else, env, [...guard, { op: 'not', x: c }], through);
|
|
1522
1754
|
return;
|
|
1523
1755
|
}
|
|
1524
1756
|
if (t.op === 'call' && t.fn === f.name) {
|
|
@@ -1538,7 +1770,7 @@ function schemes(p, l) {
|
|
|
1538
1770
|
uses.push({ subst, guard: andC(yesC, ...guard) });
|
|
1539
1771
|
}
|
|
1540
1772
|
for (const v of Object.values(t))
|
|
1541
|
-
go(v, env, guard);
|
|
1773
|
+
go(v, env, guard, through);
|
|
1542
1774
|
};
|
|
1543
1775
|
const env = new Map([...formal].flatMap(([key, e]) => (e ? [[key, e]] : [])));
|
|
1544
1776
|
go(f.body(), env, []);
|
|
@@ -1574,13 +1806,13 @@ function instancesOf(p, fs, w) {
|
|
|
1574
1806
|
console.error(`[data] instances: ${what} at ${Math.round(performance.now() - tt)} ms`); };
|
|
1575
1807
|
const insts = [], seen = new Set();
|
|
1576
1808
|
const inst = (fact, at) => { const i = fs.at.get(fact); if (i === undefined)
|
|
1577
|
-
return; const id =
|
|
1809
|
+
return; const id = sid([i, at]); if (!seen.has(id)) {
|
|
1578
1810
|
seen.add(id);
|
|
1579
1811
|
insts.push({ fact: i, at });
|
|
1580
1812
|
} };
|
|
1581
|
-
const holdsAt = (fact, at) => { const f = fs.facts[fs.at.get(fact)]; return
|
|
1582
|
-
|
|
1583
|
-
|
|
1813
|
+
const holdsAt = (fact, at) => { const f = fs.facts[fs.at.get(fact)]; return substShared(f.holds, Object.fromEntries(f.keys.map((key, q) => [key, at[q]]))); };
|
|
1814
|
+
// (each read once, where walk first reaches it: a read again adds nothing where these are used)
|
|
1815
|
+
const reads = (t) => readsOnce(t).map(o => ({ map: o.map, key: o.key }));
|
|
1584
1816
|
const fnOfMap = (map) => p.fns.find(g => g.name === map);
|
|
1585
1817
|
const ctorOf = (map) => { for (const d of p.datas)
|
|
1586
1818
|
for (const [j, c] of d.ctors.entries())
|
|
@@ -1588,7 +1820,7 @@ function instancesOf(p, fs, w) {
|
|
|
1588
1820
|
return c.fields.length; return undefined; };
|
|
1589
1821
|
const all = [], had = new Set();
|
|
1590
1822
|
const note = (rs) => { const out = []; for (const r of rs) {
|
|
1591
|
-
const id =
|
|
1823
|
+
const id = sid(r);
|
|
1592
1824
|
if (!had.has(id)) {
|
|
1593
1825
|
had.add(id);
|
|
1594
1826
|
all.push(r);
|
|
@@ -1618,7 +1850,7 @@ function instancesOf(p, fs, w) {
|
|
|
1618
1850
|
for (let round = 0; round < w.depth && frontier.length; round++) {
|
|
1619
1851
|
const next = [];
|
|
1620
1852
|
for (const r of frontier) {
|
|
1621
|
-
const f = fnOfMap(r.map), as = f && argsOf(r.key, f.params.length), rid =
|
|
1853
|
+
const f = fnOfMap(r.map), as = f && argsOf(r.key, f.params.length), rid = sid(r);
|
|
1622
1854
|
if (!f || !as || unfolded.has(rid))
|
|
1623
1855
|
continue;
|
|
1624
1856
|
unfolded.add(rid);
|
|
@@ -1714,6 +1946,21 @@ function instancesOf(p, fs, w) {
|
|
|
1714
1946
|
if (as)
|
|
1715
1947
|
(cells.get(r.map) ?? cells.set(r.map, []).get(r.map)).push({ key: r.key, as });
|
|
1716
1948
|
}
|
|
1949
|
+
// Arguments equal by arithmetic alone, one class: (n + 1) ∸ 1 and n (a successor's predecessor, where a definition
|
|
1950
|
+
// on the naturals is unfolded at n + 1), so their reads meet by congruence. The kernel proves the equality itself.
|
|
1951
|
+
const byForm = new Map();
|
|
1952
|
+
for (const list of cells.values())
|
|
1953
|
+
for (const x of list)
|
|
1954
|
+
for (const t of x.as) {
|
|
1955
|
+
const f = linearForm(t);
|
|
1956
|
+
if (f === undefined)
|
|
1957
|
+
continue;
|
|
1958
|
+
const had = byForm.get(f);
|
|
1959
|
+
if (!had)
|
|
1960
|
+
byForm.set(f, t);
|
|
1961
|
+
else if (tid(had) !== tid(t))
|
|
1962
|
+
edge(had, t);
|
|
1963
|
+
}
|
|
1717
1964
|
for (let changed = true; changed && !late();) {
|
|
1718
1965
|
changed = false;
|
|
1719
1966
|
for (const [map, list] of cells) {
|
|
@@ -1761,7 +2008,7 @@ function instancesOf(p, fs, w) {
|
|
|
1761
2008
|
const built = (t) => (t.op === 'get' && d.ctors.some((c, j) => c.fields.length && t.map === ctorMap(d, j))) || (t.op === 'const' && t.value < d.nullary);
|
|
1762
2009
|
const cands = built(own) ? [own] : [...cl.terms.values()].filter(t => built(t) && cl.find(tid(t)) === root);
|
|
1763
2010
|
for (const t of cands) {
|
|
1764
|
-
const as2 = as.map((a, i) => (i === di ? t : a)), rid =
|
|
2011
|
+
const as2 = as.map((a, i) => (i === di ? t : a)), rid = sid({ map: f.name, key: keyOf(as2) }), key2 = sid([fs.at.get(`fn ${f.name}`), as2]);
|
|
1765
2012
|
const anchor = { read: tid(get(f.name, r.key)), arg: own, value: t }, had = anchoredAt.get(key2) ?? [];
|
|
1766
2013
|
if (!had.some(x => x.read === anchor.read))
|
|
1767
2014
|
anchoredAt.set(key2, [...had, anchor]);
|
|
@@ -1771,7 +2018,7 @@ function instancesOf(p, fs, w) {
|
|
|
1771
2018
|
extra++;
|
|
1772
2019
|
done.add(sigOf(f.name, as2));
|
|
1773
2020
|
if (dataTrace)
|
|
1774
|
-
console.error(`[data] unfold ${f.name} at ${
|
|
2021
|
+
console.error(`[data] unfold ${f.name} at ${brief(as2, 160)} for ${brief(r.key, 80)}`);
|
|
1775
2022
|
inst(`fn ${f.name}`, as2);
|
|
1776
2023
|
note([{ map: f.name, key: keyOf(as2) }]);
|
|
1777
2024
|
ctors(note(reads(holdsAt(`fn ${f.name}`, as2))));
|
|
@@ -1812,6 +2059,28 @@ function instancesOf(p, fs, w) {
|
|
|
1812
2059
|
for (const d of p.datas)
|
|
1813
2060
|
if (r.map === sizeMap(d.name))
|
|
1814
2061
|
shape(r.key, d);
|
|
2062
|
+
// Where it does, the sizes those shapes read in turn (a field's, a value built's), `depth` rounds: size(x) is 1 plus
|
|
2063
|
+
// its tail's, and the tail's size is its own shape's (a size law of a recursion two fields deep).
|
|
2064
|
+
{
|
|
2065
|
+
const sizeOf = (r) => p.datas.find(d => r.map === sizeMap(d.name));
|
|
2066
|
+
let todo = reads([w.roots, w.others]).filter(r => sizeOf(r)).map(r => r.key);
|
|
2067
|
+
const shaped = new Set(todo.map(t => sid(t)));
|
|
2068
|
+
for (let round = 0; round < w.depth && todo.length; round++) {
|
|
2069
|
+
const next = [];
|
|
2070
|
+
for (const t of todo) {
|
|
2071
|
+
const d = sizeOf({ map: (reads([w.roots, w.others]).find(r => sid(r.key) === sid(t) && sizeOf(r)) ?? { map: '' }).map }) ?? dataOfTerm(t);
|
|
2072
|
+
if (!d)
|
|
2073
|
+
continue;
|
|
2074
|
+
for (const r of reads(holdsAt(`shape ${d.name}`, [t])))
|
|
2075
|
+
if (sizeOf(r) && !shaped.has(sid(r.key))) {
|
|
2076
|
+
shaped.add(sid(r.key));
|
|
2077
|
+
shape(r.key, sizeOf(r));
|
|
2078
|
+
next.push(r.key);
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
todo = next;
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
1815
2084
|
if (w.depth >= 2)
|
|
1816
2085
|
for (const r of [...all])
|
|
1817
2086
|
for (const d of p.datas)
|
|
@@ -1873,10 +2142,10 @@ function instancesOf(p, fs, w) {
|
|
|
1873
2142
|
for (let at = b2; at !== a2;) {
|
|
1874
2143
|
const step = back.get(at);
|
|
1875
2144
|
if (step.cong) {
|
|
1876
|
-
const c = step.cong, k2 =
|
|
2145
|
+
const c = step.cong, k2 = sid([c.map, c.x, c.y]);
|
|
1877
2146
|
if (!counted.has(k2)) {
|
|
1878
2147
|
counted.add(k2);
|
|
1879
|
-
const had = used.get(k2) ?? used.get(
|
|
2148
|
+
const had = used.get(k2) ?? used.get(sid([c.map, c.y, c.x]));
|
|
1880
2149
|
if (had)
|
|
1881
2150
|
had.n++;
|
|
1882
2151
|
else
|
|
@@ -1889,10 +2158,11 @@ function instancesOf(p, fs, w) {
|
|
|
1889
2158
|
};
|
|
1890
2159
|
// The values this model reads: the conclusions' reads, and each fact's where the model takes it (an if's condition
|
|
1891
2160
|
// and taken branch, an implication's conclusion where its premise holds).
|
|
1892
|
-
const read = new Set();
|
|
2161
|
+
const read = new Set(), looked = [new WeakSet(), new WeakSet()];
|
|
1893
2162
|
const look = (t, whole) => {
|
|
1894
|
-
if (!t || typeof t !== 'object')
|
|
2163
|
+
if (!t || typeof t !== 'object' || looked[+whole].has(t))
|
|
1895
2164
|
return;
|
|
2165
|
+
looked[+whole].add(t);
|
|
1896
2166
|
if (Array.isArray(t)) {
|
|
1897
2167
|
t.forEach(x => look(x, whole));
|
|
1898
2168
|
return;
|
|
@@ -1960,7 +2230,7 @@ function instancesOf(p, fs, w) {
|
|
|
1960
2230
|
for (const es of adj.values())
|
|
1961
2231
|
for (const e of es)
|
|
1962
2232
|
if (e.cong) {
|
|
1963
|
-
const k2 =
|
|
2233
|
+
const k2 = sid([e.cong.map, e.cong.x, e.cong.y]), k3 = sid([e.cong.map, e.cong.y, e.cong.x]);
|
|
1964
2234
|
if (!used.has(k2) && !used.has(k3))
|
|
1965
2235
|
used.set(k2, { map: e.cong.map, at: [...e.cong.x, ...e.cong.y], n: 1 });
|
|
1966
2236
|
}
|
|
@@ -1975,10 +2245,156 @@ function instancesOf(p, fs, w) {
|
|
|
1975
2245
|
return insts;
|
|
1976
2246
|
}
|
|
1977
2247
|
let varSorts = new Map();
|
|
1978
|
-
// A term's
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
2248
|
+
// A term's id, once per object: equal exactly when the terms' texts (JSON.stringify) are, a leaf's id its text. A key's
|
|
2249
|
+
// pairing reads its arguments again ((a + b)·(a + b) + b), so a nested read's text grows exponentially with its depth
|
|
2250
|
+
// while its objects are shared: the id of a term is its node's, over its children's ids, in time linear in the objects.
|
|
2251
|
+
let idMemo = new WeakMap(), idTable = new Map(), idGen = 0;
|
|
2252
|
+
const sid = (t) => {
|
|
2253
|
+
if (t === null || typeof t !== 'object')
|
|
2254
|
+
return JSON.stringify(t) ?? String(t);
|
|
2255
|
+
const had = idMemo.get(t);
|
|
2256
|
+
if (had !== undefined)
|
|
2257
|
+
return had;
|
|
2258
|
+
let leaf = true;
|
|
2259
|
+
const part = (v) => { if (v !== null && typeof v === 'object') {
|
|
2260
|
+
leaf = false;
|
|
2261
|
+
return sid(v);
|
|
2262
|
+
} return JSON.stringify(v) ?? 'null'; };
|
|
2263
|
+
const shape = Array.isArray(t) ? `[${t.map(part).join(',')}]` : `{${Object.entries(t).filter(([, v]) => v !== undefined && typeof v !== 'function').map(([key, v]) => `${key}:${part(v)}`).join(',')}}`;
|
|
2264
|
+
let out;
|
|
2265
|
+
if (leaf)
|
|
2266
|
+
out = JSON.stringify(t);
|
|
2267
|
+
else {
|
|
2268
|
+
if (idTable.size > 1_000_000) {
|
|
2269
|
+
idTable = new Map();
|
|
2270
|
+
idMemo = new WeakMap();
|
|
2271
|
+
idGen++;
|
|
2272
|
+
}
|
|
2273
|
+
out = idTable.get(shape) ?? `#${idGen}.${idTable.size}`;
|
|
2274
|
+
if (!idTable.has(shape))
|
|
2275
|
+
idTable.set(shape, out);
|
|
2276
|
+
}
|
|
2277
|
+
idMemo.set(t, out);
|
|
2278
|
+
return out;
|
|
2279
|
+
};
|
|
2280
|
+
const tid = (t) => sid(t);
|
|
2281
|
+
// A natural term's linear form (Σ cᵢ·atomᵢ + c, an atom a variable or a read, its text its id), where it is one: a
|
|
2282
|
+
// truncated difference by a constant only where the constant is at most the term's (x + 1 ∸ 1 is x); else undefined.
|
|
2283
|
+
function linearForm(e) {
|
|
2284
|
+
const go = (t) => {
|
|
2285
|
+
switch (t.op) {
|
|
2286
|
+
case 'const': return { cs: new Map(), c: t.value };
|
|
2287
|
+
case 'var':
|
|
2288
|
+
case 'get': return { cs: new Map([[tid(t), 1]]), c: 0 };
|
|
2289
|
+
case 'add': {
|
|
2290
|
+
const a = go(t.a), b = go(t.b);
|
|
2291
|
+
if (!a || !b)
|
|
2292
|
+
return undefined;
|
|
2293
|
+
const cs = new Map(a.cs);
|
|
2294
|
+
for (const [x, k2] of b.cs)
|
|
2295
|
+
cs.set(x, (cs.get(x) ?? 0) + k2);
|
|
2296
|
+
return { cs, c: a.c + b.c };
|
|
2297
|
+
}
|
|
2298
|
+
case 'mul': {
|
|
2299
|
+
const a = go(t.a);
|
|
2300
|
+
return a && { cs: new Map([...a.cs].map(([x, k2]) => [x, k2 * t.k])), c: a.c * t.k };
|
|
2301
|
+
}
|
|
2302
|
+
case 'sub': {
|
|
2303
|
+
const a = go(t.a);
|
|
2304
|
+
return a && t.b.op === 'const' && a.c >= t.b.value ? { cs: a.cs, c: a.c - t.b.value } : undefined;
|
|
2305
|
+
}
|
|
2306
|
+
case 'if':
|
|
2307
|
+
case 'min':
|
|
2308
|
+
case 'max':
|
|
2309
|
+
case 'prod': return undefined;
|
|
2310
|
+
}
|
|
2311
|
+
};
|
|
2312
|
+
const f = go(e);
|
|
2313
|
+
return f && `${[...f.cs].filter(([, k2]) => k2).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([x, k2]) => `${k2}*${x}`).join('+')}+${f.c}`;
|
|
2314
|
+
}
|
|
2315
|
+
// substC and substE (kernel/kernel.ts) at variables alone, each object once: a term read twice within another (a key's
|
|
2316
|
+
// pairing) is substituted once and shared, so what the search reads of a fact stays the size of its objects. The same
|
|
2317
|
+
// terms, field for field; a flag or a binder is left to substC.
|
|
2318
|
+
function substShared(c, vars) {
|
|
2319
|
+
const memo = new Map();
|
|
2320
|
+
const e = (x) => {
|
|
2321
|
+
const had = memo.get(x);
|
|
2322
|
+
if (had)
|
|
2323
|
+
return had;
|
|
2324
|
+
let out;
|
|
2325
|
+
switch (x.op) {
|
|
2326
|
+
case 'var':
|
|
2327
|
+
out = vars[x.name] ?? x;
|
|
2328
|
+
break;
|
|
2329
|
+
case 'const':
|
|
2330
|
+
out = x;
|
|
2331
|
+
break;
|
|
2332
|
+
case 'mul':
|
|
2333
|
+
out = { ...x, a: e(x.a) };
|
|
2334
|
+
break;
|
|
2335
|
+
case 'if':
|
|
2336
|
+
out = { op: 'if', c: cc(x.c), then: e(x.then), else: e(x.else) };
|
|
2337
|
+
break;
|
|
2338
|
+
case 'get':
|
|
2339
|
+
out = { op: 'get', map: x.map, key: e(x.key) };
|
|
2340
|
+
break;
|
|
2341
|
+
case 'prod':
|
|
2342
|
+
case 'add':
|
|
2343
|
+
case 'sub':
|
|
2344
|
+
case 'min':
|
|
2345
|
+
case 'max':
|
|
2346
|
+
out = { ...x, a: e(x.a), b: e(x.b) };
|
|
2347
|
+
break;
|
|
2348
|
+
default: out = substE(x, { vars, maps: {}, flags: {} });
|
|
2349
|
+
}
|
|
2350
|
+
memo.set(x, out);
|
|
2351
|
+
return out;
|
|
2352
|
+
};
|
|
2353
|
+
const cc = (y) => {
|
|
2354
|
+
const had = memo.get(y);
|
|
2355
|
+
if (had)
|
|
2356
|
+
return had;
|
|
2357
|
+
let out;
|
|
2358
|
+
if (y.op === 'not')
|
|
2359
|
+
out = { op: 'not', x: cc(y.x) };
|
|
2360
|
+
else if (y.op === 'and' || y.op === 'or')
|
|
2361
|
+
out = { op: y.op, xs: y.xs.map(cc) };
|
|
2362
|
+
else if (y.op === 'flag' || y.op === 'all')
|
|
2363
|
+
out = substC(y, { vars, maps: {}, flags: {} });
|
|
2364
|
+
else
|
|
2365
|
+
out = { ...y, a: e(y.a), b: e(y.b) };
|
|
2366
|
+
memo.set(y, out);
|
|
2367
|
+
return out;
|
|
2368
|
+
};
|
|
2369
|
+
return cc(c);
|
|
2370
|
+
}
|
|
2371
|
+
// Whether a term reads a variable (its text has `"op":"var"`), once per object.
|
|
2372
|
+
const varMemo = new WeakMap();
|
|
2373
|
+
const readsVar = (t) => {
|
|
2374
|
+
if (!t || typeof t !== 'object')
|
|
2375
|
+
return false;
|
|
2376
|
+
const had = varMemo.get(t);
|
|
2377
|
+
if (had !== undefined)
|
|
2378
|
+
return had;
|
|
2379
|
+
const out = t.op === 'var' || (Array.isArray(t) ? t.some(readsVar) : Object.values(t).some(readsVar));
|
|
2380
|
+
varMemo.set(t, out);
|
|
2381
|
+
return out;
|
|
2382
|
+
};
|
|
2383
|
+
// A term's text for a trace, cut at n characters (not written out past 4,000).
|
|
2384
|
+
const brief = (t, n) => (textLength(t) > 4000 ? `(${textLength(t)} characters)` : JSON.stringify(t).slice(0, n));
|
|
2385
|
+
// The length of a term's text, without writing it (memoised per object, as `sid`).
|
|
2386
|
+
const lenMemo = new WeakMap();
|
|
2387
|
+
const textLength = (t) => {
|
|
2388
|
+
if (t === null || typeof t !== 'object')
|
|
2389
|
+
return (JSON.stringify(t) ?? 'null').length;
|
|
2390
|
+
const had = lenMemo.get(t);
|
|
2391
|
+
if (had !== undefined)
|
|
2392
|
+
return had;
|
|
2393
|
+
const parts = Array.isArray(t) ? t.map(textLength) : Object.entries(t).filter(([, v]) => v !== undefined && typeof v !== 'function').map(([key, v]) => JSON.stringify(key).length + 1 + textLength(v));
|
|
2394
|
+
const out = 2 + parts.reduce((a, b) => a + b, 0) + Math.max(0, parts.length - 1);
|
|
2395
|
+
lenMemo.set(t, out);
|
|
2396
|
+
return out;
|
|
2397
|
+
};
|
|
1982
2398
|
// An instance unfolded where a read's argument equals a constructor's value: the read it stands for (for `reached`).
|
|
1983
2399
|
const anchoredAt = new Map();
|
|
1984
2400
|
const typeOfVar = (_p, t) => (t.op === 'var' ? varSorts.get(t.name) : undefined);
|
|
@@ -1999,7 +2415,7 @@ function matches(pattern, vars, t, s) {
|
|
|
1999
2415
|
if (pattern.op === 'var' && vars.has(pattern.name)) {
|
|
2000
2416
|
const had = s[pattern.name];
|
|
2001
2417
|
if (had)
|
|
2002
|
-
return
|
|
2418
|
+
return sid(had) === sid(t) ? s : undefined;
|
|
2003
2419
|
return { ...s, [pattern.name]: t };
|
|
2004
2420
|
}
|
|
2005
2421
|
if (pattern.op !== t.op)
|
|
@@ -2014,11 +2430,11 @@ function matches(pattern, vars, t, s) {
|
|
|
2014
2430
|
if (!b || typeof b !== 'object')
|
|
2015
2431
|
return undefined;
|
|
2016
2432
|
if (a.op && ['<', '<=', '=', 'and', 'or', 'not'].includes(a.op))
|
|
2017
|
-
out =
|
|
2433
|
+
out = sid(a) === sid(b) ? out : undefined;
|
|
2018
2434
|
else
|
|
2019
2435
|
out = matches(a, vars, b, out);
|
|
2020
2436
|
}
|
|
2021
|
-
else if (
|
|
2437
|
+
else if (sid(a) !== sid(b))
|
|
2022
2438
|
return undefined;
|
|
2023
2439
|
}
|
|
2024
2440
|
return out;
|
|
@@ -2026,7 +2442,7 @@ function matches(pattern, vars, t, s) {
|
|
|
2026
2442
|
function casesOf(p, unfolded, vars, models) {
|
|
2027
2443
|
const plain = (e) => (e.op === 'var' ? vars.has(e.name) : e.op === 'const' ? true : e.op === 'get' ? p.datas.some(d => e.map.startsWith(`${d.name}.`)) && !p.datas.some(d => d.ctors.some((c, j) => c.fields.length > 0 && e.map === ctorMap(d, j))) && plain(e.key)
|
|
2028
2444
|
: 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);
|
|
2029
|
-
const plainC = (c) =>
|
|
2445
|
+
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);
|
|
2030
2446
|
// The functions' facts the goal unfolds.
|
|
2031
2447
|
const roots = unfolded;
|
|
2032
2448
|
const sigs = models.map(({ m, env }) => {
|
|
@@ -2037,9 +2453,11 @@ function casesOf(p, unfolded, vars, models) {
|
|
|
2037
2453
|
catch {
|
|
2038
2454
|
return undefined;
|
|
2039
2455
|
} };
|
|
2456
|
+
const seen = new WeakSet();
|
|
2040
2457
|
const go = (t) => {
|
|
2041
|
-
if (!t || typeof t !== 'object')
|
|
2458
|
+
if (!t || typeof t !== 'object' || seen.has(t))
|
|
2042
2459
|
return;
|
|
2460
|
+
seen.add(t);
|
|
2043
2461
|
if (Array.isArray(t)) {
|
|
2044
2462
|
t.forEach(go);
|
|
2045
2463
|
return;
|
|
@@ -2050,7 +2468,7 @@ function casesOf(p, unfolded, vars, models) {
|
|
|
2050
2468
|
if (v === undefined)
|
|
2051
2469
|
return;
|
|
2052
2470
|
if (plainC(o.c)) {
|
|
2053
|
-
const key =
|
|
2471
|
+
const key = sid(o.c);
|
|
2054
2472
|
if (!out.has(key))
|
|
2055
2473
|
out.set(key, { c: o.c, t: v });
|
|
2056
2474
|
}
|
|
@@ -2127,7 +2545,7 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
|
|
|
2127
2545
|
const uses = [...ih, ...lemmaUses];
|
|
2128
2546
|
if (dataTrace)
|
|
2129
2547
|
for (const u of lemmaUses)
|
|
2130
|
-
console.error(`[data] lemma use ${specs[u.node].name.slice(0, 40)} at ${Object.entries(u.subst).map(([x, t]) => `${x} := ${
|
|
2548
|
+
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('; ')}`);
|
|
2131
2549
|
// The lemmas' conclusions are unfolded like the law's (they are what the goal reads, said another way); the cycle's
|
|
2132
2550
|
// own uses only from depth 3.
|
|
2133
2551
|
const instsFor = (ms, us, every = false) => instancesOf(p, fs, { roots: [concl], others: us.map(useConcl), depth, shapesAt, etaAt: [...shapesAt, ...valuesCompared(p, mb.law)], models: ms, every, until: t0 + attemptMs.ms });
|
|
@@ -2195,10 +2613,15 @@ const dataRate = 300;
|
|
|
2195
2613
|
// value whose tag is read), the reads of what it gives where the models take it (an if's taken branch, an implication's
|
|
2196
2614
|
// conclusion where its premise holds); a congruence where both its reads are reached.
|
|
2197
2615
|
function reached(p, fs, insts, from, ms) {
|
|
2198
|
-
const reach = new Set(), id = (t) =>
|
|
2616
|
+
const reach = new Set(), id = (t) => sid(t), done = new Map();
|
|
2617
|
+
// (an object once a model: what it reaches there is the same each time)
|
|
2199
2618
|
const active = (t, m, env) => {
|
|
2200
2619
|
if (!t || typeof t !== 'object')
|
|
2201
2620
|
return;
|
|
2621
|
+
const seen = done.get(env) ?? done.set(env, new WeakSet()).get(env);
|
|
2622
|
+
if (seen.has(t))
|
|
2623
|
+
return;
|
|
2624
|
+
seen.add(t);
|
|
2202
2625
|
if (Array.isArray(t)) {
|
|
2203
2626
|
t.forEach(x => active(x, m, env));
|
|
2204
2627
|
return;
|
|
@@ -2233,8 +2656,8 @@ function reached(p, fs, insts, from, ms) {
|
|
|
2233
2656
|
const each = (t) => { for (const { m, env } of ms)
|
|
2234
2657
|
active(t, m, env); };
|
|
2235
2658
|
// The conclusion and the uses' are read whole: the goal is where the law fails, which no model is.
|
|
2236
|
-
|
|
2237
|
-
reach.add(
|
|
2659
|
+
walkOnce(from, o => { if (o.op === 'get')
|
|
2660
|
+
reach.add(sid(o)); });
|
|
2238
2661
|
const anchor = (q) => {
|
|
2239
2662
|
const name = fs.facts[q.fact].name;
|
|
2240
2663
|
if (name.startsWith('fn '))
|
|
@@ -2268,7 +2691,7 @@ function reached(p, fs, insts, from, ms) {
|
|
|
2268
2691
|
const name = fs.facts[q.fact].name;
|
|
2269
2692
|
if (name.startsWith('cong ') || name.startsWith('nullary '))
|
|
2270
2693
|
continue;
|
|
2271
|
-
const virtual = anchoredAt.get(
|
|
2694
|
+
const virtual = anchoredAt.get(sid([q.fact, q.at])) ?? [];
|
|
2272
2695
|
const same = (v) => ms.every(({ m, env }) => { try {
|
|
2273
2696
|
return m.evalE(v.arg, env) === m.evalE(v.value, env);
|
|
2274
2697
|
}
|
|
@@ -2308,37 +2731,39 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
|
|
|
2308
2731
|
for (const leaf of leaves(b))
|
|
2309
2732
|
union(a, leaf);
|
|
2310
2733
|
// Closed under congruence (two reads of one map at arguments of one class), by signatures.
|
|
2311
|
-
const cells = new Map();
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
changed =
|
|
2317
|
-
|
|
2318
|
-
const
|
|
2319
|
-
|
|
2320
|
-
const
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2734
|
+
const cells = new Map(), classes = new Map();
|
|
2735
|
+
const close = (t) => {
|
|
2736
|
+
walkOnce(t, o => { if (o.op !== 'get')
|
|
2737
|
+
return; const n = fs.arity.get(o.map), as = n ? argsOf(o.key, n) : undefined; if (as)
|
|
2738
|
+
(cells.get(o.map) ?? cells.set(o.map, []).get(o.map)).push({ key: o.key, as }); });
|
|
2739
|
+
for (let changed = true, rounds = 0; changed && rounds < 8; rounds++) {
|
|
2740
|
+
changed = false;
|
|
2741
|
+
for (const [map, list] of cells) {
|
|
2742
|
+
const bySig = new Map();
|
|
2743
|
+
for (const x of list) {
|
|
2744
|
+
const sig = x.as.map(t2 => find(id(t2))).join('\u0001'), y = bySig.get(sig), cx = get(map, x.key);
|
|
2745
|
+
if (!y) {
|
|
2746
|
+
bySig.set(sig, cx);
|
|
2747
|
+
continue;
|
|
2748
|
+
}
|
|
2749
|
+
if (find(id(y)) !== find(id(cx))) {
|
|
2750
|
+
union(y, cx);
|
|
2751
|
+
changed = true;
|
|
2752
|
+
}
|
|
2328
2753
|
}
|
|
2329
2754
|
}
|
|
2330
2755
|
}
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
}
|
|
2756
|
+
classes.clear();
|
|
2757
|
+
for (const [key, e] of terms) {
|
|
2758
|
+
const r = find(key);
|
|
2759
|
+
(classes.get(r) ?? classes.set(r, []).get(r)).push(e);
|
|
2760
|
+
}
|
|
2761
|
+
};
|
|
2762
|
+
close([from, insts.map(q => holdsAt(fs, q))]);
|
|
2337
2763
|
const members = (t) => { const k0 = tid(t); return [t, ...(classes.get(find(k0)) ?? []).filter(e => tid(e) !== k0)]; };
|
|
2338
2764
|
const out = [], seen = new Set();
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
reads.push(o); });
|
|
2765
|
+
const goalReads = readsOnce([from, insts.map(q => holdsAt(fs, q))]);
|
|
2766
|
+
let reads = goalReads;
|
|
2342
2767
|
for (let round = 0; round < 2; round++) {
|
|
2343
2768
|
const fresh = [];
|
|
2344
2769
|
const cands = [];
|
|
@@ -2349,18 +2774,47 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
|
|
|
2349
2774
|
const vars = new Set(lm.law.vars.map(v => v.name)), sides = [];
|
|
2350
2775
|
walk(encY(p, lm.law.holds, new Map()), o => { if (o.op === 'get')
|
|
2351
2776
|
sides.push(o); });
|
|
2352
|
-
const
|
|
2353
|
-
|
|
2777
|
+
const tops0 = sides.filter(a => !sides.some(b => b !== a && JSON.stringify(b).includes(JSON.stringify(a))));
|
|
2778
|
+
// (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
|
|
2779
|
+
// every size the goal reads)
|
|
2780
|
+
const callsFn = (t) => { let yes = false; walk(t, o => { if (o.op === 'get' && fs.arity.has(o.map) && p.fns.some(f => f.name === o.map))
|
|
2781
|
+
yes = true; }); return yes; };
|
|
2782
|
+
const tops = tops0.some(callsFn) ? tops0.filter(callsFn) : tops0;
|
|
2783
|
+
for (const top of tops) {
|
|
2784
|
+
const n = fs.arity.get(top.map) ?? 1, pats = argsOf(top.key, n);
|
|
2785
|
+
// A pattern's match at a term alone, once (a match given others' bindings is it, where it agrees with them).
|
|
2786
|
+
const alone = pats?.map(() => new Map());
|
|
2787
|
+
const matchAt = (q, m, sb) => {
|
|
2788
|
+
const memo = alone[q];
|
|
2789
|
+
if (!memo.has(m))
|
|
2790
|
+
memo.set(m, matches(pats[q], vars, m, {}));
|
|
2791
|
+
const r = memo.get(m);
|
|
2792
|
+
if (!r)
|
|
2793
|
+
return undefined;
|
|
2794
|
+
let out = sb;
|
|
2795
|
+
for (const [x, v] of Object.entries(r)) {
|
|
2796
|
+
const had = sb[x];
|
|
2797
|
+
if (had) {
|
|
2798
|
+
if (sid(had) !== sid(v))
|
|
2799
|
+
return undefined;
|
|
2800
|
+
}
|
|
2801
|
+
else
|
|
2802
|
+
out = out === sb ? { ...sb, [x]: v } : (out[x] = v, out);
|
|
2803
|
+
}
|
|
2804
|
+
return out;
|
|
2805
|
+
};
|
|
2354
2806
|
for (const t of reads) {
|
|
2355
2807
|
if (t.op !== 'get' || t.map !== top.map)
|
|
2356
2808
|
continue;
|
|
2357
2809
|
// Each argument of the read matched up to its class (a key of several arguments is their pairing).
|
|
2358
|
-
const
|
|
2810
|
+
const args = argsOf(t.key, n);
|
|
2359
2811
|
if (!pats || !args)
|
|
2360
2812
|
continue;
|
|
2361
2813
|
let subs = [{}];
|
|
2362
|
-
for (const
|
|
2363
|
-
|
|
2814
|
+
for (const q of pats.keys()) {
|
|
2815
|
+
const ms = members(args[q]).slice(0, 256);
|
|
2816
|
+
subs = subs.flatMap(sb => ms.flatMap(m => { const r = matchAt(q, m, sb); return r ? [r] : []; })).slice(0, 512);
|
|
2817
|
+
}
|
|
2364
2818
|
for (const sub of subs) {
|
|
2365
2819
|
if (Object.keys(sub).length !== vars.size)
|
|
2366
2820
|
continue;
|
|
@@ -2374,7 +2828,7 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
|
|
|
2374
2828
|
} }).length : 1;
|
|
2375
2829
|
if (!score)
|
|
2376
2830
|
continue;
|
|
2377
|
-
const k2 =
|
|
2831
|
+
const k2 = sid([lm.node, sub]);
|
|
2378
2832
|
if (seen.has(k2))
|
|
2379
2833
|
continue;
|
|
2380
2834
|
seen.add(k2);
|
|
@@ -2385,9 +2839,10 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
|
|
|
2385
2839
|
catch {
|
|
2386
2840
|
return -1;
|
|
2387
2841
|
} }))]) : k2;
|
|
2388
|
-
cands.push({ use: { node: lm.node, subst: sub, guard: yesC }, at: { goal: t, lemma: substE(top, { vars: sub, maps: {}, flags: {} }) }, score, fp, size:
|
|
2842
|
+
cands.push({ use: { node: lm.node, subst: sub, guard: yesC }, at: { goal: t, lemma: substE(top, { vars: sub, maps: {}, flags: {} }) }, score, fp, size: textLength([lm.node, sub]) });
|
|
2389
2843
|
}
|
|
2390
2844
|
}
|
|
2845
|
+
}
|
|
2391
2846
|
}
|
|
2392
2847
|
// First, as found: four of a lemma, twelve in all (the next round reads their conclusions). Then the rest, best first
|
|
2393
2848
|
// (the most models, then the smallest terms), one of each set of values, up to `perLemma` of a lemma and `total` in
|
|
@@ -2400,14 +2855,20 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
|
|
|
2400
2855
|
continue;
|
|
2401
2856
|
take(c);
|
|
2402
2857
|
first.add(c);
|
|
2403
|
-
|
|
2404
|
-
fresh.push(o); });
|
|
2858
|
+
fresh.push(substC(lemmas.find(lm => lm.node === c.use.node).concl, { vars: c.use.subst, maps: {}, flags: {} }));
|
|
2405
2859
|
}
|
|
2406
2860
|
const rest = cands.filter(c => !first.has(c)).sort((a, b) => b.score - a.score || a.size - b.size);
|
|
2407
2861
|
for (const c of rest)
|
|
2408
2862
|
if (!fps.has(c.fp) && out.length < lemmaCaps.total && out.filter(u => u.node === c.use.node).length < lemmaCaps.perLemma)
|
|
2409
2863
|
take(c);
|
|
2410
|
-
reads
|
|
2864
|
+
// The second round: the reads of the first's conclusions, and the goal's again, matched up to the classes those
|
|
2865
|
+
// conclusions join (assoc's use makes x ++ (y ++ [z]) and (x ++ y) ++ [z] one, where rev of a snoc then matches).
|
|
2866
|
+
for (const c of fresh)
|
|
2867
|
+
for (const [a2, b2] of equalities(c))
|
|
2868
|
+
for (const leaf of leaves(b2))
|
|
2869
|
+
union(a2, leaf);
|
|
2870
|
+
close(fresh);
|
|
2871
|
+
reads = readsOnce([fresh, goalReads]);
|
|
2411
2872
|
}
|
|
2412
2873
|
return out;
|
|
2413
2874
|
}
|
|
@@ -2441,7 +2902,7 @@ function equalities(c) {
|
|
|
2441
2902
|
}
|
|
2442
2903
|
// A lemma use: the goal's read it matched, and the lemma's read there (equal where the use applies).
|
|
2443
2904
|
const matchedAt = new WeakMap();
|
|
2444
|
-
const holdsAt = (fs, q) => { const f = fs.facts[q.fact]; return
|
|
2905
|
+
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]]))); };
|
|
2445
2906
|
// The models a search compares terms in: random values of the law's variables.
|
|
2446
2907
|
function modelsFor(p, l, n, seed) {
|
|
2447
2908
|
return samples(l.vars, p.params, n, seed).map(s => {
|
|
@@ -2450,22 +2911,33 @@ function modelsFor(p, l, n, seed) {
|
|
|
2450
2911
|
return { m, env };
|
|
2451
2912
|
});
|
|
2452
2913
|
}
|
|
2914
|
+
// The attempts that failed within their time, by program: one tried again with more time (a later step) fails again, as
|
|
2915
|
+
// nothing in it was cut short (its instances, its proof search), so it isn't tried again.
|
|
2916
|
+
const settled = new WeakMap();
|
|
2453
2917
|
// Prove a law with the lemmas given (each proven, with its nodes), trying each scheme at each depth.
|
|
2454
2918
|
// `without`: 'plain', the law with no induction where no scheme applies; 'cases', no induction, then by the cases of
|
|
2455
|
-
// each variable (a natural's zero and successor, a datatype's constructors), none of them using the law again
|
|
2919
|
+
// each variable (a natural's zero and successor, a datatype's constructors), none of them using the law again; 'first',
|
|
2920
|
+
// no induction before the schemes (a law that follows from its lemmas by rewriting).
|
|
2456
2921
|
function proveWith(p, fs, l, lemmas, level, opts, until, per, depths, without) {
|
|
2457
2922
|
const models = modelsFor(p, l, 240, opts.seed ?? 3);
|
|
2458
2923
|
let tried = 0, last;
|
|
2459
2924
|
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: [] }] : []));
|
|
2460
2925
|
const found = opts.induction === false || without === 'cases' ? [] : schemes(p, l);
|
|
2461
|
-
const ss = opts.induction === false ? [undefined] : without === 'cases' ? [undefined, ...cases] : without === 'plain' && !found.length ? [undefined] : found;
|
|
2926
|
+
const ss = opts.induction === false ? [undefined] : without === 'cases' ? [undefined, ...cases] : without === 'plain' && !found.length ? [undefined] : without === 'first' ? [undefined, ...found] : found;
|
|
2927
|
+
const done = settled.get(fs) ?? settled.set(fs, new Set()).get(fs);
|
|
2462
2928
|
for (const depth of depths.filter(d => d <= (opts.depth ?? 3)))
|
|
2463
2929
|
for (const s of ss) {
|
|
2464
2930
|
if (clock() > until)
|
|
2465
2931
|
return { tried, last };
|
|
2932
|
+
const key = JSON.stringify([l.name, s?.name, depth, level, lemmas.map(q => q.spec.name), opts.seed]);
|
|
2933
|
+
if (done.has(key))
|
|
2934
|
+
continue;
|
|
2466
2935
|
tried++;
|
|
2936
|
+
const t1 = clock();
|
|
2467
2937
|
const { verdict, specs, main } = (attemptMs.ms = Math.min(per * (opts.patience ?? 1), until - clock()), attempt(p, fs, l, s, depth, lemmas, level, models));
|
|
2468
2938
|
last = verdict;
|
|
2939
|
+
if (!(verdict.proven && verdict.checked) && clock() <= t1 + attemptMs.ms)
|
|
2940
|
+
done.add(key);
|
|
2469
2941
|
if (verdict.proven && verdict.checked)
|
|
2470
2942
|
return { out: { law: l, spec: specs[main], nodes: specs }, verdict, scheme: s?.name ?? (without ? 'no induction' : undefined), tried };
|
|
2471
2943
|
}
|
|
@@ -2479,8 +2951,16 @@ function proveWith(p, fs, l, lemmas, level, opts, until, per, depths, without) {
|
|
|
2479
2951
|
export function conjectures(p, l, max = 24, maxSize = 6) {
|
|
2480
2952
|
const sortsOf = (s) => (s instanceof Data ? s.name : s);
|
|
2481
2953
|
const vars = [...p.datas.flatMap(d => [{ name: `${d.name.toLowerCase()}1`, sort: d }, { name: `${d.name.toLowerCase()}2`, sort: d }]), { name: 'n1', sort: 'nat' }, { name: 'n2', sort: 'nat' }];
|
|
2482
|
-
|
|
2483
|
-
const
|
|
2954
|
+
// (a third of each sort, read only where an equation is generalised: below)
|
|
2955
|
+
const thirds = [...p.datas.map(d => ({ name: `${d.name.toLowerCase()}3`, sort: d })), { name: 'n3', sort: 'nat' }];
|
|
2956
|
+
const sortOfVar = new Map([...vars, ...thirds].map(v => [v.name, v.sort]));
|
|
2957
|
+
// The values terms are told apart by: 80 drawn as refute draws them, and 40 that fill their size (lists of up to six,
|
|
2958
|
+
// deeper trees), where an equation true of short values only (three butlasts of anything are empty) fails. A term past
|
|
2959
|
+
// the evaluation's bounds at one of the 80 is dropped; at one of the 40 (a tenth of the bounds), that value is unknown.
|
|
2960
|
+
const ss = samples([...vars, ...thirds], p.params, 80, 11), rich = (() => {
|
|
2961
|
+
const rand = rng(13);
|
|
2962
|
+
return Array.from({ length: 40 }, (_, i) => ({ env: new Map([...vars, ...thirds].map(v => [v.name, randomValue(v.sort, rand, 2 + (i % 5), 5, true)])), params: Object.fromEntries(p.params.map(q => [q, randomFn(rand)])) }));
|
|
2963
|
+
})();
|
|
2484
2964
|
const used = new Set();
|
|
2485
2965
|
walk(l.holds, o => { if (o.op === 'call')
|
|
2486
2966
|
used.add(o.fn); });
|
|
@@ -2497,12 +2977,29 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
|
|
|
2497
2977
|
}
|
|
2498
2978
|
}
|
|
2499
2979
|
const fnsUsed = p.fns.filter(f => used.has(f.name));
|
|
2500
|
-
const fp = (x) => {
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2980
|
+
const fp = (x) => {
|
|
2981
|
+
let base;
|
|
2982
|
+
try {
|
|
2983
|
+
base = ss.map(s => evalX(x, s.env, s.params));
|
|
2984
|
+
}
|
|
2985
|
+
catch {
|
|
2986
|
+
return undefined;
|
|
2987
|
+
}
|
|
2988
|
+
// (a tenth of the bounds at those: a value long enough to take more is no witness worth the time)
|
|
2989
|
+
const was = evalBounds.calls;
|
|
2990
|
+
evalBounds.calls = Math.min(was, 2000);
|
|
2991
|
+
try {
|
|
2992
|
+
return JSON.stringify([base, rich.map(s => { try {
|
|
2993
|
+
return evalX(x, s.env, s.params);
|
|
2994
|
+
}
|
|
2995
|
+
catch {
|
|
2996
|
+
return '?';
|
|
2997
|
+
} })]);
|
|
2998
|
+
}
|
|
2999
|
+
finally {
|
|
3000
|
+
evalBounds.calls = was;
|
|
3001
|
+
}
|
|
3002
|
+
};
|
|
2506
3003
|
const classes = new Map();
|
|
2507
3004
|
const addT = (t) => { const f = fp(t.x); if (f === undefined)
|
|
2508
3005
|
return; const key = `${sortsOf(t.sort)}:${f}`; const c = classes.get(key) ?? []; c.push(t); classes.set(key, c); };
|
|
@@ -2671,12 +3168,47 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
|
|
|
2671
3168
|
if (size(big) > size(small))
|
|
2672
3169
|
rules.push({ l: big, r: small, vs });
|
|
2673
3170
|
}
|
|
2674
|
-
|
|
2675
|
-
|
|
3171
|
+
// An equation reading a variable more than once, generalised apart: some of its reads a fresh variable of its sort
|
|
3172
|
+
// (the sort's third), where every value still meets it, so (l1 ++ l1) ++ l2 = l1 ++ (l1 ++ l2) is ++'s associativity.
|
|
3173
|
+
// The split renaming fewest reads is kept (named again in order of appearance); else the equation as found.
|
|
3174
|
+
const bits = (n) => { let c = 0; for (let x = n; x; x >>= 1)
|
|
3175
|
+
c += x & 1; return c; };
|
|
3176
|
+
const apart = (e) => {
|
|
3177
|
+
const count = new Map();
|
|
3178
|
+
walk([e.a, e.b], o => { if (o.op === 'var' && sortOfVar.has(o.name))
|
|
3179
|
+
count.set(o.name, (count.get(o.name) ?? 0) + 1); });
|
|
3180
|
+
for (const [v, m] of count) {
|
|
3181
|
+
const fresh = thirds.find(t => sortsOf(t.sort) === sortsOf(sortOfVar.get(v))).name;
|
|
3182
|
+
if (m < 2 || m > 6 || count.has(fresh))
|
|
3183
|
+
continue;
|
|
3184
|
+
// (the first read never renamed: a split and its mirror are one equation)
|
|
3185
|
+
const masks = Array.from({ length: 2 ** (m - 1) - 1 }, (_, i) => (i + 1) << 1).sort((x, y) => bits(x) - bits(y) || x - y);
|
|
3186
|
+
for (const mask of masks) {
|
|
3187
|
+
let i = 0;
|
|
3188
|
+
const ren = (x) => (Array.isArray(x) ? x.map(ren) : x && typeof x === 'object' ? (x.op === 'var' && x.name === v ? ((mask >> i++) & 1 ? { op: 'var', name: fresh } : x) : Object.fromEntries(Object.entries(x).map(([key, w]) => [key, ren(w)]))) : x);
|
|
3189
|
+
const [a2, b2] = ren([e.a, e.b]), reads = (x, n) => JSON.stringify(x).includes(`"name":"${n}"`);
|
|
3190
|
+
// (each of the two read on both sides: a side that no longer reads a variable says nothing more)
|
|
3191
|
+
if (![v, fresh].every(n => reads(a2, n) && reads(b2, n)))
|
|
3192
|
+
continue;
|
|
3193
|
+
const fa = fp(a2);
|
|
3194
|
+
if (fa !== undefined && fa === fp(b2) && JSON.stringify(a2) !== JSON.stringify(b2)) {
|
|
3195
|
+
const [ca, cb] = canon([a2, b2]).t;
|
|
3196
|
+
return { a: ca, b: cb, size: e.size };
|
|
3197
|
+
}
|
|
3198
|
+
}
|
|
3199
|
+
}
|
|
3200
|
+
return e;
|
|
3201
|
+
};
|
|
3202
|
+
const instance = (e) => kept.some(q => [[q.a, q.b], [q.b, q.a]].some(([x1, x2]) => { const sub = new Map(); return matchX(x1, e.a, q.vs, sub) && matchX(x2, e.b, q.vs, sub); }));
|
|
3203
|
+
for (const found of eqs) {
|
|
3204
|
+
const na = norm(found.a), nb = norm(found.b);
|
|
2676
3205
|
if (JSON.stringify(na) === JSON.stringify(nb))
|
|
2677
3206
|
continue;
|
|
2678
3207
|
// An instance of one kept (both sides at one substitution) adds nothing.
|
|
2679
|
-
if (
|
|
3208
|
+
if (instance(found))
|
|
3209
|
+
continue;
|
|
3210
|
+
const e = apart(found);
|
|
3211
|
+
if (e !== found && instance(e))
|
|
2680
3212
|
continue;
|
|
2681
3213
|
const y = { op: '=', a: e.a, b: e.b }, text = JSON.stringify(y);
|
|
2682
3214
|
if (seen.has(text) || text === lawText || JSON.stringify({ op: '=', a: e.b, b: e.a }) === lawText)
|
|
@@ -2702,8 +3234,11 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
|
|
|
2702
3234
|
if (di < 0)
|
|
2703
3235
|
continue;
|
|
2704
3236
|
const dvar = vars.find(v => v.sort === mk.ret).name;
|
|
2705
|
-
const argSets = (qs) => qs.reduce((acc, q) => acc.flatMap(a2 => (q.sort === 'nat' ? nats.map(n => [...a2, { op: 'var', name: n }]) : q.sort === 'bool' ? [] : [
|
|
2706
|
-
|
|
3237
|
+
const argSets = (qs, both = false) => qs.reduce((acc, q) => acc.flatMap(a2 => (q.sort === 'nat' ? nats.map(n => [...a2, { op: 'var', name: n }]) : q.sort === 'bool' ? [] : vars.filter(v => v.sort === q.sort).slice(0, both ? 2 : 1).map(v => [...a2, { op: 'var', name: v.name }]))), [[]]);
|
|
3238
|
+
// (the function's arguments of the datatype either variable of it, one of them the premise's: elem x z implies
|
|
3239
|
+
// elem x (union y z))
|
|
3240
|
+
const reads = (as) => as.some(a2 => a2.op === 'var' && a2.name === dvar);
|
|
3241
|
+
for (const margs of argSets(mk.params, true).filter(reads))
|
|
2707
3242
|
for (const pargs of argSets(pr.params.filter((_, i) => i !== di))) {
|
|
2708
3243
|
const pAt = (x) => { const as = [...pargs]; as.splice(di, 0, x); return { op: 'holds', x: { op: 'call', fn: pr.name, args: as } }; };
|
|
2709
3244
|
const premise = pAt({ op: 'var', name: dvar }), conclusion = pAt({ op: 'call', fn: mk.name, args: margs });
|
|
@@ -2855,7 +3390,7 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
2855
3390
|
if (c)
|
|
2856
3391
|
return c;
|
|
2857
3392
|
}
|
|
2858
|
-
const first = phase === 'rest' ? undefined : proveWith(p, fs, l, base, lv + 1, opts, until, 6000, [1], 'plain');
|
|
3393
|
+
const first = phase === 'rest' || (opts.lemmasFirst && Array.isArray(opts.lemmas)) ? undefined : proveWith(p, fs, l, base, lv + 1, opts, until, 6000, [1], 'plain');
|
|
2859
3394
|
const one = first && ok(first, base);
|
|
2860
3395
|
if (one)
|
|
2861
3396
|
return one;
|
|
@@ -2864,6 +3399,14 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
2864
3399
|
const without = opts.lemmas === false || opts.induction === false;
|
|
2865
3400
|
if (without)
|
|
2866
3401
|
return ok(proveWith(p, fs, l, base, lv + 1, opts, until, 20000, [2, 3]), base) ?? (opts.induction === false ? undefined : ok(proveWith(p, fs, l, base, lv + 1, opts, until, 3000, [1, 2], 'cases'), base)) ?? done({ proven: false, checked: false, lemmas: [], tried, ...stuckOf(first?.last) });
|
|
3402
|
+
// The law at two unfoldings before any conjecture, each scheme within a short time (3 s of counted work): a law that
|
|
3403
|
+
// needs a case of a field and no lemma is proven there (last (xs ++ [x]) = x: the cases of the tail), and the
|
|
3404
|
+
// conjectures are costly to make. One out of its time is tried again below, with more.
|
|
3405
|
+
if (!Array.isArray(opts.lemmas)) {
|
|
3406
|
+
const two = ok(proveWith(p, fs, l, base, lv + 1, opts, until, 3000, [2]), base);
|
|
3407
|
+
if (two)
|
|
3408
|
+
return two;
|
|
3409
|
+
}
|
|
2867
3410
|
const cands = Array.isArray(opts.lemmas) ? opts.lemmas : conjectures(p, l);
|
|
2868
3411
|
const p2 = ctx ? p : programOf([l, ...cands]), fs2 = ctx ? fs : factsOf(p2);
|
|
2869
3412
|
// Each scheme's goals: the law's, and each companion's (a lemma may be what only a companion's goal reads).
|
|
@@ -2880,17 +3423,30 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
2880
3423
|
const implication = (y) => y.op === 'or' && y.xs.length === 2 && y.xs[0].op === 'not';
|
|
2881
3424
|
const score = (c, hit) => (hit ? 2 : 0) + (implication(c.holds) === implication(l.holds) ? 1 : 0);
|
|
2882
3425
|
if (dataTrace)
|
|
2883
|
-
console.error(`[data] ${l.name}: ${cands.length} conjectures at ${Math.round(clock())} of ${Math.round(until)}`);
|
|
3426
|
+
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('')}`);
|
|
2884
3427
|
const ranked = cands.map(c => ({ c, hit: matchesGoal(c) })).sort((a, b) => score(b.c, b.hit) - score(a.c, a.hit));
|
|
2885
3428
|
// The lemmas proven: those given (`base`) and those found, each found one a level above the last.
|
|
2886
3429
|
const proven = [...base], failed = new Set(), level = () => lv + 1 + proven.length - base.length;
|
|
2887
|
-
|
|
3430
|
+
// A pass of lemmas: of those the goal reads (`hits`) or the others, each proven at one unfolding (8 s of counted work
|
|
3431
|
+
// a lemma, 5 s an attempt), until `most` are proven, three times as many tried, or the pass's time is spent (`end`).
|
|
3432
|
+
// (An attempt's instances aren't counted work, so a pass of many short attempts is bounded by their number too.) The
|
|
3433
|
+
// law is tried again with every lemma proven so far, without induction first (a law that follows from them by
|
|
3434
|
+
// rewriting), then by its schemes: after each lemma the goal reads or of the law's shape, else at the end of the pass.
|
|
3435
|
+
const refuted = new Set();
|
|
3436
|
+
const lemmaPass = (which, most, end, cap, depths) => {
|
|
3437
|
+
let n = 0, since = 0, tries = 0;
|
|
3438
|
+
const again = (how) => ok(proveWith(p2, fs2, l, proven, level(), opts, until, cap, depths, how), proven, p2);
|
|
2888
3439
|
for (const { c, hit } of ranked) {
|
|
2889
|
-
if (clock() >
|
|
2890
|
-
|
|
2891
|
-
if (proven.some(q => q.law === c) ||
|
|
3440
|
+
if (n >= most || tries >= 3 * most || clock() > end)
|
|
3441
|
+
break;
|
|
3442
|
+
if ((which === 'hits') !== hit || proven.some(q => q.law === c) || refuted.has(c))
|
|
3443
|
+
continue;
|
|
3444
|
+
if (refute(c, 200)) {
|
|
3445
|
+
refuted.add(c);
|
|
2892
3446
|
continue;
|
|
2893
|
-
|
|
3447
|
+
}
|
|
3448
|
+
tries++;
|
|
3449
|
+
const r = proveWith(p2, fs2, c, proven, level(), opts, Math.min(end, clock() + 8000 * (opts.patience ?? 1)), 5000, [1]);
|
|
2894
3450
|
tried += r.tried;
|
|
2895
3451
|
if (!r.out) {
|
|
2896
3452
|
failed.add(c);
|
|
@@ -2898,23 +3454,60 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
2898
3454
|
}
|
|
2899
3455
|
failed.delete(c);
|
|
2900
3456
|
proven.push(r.out);
|
|
2901
|
-
|
|
3457
|
+
n++;
|
|
3458
|
+
since++;
|
|
3459
|
+
// (as before the passes: again after a lemma the goal reads, or one of the law's shape, an implication for one)
|
|
3460
|
+
if (which === 'hits' || implication(c.holds) === implication(l.holds)) {
|
|
3461
|
+
since = 0;
|
|
3462
|
+
const r2 = again('first');
|
|
3463
|
+
if (r2)
|
|
3464
|
+
return r2;
|
|
3465
|
+
}
|
|
3466
|
+
}
|
|
3467
|
+
return since ? again('first') : undefined;
|
|
3468
|
+
};
|
|
3469
|
+
// depth 2's round: the lemmas that failed at one unfolding (the first eight, in their order), each at two, the law
|
|
3470
|
+
// tried again after each.
|
|
3471
|
+
const lemmasAt2 = () => {
|
|
3472
|
+
let tries = 0;
|
|
3473
|
+
for (const { c } of ranked) {
|
|
3474
|
+
if (clock() > until || tries >= 8)
|
|
3475
|
+
return undefined;
|
|
3476
|
+
if (proven.some(q => q.law === c) || !failed.has(c) || refuted.has(c))
|
|
3477
|
+
continue;
|
|
3478
|
+
tries++;
|
|
3479
|
+
const r = proveWith(p2, fs2, c, proven, level(), opts, Math.min(until, clock() + 12000 * (opts.patience ?? 1)), 5000, [2]);
|
|
3480
|
+
tried += r.tried;
|
|
3481
|
+
if (!r.out)
|
|
2902
3482
|
continue;
|
|
2903
|
-
|
|
3483
|
+
failed.delete(c);
|
|
3484
|
+
proven.push(r.out);
|
|
3485
|
+
const again = ok(proveWith(p2, fs2, l, proven, level(), opts, until, 6000, [1, 2], 'first'), proven, p2);
|
|
2904
3486
|
if (again)
|
|
2905
3487
|
return again;
|
|
2906
3488
|
}
|
|
2907
3489
|
return undefined;
|
|
2908
3490
|
};
|
|
3491
|
+
// The order: the lemmas the goal reads (up to six proven, the law tried again as lemmaPass says), within 30% of the
|
|
3492
|
+
// time left; the law alone with more time, at two
|
|
3493
|
+
// unfoldings and three; the other lemmas (up to eight, within half the time then left) and the law with them all;
|
|
3494
|
+
// the lemmas that failed at one unfolding, at two; the law at three with every lemma; the law by the cases of a
|
|
3495
|
+
// variable (no induction). An attempt that failed within its time isn't tried again (`settled`).
|
|
3496
|
+
const share = (f) => Math.min(until, clock() + f * Math.max(0, until - clock()));
|
|
2909
3497
|
const steps = [
|
|
2910
|
-
() =>
|
|
3498
|
+
() => lemmaPass('hits', 6, share(0.3), 6000, [1]),
|
|
2911
3499
|
() => ok(proveWith(p, fs, l, base, lv + 1, opts, until, 30000, [2]), base),
|
|
2912
|
-
() =>
|
|
2913
|
-
() =>
|
|
3500
|
+
() => ok(proveWith(p, fs, l, base, lv + 1, opts, until, 12000, [3]), base),
|
|
3501
|
+
() => lemmaPass('others', 8, share(0.5), 12000, [1, 2]),
|
|
3502
|
+
() => lemmasAt2(),
|
|
2914
3503
|
() => ok(proveWith(p2, fs2, l, proven, level(), opts, until, 12000, [3]), proven, p2),
|
|
2915
3504
|
// No induction: the law by the cases of a variable (or none), its definitions unfolded.
|
|
2916
3505
|
() => ok(proveWith(p, fs, l, base, lv + 1, opts, until, 3000, [1, 2], 'cases'), base),
|
|
2917
3506
|
];
|
|
3507
|
+
// Lemmas first (a call's decrease from size laws): those the goal reads, the others, each proven and the law tried
|
|
3508
|
+
// again after it; then the law with every lemma proven, at two unfoldings.
|
|
3509
|
+
if (opts.lemmasFirst && Array.isArray(opts.lemmas))
|
|
3510
|
+
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));
|
|
2918
3511
|
for (const [i, step] of steps.entries()) {
|
|
2919
3512
|
if (clock() > until)
|
|
2920
3513
|
break;
|
|
@@ -2929,3 +3522,179 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
2929
3522
|
const stuckOf = (v) => (v && !v.proven ? { goal: v.goal, stuck: v.stuck } : v && !v.checked ? { goal: 'check', stuck: v.why } : {});
|
|
2930
3523
|
// The law with no cycle: its definitions unfolded, the kernel's prover alone (what the library proves without the search).
|
|
2931
3524
|
export const proveDataToday = (l) => proveData(l, { induction: false });
|
|
3525
|
+
// --- abstract sorts, unknown functions, closures ----------------------------------------------------------------------
|
|
3526
|
+
//
|
|
3527
|
+
// An abstract sort, `opaque('Elem')`: values a law compares for equality and passes around (arguments, results, fields,
|
|
3528
|
+
// an if's choice), and nothing else. It is an ordinary datatype of one constructor of one natural (`el`), so the kernel
|
|
3529
|
+
// and Lean's twin see what they see of any datatype; the restriction is a check (`equalityOnly`, at every `law`): a
|
|
3530
|
+
// match, a constructor, a test or a size of an abstract sort, in the law or in a function it reaches, is refused, save
|
|
3531
|
+
// in the sort's own codecs below (its code and its value at a code), which only an unknown function's encoding reaches.
|
|
3532
|
+
//
|
|
3533
|
+
// Why a law proven so holds at every sort, not only at the naturals the encoding is (what TIP's `declare-sort` and a
|
|
3534
|
+
// goal's `par` claim): a law is ∀ x̄. φ(x̄), φ evaluated by the program's equations. Suppose φ false at values of some
|
|
3535
|
+
// nonempty set S. The evaluation is finite, so it reads finitely many elements of S: send them injectively into the
|
|
3536
|
+
// naturals (S may be finite, of one element even: the naturals being infinite, an injection always exists, which is why
|
|
3537
|
+
// the domain proven over must be infinite). A program that reads elements only by equality, choices and moves computes
|
|
3538
|
+
// at the images the images of what it computed at S: every comparison answers the same (the map is injective), every
|
|
3539
|
+
// other step moves a value; an unknown function is arbitrary, so it may take the images too. So φ is false at the
|
|
3540
|
+
// images, against the proof at the naturals. The check makes the premise true: an order (x < y), arithmetic, a
|
|
3541
|
+
// constant of the sort (el(0)) or a match on its code would tell the encoding apart from S, and is refused. What the
|
|
3542
|
+
// proof uses is beside the point (the kernel may compare codes): the proof is about the naturals, and the claim moved
|
|
3543
|
+
// to S is the law, which reads equality alone. Lean's twin states the law about the inductive `Elem`, whose code no
|
|
3544
|
+
// definition of the law reads: no arithmetic fact about the sort is in the statement it checks.
|
|
3545
|
+
const codecs = new Set(), made = new Map();
|
|
3546
|
+
const madeFn = (name, mk) => { let f = made.get(name); if (!f) {
|
|
3547
|
+
f = mk();
|
|
3548
|
+
made.set(name, f);
|
|
3549
|
+
codecs.add(name);
|
|
3550
|
+
} return f; };
|
|
3551
|
+
export function opaque(name) {
|
|
3552
|
+
const d = data(name, { el: { code: natural } });
|
|
3553
|
+
d.abstract = true;
|
|
3554
|
+
return d;
|
|
3555
|
+
}
|
|
3556
|
+
function equalityOnly(name, y) {
|
|
3557
|
+
if (![...declared.values()].some(d => d.abstract))
|
|
3558
|
+
return;
|
|
3559
|
+
const seen = new Set();
|
|
3560
|
+
const go = (t, where) => walk(t, o => {
|
|
3561
|
+
if ((o.op === 'match' || o.op === 'ctor' || o.op === 'is' || o.op === 'size') && dataNamed(o.data).abstract)
|
|
3562
|
+
throw new Error(`${where} reads ${o.data}, an abstract sort, beyond equality (${o.op === 'ctor' ? 'a constant of it' : o.op === 'size' ? 'its size' : 'its code'}): its values may only be compared and passed around`);
|
|
3563
|
+
if (o.op === 'call' && !codecs.has(o.fn) && !seen.has(o.fn)) {
|
|
3564
|
+
seen.add(o.fn);
|
|
3565
|
+
go(fnOf(o.fn).body(), o.fn);
|
|
3566
|
+
}
|
|
3567
|
+
});
|
|
3568
|
+
go(y, name);
|
|
3569
|
+
}
|
|
3570
|
+
// An unknown function between any sorts, `unknownFn('f', [natural], List)`: a law about it is about every such function.
|
|
3571
|
+
// It is one unknown g of a natural (`fnParam`) read at its arguments' key a: their codes (each injective: a natural
|
|
3572
|
+
// itself, a condition 0 or 1, an abstract value its code, a datatype value its constructor and its fields' codes)
|
|
3573
|
+
// paired, ⟨x, y⟩ = (x + y)² + y being the library's pairing (injective; the function `pairing`). A result of a natural
|
|
3574
|
+
// is g(a) (of one natural argument, f(x) is fnParam's f(x)), a condition g(a) = 0 (the predicate every predicate is), an
|
|
3575
|
+
// integer g(a)'s zigzag decoding, an abstract value the one of code g(a). A datatype's value is decoded at most
|
|
3576
|
+
// g(⟨a, 0⟩) constructors deep: its node at place p (the root 0, the i-th field of the node at p at B·p + i + 1, B the
|
|
3577
|
+
// most fields of a constructor among the datatypes it reaches: a heap's numbering, injective) is the constructor
|
|
3578
|
+
// g(⟨a, 3p + 1⟩) says (0, 1, ..: the first ones, the last for the rest), its natural there g(⟨a, 3p + 2⟩), a field of
|
|
3579
|
+
// another datatype (one declared before, not of its group) decoded from its place g(⟨a, 3p⟩) deep, and at depth 0 the
|
|
3580
|
+
// value of least height. All of it is ordinary functions of the datatype language (structural recursion on the depth):
|
|
3581
|
+
// nothing trusted reads it, and the places grow by a constant factor a level, not by squaring.
|
|
3582
|
+
// Why every function is one of these (the law about every g is then the law about every function): the points read are
|
|
3583
|
+
// ⟨a, 3p + k⟩ for the argument's key a, the node's place p and what is read k, distinct for distinct triples, so for
|
|
3584
|
+
// any function F a g reads at each argument's points F's value there: its depth, its constructors, its naturals.
|
|
3585
|
+
const natN = (n) => (typeof n === 'number' ? new Nat({ op: 'nat', value: n }) : n);
|
|
3586
|
+
// (by recursion on x, ⟨0, y⟩ = y·y + y and ⟨x + 1, y⟩ = ⟨x, y⟩ + 2x + 2y + 1, so that it is a function the search keeps
|
|
3587
|
+
// as one: unfolded, the square of a square is past what the kernel's arithmetic relates, and a read of it at equal
|
|
3588
|
+
// arguments is the same read, which the search's congruences see; on x, an argument's key, which is a variable where
|
|
3589
|
+
// Lean's twin reads the definition, not a successor it would unfold)
|
|
3590
|
+
const pairN = (a, b) => madeFn('pairing', () => {
|
|
3591
|
+
const f = define('pairing', { x: natural, y: natural }, natural, ({ x, y }) => x.match({ zero: () => y.mul(y).plus(y), succ: ({ pred }) => f(pred, y).plus(pred.times(2)).plus(y.times(2)).plus(1) }));
|
|
3592
|
+
return f;
|
|
3593
|
+
})(a, b);
|
|
3594
|
+
const asNatV = (v) => v;
|
|
3595
|
+
// A value's code, injectively.
|
|
3596
|
+
function codeOf(s, v) {
|
|
3597
|
+
if (s === 'nat')
|
|
3598
|
+
return natN(v);
|
|
3599
|
+
if (s === 'bool')
|
|
3600
|
+
return when(v, 1, 0);
|
|
3601
|
+
if (s === 'int')
|
|
3602
|
+
throw new Error('an unknown function of an integer argument isn\'t taken');
|
|
3603
|
+
return asNatV(encoder(s)(v));
|
|
3604
|
+
}
|
|
3605
|
+
function encoder(d) {
|
|
3606
|
+
if (d.abstract)
|
|
3607
|
+
return madeFn(`${d.name}_code`, () => define(`${d.name}_code`, { x: d }, natural, ({ x }) => x.match({ el: ({ code }) => code })));
|
|
3608
|
+
for (const c of d.ctors)
|
|
3609
|
+
for (const f of c.fields)
|
|
3610
|
+
if (f.sort === 'int')
|
|
3611
|
+
throw new Error(`${d.name}: an unknown function of a datatype with an integer field isn't taken`);
|
|
3612
|
+
return madeFn(`${d.name}_code`, () => define(`${d.name}_code`, { x: d }, natural, ({ x }) => x.match(Object.fromEntries(d.ctors.map((c, j) => [c.name,
|
|
3613
|
+
(fs) => pairN(c.fields.length ? c.fields.map(f => codeOf(fieldSort(f), fs[f.name])).reduce((a, b) => pairN(a, b)) : 0, j)])))));
|
|
3614
|
+
}
|
|
3615
|
+
const valueOfCode = (d, n) => madeFn(`${d.name}_of`, () => define(`${d.name}_of`, { n: natural }, d, ({ n: c }) => d.make('el', c)))(n);
|
|
3616
|
+
// A value of a sort of no constructors (a natural, a condition, an integer, an abstract value) from a natural.
|
|
3617
|
+
function primOf(s, n) {
|
|
3618
|
+
if (s === 'nat')
|
|
3619
|
+
return n;
|
|
3620
|
+
if (s === 'bool')
|
|
3621
|
+
return n.eq(0);
|
|
3622
|
+
if (s === 'int')
|
|
3623
|
+
return when(n.modBy(2).eq(0), n.divBy(2).toInt(), n.divBy(2).toInt().negate().minus(1));
|
|
3624
|
+
return valueOfCode(s, n);
|
|
3625
|
+
}
|
|
3626
|
+
const decodable = (s) => s instanceof Data && !s.abstract;
|
|
3627
|
+
// The datatypes a decoding reaches, and the most fields of their constructors (B).
|
|
3628
|
+
function reachOf(d, out = new Set()) {
|
|
3629
|
+
if (out.has(d))
|
|
3630
|
+
return out;
|
|
3631
|
+
out.add(d);
|
|
3632
|
+
for (const c of d.ctors)
|
|
3633
|
+
for (const f of c.fields) {
|
|
3634
|
+
const s = fieldSort(f);
|
|
3635
|
+
if (decodable(s))
|
|
3636
|
+
reachOf(s, out);
|
|
3637
|
+
}
|
|
3638
|
+
return out;
|
|
3639
|
+
}
|
|
3640
|
+
// The value of datatype x at key a, place p, depth: the decoders of g (`gname`), one for each datatype, B its branching.
|
|
3641
|
+
function decoder(gname, x, b) {
|
|
3642
|
+
const name = (y) => `${gname}_${y.name}_dec`;
|
|
3643
|
+
return madeFn(name(x), () => define(name(x), { a: natural, p: natural, depth: natural }, x, ({ a, p, depth }) => depth.match({
|
|
3644
|
+
zero: () => leastOf(x),
|
|
3645
|
+
succ: ({ pred }) => {
|
|
3646
|
+
const g = fnParam(gname), at = (k) => g(pairN(a, p.times(3).plus(k)));
|
|
3647
|
+
const vals = x.ctors.map(c => x.make(c.name, ...c.fields.map((f, i) => {
|
|
3648
|
+
const s = fieldSort(f), q = p.times(b).plus(i + 1);
|
|
3649
|
+
if (!decodable(s))
|
|
3650
|
+
return primOf(s, g(pairN(a, q.times(3).plus(2))));
|
|
3651
|
+
// (a field of the group one level less deep; of another datatype, as deep as its own place says)
|
|
3652
|
+
return decoder(gname, s, b)(a, q, x.group.includes(s.name) ? pred : g(pairN(a, q.times(3))));
|
|
3653
|
+
})));
|
|
3654
|
+
const tag = at(1);
|
|
3655
|
+
return vals.slice(0, -1).reduceRight((acc, v, j) => when(tag.eq(j), v, acc), vals.at(-1));
|
|
3656
|
+
}
|
|
3657
|
+
})));
|
|
3658
|
+
}
|
|
3659
|
+
// A datatype's value of least height (a constructor of least height, its naturals 0).
|
|
3660
|
+
function leastOf(d) {
|
|
3661
|
+
const c = d.ctors.find(k => d.ctorHeight(k) === d.height);
|
|
3662
|
+
return d.make(c.name, ...c.fields.map(f => { const s = fieldSort(f); return s === 'nat' ? 0 : s === 'int' ? new Integer({ op: 'int', value: 0 }) : s.abstract ? valueOfCode(s, 0) : leastOf(s); }));
|
|
3663
|
+
}
|
|
3664
|
+
export function unknownFn(name, from, to) {
|
|
3665
|
+
if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name))
|
|
3666
|
+
throw new Error(`${name}: an unknown function's name is letters and digits`);
|
|
3667
|
+
for (const s of from)
|
|
3668
|
+
if (s instanceof Data)
|
|
3669
|
+
encoder(s);
|
|
3670
|
+
const b = decodable(to) ? Math.max(1, ...[...reachOf(to)].flatMap(d => d.ctors.map(c => c.fields.length))) : 0;
|
|
3671
|
+
return Object.assign((...args) => {
|
|
3672
|
+
if (args.length !== from.length)
|
|
3673
|
+
throw new Error(`${name} takes ${from.length} arguments`);
|
|
3674
|
+
const a = args.length ? args.map((v, i) => codeOf(from[i], v)).reduce((x, y) => pairN(x, y)) : natN(0), g = fnParam(name);
|
|
3675
|
+
return decodable(to) ? decoder(name, to, b)(a, 0, g(pairN(a, 0))) : primOf(to, g(a));
|
|
3676
|
+
}, { param: name });
|
|
3677
|
+
}
|
|
3678
|
+
// Closures (defunctionalisation): a datatype of the functions a field or an argument may hold, one constructor for each
|
|
3679
|
+
// with the values it captures as fields, and `apply`, which matches on the closure: `closures('Op', {x: natural},
|
|
3680
|
+
// natural, {inc: {apply: (_, {x}) => x.plus(1)}, add: {fields: {k: natural}, apply: ({k}, {x}) => x.plus(k)}})`. A field
|
|
3681
|
+
// of sort `Op` is a function-typed field; `Op.add(3)` is a closure; `apply(c, x)` its application. With `unknown: 'other'`,
|
|
3682
|
+
// a constructor `other(code)` whose application is an unknown function of the code and the arguments: a law about every
|
|
3683
|
+
// closure is then about every function too (each is other(0) for some unknown function). Closures are ordinary values
|
|
3684
|
+
// and `apply` an ordinary function: the search and the kernel see nothing new.
|
|
3685
|
+
export function closures(name, args, ret,
|
|
3686
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
3687
|
+
cases, opts = {}) {
|
|
3688
|
+
if ('c' in args)
|
|
3689
|
+
throw new Error(`${name}: an argument named c (the closure's own name in apply)`);
|
|
3690
|
+
const decl = Object.fromEntries(Object.entries(cases).map(([c, x]) => [c, x.fields ?? {}]));
|
|
3691
|
+
if (opts.unknown)
|
|
3692
|
+
decl[opts.unknown] = { code: natural };
|
|
3693
|
+
const d = data(name, decl);
|
|
3694
|
+
const u = opts.unknown ? unknownFn(`${name}_${opts.unknown}`, ['nat', ...Object.values(args)], ret) : undefined;
|
|
3695
|
+
const apply = define(`${name}_apply`, { c: d, ...args }, ret, a => a.c.match({
|
|
3696
|
+
...Object.fromEntries(Object.entries(cases).map(([c, x]) => [c, (fs) => x.apply(fs, Object.fromEntries(Object.keys(args).map(k => [k, a[k]])))])),
|
|
3697
|
+
...(u ? { [opts.unknown]: ({ code }) => u(code, ...Object.keys(args).map(k => a[k])) } : {}),
|
|
3698
|
+
}));
|
|
3699
|
+
return { data: d, apply };
|
|
3700
|
+
}
|