gdp-wired 0.33.1 → 0.35.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/dist/core/counts.d.ts +31 -0
- package/dist/core/counts.js +264 -0
- package/dist/core/cycles.js +2 -1
- package/dist/core/dsl.d.ts +40 -8
- package/dist/core/dsl.js +71 -10
- package/dist/core/extract-check.js +4 -4
- package/dist/core/extract-print.d.ts +1 -0
- package/dist/core/extract-print.js +16 -2
- package/dist/core/extract-read.d.ts +13 -0
- package/dist/core/extract-step.d.ts +45 -2
- package/dist/core/extract-step.js +268 -8
- package/dist/core/extract.d.ts +1 -0
- package/dist/core/extract.js +12 -5
- package/dist/core/laws.js +39 -6
- package/dist/core/live.d.ts +22 -1
- package/dist/core/live.js +164 -11
- package/dist/core/machine.d.ts +20 -1
- package/dist/core/machine.js +76 -10
- package/dist/core/py/harness.py +5 -4
- package/dist/core/py/reader.py +11 -1
- package/dist/core/watch.js +1 -1
- package/dist/kernel/kernel.d.ts +25 -0
- package/dist/kernel/kernel.js +159 -2
- package/dist/lean-kernel/emit.d.ts +8 -1
- package/dist/lean-kernel/emit.js +68 -1
- package/package.json +1 -1
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type C, type E, type Law, type Machine, type State } from './machine.js';
|
|
2
|
+
import { type CountCert, type CountInst, type Instances, type MapRead } from '../kernel/kernel.js';
|
|
3
|
+
type Env = Record<string, number>;
|
|
4
|
+
export declare function guardLaws(m: Machine): {
|
|
5
|
+
counts: Machine['counts'];
|
|
6
|
+
laws: Law[];
|
|
7
|
+
};
|
|
8
|
+
export declare function pairLaws(m: Machine): Law[];
|
|
9
|
+
export declare function small(m: Machine, p: Env, b: number, cap?: number): State[];
|
|
10
|
+
export declare function certFor(goal: {
|
|
11
|
+
hyps: C[];
|
|
12
|
+
}, decls: {
|
|
13
|
+
map: string;
|
|
14
|
+
below: E;
|
|
15
|
+
}[]): {
|
|
16
|
+
reads: MapRead[];
|
|
17
|
+
insts: CountInst[];
|
|
18
|
+
wits: string[];
|
|
19
|
+
};
|
|
20
|
+
export type Counted = {
|
|
21
|
+
proven: boolean;
|
|
22
|
+
laws: Law[];
|
|
23
|
+
m: Machine;
|
|
24
|
+
proof?: {
|
|
25
|
+
instances: Record<string, Instances>;
|
|
26
|
+
certs: Record<string, CountCert>;
|
|
27
|
+
};
|
|
28
|
+
why?: string;
|
|
29
|
+
};
|
|
30
|
+
export declare function searchCounted(m0: Machine, caller: Law[], ms?: number): Counted;
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
// The search for a machine with counts (Machine.counts; the kernel's countedObligations and checkCountedLaws, Lean's
|
|
2
|
+
// CountMachine.lean): untrusted. It proposes laws that read counts of the state, filters every candidate on the small
|
|
3
|
+
// instances' reachable states, and keeps the largest set the kernel accepts (Houdini), each goal's certificate built
|
|
4
|
+
// here: the count cells the goal reads, Count.lean's instances over pairs of them, and the laws and quantified flags at
|
|
5
|
+
// the instances' witnesses.
|
|
6
|
+
// - The guard's shape: a step writes P[t] where a quantified flag says every member of a set the request counts
|
|
7
|
+
// satisfies R(member, t), and the assumption compares that count with a bound (2·|Q| > size, |Q| ≥ n − t, …). Then
|
|
8
|
+
// a state count c_R(x) = |{k < bound: R(k, x)}| is declared, and P[a] ⇒ the same comparison with c_R[a] for |Q| is
|
|
9
|
+
// proposed: what every majority, quorum or threshold protocol keeps of its decisions.
|
|
10
|
+
// - A guard comparing a state count at the written key (2·voters[n] > size, Leader[n] := 1): P[a] ⇒ that comparison
|
|
11
|
+
// at a.
|
|
12
|
+
// - Each map's cells at most what the small instances reach.
|
|
13
|
+
import { carriedView, evalC, interpret } from "./machine.js";
|
|
14
|
+
import { checkCountedLaws, countedObligations, mcGoal, substC } from "../kernel/kernel.js";
|
|
15
|
+
import { clock, grow } from "../kernel/prove.js";
|
|
16
|
+
import { env } from "./solver.js";
|
|
17
|
+
const v = (name) => ({ op: 'var', name }), k = (value) => ({ op: 'const', value });
|
|
18
|
+
const json = (t) => JSON.stringify(t);
|
|
19
|
+
const one = k(1), zero = k(0);
|
|
20
|
+
// Every term t with `get(map, t)` in t0.
|
|
21
|
+
function reads(t0, map, out = new Map()) {
|
|
22
|
+
const go = (x) => {
|
|
23
|
+
if (!x || typeof x !== 'object')
|
|
24
|
+
return;
|
|
25
|
+
const o = x;
|
|
26
|
+
if (o.op === 'get' && map(o.map))
|
|
27
|
+
out.set(json([o.map, o.key]), [o.map, o.key]);
|
|
28
|
+
for (const y of Object.values(o))
|
|
29
|
+
go(y);
|
|
30
|
+
};
|
|
31
|
+
go(t0);
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
const mentions = (t, name) => json(t).includes(`"name":${json(name)}`);
|
|
35
|
+
const atoms = (c) => (c.op === 'and' || c.op === 'or' ? c.xs.flatMap(atoms) : c.op === 'not' ? atoms(c.x) : [c]);
|
|
36
|
+
// --- candidates from the guard's shape -----------------------------------------------------------------------------------
|
|
37
|
+
export function guardLaws(m) {
|
|
38
|
+
const counts = {}, laws = [];
|
|
39
|
+
const flags = m.step.flags ?? {}, fsub = { vars: {}, maps: {}, flags: Object.fromEntries(Object.entries(flags).map(([f, fc]) => [f, fc.op === 'all' ? { op: '=', a: v(`?${f}`), b: one } : fc])) };
|
|
40
|
+
const inline = (c) => { let x = c; for (let i = 0; i < 4 && json(x).includes('"op":"flag"'); i++)
|
|
41
|
+
x = substC(x, fsub); return x; };
|
|
42
|
+
const guards = m.assume ? atoms(m.assume).filter(a => a.op === '<' || a.op === '<=') : [];
|
|
43
|
+
const isCount = (mp) => !!m.counts?.[mp];
|
|
44
|
+
for (const [mp, w] of Object.entries(m.step.maps ?? {})) {
|
|
45
|
+
if ('each' in w || w.key.op !== 'var' || !m.inputs.includes(w.key.name))
|
|
46
|
+
continue;
|
|
47
|
+
const t = w.key.name, written = inline({ op: '<=', a: one, b: w.value });
|
|
48
|
+
const law = (name, cmp) => ({ name, forall: 'a$c', holds: { op: 'or', xs: [{ op: 'not', x: { op: '<=', a: one, b: { op: 'get', map: mp, key: v('a$c') } } }, cmp] } });
|
|
49
|
+
// A comparison with a state count at the written key.
|
|
50
|
+
for (const g of guards)
|
|
51
|
+
for (const [, [c, key]] of reads(g, isCount)) {
|
|
52
|
+
if (json(key) !== json(v(t)) || mentions(m.counts[c].body, t))
|
|
53
|
+
continue;
|
|
54
|
+
if (m.inputs.some(i => i !== t && mentions(g, i)))
|
|
55
|
+
continue;
|
|
56
|
+
laws.push(law(`${mp} keeps ${c}'s bound`, substC(g, { vars: { [t]: v('a$c') }, maps: {}, flags: {} })));
|
|
57
|
+
}
|
|
58
|
+
// A quantified flag the write reads: every member of a counted set satisfies R(member, t).
|
|
59
|
+
for (const [f, q] of Object.entries(flags)) {
|
|
60
|
+
if (q.op !== 'all' || q.keys?.length || !mentions(written, `?${f}`) || q.c.op !== 'or' || q.c.xs.length !== 2)
|
|
61
|
+
continue;
|
|
62
|
+
const [h, r] = q.c.xs[0].op === 'not' ? [q.c.xs[0].x, q.c.xs[1]] : [q.c.xs[1].op === 'not' ? q.c.xs[1].x : undefined, q.c.xs[0]];
|
|
63
|
+
if (!h || !r)
|
|
64
|
+
continue;
|
|
65
|
+
for (const [c, d] of Object.entries(m.counts ?? {})) {
|
|
66
|
+
// the set: the count's body is the flag's hypothesis at its key
|
|
67
|
+
const body = d.body.op === 'if' ? d.body.c : undefined;
|
|
68
|
+
if (!body || json(substC(body, { vars: { [d.key]: v(q.key) }, maps: {}, flags: {} })) !== json(h))
|
|
69
|
+
continue;
|
|
70
|
+
if (m.inputs.some(i => i !== t && mentions(r, i)))
|
|
71
|
+
continue;
|
|
72
|
+
const name = `${c}$${mp}`, j = `${name}$x`, key = `${name}$k`;
|
|
73
|
+
counts[name] = { j, key, below: d.below, body: { op: 'if', c: substC(r, { vars: { [q.key]: v(key), [t]: v(j) }, maps: {}, flags: {} }), then: one, else: zero } };
|
|
74
|
+
for (const g of guards)
|
|
75
|
+
if (reads(g, x => x === c).size)
|
|
76
|
+
laws.push(law(`${mp} keeps ${c}'s bound through ${name}`, substC(g, { vars: {}, maps: { [c]: () => ({ op: 'get', map: name, key: v('a$c') }) }, flags: {} })));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return { counts, laws };
|
|
81
|
+
}
|
|
82
|
+
// --- relations over pairs: one value per first key, and one relation inside another ---------------------------------
|
|
83
|
+
// A map written at x·N + y (a relation, x's row) is a candidate for "at most one y in a row", and each two such maps for
|
|
84
|
+
// "one holds where the other does", at the same pair or the swapped one; the small instances keep the true ones.
|
|
85
|
+
export function pairLaws(m) {
|
|
86
|
+
const widths = new Map();
|
|
87
|
+
for (const [mp, w] of Object.entries(m.step.maps ?? {}))
|
|
88
|
+
if (!('each' in w) && w.key.op === 'add' && w.key.a.op === 'mul' && w.key.a.a.op === 'var' && w.key.b.op === 'var')
|
|
89
|
+
widths.set(mp, w.key.a.k);
|
|
90
|
+
const at = (mp, x, y, n) => ({ op: 'get', map: mp, key: { op: 'add', a: { op: 'mul', k: n, a: v(x) }, b: v(y) } });
|
|
91
|
+
const has = (e) => ({ op: '<=', a: one, b: e }), lt = (x, n) => ({ op: '<', a: v(x), b: k(n) });
|
|
92
|
+
const out = [];
|
|
93
|
+
for (const [mp, n] of widths)
|
|
94
|
+
out.push({ name: `${mp}: one per row`, forall: 'p$c', keys: ['q$c', 'r$c'], holds: { op: 'or', xs: [{ op: 'not', x: { op: 'and', xs: [lt('q$c', n), lt('r$c', n), has(at(mp, 'p$c', 'q$c', n)), has(at(mp, 'p$c', 'r$c', n))] } }, { op: '=', a: v('q$c'), b: v('r$c') }] } });
|
|
95
|
+
for (const [a, n] of widths)
|
|
96
|
+
for (const [b, n2] of widths)
|
|
97
|
+
if (a !== b && n === n2)
|
|
98
|
+
for (const swap of [false, true])
|
|
99
|
+
out.push({ name: `${a} inside ${b}${swap ? ', swapped' : ''}`, forall: 'p$c', keys: ['q$c'], holds: { op: 'or', xs: [{ op: 'not', x: { op: 'and', xs: [lt('q$c', n), lt('p$c', n), has(at(a, 'p$c', 'q$c', n))] } }, has(swap ? at(b, 'q$c', 'p$c', n) : at(b, 'p$c', 'q$c', n))] } });
|
|
100
|
+
// (and over one key: where one map's cell is set, another's is)
|
|
101
|
+
const singles = Object.entries(m.step.maps ?? {}).filter(([, w]) => !('each' in w) && w.key.op === 'var').map(([mp]) => mp);
|
|
102
|
+
for (const a of singles)
|
|
103
|
+
for (const b of singles)
|
|
104
|
+
if (a !== b)
|
|
105
|
+
out.push({ name: `${a} inside ${b}`, forall: 'p$c', holds: { op: 'or', xs: [{ op: 'not', x: has({ op: 'get', map: a, key: v('p$c') }) }, has({ op: 'get', map: b, key: v('p$c') })] } });
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
// --- the small instances --------------------------------------------------------------------------------------------------
|
|
109
|
+
// Every state reached from the start with the params at `p`, each input below `b`, each carried map a subset of 0 .. b − 1.
|
|
110
|
+
export function small(m, p, b, cap = 3000) {
|
|
111
|
+
const run = interpret(m), start = run.init(p);
|
|
112
|
+
const subsets = Array.from({ length: 1 << b }, (_, s) => new Map(Array.from({ length: b }, (_, i) => i).filter(i => (s >> i) & 1).map(i => [i, 1])));
|
|
113
|
+
let reqs = [{}];
|
|
114
|
+
for (const i of m.inputs)
|
|
115
|
+
reqs = reqs.flatMap(r => Array.from({ length: b }, (_, x) => ({ ...r, [i]: x })));
|
|
116
|
+
for (const c of m.inputMaps ?? [])
|
|
117
|
+
reqs = reqs.flatMap(r => subsets.map(s => ({ ...r, [c]: s })));
|
|
118
|
+
const seen = new Map([[json(start), start]]), queue = [start];
|
|
119
|
+
while (queue.length && seen.size < cap) {
|
|
120
|
+
const st = queue.shift();
|
|
121
|
+
for (const r of reqs) {
|
|
122
|
+
let next;
|
|
123
|
+
try {
|
|
124
|
+
next = run.step(p, st, r);
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
const key = json([next.scalars, Object.entries(next.maps).map(([n, cs]) => [n, [...cs].filter(([, x]) => x).sort((a, c) => a[0] - c[0])])]);
|
|
130
|
+
if (!seen.has(key)) {
|
|
131
|
+
seen.set(key, next);
|
|
132
|
+
queue.push(next);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return [...seen.values()];
|
|
137
|
+
}
|
|
138
|
+
// A law at a state, its counts the state's, at every key below b.
|
|
139
|
+
function holdsAt(m, law, p, st, b) {
|
|
140
|
+
const empty = Object.fromEntries((m.inputMaps ?? []).map(c => [c, new Map()]));
|
|
141
|
+
const view = carriedView(m, st, empty, undefined, p), keys = [law.forall, ...(law.keys ?? [])].filter((x) => !!x);
|
|
142
|
+
const go = (env, ks) => (ks.length ? Array.from({ length: b }, (_, x) => x).every(x => go({ ...env, [ks[0]]: x }, ks.slice(1))) : evalC(law.holds, { ...env, ...st.scalars }, view, m));
|
|
143
|
+
return go({ ...p }, keys);
|
|
144
|
+
}
|
|
145
|
+
// --- a goal's certificate -------------------------------------------------------------------------------------------------
|
|
146
|
+
// The count cells the goal reads (each before the step with its post name's twin), instances over pairs of them with one
|
|
147
|
+
// bound (a count that doesn't drop, +1 and −1; two that meet, +1, +1 and −1), each with a fresh witness; and the laws and
|
|
148
|
+
// quantified flags at the witnesses (returned, for the goal's law's instances).
|
|
149
|
+
export function certFor(goal, decls) {
|
|
150
|
+
const byMap = new Map(decls.map(d => [d.map, d])), last = goal.hyps.at(-1);
|
|
151
|
+
// (the conclusion's reads first, then those at a constant or the law's own names, then the rest)
|
|
152
|
+
const own = (t) => t.op === 'const' || (t.op === 'var' && json(last).includes(`"name":${json(t.name)}`));
|
|
153
|
+
const all0 = [...reads(goal.hyps, mp => byMap.has(mp)).values()], inLast = [...reads(last, mp => byMap.has(mp)).keys()];
|
|
154
|
+
const rank = ([mp, t]) => (inLast.includes(json([mp, t])) ? 0 : own(t) ? 1 : 2);
|
|
155
|
+
const rs = all0.sort((x, y) => rank(x) - rank(y));
|
|
156
|
+
// (each read after the step beside its twin before it, when the goal declares both)
|
|
157
|
+
for (const [mp, t] of [...rs])
|
|
158
|
+
if (mp.endsWith('#') && byMap.has(mp.slice(0, -1)) && !rs.some(([m2, t2]) => m2 === mp.slice(0, -1) && json(t2) === json(t)))
|
|
159
|
+
rs.push([mp.slice(0, -1), t]);
|
|
160
|
+
const named = rs.slice(0, 6).map(([mp, t], i) => [`r$${i}`, mp, t]);
|
|
161
|
+
const bound = (r) => json(byMap.get(r[1]).below);
|
|
162
|
+
const insts = [], wits = [];
|
|
163
|
+
const add = (terms, unit, below) => { const w = `w$${insts.length}`; wits.push(w); insts.push({ wit: w, below, terms, unit }); };
|
|
164
|
+
// first: a count after the step at least each other one (it doesn't drop; what the step adds); then two counts before it
|
|
165
|
+
// that meet, the first of the pair one the conclusion or the law's own names read; then the rest at most another
|
|
166
|
+
const post = (r) => r[1].endsWith('#'), ranked = (r) => rank([r[1], r[2]]) <= 1;
|
|
167
|
+
for (const c of named)
|
|
168
|
+
if (post(c))
|
|
169
|
+
for (const a of named)
|
|
170
|
+
if (a !== c && !post(a) && bound(a) === bound(c))
|
|
171
|
+
add([[1, a[0]], [-1, c[0]]], 0, byMap.get(c[1]).below);
|
|
172
|
+
for (const [i, a] of named.entries())
|
|
173
|
+
for (const [j, c] of named.entries())
|
|
174
|
+
if (i < j && (ranked(a) || ranked(c)) && bound(a) === bound(c) && !post(a) && !post(c))
|
|
175
|
+
add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
|
|
176
|
+
for (const [i, a] of named.entries())
|
|
177
|
+
for (const [j, c] of named.entries())
|
|
178
|
+
if (i < j && !(ranked(a) || ranked(c)) && bound(a) === bound(c) && !post(a) && !post(c))
|
|
179
|
+
add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
|
|
180
|
+
return { reads: named, insts: insts.slice(0, 10), wits: wits.slice(0, 10) };
|
|
181
|
+
}
|
|
182
|
+
export function searchCounted(m0, caller, ms = 60_000) {
|
|
183
|
+
const until = clock() + ms, g = guardLaws(m0), m = { ...m0, counts: { ...m0.counts, ...g.counts } };
|
|
184
|
+
// The small instances: each param 2 and 3 (where the precondition allows), inputs and sets below 3.
|
|
185
|
+
const insts = [2, 3].map(x => Object.fromEntries(m.params.map(p => [p, x])));
|
|
186
|
+
const states = insts.map(p => {
|
|
187
|
+
try {
|
|
188
|
+
return { p, sts: small(m, p, 3) };
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
return { p, sts: [] };
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
const kinds = Object.keys(m.maps ?? {}).map(mp => {
|
|
195
|
+
const most = Math.max(0, ...states.flatMap(({ sts }) => sts.flatMap(st => [...(st.maps[mp]?.values() ?? [])])));
|
|
196
|
+
return { name: `${mp} at most ${most}`, forall: 'a$c', holds: { op: '<=', a: { op: 'get', map: mp, key: v('a$c') }, b: k(most) } };
|
|
197
|
+
});
|
|
198
|
+
const trueAll = (l) => states.every(({ p, sts }) => sts.every(st => holdsAt(m, l, p, st, 4)));
|
|
199
|
+
if (!caller.every(trueAll))
|
|
200
|
+
return { proven: false, laws: caller, m, why: 'a law fails on the small instances' };
|
|
201
|
+
let set = [...caller, ...[...kinds, ...pairLaws(m), ...g.laws].filter(trueAll)];
|
|
202
|
+
if (env.GDP_COUNTS_TRACE)
|
|
203
|
+
console.error(`counts: candidates ${set.map(l => l.name).join('; ')}`);
|
|
204
|
+
for (let round = 0; clock() < until; round++) {
|
|
205
|
+
const terms = (l) => [...(l.forall ? [v(`${l.forall}#`)] : []), ...(l.keys ?? []).map(v), ...m.inputs.map(v)];
|
|
206
|
+
const instances = {}, certs = {}, failed = new Set();
|
|
207
|
+
for (const law of set) {
|
|
208
|
+
if (clock() > until)
|
|
209
|
+
return { proven: false, laws: set, m, why: 'time' };
|
|
210
|
+
const ts = terms(law);
|
|
211
|
+
const inst = (wits) => {
|
|
212
|
+
const out = {};
|
|
213
|
+
for (const l of set) {
|
|
214
|
+
if (l.keys?.length === 1)
|
|
215
|
+
out[l.name] = ts.flatMap(x => ts.flatMap(y => (json(x) === json(y) ? [] : [x, y])));
|
|
216
|
+
else if (l.keys?.length === 2)
|
|
217
|
+
out[l.name] = ts.flatMap(x => ts.flatMap(y => ts.flatMap(z => (json(y) === json(z) ? [] : [x, y, z]))));
|
|
218
|
+
else if (l.forall)
|
|
219
|
+
out[l.name] = [...ts, ...wits.map(v)];
|
|
220
|
+
}
|
|
221
|
+
for (const [f, q] of Object.entries(m.step.flags ?? {}))
|
|
222
|
+
if (q.op === 'all' && !q.keys?.length)
|
|
223
|
+
out[`?${f}`] = [...wits.map(v), ...m.inputs.map(v)];
|
|
224
|
+
return out;
|
|
225
|
+
};
|
|
226
|
+
// The goals' certificates: first with no instances of the lemma, then with the cells' (one set of witnesses a law).
|
|
227
|
+
let ok = true;
|
|
228
|
+
for (const pass of [0, 1]) {
|
|
229
|
+
const wits0 = pass ? Array.from({ length: 10 }, (_, i) => `w$${i}`) : [];
|
|
230
|
+
instances[law.name] = inst(wits0);
|
|
231
|
+
ok = true;
|
|
232
|
+
for (const { goal, decls } of countedObligations(m, set, instances, set.indexOf(law))) {
|
|
233
|
+
const c = pass ? certFor(goal, decls) : { reads: [], insts: [] };
|
|
234
|
+
const gg = mcGoal(goal.hyps, decls, c);
|
|
235
|
+
const o = gg && grow(gg, new Map(), { nodes: 0, until: Math.min(until, clock() + 10_000) });
|
|
236
|
+
if (!o || !('tree' in o)) {
|
|
237
|
+
ok = false;
|
|
238
|
+
if (env.GDP_COUNTS_TRACE && pass)
|
|
239
|
+
console.error(`counts: ${goal.name}: ${gg ? json(o).slice(0, 300) : 'a read of no count'} (reads ${c.reads.map(r => `${r[1]}[${json(r[2])}]`).join(' ')})`);
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
certs[goal.name] = { reads: c.reads, insts: c.insts, tree: o.tree };
|
|
243
|
+
}
|
|
244
|
+
if (ok)
|
|
245
|
+
break;
|
|
246
|
+
}
|
|
247
|
+
if (!ok)
|
|
248
|
+
failed.add(law.name);
|
|
249
|
+
}
|
|
250
|
+
if (!failed.size) {
|
|
251
|
+
const proof = { instances, certs };
|
|
252
|
+
return checkCountedLaws(m, set, proof) ? { proven: true, laws: set, m, proof } : { proven: false, laws: set, m, why: 'the kernel refused the set' };
|
|
253
|
+
}
|
|
254
|
+
if (caller.some(l => failed.has(l.name)) && set.length === caller.length)
|
|
255
|
+
return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
|
|
256
|
+
const next = set.filter(l => !failed.has(l.name) || caller.includes(l));
|
|
257
|
+
if (next.length === set.length) {
|
|
258
|
+
// only callers fail: drop nothing more, give up
|
|
259
|
+
return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
|
|
260
|
+
}
|
|
261
|
+
set = next;
|
|
262
|
+
}
|
|
263
|
+
return { proven: false, laws: set, m, why: 'time' };
|
|
264
|
+
}
|
package/dist/core/cycles.js
CHANGED
|
@@ -1904,7 +1904,8 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
|
|
|
1904
1904
|
const ms = until - clock();
|
|
1905
1905
|
if (ms > 300) {
|
|
1906
1906
|
const { stay, cover, helps } = livenessParts(m, lv), inf = inferLaws(sample.rule ?? m, laws, [stay, cover, ...helps], { ms });
|
|
1907
|
-
|
|
1907
|
+
// (laws about every key too: a liveness about every key needs those of its key's cells)
|
|
1908
|
+
const kept = inf.found.filter(f => !f.law.some?.length), more = kept.map(f => f.law);
|
|
1908
1909
|
if (inf.proven && more.length) {
|
|
1909
1910
|
const again = withDeadline(until + 5000, () => proveLiveness(m, [...laws, ...more], lv));
|
|
1910
1911
|
if (again.proven && again.checked)
|
package/dist/core/dsl.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type C, type E, type Law, type Recurrence, type Machine, type Rand, type Request, type State, type Sum } from './machine.js';
|
|
2
2
|
import { type Fold, type Goal, type Liveness, type Loop, type Recur, type StepLaw, type Tree } from '../kernel/kernel.js';
|
|
3
3
|
import { type Report } from '../kernel/prove.js';
|
|
4
|
+
import { findRing } from './live.js';
|
|
4
5
|
export type TermLike = Term | number;
|
|
5
6
|
export declare const termOf: (t: TermLike) => E;
|
|
6
7
|
export declare class Term {
|
|
@@ -267,6 +268,15 @@ export type MapWrite = {
|
|
|
267
268
|
};
|
|
268
269
|
};
|
|
269
270
|
export declare const everyKey: (f: (key: Term, key2: Term, key3: Term) => Cond) => Cond;
|
|
271
|
+
export type LeastDef = {
|
|
272
|
+
where: (key: Term) => Cond;
|
|
273
|
+
by: (key: Term) => (IntLike | {
|
|
274
|
+
desc: IntLike;
|
|
275
|
+
})[];
|
|
276
|
+
};
|
|
277
|
+
export declare const desc: (t: IntLike) => {
|
|
278
|
+
desc: IntLike;
|
|
279
|
+
};
|
|
270
280
|
export declare const someKey: (f: (key: Term) => Cond, witness?: TermLike) => Cond;
|
|
271
281
|
export type ExistsWitness<V> = V | number | {
|
|
272
282
|
start: V | number;
|
|
@@ -518,6 +528,10 @@ type Spec = {
|
|
|
518
528
|
nodes?: [string, Kind<unknown>, string[], Record<string, NodeFold<unknown, string>>][];
|
|
519
529
|
kinded?: [string, Kind<unknown>][];
|
|
520
530
|
carried?: string[];
|
|
531
|
+
counts?: [string, (env: never) => {
|
|
532
|
+
below: TermLike;
|
|
533
|
+
body: (x: Term, k: Term) => Cond | TermLike;
|
|
534
|
+
}][];
|
|
521
535
|
seqs?: string[];
|
|
522
536
|
seqTables?: string[];
|
|
523
537
|
lists2?: [string, Kind<unknown>, Record<string, ListFold<unknown>>, Record<string, ListLemma>][];
|
|
@@ -532,6 +546,7 @@ type Spec = {
|
|
|
532
546
|
record?: string[];
|
|
533
547
|
sums: [string, (r: never, p: never) => TermLike][];
|
|
534
548
|
queries: [string, (r: never, v: never) => TermLike][];
|
|
549
|
+
leasts?: [string, (env: never) => LeastDef][];
|
|
535
550
|
keep?: (env: never) => Cond;
|
|
536
551
|
relations?: (env: never) => Relation[];
|
|
537
552
|
prune?: {
|
|
@@ -590,6 +605,12 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
|
|
|
590
605
|
carries<const N extends string>(...names: N[]): Rule<P, I & {
|
|
591
606
|
[k in N]: MapRef;
|
|
592
607
|
}, S, M, F, R, Su, Q>;
|
|
608
|
+
counts<T extends Record<string, (env: P & I & S & M) => {
|
|
609
|
+
below: TermLike;
|
|
610
|
+
body: (x: Term, k: Term) => Cond | TermLike;
|
|
611
|
+
}>>(cs: T): Rule<P, I & {
|
|
612
|
+
[k in keyof T]: MapRef;
|
|
613
|
+
}, S, M, F, R, Su, Q>;
|
|
593
614
|
carriesSeq<const N extends string>(...names: N[]): Rule<P, I & {
|
|
594
615
|
[k in N]: SeqRef;
|
|
595
616
|
}, S, M, F, R, Su, Q>;
|
|
@@ -612,6 +633,9 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
|
|
|
612
633
|
queries<T extends Record<string, (r: R, v: P & I) => TermLike>>(queries: T): Rule<P, I, S, M, F, R, Su, Q & {
|
|
613
634
|
[k in keyof T]: Term;
|
|
614
635
|
}>;
|
|
636
|
+
least<T extends Record<string, (env: P & I & S & M & Su & Q) => LeastDef>>(defs: T): Rule<P, I, S, M, F, R, Su, Q & {
|
|
637
|
+
[k in keyof T]: Maybe<Term>;
|
|
638
|
+
}>;
|
|
615
639
|
keep(f: (env: P & I & S & M & F & Su & Q) => Cond): Rule<P, I, S, M, F, R, Su, Q>;
|
|
616
640
|
relations(f: (env: P & I & Su & Q) => Relation[]): Rule<P, I, S, M, F, R, Su, Q>;
|
|
617
641
|
prune(order: keyof R & string, after: (p: P) => TermLike): Rule<P, I, S, M, F, R, Su, Q>;
|
|
@@ -628,16 +652,16 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
|
|
|
628
652
|
stepLaw(name: string, then: (before: P & I & S & M & F & Su & Q, after: S & M & Su) => Cond | Forall, when?: (before: P & I & S & M & F & Su & Q) => Cond): StepLaw;
|
|
629
653
|
stepsLaw(name: string, k: number, then: (first: P & I & S & M & F & Su & Q, last: S & M & Su, requests: (I & Q)[]) => Cond | Forall, when?: (before: P & I & S & M & F & Su & Q, j: number) => Cond | undefined): StepLaw;
|
|
630
654
|
leadsTo(name: string, spec: {
|
|
631
|
-
from: (env: P & S & M & Su) => Cond;
|
|
632
|
-
to: (env: P & S & M & Su) => Cond;
|
|
633
|
-
rank?: (env: P & S & M & Su) => TermLike | TermLike[];
|
|
634
|
-
helpful: ((env: P & S & M & Su) => Record<string, TermLike>) | {
|
|
635
|
-
when?: (env: P & S & M & Su) => Cond;
|
|
636
|
-
request: (env: P & S & M & Su) => Record<string, TermLike>;
|
|
655
|
+
from: (env: P & S & M & Su, key: Term) => Cond;
|
|
656
|
+
to: (env: P & S & M & Su, key: Term) => Cond;
|
|
657
|
+
rank?: (env: P & S & M & Su, key: Term) => TermLike | TermLike[];
|
|
658
|
+
helpful: ((env: P & S & M & Su, key: Term) => Record<string, TermLike>) | {
|
|
659
|
+
when?: (env: P & S & M & Su, key: Term) => Cond;
|
|
660
|
+
request: (env: P & S & M & Su, key: Term) => Record<string, TermLike>;
|
|
637
661
|
}[];
|
|
638
662
|
fairness?: 'weak' | 'strong';
|
|
639
663
|
levels?: number[];
|
|
640
|
-
}):
|
|
664
|
+
}): KeyedLiveness;
|
|
641
665
|
decide(name: string, given: (env: P & I) => Cond | Cond[], then: (env: P & I) => Cond): Decision;
|
|
642
666
|
relate(name: string, given: (a: P & I, b: P & I) => Cond | Cond[], then: (a: P & I, b: P & I) => Cond): Decision;
|
|
643
667
|
private kindAssumptions;
|
|
@@ -843,6 +867,7 @@ export type Verdict = {
|
|
|
843
867
|
witnesses?: Record<string, string>;
|
|
844
868
|
k?: number;
|
|
845
869
|
assumes?: Assumes;
|
|
870
|
+
rank?: E | E[];
|
|
846
871
|
};
|
|
847
872
|
export type Assumes = {
|
|
848
873
|
states: 'reachable';
|
|
@@ -878,9 +903,16 @@ export declare function proveRule(r: Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj
|
|
|
878
903
|
export declare function proveSteps(r: Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>, laws: Law[], stepLaws: StepLaw[], opts?: ProveOptions): Verdict;
|
|
879
904
|
export type { StepLaw };
|
|
880
905
|
export type { Liveness };
|
|
881
|
-
export
|
|
906
|
+
export type KeyedLiveness = Liveness & {
|
|
907
|
+
forall?: string;
|
|
908
|
+
};
|
|
909
|
+
export declare const keyed: <R extends Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>>(r: R, l: KeyedLiveness) => R;
|
|
910
|
+
export declare function proveLeadsTo(r: Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>, laws: Law[], l: KeyedLiveness, opts?: {
|
|
882
911
|
ms?: number;
|
|
883
912
|
}): Verdict;
|
|
913
|
+
export declare function refuteLeadsTo(r: Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>, laws: Law[], l: KeyedLiveness, opts?: {
|
|
914
|
+
ms?: number;
|
|
915
|
+
}): ReturnType<typeof findRing>;
|
|
884
916
|
export declare const proveDecision: (d: Decision, opts?: {
|
|
885
917
|
ms?: number;
|
|
886
918
|
}) => Verdict;
|
package/dist/core/dsl.js
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
//
|
|
16
16
|
// A step returns its updates as one object: every right-hand side reads the state before the step, as the kernel and
|
|
17
17
|
// both runtimes do.
|
|
18
|
+
import { searchCounted } from "./counts.js";
|
|
18
19
|
import { argsKey, machineTerms, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, withArithmetic } from "./machine.js";
|
|
19
20
|
import { allowed, keysOf, requestEnv, watch, watchWork } from "./watch.js";
|
|
20
21
|
import { someHolds, substVars, substVarsE } from "./exists.js";
|
|
@@ -27,7 +28,7 @@ import { findBoundedRun } from "./bmc.js";
|
|
|
27
28
|
import { conjunction, proveKInduction } from "./kind.js";
|
|
28
29
|
import { cycleLemmas, findLeadsTo, findRank } from "./cycles.js";
|
|
29
30
|
import { findNeverEnds } from "./nonterm.js";
|
|
30
|
-
import { leadsByTerms } from "./live.js";
|
|
31
|
+
import { findRing, leadsByTerms } from "./live.js";
|
|
31
32
|
import { freshLaws } from "./fresh.js";
|
|
32
33
|
// --- terms and conditions -------------------------------------------------------------------------------------------
|
|
33
34
|
const naturalConst = (v) => {
|
|
@@ -832,6 +833,8 @@ export const everyKey = (f) => {
|
|
|
832
833
|
const ok = (picked) => (picked.length === names.length ? g(...picked).ok : everyOk(scope?.keys, k => ok([...picked, keyTerm(k)])));
|
|
833
834
|
return new Cond({ op: 'all', key: names[0], ...(names.length > 1 ? { keys: names.slice(1) } : {}), c: g(...names.map(v)).c }, ok([]));
|
|
834
835
|
};
|
|
836
|
+
// A part of a least key's order compared the other way (the greatest first).
|
|
837
|
+
export const desc = (t) => ({ desc: t });
|
|
835
838
|
// Some key where f holds, in a law or a step law's conclusion (¬∀k. ¬f(k)): proven through a witness, a term naming the
|
|
836
839
|
// key, given here or found by the prover among a few candidates (kernel/prove.ts).
|
|
837
840
|
export const someKey = (f, witness) => {
|
|
@@ -1809,6 +1812,12 @@ export class Rule {
|
|
|
1809
1812
|
facts(f) { return this.with({ facts: [...(this.spec.facts ?? []), f] }); }
|
|
1810
1813
|
// Maps each request carries whole (a set of names, say: cells 0 or 1), every cell past them 0; read like any map.
|
|
1811
1814
|
carries(...names) { return this.with({ carried: [...(this.spec.carried ?? []), ...names] }); }
|
|
1815
|
+
// Counts (Machine.counts): `.counts({votes: env => ({below: env.size, body: (x, k) => env.Vote.at(k).eq(x.plus(1))})})`;
|
|
1816
|
+
// each a map no step writes, at x the number of keys k below the bound where the body holds (or its sum), read by the
|
|
1817
|
+
// flags, the assumption and the step at the request's view, and by a law at the state.
|
|
1818
|
+
counts(cs) {
|
|
1819
|
+
return this.with({ counts: [...(this.spec.counts ?? []), ...Object.entries(cs)] });
|
|
1820
|
+
}
|
|
1812
1821
|
// Sequences each request carries (SeqRef): `.carriesSeq('Path')`, then `Path.at(i)`, `Path.len`, `A.prefixOf(B)`; the
|
|
1813
1822
|
// request gives each as an array of naturals.
|
|
1814
1823
|
carriesSeq(...names) {
|
|
@@ -1866,6 +1875,16 @@ export class Rule {
|
|
|
1866
1875
|
queries(queries) {
|
|
1867
1876
|
return this.with({ queries: [...this.spec.queries, ...Object.entries(queries)] });
|
|
1868
1877
|
}
|
|
1878
|
+
// Ordered collections, as a keyed map and the least key the step reads: `name`, a Maybe (none where no key meets
|
|
1879
|
+
// `where`), the key where `where` holds that is least by `by`, compared part by part (`desc(t)`: the greatest first).
|
|
1880
|
+
// The runtimes find it in the state before the step (the smaller key where all tie); the kernel knows it only by the
|
|
1881
|
+
// assumption it adds: where some, `where` holds there and it is at most every key `where` holds at, by `by`; where
|
|
1882
|
+
// none, `where` holds nowhere. A priority queue, a sorted map's first entry, a list's first item by insertion:
|
|
1883
|
+
// .least({best: ({Asks}) => ({where: k => Asks.at(k).has, by: k => [Asks.at(k).price, Asks.at(k).seq]})})
|
|
1884
|
+
// .step(({best, Asks}) => ({Asks: Asks.set(best.inner, ...)})) (best.isSome, best.inner)
|
|
1885
|
+
least(defs) {
|
|
1886
|
+
return this.with({ leasts: [...(this.spec.leasts ?? []), ...Object.entries(defs)] });
|
|
1887
|
+
}
|
|
1869
1888
|
keep(f) { return this.with({ keep: f }); }
|
|
1870
1889
|
relations(f) { return this.with({ relations: f }); }
|
|
1871
1890
|
// Requests come in nondecreasing `order`; a record whose order plus `after` is at most the request's is dropped
|
|
@@ -1999,12 +2018,19 @@ export class Rule {
|
|
|
1999
2018
|
// infinitely often (an event that keeps coming back is taken). Its regions need not stay; a helpful request may move to
|
|
2000
2019
|
// the region of one of a higher `levels` (found where left out) instead of reaching `to` or lowering the rank:
|
|
2001
2020
|
// job.leadsTo('every job ends', {..., fairness: 'strong', helpful: [{when: waiting, request: fetch}, {when: active, request: fail}]})
|
|
2021
|
+
// About every key: callbacks that take a second parameter, the key (one for every key, the same in every callback):
|
|
2022
|
+
// outbox.leadsTo('every row is published', {from: ({Rows}, k) => Rows.at(k).eq(1), to: ({Pub}, k) => Pub.at(k).eq(1), helpful: (_, k) => ({act: 1, row: k})})
|
|
2023
|
+
// The key is a fresh param no step reads (`forall`), which proveLeadsTo adds to the rule (`keyed`): a run of the rule
|
|
2024
|
+
// with it is a run of the rule without it, at every value of the key, so the one-machine argument at that param is
|
|
2025
|
+
// the law at every key, each key's helpful requests fair on their own (fairness per key).
|
|
2002
2026
|
leadsTo(name, spec) {
|
|
2003
2027
|
const env = this.env({ flags: false, inputs: false, queries: false });
|
|
2004
|
-
const
|
|
2005
|
-
const
|
|
2006
|
-
const
|
|
2007
|
-
|
|
2028
|
+
const fs = [spec.from, spec.to, spec.rank, ...(typeof spec.helpful === 'function' ? [spec.helpful] : spec.helpful.flatMap(h => [h.when, h.request]))];
|
|
2029
|
+
const forall = fs.some(f => f && f.length > 1) ? `key$${++keyCounter}` : undefined, key = (forall ? v(forall) : undefined);
|
|
2030
|
+
const req = (f) => Object.fromEntries(Object.entries(f(env, key)).map(([n, t]) => [n, termOf(t)]));
|
|
2031
|
+
const r = spec.rank ? spec.rank(env, key) : [], rank = Array.isArray(r) ? r.map(termOf) : termOf(r);
|
|
2032
|
+
const base = { name, from: spec.from(env, key).c, to: spec.to(env, key).c, rank, ...(spec.fairness === 'strong' ? { fairness: 'strong' } : {}), ...(spec.levels ? { levels: spec.levels } : {}), ...(forall ? { forall } : {}) };
|
|
2033
|
+
return this.divides(typeof spec.helpful === 'function' ? { ...base, request: req(spec.helpful) } : { ...base, helpful: spec.helpful.map(h => ({ ...(h.when ? { when: h.when(env, key).c } : {}), request: req(h.request) })) });
|
|
2008
2034
|
}
|
|
2009
2035
|
// A decision: whenever the params and the request meet `given`, `then` holds. Decisions don't read the state; the
|
|
2010
2036
|
// functions' facts are assumed at the arguments the decision reads them at, and a carried list's equations (each
|
|
@@ -2078,6 +2104,8 @@ export class Rule {
|
|
|
2078
2104
|
out[n] = k.value(n);
|
|
2079
2105
|
for (const n of this.spec.carried ?? [])
|
|
2080
2106
|
out[n] = new MapRef(n, 0);
|
|
2107
|
+
for (const [n] of this.spec.counts ?? [])
|
|
2108
|
+
out[n] = new MapRef(n, 0);
|
|
2081
2109
|
for (const n of this.spec.seqs ?? []) {
|
|
2082
2110
|
delete out[`${n}_len`];
|
|
2083
2111
|
out[n] = new SeqRef(new MapRef(n, 0), v(`${n}_len`));
|
|
@@ -2094,6 +2122,8 @@ export class Rule {
|
|
|
2094
2122
|
delete out[part];
|
|
2095
2123
|
out[n] = l;
|
|
2096
2124
|
}
|
|
2125
|
+
for (const [n] of this.spec.leasts ?? [])
|
|
2126
|
+
out[n] = maybe(nat).value(n);
|
|
2097
2127
|
}
|
|
2098
2128
|
if (parts.state !== false) {
|
|
2099
2129
|
for (const [n] of this.spec.state)
|
|
@@ -2151,7 +2181,7 @@ export class Rule {
|
|
|
2151
2181
|
names() {
|
|
2152
2182
|
const s = this.spec;
|
|
2153
2183
|
return [...s.params.map(([n]) => [n, 'a param']), ...(s.fns ?? []).map(([n]) => [n, 'a function']), ...s.inputs.map(([n]) => [n, 'an input']), ...(s.carried ?? []).map(n => [n, 'a carried map']),
|
|
2154
|
-
...s.state.map(([n]) => [n, 'a state variable']), ...s.maps.map(([n]) => [n, 'a map']), ...s.sums.map(([n]) => [n, 'a sum']), ...s.queries.map(([n]) => [n, 'a query']),
|
|
2184
|
+
...s.state.map(([n]) => [n, 'a state variable']), ...s.maps.map(([n]) => [n, 'a map']), ...s.sums.map(([n]) => [n, 'a sum']), ...s.queries.map(([n]) => [n, 'a query']), ...(s.leasts ?? []).map(([n]) => [n, 'a least key']),
|
|
2155
2185
|
...[...(s.cells ?? []), ...(s.items ?? [])].filter(([n, k]) => !k.vars(n).includes(n)).map(([n]) => [n, 'a map of a kind']),
|
|
2156
2186
|
...(s.nodes ?? []).map(([n]) => [n, 'a table of nodes']),
|
|
2157
2187
|
];
|
|
@@ -2226,7 +2256,19 @@ export class Rule {
|
|
|
2226
2256
|
params.push(...pre0.vars);
|
|
2227
2257
|
inputs.push(...as0.vars);
|
|
2228
2258
|
const pre = [...this.kindAssumptions('params'), ...pre0.cs];
|
|
2229
|
-
|
|
2259
|
+
// The least keys: inputs the runtimes find, assumed least.
|
|
2260
|
+
const leasts = {}, leastAssume = [];
|
|
2261
|
+
for (const [n, f] of s.leasts ?? []) {
|
|
2262
|
+
const d = f(env), key = `k$${++boundCounter}`, best = env[n];
|
|
2263
|
+
const parts = (k) => d.by(k).map(b => (typeof b === 'object' && !(b instanceof Term) && !(b instanceof Int) && 'desc' in b ? { t: Int.of(b.desc), desc: true } : { t: Int.of(b), desc: false }));
|
|
2264
|
+
const zero = (e) => e.op === 'const' && e.value === 0;
|
|
2265
|
+
leasts[n] = { some: `${n}$some`, key, where: d.where(v(key)).c, by: parts(v(key)).map(b => ({ e: b.t.pos.e, ...(zero(b.t.neg.e) ? {} : { neg: b.t.neg.e }), ...(b.desc ? { desc: true } : {}) })) };
|
|
2266
|
+
inputs.push(`${n}$some`, n);
|
|
2267
|
+
const atMost = (a, b) => (a.length === 0 ? yes
|
|
2268
|
+
: ((x, y) => (a.length === 1 ? x.atMost(y) : x.lt(y).or(x.eq(y).and(atMost(a.slice(1), b.slice(1))))))(a[0].desc ? b[0].t : a[0].t, a[0].desc ? a[0].t : b[0].t));
|
|
2269
|
+
leastAssume.push(best.present.atMost(1), best.isSome.implies(d.where(best.inner)), best.isNone.implies(everyKey(k => d.where(k).not())), best.isSome.implies(everyKey(k => d.where(k).implies(atMost(parts(best.inner), parts(k))))));
|
|
2270
|
+
}
|
|
2271
|
+
const assume = [...this.kindAssumptions('inputs'), ...leastAssume.map(c => hoist.cond(c.c)), ...(s.lists2 ?? []).flatMap(([n]) => env[n].equations().map(c => hoist.cond(c.c))), ...as0.cs.map(c => hoist.cond(c))];
|
|
2230
2272
|
placed();
|
|
2231
2273
|
// Functions, and their facts: each function's own (named after it), then the rule's.
|
|
2232
2274
|
// The functions a function reads come first, each named <function>.<use>.
|
|
@@ -2241,11 +2283,16 @@ export class Rule {
|
|
|
2241
2283
|
state: Object.fromEntries(s.state.map(([n, init]) => [n, typeof init === 'number' ? termOf(init) : termOf(init(pEnv))])),
|
|
2242
2284
|
...(s.maps.length ? { maps: Object.fromEntries(s.maps) } : {}),
|
|
2243
2285
|
...(s.carried?.length ? { inputMaps: s.carried } : {}),
|
|
2286
|
+
...(s.counts?.length ? { counts: Object.fromEntries(s.counts.map(([n, f]) => {
|
|
2287
|
+
const c = f(env), j = `${n}$x`, key = `${n}$k`, b = c.body(v(j), v(key));
|
|
2288
|
+
return [n, { j, key, below: termOf(c.below), body: b instanceof Cond ? { op: 'if', c: b.c, then: { op: 'const', value: 1 }, else: { op: 'const', value: 0 } } : termOf(b) }];
|
|
2289
|
+
})) } : {}),
|
|
2244
2290
|
step: { ...(Object.keys(flags).length ? { flags } : {}), ...(Object.keys(state).length ? { state } : {}), ...(Object.keys(maps).length ? { maps } : {}) },
|
|
2245
2291
|
...(pre.length ? { pre: pre.length === 1 ? pre[0] : { op: 'and', xs: pre } } : {}),
|
|
2246
2292
|
...(assume.length ? { assume: assume.length === 1 ? assume[0] : { op: 'and', xs: assume } } : {}),
|
|
2247
2293
|
...(Object.keys(fns).length ? { fns } : {}),
|
|
2248
2294
|
...(facts.length ? { facts } : {}),
|
|
2295
|
+
...(Object.keys(leasts).length ? { leasts } : {}),
|
|
2249
2296
|
};
|
|
2250
2297
|
if (s.record) {
|
|
2251
2298
|
const kinds = new Map(s.inputs);
|
|
@@ -2327,7 +2374,7 @@ export class Rule {
|
|
|
2327
2374
|
}
|
|
2328
2375
|
// One step: the flags, the updates and the step laws, each against what the interpreter computed.
|
|
2329
2376
|
crossStep(params, st, input, next, stepLaws, bound, count) {
|
|
2330
|
-
const s = this.spec, m = this.machine, run = interpret(m), seen = carriedView(m, st, input), req = requestEnv(m, run, params, st, input);
|
|
2377
|
+
const s = this.spec, m = this.machine, run = interpret(m), seen = carriedView(m, st, input, undefined, params), req = requestEnv(m, run, params, st, input);
|
|
2331
2378
|
const keys = keysOf(bound, seen, next), vars = { ...params, ...st.scalars, ...req };
|
|
2332
2379
|
const sc = { vars, maps: Object.fromEntries(Object.entries(seen.maps).map(([n, cells]) => [n, { cells, dflt: seen.defaults?.[n] ?? m.maps?.[n] ?? 0 }])), keys: exactKeys(keys, vars, seen, next), flags: {} };
|
|
2333
2380
|
// Flags: every callback in order, each name's last definition winning, until the values settle (a name defined
|
|
@@ -2880,6 +2927,11 @@ export function proveRule(r, laws, opts = {}) {
|
|
|
2880
2927
|
// (A step law broken so is refused, proveSteps below: it holds from every state the laws allow, reached or not.)
|
|
2881
2928
|
if (refuted)
|
|
2882
2929
|
return refuted.run ? refutedVerdict(refuted) : searched(r, laws, [], refutedVerdict(refuted), opts);
|
|
2930
|
+
// A rule with counts: its goals are the counted ones (core/counts.ts searches them; the kernel checks the set).
|
|
2931
|
+
if (r.machine.counts && Object.keys(r.machine.counts).length) {
|
|
2932
|
+
const c = searchCounted(r.machine, withKinds(r, laws), typeof opts.search === 'object' ? opts.search.ms ?? 60_000 : 60_000);
|
|
2933
|
+
return { proven: c.proven, checked: c.proven, ...(c.why ? { why: c.why } : {}), found: { laws: c.laws.map(l => ({ text: l.name })) } };
|
|
2934
|
+
}
|
|
2883
2935
|
const out = (opts.fast ? proveSetFast : proveLaws)(r.machine, withKinds(r, laws));
|
|
2884
2936
|
const v = { ...verdictOf(out), ...(out.witnesses && out.proven ? { witnesses: out.witnesses } : {}) };
|
|
2885
2937
|
return searched(r, laws, [], v, opts);
|
|
@@ -3028,8 +3080,10 @@ function searchedUntil(r, laws, stepLaws, v, opts, until) {
|
|
|
3028
3080
|
// What a verdict proven with these found laws rests on: the states reachable from init (each found law is proven so).
|
|
3029
3081
|
const reachableBy = (found) => ({ states: 'reachable', laws: found.map(f => f.text) });
|
|
3030
3082
|
const withAssumes = (found) => (found.length ? { assumes: reachableBy(found) } : {});
|
|
3083
|
+
// The rule a keyed liveness is proven on: the rule with its key as one more param (a natural), any other rule as it is.
|
|
3084
|
+
export const keyed = (r, l) => (l.forall ? r.params({ [l.forall]: nat }) : r);
|
|
3031
3085
|
export function proveLeadsTo(r, laws, l, opts = {}) {
|
|
3032
|
-
r = r.withSumsOf(laws, l);
|
|
3086
|
+
r = keyed(r, l).withSumsOf(laws, l);
|
|
3033
3087
|
noting(r, laws, l);
|
|
3034
3088
|
if (laws.some(law => law.some?.length))
|
|
3035
3089
|
throw new Error(`${r.machine.name}: a law with "there exists" goes to proveRule or proveSteps; a liveness takes plain laws (the ones its proof printed, Verdict.witnesses)`);
|
|
@@ -3061,12 +3115,19 @@ export function proveLeadsTo(r, laws, l, opts = {}) {
|
|
|
3061
3115
|
}
|
|
3062
3116
|
}
|
|
3063
3117
|
const helpers = [...fresh, ...(f.laws ?? []).map((law, i) => ({ law, text: f.found?.laws[i] ?? law.name }))];
|
|
3064
|
-
return { proven: f.proven, checked: f.checked, ...(f.goal ? { goal: f.goal, stuck: f.stuck } : {}), ...(f.witness ? { witness: f.witness } : {}), ...(f.why ? { why: f.why } : {}),
|
|
3118
|
+
return { proven: f.proven, checked: f.checked, ...(f.proven && f.rank ? { rank: f.rank } : {}), ...(f.goal ? { goal: f.goal, stuck: f.stuck } : {}), ...(f.witness ? { witness: f.witness } : {}), ...(f.why ? { why: f.why } : {}),
|
|
3065
3119
|
...(f.found ? { found: { rank: f.found.rank, ...(helpers.length ? { laws: helpers } : {}) } } : {}), ...(f.proven ? withAssumes(helpers) : {}) };
|
|
3066
3120
|
}
|
|
3067
3121
|
const out = proveLiveness(r.machine, withKinds(r, laws), l);
|
|
3068
3122
|
return verdictOf(out);
|
|
3069
3123
|
}
|
|
3124
|
+
// A leads-to refuted by a fair run that never gets there (core/live.ts's findRing, checked by refutedBy): a stem from
|
|
3125
|
+
// the start, then round a ring of sets each request of which the kernel proves allowed and into the next set, fair to
|
|
3126
|
+
// each helpful request (taken in the ring, or never allowed in a set). Undefined where none is found within `ms`.
|
|
3127
|
+
export function refuteLeadsTo(r, laws, l, opts = {}) {
|
|
3128
|
+
const k = keyed(r, l);
|
|
3129
|
+
return findRing(k.machine, withKinds(k, laws), l, { params: (rand, bound) => k.randomParams(rand, bound), input: (rand, bound, ps) => k.randomInput(rand, bound, ps) }, opts);
|
|
3130
|
+
}
|
|
3070
3131
|
// `ms`: the budget (the prover's own per goal, 20 s or a second a hypothesis, where none is given), on the clock the
|
|
3071
3132
|
// prover reads (the counted one inside a counted search): past it the verdict is unknown.
|
|
3072
3133
|
export const proveDecision = (d, opts = {}) => {
|
|
@@ -289,10 +289,10 @@ export function ruleSnap(r, m, st, sorts) {
|
|
|
289
289
|
leaves[v.name] = d[v.name];
|
|
290
290
|
for (const md of m.maps) {
|
|
291
291
|
const cells = {};
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
const key = md.key === 'str' ? idText(Number(k)) ?? `#${k}` : k;
|
|
292
|
+
// (a list: its items by their places in its order, 0 first, as the code's list holds them)
|
|
293
|
+
const held = Object.entries((d[md.name] ?? {})).filter(([, c]) => c.has).sort(([a], [b]) => Number(a) - Number(b));
|
|
294
|
+
for (const [i, [k, c]] of held.entries()) {
|
|
295
|
+
const key = md.ordered ? String(i) : md.key === 'str' ? idText(Number(k)) ?? `#${k}` : k;
|
|
296
296
|
cells[key] = Object.fromEntries(md.fields.map(f => [f.name, c[f.name]]));
|
|
297
297
|
}
|
|
298
298
|
maps[md.name] = cells;
|