gdp-wired 0.20.0 → 0.22.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.
@@ -0,0 +1,476 @@
1
+ import { Bool, Integer, Nat, Val, argsOf, bindName, define, encX, encY, evalX, factsOf, fnNamed, programOf, schemesOf, searchIn } from "./data.js";
2
+ import { proveCyclic } from "./cyclic.js";
3
+ import { clock, pairedKeys, withDeadline } from "../kernel/prove.js";
4
+ import { substE } from "../kernel/kernel.js";
5
+ const nat = (value) => ({ op: 'nat', value });
6
+ const cond = (c) => ({ op: 'bool', c });
7
+ const OPS = [
8
+ { name: '+', args: 2, ret: 'nat', x: (a, b) => ({ op: 'add', a, b }), at: (a, b) => a + b },
9
+ { name: '∸', args: 2, ret: 'nat', x: (a, b) => ({ op: 'sub', a, b }), at: (a, b) => Math.max(0, a - b) },
10
+ { name: 'min', args: 2, ret: 'nat', x: (a, b) => ({ op: 'min', a, b }), at: Math.min },
11
+ { name: 'max', args: 2, ret: 'nat', x: (a, b) => ({ op: 'max', a, b }), at: Math.max },
12
+ { name: '≤', args: 2, ret: 'bool', x: (a, b) => cond({ op: '<=', a, b }), at: (a, b) => +(a <= b) },
13
+ { name: '<', args: 2, ret: 'bool', x: (a, b) => cond({ op: '<', a, b }), at: (a, b) => +(a < b) },
14
+ { name: '=', args: 2, ret: 'bool', x: (a, b) => cond({ op: '=', a, b }), at: (a, b) => +(a === b) },
15
+ { name: '≥', args: 2, ret: 'bool', x: (a, b) => cond({ op: '<=', a: b, b: a }), at: (a, b) => +(a >= b) },
16
+ { name: '>', args: 2, ret: 'bool', x: (a, b) => cond({ op: '<', a: b, b: a }), at: (a, b) => +(a > b) },
17
+ { name: '≠', args: 2, ret: 'bool', x: (a, b) => cond({ op: 'not', x: { op: '=', a, b } }), at: (a, b) => +(a !== b) },
18
+ { name: 'x + 1', args: 1, ret: 'nat', x: a => ({ op: 'add', a, b: nat(1) }), at: a => a + 1 },
19
+ { name: 'x ∸ 1', args: 1, ret: 'nat', x: a => ({ op: 'sub', a, b: nat(1) }), at: a => Math.max(0, a - 1) },
20
+ { name: '2·x', args: 1, ret: 'nat', x: a => ({ op: 'mul', k: 2, a }), at: a => 2 * a },
21
+ { name: 'x = 0', args: 1, ret: 'bool', x: a => cond({ op: '=', a, b: nat(0) }), at: a => +(a === 0) },
22
+ ];
23
+ const fnOf = (name) => { const f = fnNamed(name); if (!f)
24
+ throw new Error(`no function ${name}`); return f; };
25
+ const recursive = (f) => f.decreases !== undefined;
26
+ // The built-in a recursive function of naturals computes at every argument up to 6 (one argument: up to 12), if one.
27
+ function builtinOf(f) {
28
+ if (!recursive(f) || f.paramFns.length || !(f.ret === 'nat' || f.ret === 'bool') || !f.params.every(q => q.sort === 'nat'))
29
+ return undefined;
30
+ const n = f.params.length;
31
+ return OPS.find(op => {
32
+ if (op.args !== n || op.ret !== f.ret)
33
+ return false;
34
+ try {
35
+ for (let a = 0; a <= (n === 1 ? 12 : 6); a++)
36
+ for (let b = 0; b <= (n === 1 ? 0 : 6); b++) {
37
+ if (evalX({ op: 'call', fn: f.name, args: [nat(a), nat(b)].slice(0, n) }, new Map(), {}) !== op.at(a, b))
38
+ return false;
39
+ }
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ return true;
45
+ });
46
+ }
47
+ // Whether `y` is f's bridge law: f at distinct variables equal (either side) to the built-in at them.
48
+ function isBridge(y, f, op) {
49
+ if (y.op !== '=')
50
+ return false;
51
+ const sides = [[y.a, y.b], [y.b, y.a]];
52
+ return sides.some(([c, x]) => c.op === 'call' && c.fn === f.name && c.args.every(a => a.op === 'var') && new Set(c.args.map(a => JSON.stringify(a))).size === c.args.length
53
+ && JSON.stringify(x) === JSON.stringify(op.x(c.args[0], c.args[1] ?? nat(0))));
54
+ }
55
+ const callsOf = (t) => { const out = []; walkO(t, o => { if (o.op === 'call')
56
+ out.push(o.fn); }); return out; };
57
+ function walkO(t, f) {
58
+ if (Array.isArray(t)) {
59
+ t.forEach(x => walkO(x, f));
60
+ return;
61
+ }
62
+ if (!t || typeof t !== 'object')
63
+ return;
64
+ f(t);
65
+ for (const v of Object.values(t))
66
+ walkO(v, f);
67
+ }
68
+ export function transferPlan(l) {
69
+ const p = programOf([l]), bridges = new Map();
70
+ for (const f of p.fns) {
71
+ const op = builtinOf(f);
72
+ if (op && !isBridge(l.holds, f, op))
73
+ bridges.set(f.name, op);
74
+ }
75
+ const unfolds = p.fns.some(f => !recursive(f));
76
+ return bridges.size || unfolds ? { bridges, unfolds } : undefined;
77
+ }
78
+ // --- the law said another way ------------------------------------------------------------------------------------------
79
+ // A function's body at arguments (its parameters replaced, each bound name fresh).
80
+ function instantiate(f, args) {
81
+ const sub = new Map(f.params.map((q, i) => [`${f.name}.${q.name}`, args[i]])), ren = new Map();
82
+ const fresh = (b) => { const n = bindName(b.replace(/#\d+$/, '')); ren.set(b, n); return n; };
83
+ const go = (t) => {
84
+ if (Array.isArray(t))
85
+ return t.map(go);
86
+ if (!t || typeof t !== 'object')
87
+ return t;
88
+ const o = t;
89
+ if (o.op === 'var') {
90
+ const name = o.name;
91
+ return sub.get(name) ?? (ren.has(name) ? { op: 'var', name: ren.get(name) } : o);
92
+ }
93
+ if (o.op === 'match') {
94
+ const cases = o.cases.map(c => ({ binds: c.binds.map(fresh), body: c.body }));
95
+ return { ...o, of: go(o.of), cases: cases.map(c => ({ binds: c.binds, body: go(c.body) })) };
96
+ }
97
+ if (o.op === 'natmatch') {
98
+ const pred = fresh(o.pred);
99
+ return { ...o, of: go(o.of), zero: go(o.zero), pred, succ: go(o.succ) };
100
+ }
101
+ return Object.fromEntries(Object.entries(o).map(([key, v]) => [key, go(v)]));
102
+ };
103
+ return go(f.body());
104
+ }
105
+ // A term with each bridged call the built-in and each call to a copied function its copy's; in a law (`unfold`), a call
106
+ // to a function that isn't recursive also its body. `holds` of a condition made a value is the condition.
107
+ function rewriter(bridges, copies, unfold, ren = new Map()) {
108
+ let unfolded = 0;
109
+ const rx = (x) => {
110
+ switch (x.op) {
111
+ case 'var': return ren.has(x.name) ? { op: 'var', name: ren.get(x.name) } : x;
112
+ case 'nat': return x;
113
+ case 'add':
114
+ case 'sub':
115
+ case 'min':
116
+ case 'max': return { op: x.op, a: rx(x.a), b: rx(x.b) };
117
+ case 'mul': return { op: 'mul', k: x.k, a: rx(x.a) };
118
+ case 'prod':
119
+ case 'iadd':
120
+ case 'isub': return { op: x.op, a: rx(x.a), b: rx(x.b) };
121
+ case 'mod':
122
+ case 'div':
123
+ case 'imod':
124
+ case 'idiv':
125
+ case 'imul': return { op: x.op, k: x.k, a: rx(x.a) };
126
+ case 'ineg':
127
+ case 'ofnat': return { op: x.op, a: rx(x.a) };
128
+ case 'int': return x;
129
+ case 'if': return { op: 'if', c: ry(x.c), then: rx(x.then), else: rx(x.else) };
130
+ case 'bool': return { op: 'bool', c: ry(x.c) };
131
+ case 'apply': return { op: 'apply', param: x.param, arg: rx(x.arg) };
132
+ case 'size': return { op: 'size', data: x.data, of: rx(x.of) };
133
+ case 'ctor': return { ...x, args: x.args.map(rx) };
134
+ case 'match': return { ...x, of: rx(x.of), cases: x.cases.map(c => ({ binds: c.binds, body: rx(c.body) })) };
135
+ case 'natmatch': return { ...x, of: rx(x.of), zero: rx(x.zero), succ: rx(x.succ) };
136
+ case 'call': {
137
+ const op = bridges.get(x.fn);
138
+ if (op)
139
+ return op.x(rx(x.args[0]), x.args[1] ? rx(x.args[1]) : nat(0));
140
+ if (unfold && !recursive(fnOf(x.fn))) {
141
+ if (++unfolded > 400)
142
+ throw new RangeError('unfolded past 400 calls');
143
+ return rx(instantiate(fnOf(x.fn), x.args));
144
+ }
145
+ return { op: 'call', fn: copies.get(x.fn) ?? x.fn, args: x.args.map(rx) };
146
+ }
147
+ }
148
+ };
149
+ const ry = (y) => {
150
+ switch (y.op) {
151
+ case '<':
152
+ case '<=':
153
+ case '=':
154
+ case 'i<':
155
+ case 'i<=': return { op: y.op, a: rx(y.a), b: rx(y.b) };
156
+ case 'and':
157
+ case 'or': return { op: y.op, xs: y.xs.map(ry) };
158
+ case 'not': return { op: 'not', x: ry(y.x) };
159
+ case 'is': return { ...y, of: rx(y.of) };
160
+ case 'holds': {
161
+ const x = rx(y.x);
162
+ return x.op === 'bool' ? x.c : { op: 'holds', x };
163
+ }
164
+ }
165
+ };
166
+ return { rx, ry };
167
+ }
168
+ const valueOf = (s, x) => (s === 'nat' ? new Nat(x) : s === 'bool' ? new Bool(x.op === 'bool' ? x.c : { op: 'holds', x }) : s === 'int' ? new Integer(x) : new Val(s, x));
169
+ // The copies made, by function and bridges (a law proven again reads the same copies).
170
+ const made = new WeakMap();
171
+ const freshName = (base) => { let n = base; for (let i = 2; fnNamed(n); i++)
172
+ n = `${base}${i}`; return n; };
173
+ // The law through the bridges `bridged`: the copies (made once), the law said with them, the bridge and copy laws, and
174
+ // the program of all of them; none where a copied function is in a ring of several (its copy law would be mutual).
175
+ function build(l, bridged, unfold) {
176
+ // Copied: a function that calls a bridged one, or (unfolding) one that isn't recursive, or a copied one; a function
177
+ // that isn't recursive is unfolded where it is called instead.
178
+ const p0 = programOf([l]), reach = new Set(), unfolded = (n) => unfold && !recursive(fnOf(n));
179
+ for (let changed = true; changed;) {
180
+ changed = false;
181
+ for (const f of p0.fns)
182
+ if (!bridged.has(f.name) && !unfolded(f.name) && !reach.has(f.name) && callsOf(f.body()).some(g => bridged.has(g) || unfolded(g) || reach.has(g))) {
183
+ reach.add(f.name);
184
+ changed = true;
185
+ }
186
+ }
187
+ if ([...reach].some(n => fnOf(n).ring.length > 1))
188
+ return undefined;
189
+ const key = `${unfold}|${[...bridged].map(([f, op]) => `${f}:${op.name}`).sort().join(',')}`, copies = new Map();
190
+ for (const n of reach) {
191
+ const f = fnOf(n), had = made.get(f)?.get(key);
192
+ if (had && fnNamed(had))
193
+ copies.set(n, had);
194
+ }
195
+ for (const n of reach) {
196
+ if (copies.has(n))
197
+ continue;
198
+ const f = fnOf(n), name = freshName(`${n}_bi`);
199
+ copies.set(n, name);
200
+ if (!made.has(f))
201
+ made.set(f, new Map());
202
+ made.get(f).set(key, name);
203
+ }
204
+ for (const n of reach) {
205
+ const f = fnOf(n), name = copies.get(n);
206
+ if (fnNamed(name))
207
+ continue;
208
+ const ren = new Map(f.params.map(q => [`${f.name}.${q.name}`, `${name}.${q.name}`]));
209
+ let body;
210
+ try {
211
+ body = rewriter(bridged, copies, unfold, ren).rx(f.body());
212
+ }
213
+ catch (e) {
214
+ if (e instanceof RangeError)
215
+ return undefined;
216
+ throw e;
217
+ }
218
+ define(name, Object.fromEntries(f.params.map(q => [q.name, q.sort])), f.ret, () => valueOf(f.ret, body));
219
+ }
220
+ let holds;
221
+ try {
222
+ holds = rewriter(bridged, copies, unfold).ry(l.holds);
223
+ }
224
+ catch (e) {
225
+ if (e instanceof RangeError)
226
+ return undefined;
227
+ throw e;
228
+ }
229
+ const lstar = { name: `${l.name}, said through ${[...bridged.keys()].length ? 'the built-ins' : 'its definitions'}`, vars: l.vars, holds, params: l.params };
230
+ // (none the same as the law, and none past eight times its size: definitions unfolded into each other's arguments)
231
+ const size = (y) => JSON.stringify(y).length;
232
+ if (JSON.stringify(lstar.holds) === JSON.stringify(l.holds) || size(lstar.holds) > 8 * size(l.holds) + 4000)
233
+ return undefined;
234
+ const v = (name) => ({ op: 'var', name });
235
+ // Only the copies the law said through them reaches (each with those its copy calls).
236
+ const p1 = programOf([lstar]), back = new Map([...copies].map(([a, b]) => [b, a]));
237
+ const bridges = [...bridged].map(([f, op]) => {
238
+ const fn = fnOf(f), vs = fn.params.map(q => q.name);
239
+ return { fn, op, law: { name: `${f} is ${op.name}`, vars: fn.params.map(q => ({ name: q.name, sort: q.sort })), holds: { op: '=', a: { op: 'call', fn: f, args: vs.map(v) }, b: op.x(v(vs[0]), vs[1] ? v(vs[1]) : nat(0)) }, params: [] } };
240
+ });
241
+ const equivs = p1.fns.filter(f => back.has(f.name)).map(c => {
242
+ const fn = fnOf(back.get(c.name)), vs = fn.params.map(q => q.name), params = [...new Set(fn.paramFns)];
243
+ return { fn, law: { name: `${fn.name} is ${c.name}`, vars: fn.params.map(q => ({ name: q.name, sort: q.sort })), holds: { op: '=', a: { op: 'call', fn: fn.name, args: vs.map(v) }, b: { op: 'call', fn: c.name, args: vs.map(v) } }, params } };
244
+ });
245
+ const p = programOf([l, lstar, ...bridges.map(b => b.law), ...equivs.map(e => e.law)]);
246
+ return { p, lstar, bridges, equivs, copies, unfolded: unfold };
247
+ }
248
+ // --- the proof ---------------------------------------------------------------------------------------------------------
249
+ const k = (value) => ({ op: 'const', value });
250
+ const yes = { op: '<=', a: k(0), b: k(0) };
251
+ const top = (pr) => Math.max(0, ...pr.nodes.map(n => (n.rank[0]?.op === 'const' ? n.rank[0].value : 0)));
252
+ const verify = (fs, specs, until) => {
253
+ const was = pairedKeys.skip;
254
+ pairedKeys.skip = true;
255
+ try {
256
+ return withDeadline(until, () => proveCyclic(fs.facts, specs));
257
+ }
258
+ finally {
259
+ pairedKeys.skip = was;
260
+ }
261
+ };
262
+ // The law through its plan: the bridges proven (those not proven left out, and the rest built again), the copies' laws,
263
+ // the law said through them, and the node from that to the law. Undefined where any of it isn't proven.
264
+ export function proveThrough(l, plan, opts, until) {
265
+ const t0 = performance.now();
266
+ let bridged = new Map(plan.bridges), tried = 0;
267
+ for (;;) {
268
+ if (clock() > until)
269
+ return undefined;
270
+ // (unfolded where that stays within its size, else the bridges alone)
271
+ const b = (plan.unfolds ? build(l, bridged, true) : undefined) ?? (bridged.size ? build(l, bridged, false) : undefined);
272
+ if (!b)
273
+ return undefined;
274
+ // One chain of nodes: each bridge (by the search), each copy's law (its node made, or by the search), in order.
275
+ const fs = factsOf(b.p), chain = [], nodes = [], nodeOf = new Map();
276
+ const add = (pr) => { chain.push(pr); nodes.splice(0, nodes.length, ...pr.nodes); nodeOf.set(pr.law.name, nodes.findIndex(n => n.name === pr.spec.name)); };
277
+ const ctx = () => ({ p: b.p, fs, base: [...chain], level: chain.length ? top(chain.at(-1)) : 0 });
278
+ const lost = [];
279
+ for (const x of b.bridges) {
280
+ const r = searchIn(x.law, opts, Math.min(until, clock() + 6000 * (opts.patience ?? 1)), ctx());
281
+ tried += r.verdict.tried;
282
+ if (r.out)
283
+ add(r.out);
284
+ else
285
+ lost.push(x.fn.name);
286
+ }
287
+ if (lost.length) {
288
+ for (const n of lost)
289
+ bridged.delete(n);
290
+ if (!bridged.size && !plan.unfolds)
291
+ return undefined;
292
+ continue;
293
+ }
294
+ for (const x of b.equivs) {
295
+ const level = (chain.length ? top(chain.at(-1)) : 0) + 1, made = copyNode(x, b, fs, nodeOf, nodes.length, level);
296
+ const checked = made && verify(fs, [...nodes, made], Math.min(until, clock() + 4000));
297
+ if (made && checked && checked.proven && checked.checked) {
298
+ add({ law: x.law, spec: made, nodes: [...nodes, made] });
299
+ continue;
300
+ }
301
+ const r = searchIn(x.law, { ...opts, lemmas: [] }, Math.min(until, clock() + 8000 * (opts.patience ?? 1)), ctx());
302
+ tried += r.verdict.tried;
303
+ if (!r.out)
304
+ return undefined;
305
+ add(r.out);
306
+ }
307
+ // (through the bridges and unfolded: half the time left, the other half through the unfolding alone, the functions
308
+ // as written)
309
+ const again = b.unfolded && bridged.size > 0;
310
+ const r = searchIn(b.lstar, opts, again ? clock() + (until - clock()) / 2 : until, { p: b.p, fs, base: [], level: 0 });
311
+ tried += r.verdict.tried;
312
+ if (!r.out && again && clock() < until) {
313
+ bridged = new Map();
314
+ continue;
315
+ }
316
+ if (!r.out)
317
+ return { ...r.verdict, proven: false, checked: false, law: l.name, counterexample: undefined, tried };
318
+ // The nodes: the chain's, then the law's said through them, then the law's own.
319
+ const specs = [...nodes], names = new Set(specs.map(n => n.name)), off = specs.length;
320
+ for (const n of r.out.nodes) {
321
+ let name = n.name;
322
+ for (let i = 2; names.has(name); i++)
323
+ name = `${n.name} (${i})`;
324
+ names.add(name);
325
+ specs.push({ ...n, name, uses: n.uses.map(u => ({ ...u, node: u.node + off })) });
326
+ }
327
+ const lnode = off + r.out.nodes.indexOf(r.out.spec);
328
+ const node = lawNode(l, b, fs, nodeOf, lnode, Math.max(top(r.out), ...chain.map(top)) + 1);
329
+ if (!node)
330
+ return undefined;
331
+ specs.push(node);
332
+ const v = verify(fs, specs, Math.max(until, clock() + 3000));
333
+ if (!v.proven || !v.checked)
334
+ return undefined;
335
+ const through = [...b.bridges.map(x => `${x.fn.name} is ${x.op.name}`), ...b.equivs.map(x => x.law.name), ...(b.unfolded ? [`unfolded: ${programOf([l]).fns.filter(f => !recursive(f)).map(f => f.name).join(', ')}`] : [])];
336
+ return { law: l.name, proven: true, checked: true, proof: v, lemmas: [...b.bridges.map(x => x.law.name), ...b.equivs.map(x => x.law.name), ...r.verdict.lemmas], scheme: `${r.verdict.scheme ?? 'no induction'}, through the law ${b.lstar.name}`, tried, program: b.p, node: specs.length - 1, ms: Math.round(performance.now() - t0), through };
337
+ }
338
+ }
339
+ // Two terms, one of the law (or a function's body) and one said through the bridges, walked together: where they read
340
+ // different things, the reason they are equal, recorded (a bridge's or a copy's law at the call's arguments, an unfolded
341
+ // function's fact there, a congruence of a map at two keys). `own`: a function whose read is its copy's by the node's own
342
+ // induction (a copy's law: its recursive calls, given by the uses of its scheme).
343
+ function walker(b, fs, nodeOf, own) {
344
+ const p = b.p, insts = [], uses = [], seen = new Set();
345
+ const bridgeOf = new Map(b.bridges.map(x => [x.fn.name, x])), copyOf = new Map(b.equivs.map(x => [x.fn.name, x]));
346
+ const id = (t) => JSON.stringify(t);
347
+ const inst = (fact, at) => { const i = fs.at.get(fact); if (i === undefined)
348
+ return false; const key = id([i, at]); if (!seen.has(key)) {
349
+ seen.add(key);
350
+ insts.push({ fact: i, at });
351
+ } return true; };
352
+ const use = (law, subst) => { const node = nodeOf.get(law); if (node === undefined)
353
+ return false; const key = id([node, subst]); if (!seen.has(key)) {
354
+ seen.add(key);
355
+ uses.push({ node, subst, guard: yes });
356
+ } return true; };
357
+ const factBody = (f, as) => {
358
+ const holds = fs.facts[fs.at.get(`fn ${f.name}`)].holds, eq = (holds.op === 'and' ? holds.xs[0] : holds);
359
+ return substE(eq.b, { vars: Object.fromEntries(f.params.map((q, i) => [`${f.name}.${q.name}`, as[i]])), maps: {}, flags: {} });
360
+ };
361
+ // A read of the law's side one step closer to the other side (the reason recorded), or undefined.
362
+ const step = (a) => {
363
+ const f = fnNamed(a.map), n = fs.arity.get(a.map) ?? 1, as = argsOf(a.key, n);
364
+ if (!f || !as)
365
+ return undefined;
366
+ const br = bridgeOf.get(f.name);
367
+ if (br) {
368
+ if (!use(br.law.name, Object.fromEntries(f.params.map((q, i) => [q.name, as[i]]))))
369
+ return undefined;
370
+ return substE(encX(p, br.op.x({ op: 'var', name: 'a$' }, { op: 'var', name: 'b$' }), new Map()), { vars: { 'a$': as[0], 'b$': as[1] ?? k(0) }, maps: {}, flags: {} });
371
+ }
372
+ if (!recursive(f) && b.unfolded)
373
+ return inst(`fn ${f.name}`, as) ? factBody(f, as) : undefined;
374
+ const copy = b.copies.get(f.name);
375
+ if (!copy)
376
+ return undefined;
377
+ if (f.name === own)
378
+ return { op: 'get', map: copy, key: a.key };
379
+ const cp = copyOf.get(f.name);
380
+ return cp && use(cp.law.name, Object.fromEntries(f.params.map((q, i) => [q.name, as[i]]))) ? { op: 'get', map: copy, key: a.key } : undefined;
381
+ };
382
+ const walkE = (a, c) => {
383
+ if (id(a) === id(c))
384
+ return true;
385
+ if (a.op === 'get') {
386
+ if (c.op === 'get' && c.map === a.map) {
387
+ const n = fs.arity.get(a.map) ?? 1, as = argsOf(a.key, n), cs = argsOf(c.key, n);
388
+ if (!as || !cs || !as.every((x, i) => walkE(x, cs[i])))
389
+ return false;
390
+ return inst(`cong ${a.map}`, [...as, ...cs]);
391
+ }
392
+ const next = step(a);
393
+ return !!next && walkE(next, c);
394
+ }
395
+ if (a.op !== c.op)
396
+ return false;
397
+ switch (a.op) {
398
+ case 'add':
399
+ case 'sub':
400
+ case 'min':
401
+ case 'max':
402
+ case 'prod': {
403
+ const o = c;
404
+ return walkE(a.a, o.a) && walkE(a.b, o.b);
405
+ }
406
+ case 'mul': {
407
+ const o = c;
408
+ return a.k === o.k && walkE(a.a, o.a);
409
+ }
410
+ case 'if': {
411
+ const o = c;
412
+ return walkC(a.c, o.c) && walkE(a.then, o.then) && walkE(a.else, o.else);
413
+ }
414
+ case 'var':
415
+ case 'const': return false;
416
+ }
417
+ };
418
+ const walkC = (a, c) => {
419
+ if (id(a) === id(c))
420
+ return true;
421
+ // A condition made a value, read as the condition (`holds`): f(..) = 1 where f's read becomes if (cond, 1, 0).
422
+ if (a.op === '=' && a.b.op === 'const' && a.b.value === 1 && (a.a.op === 'get' || a.a.op === 'if') && !(c.op === '=' && c.a.op === a.a.op && (c.a.op !== 'get' || a.a.op !== 'get' || c.a.map === a.a.map))) {
423
+ let x = a.a;
424
+ while (x && x.op === 'get' && !(c.op === '=' && c.a.op === 'get' && c.a.map === x.map))
425
+ x = step(x);
426
+ if (x && x.op === 'if' && x.then.op === 'const' && x.then.value === 1 && x.else.op === 'const' && x.else.value === 0 && walkC(x.c, c))
427
+ return true;
428
+ }
429
+ if (a.op !== c.op)
430
+ return false;
431
+ switch (a.op) {
432
+ case '<':
433
+ case '<=':
434
+ case '=': {
435
+ const o = c;
436
+ return walkE(a.a, o.a) && walkE(a.b, o.b);
437
+ }
438
+ case 'and':
439
+ case 'or': {
440
+ const o = c;
441
+ return a.xs.length === o.xs.length && a.xs.every((x, i) => walkC(x, o.xs[i]));
442
+ }
443
+ case 'not': return walkC(a.x, c.x);
444
+ case 'all':
445
+ case 'flag': return false;
446
+ }
447
+ };
448
+ return { walkC, walkE, insts, uses, inst };
449
+ }
450
+ // The law's node: its conclusion, using the law said through the bridges (at its own variables) and the walk's reasons.
451
+ function lawNode(l, b, fs, nodeOf, lnode, level) {
452
+ const w = walker(b, fs, nodeOf), concl = encY(b.p, l.holds, new Map());
453
+ if (!w.walkC(concl, encY(b.p, b.lstar.holds, new Map())))
454
+ return undefined;
455
+ return { name: `${l.name} (through ${b.lstar.name})`, hyps: [], concl, rank: [k(level), k(0), k(0)], insts: w.insts, uses: [{ node: lnode, subst: {}, guard: yes }, ...w.uses] };
456
+ }
457
+ // A copy's law, f(xs) = f'(xs), as one node at index `self`: both definitions' facts at xs, their bodies walked together
458
+ // (f's own recursive calls its copy's by the node itself, at the uses of f's recursion scheme), the shape of the argument
459
+ // the recursion is on (its rank, its size).
460
+ function copyNode(x, b, fs, nodeOf, self, level) {
461
+ const f = x.fn, copy = b.copies.get(f.name), vs = f.params.map(q => ({ op: 'var', name: q.name }));
462
+ const w = walker(b, fs, nodeOf, f.name);
463
+ if (!w.inst(`fn ${f.name}`, vs) || !w.inst(`fn ${copy}`, vs))
464
+ return undefined;
465
+ const body = (g) => { const h = fs.facts[fs.at.get(`fn ${g}`)].holds, eq = (h.op === 'and' ? h.xs[0] : h); return substE(eq.b, { vars: Object.fromEntries(f.params.map((q, i) => [`${g}.${q.name}`, vs[i]])), maps: {}, flags: {} }); };
466
+ if (!w.walkE(body(f.name), body(copy)))
467
+ return undefined;
468
+ const scheme = recursive(f) ? schemesOf(b.p, x.law).find(sc => sc.name.startsWith(`recursion of ${f.name} `)) : undefined;
469
+ if (recursive(f) && !scheme)
470
+ return undefined;
471
+ const on = scheme?.on, size = !on ? k(0) : on.d === 'nat' ? { op: 'var', name: on.v } : { op: 'get', map: `${on.d.name}.size`, key: { op: 'var', name: on.v } };
472
+ if (on && on.d !== 'nat')
473
+ w.inst(`shape ${on.d.name}`, [{ op: 'var', name: on.v }]);
474
+ return { name: `${x.law.name} (its copy, made)`, hyps: [], concl: encY(b.p, x.law.holds, new Map()), rank: [k(level), size, k(0)], insts: w.insts,
475
+ uses: [...(scheme?.uses ?? []).map(u => ({ node: self, subst: u.subst, guard: u.guard })), ...w.uses] };
476
+ }
@@ -8,6 +8,7 @@
8
8
  // and flags; `then` with the state before the first step (plain names), the first request and its flags, the j-th
9
9
  // request as input@j, and the state and maps after the last step (primed names).
10
10
  import { carriedView, evalC, numbersOf } from "./machine.js";
11
+ import { someHolds } from "./exists.js";
11
12
  export const isStepLaw = (w) => 'then' in w;
12
13
  // A request's environment: the params, its inputs and queries, and the step's flags decided (as ?name).
13
14
  export function requestEnv(m, run, params, st, input) {
@@ -43,7 +44,10 @@ export function watch(m, run, w, params, bound) {
43
44
  return go(0, {});
44
45
  };
45
46
  if (!isStepLaw(w)) {
46
- const holds = (st) => atKeys(w.forall, keysOf(bound, st), extra => evalC(w.holds, { ...params, ...extra }, st, m), w.keys);
47
+ // A law with "there exists" (core/exists.ts): broken only where no value can be a witness, as far as that is decided
48
+ // (one natural or integer read linearly); undecided, it is kept.
49
+ const at = (env, st) => (w.some?.length ? someHolds(w.holds, w.some, env, st, m)?.holds ?? true : evalC(w.holds, env, st, m));
50
+ const holds = (st) => atKeys(w.forall, keysOf(bound, st), extra => at({ ...params, ...extra }, st), w.keys);
47
51
  return { start: holds, step: (_before, _input, after) => holds(after) };
48
52
  }
49
53
  const k = w.steps ?? 1, whens = w.when === undefined ? [] : Array.isArray(w.when) ? w.when : [w.when];
@@ -0,0 +1,40 @@
1
+ import { type Goal, type Path } from './kernel.js';
2
+ import { type Outcome } from './prove.js';
3
+ export declare const cdclStats: {
4
+ on: boolean;
5
+ runs: number;
6
+ proven: number;
7
+ conflicts: number;
8
+ decisions: number;
9
+ solveMs: number;
10
+ rowsMs: number;
11
+ coreMs: number;
12
+ unfoldMs: number;
13
+ leaves: number;
14
+ resolved: number;
15
+ coreSize: number;
16
+ pathSize: number;
17
+ lpMisses: number;
18
+ resolved2: number;
19
+ unfoldWhy: string;
20
+ orderMs: number;
21
+ boundMs: number;
22
+ openMisses: number;
23
+ lpMs: number;
24
+ lpUnknown: number;
25
+ fmCalls: number;
26
+ pivots: number;
27
+ lpRebuilds: number;
28
+ lpRows: number;
29
+ lpNnz: number;
30
+ lpVars: number;
31
+ lpLoad: number;
32
+ nodes: number;
33
+ boundRounds: number;
34
+ };
35
+ export declare function growCdcl(goal: Goal, root: Path, budget: {
36
+ nodes: number;
37
+ until?: number;
38
+ }, opts?: {
39
+ maxLeaves?: number;
40
+ }): Outcome;