gdp-wired 0.21.0 → 0.23.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 +16 -1
- package/dist/core/bmc.d.ts +38 -0
- package/dist/core/bmc.js +137 -0
- package/dist/core/check.d.ts +1 -1
- package/dist/core/check.js +19 -6
- package/dist/core/cycles.d.ts +15 -0
- package/dist/core/cycles.js +446 -8
- package/dist/core/cyclic.d.ts +6 -1
- package/dist/core/cyclic.js +13 -1
- package/dist/core/data.d.ts +17 -1
- package/dist/core/data.js +637 -97
- package/dist/core/dsl.d.ts +10 -1
- package/dist/core/dsl.js +47 -12
- package/dist/core/infer.js +518 -5
- 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 +480 -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 +77 -42
- package/dist/kernel/cdcl.d.ts +43 -0
- package/dist/kernel/cdcl.js +564 -0
- package/dist/kernel/kernel.d.ts +91 -0
- package/dist/kernel/kernel.js +310 -0
- package/dist/kernel/prove.d.ts +20 -1
- package/dist/kernel/prove.js +119 -44
- package/dist/kernel/qprove.d.ts +18 -0
- package/dist/kernel/qprove.js +157 -0
- package/dist/kernel/reader.d.ts +79 -0
- package/dist/kernel/reader.js +539 -0
- package/dist/kernel/simplex.d.ts +36 -0
- package/dist/kernel/simplex.js +259 -0
- package/dist/lean-kernel/emit.d.ts +19 -1
- package/dist/lean-kernel/emit.js +71 -3
- package/dist/lean-kernel/library.js +2 -0
- package/dist/lean-kernel/qlean.d.ts +26 -0
- package/dist/lean-kernel/qlean.js +105 -0
- package/package.json +6 -2
package/dist/core/data.js
CHANGED
|
@@ -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 = [];
|
|
@@ -696,6 +720,7 @@ function termination(fn, why) {
|
|
|
696
720
|
export function law(name, vars, holds) {
|
|
697
721
|
const vs = Object.entries(vars).map(([n, s]) => ({ name: n, sort: s }));
|
|
698
722
|
const y = holds(Object.fromEntries(vs.map(v => [v.name, wrap(v.sort, { op: 'var', name: v.name })]))).y;
|
|
723
|
+
equalityOnly(name, y);
|
|
699
724
|
return { name, vars: vs, holds: y, params: [...new Set(paramsIn(y))] };
|
|
700
725
|
}
|
|
701
726
|
const fnOf = (name) => { const f = fns.get(name); if (!f)
|
|
@@ -813,20 +838,27 @@ export const showValue = (d, v) => {
|
|
|
813
838
|
return c.fields.length ? `${c.name}(${c.fields.map((f, i) => showValue(fieldSort(f), v.f[i])).join(', ')})` : c.name;
|
|
814
839
|
};
|
|
815
840
|
export const rng = (seed) => () => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed / 2147483648; };
|
|
816
|
-
|
|
841
|
+
// `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),
|
|
842
|
+
// where the plain draw mostly stops at a leaf (a list of length 0 or 1, most often).
|
|
843
|
+
export function randomValue(s, rand, size, natMax = 5, full = false) {
|
|
817
844
|
if (s === 'nat')
|
|
818
845
|
return Math.floor(rand() * (natMax + 1));
|
|
819
846
|
if (s === 'bool')
|
|
820
847
|
return rand() < 0.5 ? 0 : 1;
|
|
821
848
|
if (s === 'int')
|
|
822
849
|
return Math.floor(rand() * (2 * natMax + 1)) - natMax;
|
|
850
|
+
// (an abstract value drawn as a natural is: the same draws, so a law at an abstract sort meets the values it would at
|
|
851
|
+
// the naturals)
|
|
852
|
+
if (s.abstract)
|
|
853
|
+
return { c: 0, f: [Math.floor(rand() * (natMax + 1))] };
|
|
823
854
|
// The leaves: constructors of no field of the group, or (a datatype with none, a rose tree) those of least height.
|
|
824
855
|
const base = s.ctors.filter(c => c.fields.every(f => !inGroup(s, f)));
|
|
825
856
|
const leaves = base.length ? base : s.ctors.filter(c => s.ctorHeight(c) === s.height);
|
|
826
|
-
const
|
|
857
|
+
const inner = full ? s.ctors.filter(c => !leaves.includes(c)) : [];
|
|
858
|
+
const pick = size <= 0 || rand() < (full ? 0.125 : 0.25) ? leaves : inner.length ? inner : s.ctors;
|
|
827
859
|
const c = pick[Math.floor(rand() * pick.length)], j = s.ctors.indexOf(c);
|
|
828
860
|
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)) };
|
|
861
|
+
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
862
|
}
|
|
831
863
|
// A random function of a natural: a table of small values.
|
|
832
864
|
export const randomFn = (rand, natMax = 5) => { const t = new Map(); return n => { if (!t.has(n))
|
|
@@ -1443,7 +1475,7 @@ function mutualScheme(l, v, d) {
|
|
|
1443
1475
|
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
1476
|
}
|
|
1445
1477
|
// 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)));
|
|
1478
|
+
export const rankWidth = (p) => Math.max(1, ...p.fns.map(f => (f.decreases === undefined ? f.measure?.comps.length ?? 1 : 1)));
|
|
1447
1479
|
// Where a well-founded scheme's node wants a datatype's shape: at the values its measure reads, and at those its measure
|
|
1448
1480
|
// reads at each use (a constructor's value a call passes: its size from its fields).
|
|
1449
1481
|
function rankShapes(shapes, rank, uses) {
|
|
@@ -1574,13 +1606,13 @@ function instancesOf(p, fs, w) {
|
|
|
1574
1606
|
console.error(`[data] instances: ${what} at ${Math.round(performance.now() - tt)} ms`); };
|
|
1575
1607
|
const insts = [], seen = new Set();
|
|
1576
1608
|
const inst = (fact, at) => { const i = fs.at.get(fact); if (i === undefined)
|
|
1577
|
-
return; const id =
|
|
1609
|
+
return; const id = sid([i, at]); if (!seen.has(id)) {
|
|
1578
1610
|
seen.add(id);
|
|
1579
1611
|
insts.push({ fact: i, at });
|
|
1580
1612
|
} };
|
|
1581
|
-
const holdsAt = (fact, at) => { const f = fs.facts[fs.at.get(fact)]; return
|
|
1582
|
-
|
|
1583
|
-
|
|
1613
|
+
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]]))); };
|
|
1614
|
+
// (each read once, where walk first reaches it: a read again adds nothing where these are used)
|
|
1615
|
+
const reads = (t) => readsOnce(t).map(o => ({ map: o.map, key: o.key }));
|
|
1584
1616
|
const fnOfMap = (map) => p.fns.find(g => g.name === map);
|
|
1585
1617
|
const ctorOf = (map) => { for (const d of p.datas)
|
|
1586
1618
|
for (const [j, c] of d.ctors.entries())
|
|
@@ -1588,7 +1620,7 @@ function instancesOf(p, fs, w) {
|
|
|
1588
1620
|
return c.fields.length; return undefined; };
|
|
1589
1621
|
const all = [], had = new Set();
|
|
1590
1622
|
const note = (rs) => { const out = []; for (const r of rs) {
|
|
1591
|
-
const id =
|
|
1623
|
+
const id = sid(r);
|
|
1592
1624
|
if (!had.has(id)) {
|
|
1593
1625
|
had.add(id);
|
|
1594
1626
|
all.push(r);
|
|
@@ -1618,7 +1650,7 @@ function instancesOf(p, fs, w) {
|
|
|
1618
1650
|
for (let round = 0; round < w.depth && frontier.length; round++) {
|
|
1619
1651
|
const next = [];
|
|
1620
1652
|
for (const r of frontier) {
|
|
1621
|
-
const f = fnOfMap(r.map), as = f && argsOf(r.key, f.params.length), rid =
|
|
1653
|
+
const f = fnOfMap(r.map), as = f && argsOf(r.key, f.params.length), rid = sid(r);
|
|
1622
1654
|
if (!f || !as || unfolded.has(rid))
|
|
1623
1655
|
continue;
|
|
1624
1656
|
unfolded.add(rid);
|
|
@@ -1714,6 +1746,21 @@ function instancesOf(p, fs, w) {
|
|
|
1714
1746
|
if (as)
|
|
1715
1747
|
(cells.get(r.map) ?? cells.set(r.map, []).get(r.map)).push({ key: r.key, as });
|
|
1716
1748
|
}
|
|
1749
|
+
// Arguments equal by arithmetic alone, one class: (n + 1) ∸ 1 and n (a successor's predecessor, where a definition
|
|
1750
|
+
// on the naturals is unfolded at n + 1), so their reads meet by congruence. The kernel proves the equality itself.
|
|
1751
|
+
const byForm = new Map();
|
|
1752
|
+
for (const list of cells.values())
|
|
1753
|
+
for (const x of list)
|
|
1754
|
+
for (const t of x.as) {
|
|
1755
|
+
const f = linearForm(t);
|
|
1756
|
+
if (f === undefined)
|
|
1757
|
+
continue;
|
|
1758
|
+
const had = byForm.get(f);
|
|
1759
|
+
if (!had)
|
|
1760
|
+
byForm.set(f, t);
|
|
1761
|
+
else if (tid(had) !== tid(t))
|
|
1762
|
+
edge(had, t);
|
|
1763
|
+
}
|
|
1717
1764
|
for (let changed = true; changed && !late();) {
|
|
1718
1765
|
changed = false;
|
|
1719
1766
|
for (const [map, list] of cells) {
|
|
@@ -1761,7 +1808,7 @@ function instancesOf(p, fs, w) {
|
|
|
1761
1808
|
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
1809
|
const cands = built(own) ? [own] : [...cl.terms.values()].filter(t => built(t) && cl.find(tid(t)) === root);
|
|
1763
1810
|
for (const t of cands) {
|
|
1764
|
-
const as2 = as.map((a, i) => (i === di ? t : a)), rid =
|
|
1811
|
+
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
1812
|
const anchor = { read: tid(get(f.name, r.key)), arg: own, value: t }, had = anchoredAt.get(key2) ?? [];
|
|
1766
1813
|
if (!had.some(x => x.read === anchor.read))
|
|
1767
1814
|
anchoredAt.set(key2, [...had, anchor]);
|
|
@@ -1771,7 +1818,7 @@ function instancesOf(p, fs, w) {
|
|
|
1771
1818
|
extra++;
|
|
1772
1819
|
done.add(sigOf(f.name, as2));
|
|
1773
1820
|
if (dataTrace)
|
|
1774
|
-
console.error(`[data] unfold ${f.name} at ${
|
|
1821
|
+
console.error(`[data] unfold ${f.name} at ${brief(as2, 160)} for ${brief(r.key, 80)}`);
|
|
1775
1822
|
inst(`fn ${f.name}`, as2);
|
|
1776
1823
|
note([{ map: f.name, key: keyOf(as2) }]);
|
|
1777
1824
|
ctors(note(reads(holdsAt(`fn ${f.name}`, as2))));
|
|
@@ -1873,10 +1920,10 @@ function instancesOf(p, fs, w) {
|
|
|
1873
1920
|
for (let at = b2; at !== a2;) {
|
|
1874
1921
|
const step = back.get(at);
|
|
1875
1922
|
if (step.cong) {
|
|
1876
|
-
const c = step.cong, k2 =
|
|
1923
|
+
const c = step.cong, k2 = sid([c.map, c.x, c.y]);
|
|
1877
1924
|
if (!counted.has(k2)) {
|
|
1878
1925
|
counted.add(k2);
|
|
1879
|
-
const had = used.get(k2) ?? used.get(
|
|
1926
|
+
const had = used.get(k2) ?? used.get(sid([c.map, c.y, c.x]));
|
|
1880
1927
|
if (had)
|
|
1881
1928
|
had.n++;
|
|
1882
1929
|
else
|
|
@@ -1889,10 +1936,11 @@ function instancesOf(p, fs, w) {
|
|
|
1889
1936
|
};
|
|
1890
1937
|
// The values this model reads: the conclusions' reads, and each fact's where the model takes it (an if's condition
|
|
1891
1938
|
// and taken branch, an implication's conclusion where its premise holds).
|
|
1892
|
-
const read = new Set();
|
|
1939
|
+
const read = new Set(), looked = [new WeakSet(), new WeakSet()];
|
|
1893
1940
|
const look = (t, whole) => {
|
|
1894
|
-
if (!t || typeof t !== 'object')
|
|
1941
|
+
if (!t || typeof t !== 'object' || looked[+whole].has(t))
|
|
1895
1942
|
return;
|
|
1943
|
+
looked[+whole].add(t);
|
|
1896
1944
|
if (Array.isArray(t)) {
|
|
1897
1945
|
t.forEach(x => look(x, whole));
|
|
1898
1946
|
return;
|
|
@@ -1960,7 +2008,7 @@ function instancesOf(p, fs, w) {
|
|
|
1960
2008
|
for (const es of adj.values())
|
|
1961
2009
|
for (const e of es)
|
|
1962
2010
|
if (e.cong) {
|
|
1963
|
-
const k2 =
|
|
2011
|
+
const k2 = sid([e.cong.map, e.cong.x, e.cong.y]), k3 = sid([e.cong.map, e.cong.y, e.cong.x]);
|
|
1964
2012
|
if (!used.has(k2) && !used.has(k3))
|
|
1965
2013
|
used.set(k2, { map: e.cong.map, at: [...e.cong.x, ...e.cong.y], n: 1 });
|
|
1966
2014
|
}
|
|
@@ -1975,10 +2023,156 @@ function instancesOf(p, fs, w) {
|
|
|
1975
2023
|
return insts;
|
|
1976
2024
|
}
|
|
1977
2025
|
let varSorts = new Map();
|
|
1978
|
-
// A term's
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
2026
|
+
// 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
|
|
2027
|
+
// pairing reads its arguments again ((a + b)·(a + b) + b), so a nested read's text grows exponentially with its depth
|
|
2028
|
+
// 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.
|
|
2029
|
+
let idMemo = new WeakMap(), idTable = new Map(), idGen = 0;
|
|
2030
|
+
const sid = (t) => {
|
|
2031
|
+
if (t === null || typeof t !== 'object')
|
|
2032
|
+
return JSON.stringify(t) ?? String(t);
|
|
2033
|
+
const had = idMemo.get(t);
|
|
2034
|
+
if (had !== undefined)
|
|
2035
|
+
return had;
|
|
2036
|
+
let leaf = true;
|
|
2037
|
+
const part = (v) => { if (v !== null && typeof v === 'object') {
|
|
2038
|
+
leaf = false;
|
|
2039
|
+
return sid(v);
|
|
2040
|
+
} return JSON.stringify(v) ?? 'null'; };
|
|
2041
|
+
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(',')}}`;
|
|
2042
|
+
let out;
|
|
2043
|
+
if (leaf)
|
|
2044
|
+
out = JSON.stringify(t);
|
|
2045
|
+
else {
|
|
2046
|
+
if (idTable.size > 1_000_000) {
|
|
2047
|
+
idTable = new Map();
|
|
2048
|
+
idMemo = new WeakMap();
|
|
2049
|
+
idGen++;
|
|
2050
|
+
}
|
|
2051
|
+
out = idTable.get(shape) ?? `#${idGen}.${idTable.size}`;
|
|
2052
|
+
if (!idTable.has(shape))
|
|
2053
|
+
idTable.set(shape, out);
|
|
2054
|
+
}
|
|
2055
|
+
idMemo.set(t, out);
|
|
2056
|
+
return out;
|
|
2057
|
+
};
|
|
2058
|
+
const tid = (t) => sid(t);
|
|
2059
|
+
// A natural term's linear form (Σ cᵢ·atomᵢ + c, an atom a variable or a read, its text its id), where it is one: a
|
|
2060
|
+
// truncated difference by a constant only where the constant is at most the term's (x + 1 ∸ 1 is x); else undefined.
|
|
2061
|
+
function linearForm(e) {
|
|
2062
|
+
const go = (t) => {
|
|
2063
|
+
switch (t.op) {
|
|
2064
|
+
case 'const': return { cs: new Map(), c: t.value };
|
|
2065
|
+
case 'var':
|
|
2066
|
+
case 'get': return { cs: new Map([[tid(t), 1]]), c: 0 };
|
|
2067
|
+
case 'add': {
|
|
2068
|
+
const a = go(t.a), b = go(t.b);
|
|
2069
|
+
if (!a || !b)
|
|
2070
|
+
return undefined;
|
|
2071
|
+
const cs = new Map(a.cs);
|
|
2072
|
+
for (const [x, k2] of b.cs)
|
|
2073
|
+
cs.set(x, (cs.get(x) ?? 0) + k2);
|
|
2074
|
+
return { cs, c: a.c + b.c };
|
|
2075
|
+
}
|
|
2076
|
+
case 'mul': {
|
|
2077
|
+
const a = go(t.a);
|
|
2078
|
+
return a && { cs: new Map([...a.cs].map(([x, k2]) => [x, k2 * t.k])), c: a.c * t.k };
|
|
2079
|
+
}
|
|
2080
|
+
case 'sub': {
|
|
2081
|
+
const a = go(t.a);
|
|
2082
|
+
return a && t.b.op === 'const' && a.c >= t.b.value ? { cs: a.cs, c: a.c - t.b.value } : undefined;
|
|
2083
|
+
}
|
|
2084
|
+
case 'if':
|
|
2085
|
+
case 'min':
|
|
2086
|
+
case 'max':
|
|
2087
|
+
case 'prod': return undefined;
|
|
2088
|
+
}
|
|
2089
|
+
};
|
|
2090
|
+
const f = go(e);
|
|
2091
|
+
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}`;
|
|
2092
|
+
}
|
|
2093
|
+
// substC and substE (kernel/kernel.ts) at variables alone, each object once: a term read twice within another (a key's
|
|
2094
|
+
// pairing) is substituted once and shared, so what the search reads of a fact stays the size of its objects. The same
|
|
2095
|
+
// terms, field for field; a flag or a binder is left to substC.
|
|
2096
|
+
function substShared(c, vars) {
|
|
2097
|
+
const memo = new Map();
|
|
2098
|
+
const e = (x) => {
|
|
2099
|
+
const had = memo.get(x);
|
|
2100
|
+
if (had)
|
|
2101
|
+
return had;
|
|
2102
|
+
let out;
|
|
2103
|
+
switch (x.op) {
|
|
2104
|
+
case 'var':
|
|
2105
|
+
out = vars[x.name] ?? x;
|
|
2106
|
+
break;
|
|
2107
|
+
case 'const':
|
|
2108
|
+
out = x;
|
|
2109
|
+
break;
|
|
2110
|
+
case 'mul':
|
|
2111
|
+
out = { ...x, a: e(x.a) };
|
|
2112
|
+
break;
|
|
2113
|
+
case 'if':
|
|
2114
|
+
out = { op: 'if', c: cc(x.c), then: e(x.then), else: e(x.else) };
|
|
2115
|
+
break;
|
|
2116
|
+
case 'get':
|
|
2117
|
+
out = { op: 'get', map: x.map, key: e(x.key) };
|
|
2118
|
+
break;
|
|
2119
|
+
case 'prod':
|
|
2120
|
+
case 'add':
|
|
2121
|
+
case 'sub':
|
|
2122
|
+
case 'min':
|
|
2123
|
+
case 'max':
|
|
2124
|
+
out = { ...x, a: e(x.a), b: e(x.b) };
|
|
2125
|
+
break;
|
|
2126
|
+
default: out = substE(x, { vars, maps: {}, flags: {} });
|
|
2127
|
+
}
|
|
2128
|
+
memo.set(x, out);
|
|
2129
|
+
return out;
|
|
2130
|
+
};
|
|
2131
|
+
const cc = (y) => {
|
|
2132
|
+
const had = memo.get(y);
|
|
2133
|
+
if (had)
|
|
2134
|
+
return had;
|
|
2135
|
+
let out;
|
|
2136
|
+
if (y.op === 'not')
|
|
2137
|
+
out = { op: 'not', x: cc(y.x) };
|
|
2138
|
+
else if (y.op === 'and' || y.op === 'or')
|
|
2139
|
+
out = { op: y.op, xs: y.xs.map(cc) };
|
|
2140
|
+
else if (y.op === 'flag' || y.op === 'all')
|
|
2141
|
+
out = substC(y, { vars, maps: {}, flags: {} });
|
|
2142
|
+
else
|
|
2143
|
+
out = { ...y, a: e(y.a), b: e(y.b) };
|
|
2144
|
+
memo.set(y, out);
|
|
2145
|
+
return out;
|
|
2146
|
+
};
|
|
2147
|
+
return cc(c);
|
|
2148
|
+
}
|
|
2149
|
+
// Whether a term reads a variable (its text has `"op":"var"`), once per object.
|
|
2150
|
+
const varMemo = new WeakMap();
|
|
2151
|
+
const readsVar = (t) => {
|
|
2152
|
+
if (!t || typeof t !== 'object')
|
|
2153
|
+
return false;
|
|
2154
|
+
const had = varMemo.get(t);
|
|
2155
|
+
if (had !== undefined)
|
|
2156
|
+
return had;
|
|
2157
|
+
const out = t.op === 'var' || (Array.isArray(t) ? t.some(readsVar) : Object.values(t).some(readsVar));
|
|
2158
|
+
varMemo.set(t, out);
|
|
2159
|
+
return out;
|
|
2160
|
+
};
|
|
2161
|
+
// A term's text for a trace, cut at n characters (not written out past 4,000).
|
|
2162
|
+
const brief = (t, n) => (textLength(t) > 4000 ? `(${textLength(t)} characters)` : JSON.stringify(t).slice(0, n));
|
|
2163
|
+
// The length of a term's text, without writing it (memoised per object, as `sid`).
|
|
2164
|
+
const lenMemo = new WeakMap();
|
|
2165
|
+
const textLength = (t) => {
|
|
2166
|
+
if (t === null || typeof t !== 'object')
|
|
2167
|
+
return (JSON.stringify(t) ?? 'null').length;
|
|
2168
|
+
const had = lenMemo.get(t);
|
|
2169
|
+
if (had !== undefined)
|
|
2170
|
+
return had;
|
|
2171
|
+
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));
|
|
2172
|
+
const out = 2 + parts.reduce((a, b) => a + b, 0) + Math.max(0, parts.length - 1);
|
|
2173
|
+
lenMemo.set(t, out);
|
|
2174
|
+
return out;
|
|
2175
|
+
};
|
|
1982
2176
|
// An instance unfolded where a read's argument equals a constructor's value: the read it stands for (for `reached`).
|
|
1983
2177
|
const anchoredAt = new Map();
|
|
1984
2178
|
const typeOfVar = (_p, t) => (t.op === 'var' ? varSorts.get(t.name) : undefined);
|
|
@@ -1999,7 +2193,7 @@ function matches(pattern, vars, t, s) {
|
|
|
1999
2193
|
if (pattern.op === 'var' && vars.has(pattern.name)) {
|
|
2000
2194
|
const had = s[pattern.name];
|
|
2001
2195
|
if (had)
|
|
2002
|
-
return
|
|
2196
|
+
return sid(had) === sid(t) ? s : undefined;
|
|
2003
2197
|
return { ...s, [pattern.name]: t };
|
|
2004
2198
|
}
|
|
2005
2199
|
if (pattern.op !== t.op)
|
|
@@ -2014,11 +2208,11 @@ function matches(pattern, vars, t, s) {
|
|
|
2014
2208
|
if (!b || typeof b !== 'object')
|
|
2015
2209
|
return undefined;
|
|
2016
2210
|
if (a.op && ['<', '<=', '=', 'and', 'or', 'not'].includes(a.op))
|
|
2017
|
-
out =
|
|
2211
|
+
out = sid(a) === sid(b) ? out : undefined;
|
|
2018
2212
|
else
|
|
2019
2213
|
out = matches(a, vars, b, out);
|
|
2020
2214
|
}
|
|
2021
|
-
else if (
|
|
2215
|
+
else if (sid(a) !== sid(b))
|
|
2022
2216
|
return undefined;
|
|
2023
2217
|
}
|
|
2024
2218
|
return out;
|
|
@@ -2026,7 +2220,7 @@ function matches(pattern, vars, t, s) {
|
|
|
2026
2220
|
function casesOf(p, unfolded, vars, models) {
|
|
2027
2221
|
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
2222
|
: 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) =>
|
|
2223
|
+
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
2224
|
// The functions' facts the goal unfolds.
|
|
2031
2225
|
const roots = unfolded;
|
|
2032
2226
|
const sigs = models.map(({ m, env }) => {
|
|
@@ -2037,9 +2231,11 @@ function casesOf(p, unfolded, vars, models) {
|
|
|
2037
2231
|
catch {
|
|
2038
2232
|
return undefined;
|
|
2039
2233
|
} };
|
|
2234
|
+
const seen = new WeakSet();
|
|
2040
2235
|
const go = (t) => {
|
|
2041
|
-
if (!t || typeof t !== 'object')
|
|
2236
|
+
if (!t || typeof t !== 'object' || seen.has(t))
|
|
2042
2237
|
return;
|
|
2238
|
+
seen.add(t);
|
|
2043
2239
|
if (Array.isArray(t)) {
|
|
2044
2240
|
t.forEach(go);
|
|
2045
2241
|
return;
|
|
@@ -2050,7 +2246,7 @@ function casesOf(p, unfolded, vars, models) {
|
|
|
2050
2246
|
if (v === undefined)
|
|
2051
2247
|
return;
|
|
2052
2248
|
if (plainC(o.c)) {
|
|
2053
|
-
const key =
|
|
2249
|
+
const key = sid(o.c);
|
|
2054
2250
|
if (!out.has(key))
|
|
2055
2251
|
out.set(key, { c: o.c, t: v });
|
|
2056
2252
|
}
|
|
@@ -2127,7 +2323,7 @@ function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
|
|
|
2127
2323
|
const uses = [...ih, ...lemmaUses];
|
|
2128
2324
|
if (dataTrace)
|
|
2129
2325
|
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} := ${
|
|
2326
|
+
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
2327
|
// The lemmas' conclusions are unfolded like the law's (they are what the goal reads, said another way); the cycle's
|
|
2132
2328
|
// own uses only from depth 3.
|
|
2133
2329
|
const instsFor = (ms, us, every = false) => instancesOf(p, fs, { roots: [concl], others: us.map(useConcl), depth, shapesAt, etaAt: [...shapesAt, ...valuesCompared(p, mb.law)], models: ms, every, until: t0 + attemptMs.ms });
|
|
@@ -2195,10 +2391,15 @@ const dataRate = 300;
|
|
|
2195
2391
|
// 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
2392
|
// conclusion where its premise holds); a congruence where both its reads are reached.
|
|
2197
2393
|
function reached(p, fs, insts, from, ms) {
|
|
2198
|
-
const reach = new Set(), id = (t) =>
|
|
2394
|
+
const reach = new Set(), id = (t) => sid(t), done = new Map();
|
|
2395
|
+
// (an object once a model: what it reaches there is the same each time)
|
|
2199
2396
|
const active = (t, m, env) => {
|
|
2200
2397
|
if (!t || typeof t !== 'object')
|
|
2201
2398
|
return;
|
|
2399
|
+
const seen = done.get(env) ?? done.set(env, new WeakSet()).get(env);
|
|
2400
|
+
if (seen.has(t))
|
|
2401
|
+
return;
|
|
2402
|
+
seen.add(t);
|
|
2202
2403
|
if (Array.isArray(t)) {
|
|
2203
2404
|
t.forEach(x => active(x, m, env));
|
|
2204
2405
|
return;
|
|
@@ -2233,8 +2434,8 @@ function reached(p, fs, insts, from, ms) {
|
|
|
2233
2434
|
const each = (t) => { for (const { m, env } of ms)
|
|
2234
2435
|
active(t, m, env); };
|
|
2235
2436
|
// The conclusion and the uses' are read whole: the goal is where the law fails, which no model is.
|
|
2236
|
-
|
|
2237
|
-
reach.add(
|
|
2437
|
+
walkOnce(from, o => { if (o.op === 'get')
|
|
2438
|
+
reach.add(sid(o)); });
|
|
2238
2439
|
const anchor = (q) => {
|
|
2239
2440
|
const name = fs.facts[q.fact].name;
|
|
2240
2441
|
if (name.startsWith('fn '))
|
|
@@ -2268,7 +2469,7 @@ function reached(p, fs, insts, from, ms) {
|
|
|
2268
2469
|
const name = fs.facts[q.fact].name;
|
|
2269
2470
|
if (name.startsWith('cong ') || name.startsWith('nullary '))
|
|
2270
2471
|
continue;
|
|
2271
|
-
const virtual = anchoredAt.get(
|
|
2472
|
+
const virtual = anchoredAt.get(sid([q.fact, q.at])) ?? [];
|
|
2272
2473
|
const same = (v) => ms.every(({ m, env }) => { try {
|
|
2273
2474
|
return m.evalE(v.arg, env) === m.evalE(v.value, env);
|
|
2274
2475
|
}
|
|
@@ -2308,37 +2509,39 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
|
|
|
2308
2509
|
for (const leaf of leaves(b))
|
|
2309
2510
|
union(a, leaf);
|
|
2310
2511
|
// 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
|
-
|
|
2512
|
+
const cells = new Map(), classes = new Map();
|
|
2513
|
+
const close = (t) => {
|
|
2514
|
+
walkOnce(t, o => { if (o.op !== 'get')
|
|
2515
|
+
return; const n = fs.arity.get(o.map), as = n ? argsOf(o.key, n) : undefined; if (as)
|
|
2516
|
+
(cells.get(o.map) ?? cells.set(o.map, []).get(o.map)).push({ key: o.key, as }); });
|
|
2517
|
+
for (let changed = true, rounds = 0; changed && rounds < 8; rounds++) {
|
|
2518
|
+
changed = false;
|
|
2519
|
+
for (const [map, list] of cells) {
|
|
2520
|
+
const bySig = new Map();
|
|
2521
|
+
for (const x of list) {
|
|
2522
|
+
const sig = x.as.map(t2 => find(id(t2))).join('\u0001'), y = bySig.get(sig), cx = get(map, x.key);
|
|
2523
|
+
if (!y) {
|
|
2524
|
+
bySig.set(sig, cx);
|
|
2525
|
+
continue;
|
|
2526
|
+
}
|
|
2527
|
+
if (find(id(y)) !== find(id(cx))) {
|
|
2528
|
+
union(y, cx);
|
|
2529
|
+
changed = true;
|
|
2530
|
+
}
|
|
2328
2531
|
}
|
|
2329
2532
|
}
|
|
2330
2533
|
}
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
}
|
|
2534
|
+
classes.clear();
|
|
2535
|
+
for (const [key, e] of terms) {
|
|
2536
|
+
const r = find(key);
|
|
2537
|
+
(classes.get(r) ?? classes.set(r, []).get(r)).push(e);
|
|
2538
|
+
}
|
|
2539
|
+
};
|
|
2540
|
+
close([from, insts.map(q => holdsAt(fs, q))]);
|
|
2337
2541
|
const members = (t) => { const k0 = tid(t); return [t, ...(classes.get(find(k0)) ?? []).filter(e => tid(e) !== k0)]; };
|
|
2338
2542
|
const out = [], seen = new Set();
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
reads.push(o); });
|
|
2543
|
+
const goalReads = readsOnce([from, insts.map(q => holdsAt(fs, q))]);
|
|
2544
|
+
let reads = goalReads;
|
|
2342
2545
|
for (let round = 0; round < 2; round++) {
|
|
2343
2546
|
const fresh = [];
|
|
2344
2547
|
const cands = [];
|
|
@@ -2350,17 +2553,41 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
|
|
|
2350
2553
|
walk(encY(p, lm.law.holds, new Map()), o => { if (o.op === 'get')
|
|
2351
2554
|
sides.push(o); });
|
|
2352
2555
|
const tops = sides.filter(a => !sides.some(b => b !== a && JSON.stringify(b).includes(JSON.stringify(a))));
|
|
2353
|
-
for (const top of tops)
|
|
2556
|
+
for (const top of tops) {
|
|
2557
|
+
const n = fs.arity.get(top.map) ?? 1, pats = argsOf(top.key, n);
|
|
2558
|
+
// A pattern's match at a term alone, once (a match given others' bindings is it, where it agrees with them).
|
|
2559
|
+
const alone = pats?.map(() => new Map());
|
|
2560
|
+
const matchAt = (q, m, sb) => {
|
|
2561
|
+
const memo = alone[q];
|
|
2562
|
+
if (!memo.has(m))
|
|
2563
|
+
memo.set(m, matches(pats[q], vars, m, {}));
|
|
2564
|
+
const r = memo.get(m);
|
|
2565
|
+
if (!r)
|
|
2566
|
+
return undefined;
|
|
2567
|
+
let out = sb;
|
|
2568
|
+
for (const [x, v] of Object.entries(r)) {
|
|
2569
|
+
const had = sb[x];
|
|
2570
|
+
if (had) {
|
|
2571
|
+
if (sid(had) !== sid(v))
|
|
2572
|
+
return undefined;
|
|
2573
|
+
}
|
|
2574
|
+
else
|
|
2575
|
+
out = out === sb ? { ...sb, [x]: v } : (out[x] = v, out);
|
|
2576
|
+
}
|
|
2577
|
+
return out;
|
|
2578
|
+
};
|
|
2354
2579
|
for (const t of reads) {
|
|
2355
2580
|
if (t.op !== 'get' || t.map !== top.map)
|
|
2356
2581
|
continue;
|
|
2357
2582
|
// Each argument of the read matched up to its class (a key of several arguments is their pairing).
|
|
2358
|
-
const
|
|
2583
|
+
const args = argsOf(t.key, n);
|
|
2359
2584
|
if (!pats || !args)
|
|
2360
2585
|
continue;
|
|
2361
2586
|
let subs = [{}];
|
|
2362
|
-
for (const
|
|
2363
|
-
|
|
2587
|
+
for (const q of pats.keys()) {
|
|
2588
|
+
const ms = members(args[q]).slice(0, 256);
|
|
2589
|
+
subs = subs.flatMap(sb => ms.flatMap(m => { const r = matchAt(q, m, sb); return r ? [r] : []; })).slice(0, 512);
|
|
2590
|
+
}
|
|
2364
2591
|
for (const sub of subs) {
|
|
2365
2592
|
if (Object.keys(sub).length !== vars.size)
|
|
2366
2593
|
continue;
|
|
@@ -2374,7 +2601,7 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
|
|
|
2374
2601
|
} }).length : 1;
|
|
2375
2602
|
if (!score)
|
|
2376
2603
|
continue;
|
|
2377
|
-
const k2 =
|
|
2604
|
+
const k2 = sid([lm.node, sub]);
|
|
2378
2605
|
if (seen.has(k2))
|
|
2379
2606
|
continue;
|
|
2380
2607
|
seen.add(k2);
|
|
@@ -2385,9 +2612,10 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
|
|
|
2385
2612
|
catch {
|
|
2386
2613
|
return -1;
|
|
2387
2614
|
} }))]) : 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:
|
|
2615
|
+
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
2616
|
}
|
|
2390
2617
|
}
|
|
2618
|
+
}
|
|
2391
2619
|
}
|
|
2392
2620
|
// First, as found: four of a lemma, twelve in all (the next round reads their conclusions). Then the rest, best first
|
|
2393
2621
|
// (the most models, then the smallest terms), one of each set of values, up to `perLemma` of a lemma and `total` in
|
|
@@ -2400,14 +2628,20 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
|
|
|
2400
2628
|
continue;
|
|
2401
2629
|
take(c);
|
|
2402
2630
|
first.add(c);
|
|
2403
|
-
|
|
2404
|
-
fresh.push(o); });
|
|
2631
|
+
fresh.push(substC(lemmas.find(lm => lm.node === c.use.node).concl, { vars: c.use.subst, maps: {}, flags: {} }));
|
|
2405
2632
|
}
|
|
2406
2633
|
const rest = cands.filter(c => !first.has(c)).sort((a, b) => b.score - a.score || a.size - b.size);
|
|
2407
2634
|
for (const c of rest)
|
|
2408
2635
|
if (!fps.has(c.fp) && out.length < lemmaCaps.total && out.filter(u => u.node === c.use.node).length < lemmaCaps.perLemma)
|
|
2409
2636
|
take(c);
|
|
2410
|
-
reads
|
|
2637
|
+
// The second round: the reads of the first's conclusions, and the goal's again, matched up to the classes those
|
|
2638
|
+
// conclusions join (assoc's use makes x ++ (y ++ [z]) and (x ++ y) ++ [z] one, where rev of a snoc then matches).
|
|
2639
|
+
for (const c of fresh)
|
|
2640
|
+
for (const [a2, b2] of equalities(c))
|
|
2641
|
+
for (const leaf of leaves(b2))
|
|
2642
|
+
union(a2, leaf);
|
|
2643
|
+
close(fresh);
|
|
2644
|
+
reads = readsOnce([fresh, goalReads]);
|
|
2411
2645
|
}
|
|
2412
2646
|
return out;
|
|
2413
2647
|
}
|
|
@@ -2441,7 +2675,7 @@ function equalities(c) {
|
|
|
2441
2675
|
}
|
|
2442
2676
|
// A lemma use: the goal's read it matched, and the lemma's read there (equal where the use applies).
|
|
2443
2677
|
const matchedAt = new WeakMap();
|
|
2444
|
-
const holdsAt = (fs, q) => { const f = fs.facts[q.fact]; return
|
|
2678
|
+
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
2679
|
// The models a search compares terms in: random values of the law's variables.
|
|
2446
2680
|
function modelsFor(p, l, n, seed) {
|
|
2447
2681
|
return samples(l.vars, p.params, n, seed).map(s => {
|
|
@@ -2450,22 +2684,33 @@ function modelsFor(p, l, n, seed) {
|
|
|
2450
2684
|
return { m, env };
|
|
2451
2685
|
});
|
|
2452
2686
|
}
|
|
2687
|
+
// The attempts that failed within their time, by program: one tried again with more time (a later step) fails again, as
|
|
2688
|
+
// nothing in it was cut short (its instances, its proof search), so it isn't tried again.
|
|
2689
|
+
const settled = new WeakMap();
|
|
2453
2690
|
// Prove a law with the lemmas given (each proven, with its nodes), trying each scheme at each depth.
|
|
2454
2691
|
// `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
|
|
2692
|
+
// each variable (a natural's zero and successor, a datatype's constructors), none of them using the law again; 'first',
|
|
2693
|
+
// no induction before the schemes (a law that follows from its lemmas by rewriting).
|
|
2456
2694
|
function proveWith(p, fs, l, lemmas, level, opts, until, per, depths, without) {
|
|
2457
2695
|
const models = modelsFor(p, l, 240, opts.seed ?? 3);
|
|
2458
2696
|
let tried = 0, last;
|
|
2459
2697
|
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
2698
|
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;
|
|
2699
|
+
const ss = opts.induction === false ? [undefined] : without === 'cases' ? [undefined, ...cases] : without === 'plain' && !found.length ? [undefined] : without === 'first' ? [undefined, ...found] : found;
|
|
2700
|
+
const done = settled.get(fs) ?? settled.set(fs, new Set()).get(fs);
|
|
2462
2701
|
for (const depth of depths.filter(d => d <= (opts.depth ?? 3)))
|
|
2463
2702
|
for (const s of ss) {
|
|
2464
2703
|
if (clock() > until)
|
|
2465
2704
|
return { tried, last };
|
|
2705
|
+
const key = JSON.stringify([l.name, s?.name, depth, level, lemmas.map(q => q.spec.name), opts.seed]);
|
|
2706
|
+
if (done.has(key))
|
|
2707
|
+
continue;
|
|
2466
2708
|
tried++;
|
|
2709
|
+
const t1 = clock();
|
|
2467
2710
|
const { verdict, specs, main } = (attemptMs.ms = Math.min(per * (opts.patience ?? 1), until - clock()), attempt(p, fs, l, s, depth, lemmas, level, models));
|
|
2468
2711
|
last = verdict;
|
|
2712
|
+
if (!(verdict.proven && verdict.checked) && clock() <= t1 + attemptMs.ms)
|
|
2713
|
+
done.add(key);
|
|
2469
2714
|
if (verdict.proven && verdict.checked)
|
|
2470
2715
|
return { out: { law: l, spec: specs[main], nodes: specs }, verdict, scheme: s?.name ?? (without ? 'no induction' : undefined), tried };
|
|
2471
2716
|
}
|
|
@@ -2479,8 +2724,16 @@ function proveWith(p, fs, l, lemmas, level, opts, until, per, depths, without) {
|
|
|
2479
2724
|
export function conjectures(p, l, max = 24, maxSize = 6) {
|
|
2480
2725
|
const sortsOf = (s) => (s instanceof Data ? s.name : s);
|
|
2481
2726
|
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
|
|
2727
|
+
// (a third of each sort, read only where an equation is generalised: below)
|
|
2728
|
+
const thirds = [...p.datas.map(d => ({ name: `${d.name.toLowerCase()}3`, sort: d })), { name: 'n3', sort: 'nat' }];
|
|
2729
|
+
const sortOfVar = new Map([...vars, ...thirds].map(v => [v.name, v.sort]));
|
|
2730
|
+
// The values terms are told apart by: 80 drawn as refute draws them, and 40 that fill their size (lists of up to six,
|
|
2731
|
+
// deeper trees), where an equation true of short values only (three butlasts of anything are empty) fails. A term past
|
|
2732
|
+
// 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.
|
|
2733
|
+
const ss = samples([...vars, ...thirds], p.params, 80, 11), rich = (() => {
|
|
2734
|
+
const rand = rng(13);
|
|
2735
|
+
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)])) }));
|
|
2736
|
+
})();
|
|
2484
2737
|
const used = new Set();
|
|
2485
2738
|
walk(l.holds, o => { if (o.op === 'call')
|
|
2486
2739
|
used.add(o.fn); });
|
|
@@ -2497,12 +2750,29 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
|
|
|
2497
2750
|
}
|
|
2498
2751
|
}
|
|
2499
2752
|
const fnsUsed = p.fns.filter(f => used.has(f.name));
|
|
2500
|
-
const fp = (x) => {
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2753
|
+
const fp = (x) => {
|
|
2754
|
+
let base;
|
|
2755
|
+
try {
|
|
2756
|
+
base = ss.map(s => evalX(x, s.env, s.params));
|
|
2757
|
+
}
|
|
2758
|
+
catch {
|
|
2759
|
+
return undefined;
|
|
2760
|
+
}
|
|
2761
|
+
// (a tenth of the bounds at those: a value long enough to take more is no witness worth the time)
|
|
2762
|
+
const was = evalBounds.calls;
|
|
2763
|
+
evalBounds.calls = Math.min(was, 2000);
|
|
2764
|
+
try {
|
|
2765
|
+
return JSON.stringify([base, rich.map(s => { try {
|
|
2766
|
+
return evalX(x, s.env, s.params);
|
|
2767
|
+
}
|
|
2768
|
+
catch {
|
|
2769
|
+
return '?';
|
|
2770
|
+
} })]);
|
|
2771
|
+
}
|
|
2772
|
+
finally {
|
|
2773
|
+
evalBounds.calls = was;
|
|
2774
|
+
}
|
|
2775
|
+
};
|
|
2506
2776
|
const classes = new Map();
|
|
2507
2777
|
const addT = (t) => { const f = fp(t.x); if (f === undefined)
|
|
2508
2778
|
return; const key = `${sortsOf(t.sort)}:${f}`; const c = classes.get(key) ?? []; c.push(t); classes.set(key, c); };
|
|
@@ -2671,12 +2941,47 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
|
|
|
2671
2941
|
if (size(big) > size(small))
|
|
2672
2942
|
rules.push({ l: big, r: small, vs });
|
|
2673
2943
|
}
|
|
2674
|
-
|
|
2675
|
-
|
|
2944
|
+
// An equation reading a variable more than once, generalised apart: some of its reads a fresh variable of its sort
|
|
2945
|
+
// (the sort's third), where every value still meets it, so (l1 ++ l1) ++ l2 = l1 ++ (l1 ++ l2) is ++'s associativity.
|
|
2946
|
+
// The split renaming fewest reads is kept (named again in order of appearance); else the equation as found.
|
|
2947
|
+
const bits = (n) => { let c = 0; for (let x = n; x; x >>= 1)
|
|
2948
|
+
c += x & 1; return c; };
|
|
2949
|
+
const apart = (e) => {
|
|
2950
|
+
const count = new Map();
|
|
2951
|
+
walk([e.a, e.b], o => { if (o.op === 'var' && sortOfVar.has(o.name))
|
|
2952
|
+
count.set(o.name, (count.get(o.name) ?? 0) + 1); });
|
|
2953
|
+
for (const [v, m] of count) {
|
|
2954
|
+
const fresh = thirds.find(t => sortsOf(t.sort) === sortsOf(sortOfVar.get(v))).name;
|
|
2955
|
+
if (m < 2 || m > 6 || count.has(fresh))
|
|
2956
|
+
continue;
|
|
2957
|
+
// (the first read never renamed: a split and its mirror are one equation)
|
|
2958
|
+
const masks = Array.from({ length: 2 ** (m - 1) - 1 }, (_, i) => (i + 1) << 1).sort((x, y) => bits(x) - bits(y) || x - y);
|
|
2959
|
+
for (const mask of masks) {
|
|
2960
|
+
let i = 0;
|
|
2961
|
+
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);
|
|
2962
|
+
const [a2, b2] = ren([e.a, e.b]), reads = (x, n) => JSON.stringify(x).includes(`"name":"${n}"`);
|
|
2963
|
+
// (each of the two read on both sides: a side that no longer reads a variable says nothing more)
|
|
2964
|
+
if (![v, fresh].every(n => reads(a2, n) && reads(b2, n)))
|
|
2965
|
+
continue;
|
|
2966
|
+
const fa = fp(a2);
|
|
2967
|
+
if (fa !== undefined && fa === fp(b2) && JSON.stringify(a2) !== JSON.stringify(b2)) {
|
|
2968
|
+
const [ca, cb] = canon([a2, b2]).t;
|
|
2969
|
+
return { a: ca, b: cb, size: e.size };
|
|
2970
|
+
}
|
|
2971
|
+
}
|
|
2972
|
+
}
|
|
2973
|
+
return e;
|
|
2974
|
+
};
|
|
2975
|
+
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); }));
|
|
2976
|
+
for (const found of eqs) {
|
|
2977
|
+
const na = norm(found.a), nb = norm(found.b);
|
|
2676
2978
|
if (JSON.stringify(na) === JSON.stringify(nb))
|
|
2677
2979
|
continue;
|
|
2678
2980
|
// An instance of one kept (both sides at one substitution) adds nothing.
|
|
2679
|
-
if (
|
|
2981
|
+
if (instance(found))
|
|
2982
|
+
continue;
|
|
2983
|
+
const e = apart(found);
|
|
2984
|
+
if (e !== found && instance(e))
|
|
2680
2985
|
continue;
|
|
2681
2986
|
const y = { op: '=', a: e.a, b: e.b }, text = JSON.stringify(y);
|
|
2682
2987
|
if (seen.has(text) || text === lawText || JSON.stringify({ op: '=', a: e.b, b: e.a }) === lawText)
|
|
@@ -2702,8 +3007,11 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
|
|
|
2702
3007
|
if (di < 0)
|
|
2703
3008
|
continue;
|
|
2704
3009
|
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
|
-
|
|
3010
|
+
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 }]))), [[]]);
|
|
3011
|
+
// (the function's arguments of the datatype either variable of it, one of them the premise's: elem x z implies
|
|
3012
|
+
// elem x (union y z))
|
|
3013
|
+
const reads = (as) => as.some(a2 => a2.op === 'var' && a2.name === dvar);
|
|
3014
|
+
for (const margs of argSets(mk.params, true).filter(reads))
|
|
2707
3015
|
for (const pargs of argSets(pr.params.filter((_, i) => i !== di))) {
|
|
2708
3016
|
const pAt = (x) => { const as = [...pargs]; as.splice(di, 0, x); return { op: 'holds', x: { op: 'call', fn: pr.name, args: as } }; };
|
|
2709
3017
|
const premise = pAt({ op: 'var', name: dvar }), conclusion = pAt({ op: 'call', fn: mk.name, args: margs });
|
|
@@ -2790,9 +3098,11 @@ export const showY = (y) => {
|
|
|
2790
3098
|
// Prove a law over datatypes: refuted by a random value where one breaks it; else proven by a cycle the search finds,
|
|
2791
3099
|
// with lemmas found from the values when the law alone isn't (`lemmas: false` turns that off; an array gives lemmas to
|
|
2792
3100
|
// prove and use instead, which the corpus never does).
|
|
2793
|
-
export function proveData(l, opts = {}) {
|
|
2794
|
-
|
|
2795
|
-
|
|
3101
|
+
export function proveData(l, opts = {}) {
|
|
3102
|
+
return counted(dataRate, () => bounded(() => { const until = clock() + (opts.ms ?? 120_000), v = proveDataCounted(l, opts, until); return { ...v, stopped: clock() > until }; }));
|
|
3103
|
+
}
|
|
3104
|
+
function proveDataCounted(l, opts, until) {
|
|
3105
|
+
const t0 = performance.now();
|
|
2796
3106
|
// Where the law calls a non-recursive function, or reaches a recursive one that agrees with a built-in (core/transfer.ts):
|
|
2797
3107
|
// the law alone at one unfolding first, then the law said through them, then the rest of the search on the law.
|
|
2798
3108
|
const plan = opts.transfer === false || opts.induction === false || Array.isArray(opts.lemmas) ? undefined : transferPlan(l);
|
|
@@ -2862,6 +3172,14 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
2862
3172
|
const without = opts.lemmas === false || opts.induction === false;
|
|
2863
3173
|
if (without)
|
|
2864
3174
|
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) });
|
|
3175
|
+
// The law at two unfoldings before any conjecture, each scheme within a short time (3 s of counted work): a law that
|
|
3176
|
+
// needs a case of a field and no lemma is proven there (last (xs ++ [x]) = x: the cases of the tail), and the
|
|
3177
|
+
// conjectures are costly to make. One out of its time is tried again below, with more.
|
|
3178
|
+
if (!Array.isArray(opts.lemmas)) {
|
|
3179
|
+
const two = ok(proveWith(p, fs, l, base, lv + 1, opts, until, 3000, [2]), base);
|
|
3180
|
+
if (two)
|
|
3181
|
+
return two;
|
|
3182
|
+
}
|
|
2865
3183
|
const cands = Array.isArray(opts.lemmas) ? opts.lemmas : conjectures(p, l);
|
|
2866
3184
|
const p2 = ctx ? p : programOf([l, ...cands]), fs2 = ctx ? fs : factsOf(p2);
|
|
2867
3185
|
// Each scheme's goals: the law's, and each companion's (a lemma may be what only a companion's goal reads).
|
|
@@ -2878,17 +3196,30 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
2878
3196
|
const implication = (y) => y.op === 'or' && y.xs.length === 2 && y.xs[0].op === 'not';
|
|
2879
3197
|
const score = (c, hit) => (hit ? 2 : 0) + (implication(c.holds) === implication(l.holds) ? 1 : 0);
|
|
2880
3198
|
if (dataTrace)
|
|
2881
|
-
console.error(`[data] ${l.name}: ${cands.length} conjectures at ${Math.round(clock())} of ${Math.round(until)}`);
|
|
3199
|
+
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('')}`);
|
|
2882
3200
|
const ranked = cands.map(c => ({ c, hit: matchesGoal(c) })).sort((a, b) => score(b.c, b.hit) - score(a.c, a.hit));
|
|
2883
3201
|
// The lemmas proven: those given (`base`) and those found, each found one a level above the last.
|
|
2884
3202
|
const proven = [...base], failed = new Set(), level = () => lv + 1 + proven.length - base.length;
|
|
2885
|
-
|
|
3203
|
+
// A pass of lemmas: of those the goal reads (`hits`) or the others, each proven at one unfolding (8 s of counted work
|
|
3204
|
+
// a lemma, 5 s an attempt), until `most` are proven, three times as many tried, or the pass's time is spent (`end`).
|
|
3205
|
+
// (An attempt's instances aren't counted work, so a pass of many short attempts is bounded by their number too.) The
|
|
3206
|
+
// law is tried again with every lemma proven so far, without induction first (a law that follows from them by
|
|
3207
|
+
// rewriting), then by its schemes: after each lemma the goal reads or of the law's shape, else at the end of the pass.
|
|
3208
|
+
const refuted = new Set();
|
|
3209
|
+
const lemmaPass = (which, most, end, cap, depths) => {
|
|
3210
|
+
let n = 0, since = 0, tries = 0;
|
|
3211
|
+
const again = (how) => ok(proveWith(p2, fs2, l, proven, level(), opts, until, cap, depths, how), proven, p2);
|
|
2886
3212
|
for (const { c, hit } of ranked) {
|
|
2887
|
-
if (clock() >
|
|
2888
|
-
|
|
2889
|
-
if (proven.some(q => q.law === c) ||
|
|
3213
|
+
if (n >= most || tries >= 3 * most || clock() > end)
|
|
3214
|
+
break;
|
|
3215
|
+
if ((which === 'hits') !== hit || proven.some(q => q.law === c) || refuted.has(c))
|
|
2890
3216
|
continue;
|
|
2891
|
-
|
|
3217
|
+
if (refute(c, 200)) {
|
|
3218
|
+
refuted.add(c);
|
|
3219
|
+
continue;
|
|
3220
|
+
}
|
|
3221
|
+
tries++;
|
|
3222
|
+
const r = proveWith(p2, fs2, c, proven, level(), opts, Math.min(end, clock() + 8000 * (opts.patience ?? 1)), 5000, [1]);
|
|
2892
3223
|
tried += r.tried;
|
|
2893
3224
|
if (!r.out) {
|
|
2894
3225
|
failed.add(c);
|
|
@@ -2896,19 +3227,52 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
2896
3227
|
}
|
|
2897
3228
|
failed.delete(c);
|
|
2898
3229
|
proven.push(r.out);
|
|
2899
|
-
|
|
3230
|
+
n++;
|
|
3231
|
+
since++;
|
|
3232
|
+
// (as before the passes: again after a lemma the goal reads, or one of the law's shape, an implication for one)
|
|
3233
|
+
if (which === 'hits' || implication(c.holds) === implication(l.holds)) {
|
|
3234
|
+
since = 0;
|
|
3235
|
+
const r2 = again('first');
|
|
3236
|
+
if (r2)
|
|
3237
|
+
return r2;
|
|
3238
|
+
}
|
|
3239
|
+
}
|
|
3240
|
+
return since ? again('first') : undefined;
|
|
3241
|
+
};
|
|
3242
|
+
// depth 2's round: the lemmas that failed at one unfolding (the first eight, in their order), each at two, the law
|
|
3243
|
+
// tried again after each.
|
|
3244
|
+
const lemmasAt2 = () => {
|
|
3245
|
+
let tries = 0;
|
|
3246
|
+
for (const { c } of ranked) {
|
|
3247
|
+
if (clock() > until || tries >= 8)
|
|
3248
|
+
return undefined;
|
|
3249
|
+
if (proven.some(q => q.law === c) || !failed.has(c) || refuted.has(c))
|
|
3250
|
+
continue;
|
|
3251
|
+
tries++;
|
|
3252
|
+
const r = proveWith(p2, fs2, c, proven, level(), opts, Math.min(until, clock() + 12000 * (opts.patience ?? 1)), 5000, [2]);
|
|
3253
|
+
tried += r.tried;
|
|
3254
|
+
if (!r.out)
|
|
2900
3255
|
continue;
|
|
2901
|
-
|
|
3256
|
+
failed.delete(c);
|
|
3257
|
+
proven.push(r.out);
|
|
3258
|
+
const again = ok(proveWith(p2, fs2, l, proven, level(), opts, until, 6000, [1, 2], 'first'), proven, p2);
|
|
2902
3259
|
if (again)
|
|
2903
3260
|
return again;
|
|
2904
3261
|
}
|
|
2905
3262
|
return undefined;
|
|
2906
3263
|
};
|
|
3264
|
+
// The order: the lemmas the goal reads (up to six proven, the law tried again as lemmaPass says), within 30% of the
|
|
3265
|
+
// time left; the law alone with more time, at two
|
|
3266
|
+
// unfoldings and three; the other lemmas (up to eight, within half the time then left) and the law with them all;
|
|
3267
|
+
// the lemmas that failed at one unfolding, at two; the law at three with every lemma; the law by the cases of a
|
|
3268
|
+
// variable (no induction). An attempt that failed within its time isn't tried again (`settled`).
|
|
3269
|
+
const share = (f) => Math.min(until, clock() + f * Math.max(0, until - clock()));
|
|
2907
3270
|
const steps = [
|
|
2908
|
-
() =>
|
|
3271
|
+
() => lemmaPass('hits', 6, share(0.3), 6000, [1]),
|
|
2909
3272
|
() => ok(proveWith(p, fs, l, base, lv + 1, opts, until, 30000, [2]), base),
|
|
2910
|
-
() =>
|
|
2911
|
-
() =>
|
|
3273
|
+
() => ok(proveWith(p, fs, l, base, lv + 1, opts, until, 12000, [3]), base),
|
|
3274
|
+
() => lemmaPass('others', 8, share(0.5), 12000, [1, 2]),
|
|
3275
|
+
() => lemmasAt2(),
|
|
2912
3276
|
() => ok(proveWith(p2, fs2, l, proven, level(), opts, until, 12000, [3]), proven, p2),
|
|
2913
3277
|
// No induction: the law by the cases of a variable (or none), its definitions unfolded.
|
|
2914
3278
|
() => ok(proveWith(p, fs, l, base, lv + 1, opts, until, 3000, [1, 2], 'cases'), base),
|
|
@@ -2927,3 +3291,179 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
|
|
|
2927
3291
|
const stuckOf = (v) => (v && !v.proven ? { goal: v.goal, stuck: v.stuck } : v && !v.checked ? { goal: 'check', stuck: v.why } : {});
|
|
2928
3292
|
// The law with no cycle: its definitions unfolded, the kernel's prover alone (what the library proves without the search).
|
|
2929
3293
|
export const proveDataToday = (l) => proveData(l, { induction: false });
|
|
3294
|
+
// --- abstract sorts, unknown functions, closures ----------------------------------------------------------------------
|
|
3295
|
+
//
|
|
3296
|
+
// An abstract sort, `opaque('Elem')`: values a law compares for equality and passes around (arguments, results, fields,
|
|
3297
|
+
// an if's choice), and nothing else. It is an ordinary datatype of one constructor of one natural (`el`), so the kernel
|
|
3298
|
+
// and Lean's twin see what they see of any datatype; the restriction is a check (`equalityOnly`, at every `law`): a
|
|
3299
|
+
// match, a constructor, a test or a size of an abstract sort, in the law or in a function it reaches, is refused, save
|
|
3300
|
+
// in the sort's own codecs below (its code and its value at a code), which only an unknown function's encoding reaches.
|
|
3301
|
+
//
|
|
3302
|
+
// Why a law proven so holds at every sort, not only at the naturals the encoding is (what TIP's `declare-sort` and a
|
|
3303
|
+
// goal's `par` claim): a law is ∀ x̄. φ(x̄), φ evaluated by the program's equations. Suppose φ false at values of some
|
|
3304
|
+
// nonempty set S. The evaluation is finite, so it reads finitely many elements of S: send them injectively into the
|
|
3305
|
+
// naturals (S may be finite, of one element even: the naturals being infinite, an injection always exists, which is why
|
|
3306
|
+
// the domain proven over must be infinite). A program that reads elements only by equality, choices and moves computes
|
|
3307
|
+
// at the images the images of what it computed at S: every comparison answers the same (the map is injective), every
|
|
3308
|
+
// other step moves a value; an unknown function is arbitrary, so it may take the images too. So φ is false at the
|
|
3309
|
+
// images, against the proof at the naturals. The check makes the premise true: an order (x < y), arithmetic, a
|
|
3310
|
+
// constant of the sort (el(0)) or a match on its code would tell the encoding apart from S, and is refused. What the
|
|
3311
|
+
// proof uses is beside the point (the kernel may compare codes): the proof is about the naturals, and the claim moved
|
|
3312
|
+
// to S is the law, which reads equality alone. Lean's twin states the law about the inductive `Elem`, whose code no
|
|
3313
|
+
// definition of the law reads: no arithmetic fact about the sort is in the statement it checks.
|
|
3314
|
+
const codecs = new Set(), made = new Map();
|
|
3315
|
+
const madeFn = (name, mk) => { let f = made.get(name); if (!f) {
|
|
3316
|
+
f = mk();
|
|
3317
|
+
made.set(name, f);
|
|
3318
|
+
codecs.add(name);
|
|
3319
|
+
} return f; };
|
|
3320
|
+
export function opaque(name) {
|
|
3321
|
+
const d = data(name, { el: { code: natural } });
|
|
3322
|
+
d.abstract = true;
|
|
3323
|
+
return d;
|
|
3324
|
+
}
|
|
3325
|
+
function equalityOnly(name, y) {
|
|
3326
|
+
if (![...declared.values()].some(d => d.abstract))
|
|
3327
|
+
return;
|
|
3328
|
+
const seen = new Set();
|
|
3329
|
+
const go = (t, where) => walk(t, o => {
|
|
3330
|
+
if ((o.op === 'match' || o.op === 'ctor' || o.op === 'is' || o.op === 'size') && dataNamed(o.data).abstract)
|
|
3331
|
+
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`);
|
|
3332
|
+
if (o.op === 'call' && !codecs.has(o.fn) && !seen.has(o.fn)) {
|
|
3333
|
+
seen.add(o.fn);
|
|
3334
|
+
go(fnOf(o.fn).body(), o.fn);
|
|
3335
|
+
}
|
|
3336
|
+
});
|
|
3337
|
+
go(y, name);
|
|
3338
|
+
}
|
|
3339
|
+
// An unknown function between any sorts, `unknownFn('f', [natural], List)`: a law about it is about every such function.
|
|
3340
|
+
// It is one unknown g of a natural (`fnParam`) read at its arguments' key a: their codes (each injective: a natural
|
|
3341
|
+
// itself, a condition 0 or 1, an abstract value its code, a datatype value its constructor and its fields' codes)
|
|
3342
|
+
// paired, ⟨x, y⟩ = (x + y)² + y being the library's pairing (injective; the function `pairing`). A result of a natural
|
|
3343
|
+
// 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
|
|
3344
|
+
// integer g(a)'s zigzag decoding, an abstract value the one of code g(a). A datatype's value is decoded at most
|
|
3345
|
+
// 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
|
|
3346
|
+
// most fields of a constructor among the datatypes it reaches: a heap's numbering, injective) is the constructor
|
|
3347
|
+
// 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
|
|
3348
|
+
// another datatype (one declared before, not of its group) decoded from its place g(⟨a, 3p⟩) deep, and at depth 0 the
|
|
3349
|
+
// value of least height. All of it is ordinary functions of the datatype language (structural recursion on the depth):
|
|
3350
|
+
// nothing trusted reads it, and the places grow by a constant factor a level, not by squaring.
|
|
3351
|
+
// Why every function is one of these (the law about every g is then the law about every function): the points read are
|
|
3352
|
+
// ⟨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
|
|
3353
|
+
// any function F a g reads at each argument's points F's value there: its depth, its constructors, its naturals.
|
|
3354
|
+
const natN = (n) => (typeof n === 'number' ? new Nat({ op: 'nat', value: n }) : n);
|
|
3355
|
+
// (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
|
|
3356
|
+
// as one: unfolded, the square of a square is past what the kernel's arithmetic relates, and a read of it at equal
|
|
3357
|
+
// arguments is the same read, which the search's congruences see; on x, an argument's key, which is a variable where
|
|
3358
|
+
// Lean's twin reads the definition, not a successor it would unfold)
|
|
3359
|
+
const pairN = (a, b) => madeFn('pairing', () => {
|
|
3360
|
+
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) }));
|
|
3361
|
+
return f;
|
|
3362
|
+
})(a, b);
|
|
3363
|
+
const asNatV = (v) => v;
|
|
3364
|
+
// A value's code, injectively.
|
|
3365
|
+
function codeOf(s, v) {
|
|
3366
|
+
if (s === 'nat')
|
|
3367
|
+
return natN(v);
|
|
3368
|
+
if (s === 'bool')
|
|
3369
|
+
return when(v, 1, 0);
|
|
3370
|
+
if (s === 'int')
|
|
3371
|
+
throw new Error('an unknown function of an integer argument isn\'t taken');
|
|
3372
|
+
return asNatV(encoder(s)(v));
|
|
3373
|
+
}
|
|
3374
|
+
function encoder(d) {
|
|
3375
|
+
if (d.abstract)
|
|
3376
|
+
return madeFn(`${d.name}_code`, () => define(`${d.name}_code`, { x: d }, natural, ({ x }) => x.match({ el: ({ code }) => code })));
|
|
3377
|
+
for (const c of d.ctors)
|
|
3378
|
+
for (const f of c.fields)
|
|
3379
|
+
if (f.sort === 'int')
|
|
3380
|
+
throw new Error(`${d.name}: an unknown function of a datatype with an integer field isn't taken`);
|
|
3381
|
+
return madeFn(`${d.name}_code`, () => define(`${d.name}_code`, { x: d }, natural, ({ x }) => x.match(Object.fromEntries(d.ctors.map((c, j) => [c.name,
|
|
3382
|
+
(fs) => pairN(c.fields.length ? c.fields.map(f => codeOf(fieldSort(f), fs[f.name])).reduce((a, b) => pairN(a, b)) : 0, j)])))));
|
|
3383
|
+
}
|
|
3384
|
+
const valueOfCode = (d, n) => madeFn(`${d.name}_of`, () => define(`${d.name}_of`, { n: natural }, d, ({ n: c }) => d.make('el', c)))(n);
|
|
3385
|
+
// A value of a sort of no constructors (a natural, a condition, an integer, an abstract value) from a natural.
|
|
3386
|
+
function primOf(s, n) {
|
|
3387
|
+
if (s === 'nat')
|
|
3388
|
+
return n;
|
|
3389
|
+
if (s === 'bool')
|
|
3390
|
+
return n.eq(0);
|
|
3391
|
+
if (s === 'int')
|
|
3392
|
+
return when(n.modBy(2).eq(0), n.divBy(2).toInt(), n.divBy(2).toInt().negate().minus(1));
|
|
3393
|
+
return valueOfCode(s, n);
|
|
3394
|
+
}
|
|
3395
|
+
const decodable = (s) => s instanceof Data && !s.abstract;
|
|
3396
|
+
// The datatypes a decoding reaches, and the most fields of their constructors (B).
|
|
3397
|
+
function reachOf(d, out = new Set()) {
|
|
3398
|
+
if (out.has(d))
|
|
3399
|
+
return out;
|
|
3400
|
+
out.add(d);
|
|
3401
|
+
for (const c of d.ctors)
|
|
3402
|
+
for (const f of c.fields) {
|
|
3403
|
+
const s = fieldSort(f);
|
|
3404
|
+
if (decodable(s))
|
|
3405
|
+
reachOf(s, out);
|
|
3406
|
+
}
|
|
3407
|
+
return out;
|
|
3408
|
+
}
|
|
3409
|
+
// The value of datatype x at key a, place p, depth: the decoders of g (`gname`), one for each datatype, B its branching.
|
|
3410
|
+
function decoder(gname, x, b) {
|
|
3411
|
+
const name = (y) => `${gname}_${y.name}_dec`;
|
|
3412
|
+
return madeFn(name(x), () => define(name(x), { a: natural, p: natural, depth: natural }, x, ({ a, p, depth }) => depth.match({
|
|
3413
|
+
zero: () => leastOf(x),
|
|
3414
|
+
succ: ({ pred }) => {
|
|
3415
|
+
const g = fnParam(gname), at = (k) => g(pairN(a, p.times(3).plus(k)));
|
|
3416
|
+
const vals = x.ctors.map(c => x.make(c.name, ...c.fields.map((f, i) => {
|
|
3417
|
+
const s = fieldSort(f), q = p.times(b).plus(i + 1);
|
|
3418
|
+
if (!decodable(s))
|
|
3419
|
+
return primOf(s, g(pairN(a, q.times(3).plus(2))));
|
|
3420
|
+
// (a field of the group one level less deep; of another datatype, as deep as its own place says)
|
|
3421
|
+
return decoder(gname, s, b)(a, q, x.group.includes(s.name) ? pred : g(pairN(a, q.times(3))));
|
|
3422
|
+
})));
|
|
3423
|
+
const tag = at(1);
|
|
3424
|
+
return vals.slice(0, -1).reduceRight((acc, v, j) => when(tag.eq(j), v, acc), vals.at(-1));
|
|
3425
|
+
}
|
|
3426
|
+
})));
|
|
3427
|
+
}
|
|
3428
|
+
// A datatype's value of least height (a constructor of least height, its naturals 0).
|
|
3429
|
+
function leastOf(d) {
|
|
3430
|
+
const c = d.ctors.find(k => d.ctorHeight(k) === d.height);
|
|
3431
|
+
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); }));
|
|
3432
|
+
}
|
|
3433
|
+
export function unknownFn(name, from, to) {
|
|
3434
|
+
if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name))
|
|
3435
|
+
throw new Error(`${name}: an unknown function's name is letters and digits`);
|
|
3436
|
+
for (const s of from)
|
|
3437
|
+
if (s instanceof Data)
|
|
3438
|
+
encoder(s);
|
|
3439
|
+
const b = decodable(to) ? Math.max(1, ...[...reachOf(to)].flatMap(d => d.ctors.map(c => c.fields.length))) : 0;
|
|
3440
|
+
return Object.assign((...args) => {
|
|
3441
|
+
if (args.length !== from.length)
|
|
3442
|
+
throw new Error(`${name} takes ${from.length} arguments`);
|
|
3443
|
+
const a = args.length ? args.map((v, i) => codeOf(from[i], v)).reduce((x, y) => pairN(x, y)) : natN(0), g = fnParam(name);
|
|
3444
|
+
return decodable(to) ? decoder(name, to, b)(a, 0, g(pairN(a, 0))) : primOf(to, g(a));
|
|
3445
|
+
}, { param: name });
|
|
3446
|
+
}
|
|
3447
|
+
// Closures (defunctionalisation): a datatype of the functions a field or an argument may hold, one constructor for each
|
|
3448
|
+
// with the values it captures as fields, and `apply`, which matches on the closure: `closures('Op', {x: natural},
|
|
3449
|
+
// natural, {inc: {apply: (_, {x}) => x.plus(1)}, add: {fields: {k: natural}, apply: ({k}, {x}) => x.plus(k)}})`. A field
|
|
3450
|
+
// of sort `Op` is a function-typed field; `Op.add(3)` is a closure; `apply(c, x)` its application. With `unknown: 'other'`,
|
|
3451
|
+
// a constructor `other(code)` whose application is an unknown function of the code and the arguments: a law about every
|
|
3452
|
+
// closure is then about every function too (each is other(0) for some unknown function). Closures are ordinary values
|
|
3453
|
+
// and `apply` an ordinary function: the search and the kernel see nothing new.
|
|
3454
|
+
export function closures(name, args, ret,
|
|
3455
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
3456
|
+
cases, opts = {}) {
|
|
3457
|
+
if ('c' in args)
|
|
3458
|
+
throw new Error(`${name}: an argument named c (the closure's own name in apply)`);
|
|
3459
|
+
const decl = Object.fromEntries(Object.entries(cases).map(([c, x]) => [c, x.fields ?? {}]));
|
|
3460
|
+
if (opts.unknown)
|
|
3461
|
+
decl[opts.unknown] = { code: natural };
|
|
3462
|
+
const d = data(name, decl);
|
|
3463
|
+
const u = opts.unknown ? unknownFn(`${name}_${opts.unknown}`, ['nat', ...Object.values(args)], ret) : undefined;
|
|
3464
|
+
const apply = define(`${name}_apply`, { c: d, ...args }, ret, a => a.c.match({
|
|
3465
|
+
...Object.fromEntries(Object.entries(cases).map(([c, x]) => [c, (fs) => x.apply(fs, Object.fromEntries(Object.keys(args).map(k => [k, a[k]])))])),
|
|
3466
|
+
...(u ? { [opts.unknown]: ({ code }) => u(code, ...Object.keys(args).map(k => a[k])) } : {}),
|
|
3467
|
+
}));
|
|
3468
|
+
return { data: d, apply };
|
|
3469
|
+
}
|