gdp-wired 0.28.0 → 0.29.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/cycles.js +30 -3
- package/dist/core/data.d.ts +4 -0
- package/dist/core/data.js +188 -24
- package/dist/core/dsl.d.ts +11 -1
- package/dist/core/dsl.js +106 -11
- package/dist/core/extract-read.d.ts +1 -1
- package/dist/core/extract-read.js +4 -3
- package/dist/core/extract-shapes.js +9 -4
- package/dist/core/extract-xstate.js +89 -10
- package/dist/core/fresh.js +16 -1
- package/dist/core/infer.js +819 -188
- package/dist/core/machine.d.ts +5 -0
- package/dist/core/machine.js +3 -3
- package/dist/kernel/cdcl.d.ts +18 -1
- package/dist/kernel/cdcl.js +13 -8
- package/dist/kernel/kernel.d.ts +17 -1
- package/dist/kernel/kernel.js +187 -11
- package/dist/kernel/prove.d.ts +5 -1
- package/dist/kernel/prove.js +200 -63
- package/dist/kernel/reader.d.ts +2 -0
- package/dist/kernel/reader.js +7 -4
- package/dist/lean-kernel/emit.d.ts +12 -0
- package/dist/lean-kernel/emit.js +108 -14
- package/dist/lean-kernel/library.js +2 -1
- package/package.json +3 -2
package/dist/core/infer.js
CHANGED
|
@@ -10,30 +10,40 @@
|
|
|
10
10
|
// or …), and where a cell holds one value
|
|
11
11
|
// - Houdini on the runs' neighbors: a reached state moved a little that every candidate alive and every law allows,
|
|
12
12
|
// stepped; a candidate its step breaks is in no inductive set of them, so it is dropped
|
|
13
|
-
// - the join
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
13
|
+
// - the join, over the rule's own vocabulary: per control state the samples' affine hull (its equalities, exact) and
|
|
14
|
+
// each direction's largest value. Two spaces: the states (a row each), and for a rule with maps the cells at a key
|
|
15
|
+
// (a row per key a state holds and a fresh one, its forms laws at every key). The control state: the choice (loc)
|
|
16
|
+
// and a few yes/nos, then, refined on demand (as CEGAR refines its predicates), the levels the rule's comparisons
|
|
17
|
+
// with a constant cut a value or a cell into (Ts[k] ≤ 1 or past it, inflight 0 or more, a yes/no param). The values:
|
|
18
|
+
// the state, the params, the cells at the key, and the terms the laws read that aren't linear (max(attempts, 1)).
|
|
19
|
+
// The directions: each value up and down, pairs where there are few, the rule's own comparisons (its flags', a clock
|
|
20
|
+
// moved by a request read as the clock after), and the laws' preimages: a law's comparison read after the step
|
|
21
|
+
// through each branch of its terms, the request's values eliminated against the step's own comparisons, and a form's
|
|
22
|
+
// own when its goal has a counterexample. Houdini on the cone of the caller's laws and step laws: each goal proven
|
|
23
|
+
// with as little of that set assumed as will do (none, then the forms a counterexample breaks, as IC3's relative
|
|
24
|
+
// induction, then all), each asked first of the CDCL search for a model alone (a refutation's core: the forms it
|
|
25
|
+
// read), a counterexample the whole set allows joined in (the hull grows to hold it, a bound rises to the next of
|
|
26
|
+
// the rule's constants, then goes), one to a caller's law ruled out by a level of the control that leaves it out, a
|
|
27
|
+
// candidate, or a cube blocked as IC3 blocks one (its control state, the rule's own comparisons true there and the
|
|
28
|
+
// bounds that keep the samples out, the literals its refutation's core read, its predecessors blocked first), the
|
|
29
|
+
// cube first where no sample is at its control state; every goal of the cone proven, the cone is the answer
|
|
23
30
|
// - the kernel (where the join proves nothing, as it was): the laws with the candidates chosen so far, proven one law
|
|
24
31
|
// at a time; when a goal is stuck at a step, its witness is a counterexample to induction, so the candidate that
|
|
25
32
|
// rules it out (and the most of those seen) is added; a chosen candidate that nothing supports, or that makes a proof slow, is dropped; the set proven as a whole
|
|
26
33
|
// is the answer, after each chosen candidate the proof doesn't need is taken out again
|
|
27
34
|
import { quietly } from "./cyclic.js";
|
|
28
|
-
import { all, any, atMost, divisorsIn, evalC, get, interpret, machineTerms, modName, n, not, plus, same, seeded, times, withArithmetic, x } from "./machine.js";
|
|
35
|
+
import { all, any, atMost, divisorsIn, evalC, evalE, get, interpret, machineTerms, modName, n, not, plus, same, seeded, times, withArithmetic, x } from "./machine.js";
|
|
29
36
|
import { proveRule, proveSteps, verdictOf } from "./dsl.js";
|
|
30
37
|
import { allowed, watch } from "./watch.js";
|
|
31
|
-
import { clock, counted, grow, proveLaw, proveLaws, proveStepLaws, usedHyps, withDeadline, withTrees } from "../kernel/prove.js";
|
|
32
|
-
import { obligations, substC } from "../kernel/kernel.js";
|
|
38
|
+
import { clock, counted, grow, lawInstances, proveLaw, proveLaws, proveStepLaws, stepLawInstances, usedHyps, withDeadline, withTrees } from "../kernel/prove.js";
|
|
39
|
+
import { assumed, obligations, plainOf, stepLawObligations, substC } from "../kernel/kernel.js";
|
|
33
40
|
import { env, gcd, work } from "./solver.js";
|
|
34
41
|
import { bgcd } from "./q.js";
|
|
42
|
+
import { showC, showE } from "./exists.js";
|
|
35
43
|
import { REFUTED, growCdcl } from "../kernel/cdcl.js";
|
|
36
|
-
|
|
44
|
+
// a value outside a guard's (or a control value's) values
|
|
45
|
+
const off = (g, v) => v < g.value || v > (g.hi ?? g.value);
|
|
46
|
+
const KEY = 'key$found', KEY2 = 'key2$found', AT = '@', K = '#', K2 = '##', SOME = 'k$found';
|
|
37
47
|
// The counted clock's rates, units a millisecond: about the slowest tenth of what Modal's 1-vCPU containers do in each
|
|
38
48
|
// phase (`runs/modal/infer/after2`, GDP_INFER_TRACE=1: requests tried 85 a ms, rows 13,093, forms evaluated 11,240, the
|
|
39
49
|
// kernel's work 37; laws watched 198 by a fit), so a counted budget runs out no later than a timed one would there.
|
|
@@ -75,6 +85,8 @@ const joinPrime = env.GDP_JOIN_PRIME !== '0';
|
|
|
75
85
|
// queries a cube's generalization may ask.
|
|
76
86
|
const joinDown = env.GDP_JOIN_DOWN !== '0', joinDownQueries = 24;
|
|
77
87
|
// GDP_INFER_HALVES=0: a cell form chosen without its equality's other half (below).
|
|
88
|
+
// GDP_JOIN_LEVELS=0: the join's control never refined by the levels of the rule's comparisons (the join, `refine`);
|
|
89
|
+
// GDP_JOIN_CLOCKS=0: a request's value a step adds to a state variable kept apart from it in the rule's comparisons.
|
|
78
90
|
const inferHalves = env.GDP_INFER_HALVES !== '0';
|
|
79
91
|
const isRule = (t) => typeof t.kindsOfState === 'function';
|
|
80
92
|
// The constants a machine's expressions hold, and the factors it multiplies by.
|
|
@@ -145,6 +157,7 @@ function constantsOf(m, laws) {
|
|
|
145
157
|
return [...out].filter(k => Number.isSafeInteger(k) && Math.abs(k) <= 1e6);
|
|
146
158
|
}
|
|
147
159
|
// A cell's key as the kernel names it (kernel.ts keyOf): `name:coef` parts joined by ',', '1' the constant.
|
|
160
|
+
// (a name the model leaves out is 0, as the state's and the request's are read: a law's key it left free, say)
|
|
148
161
|
const keyValue = (cell, w) => {
|
|
149
162
|
const inner = cell.slice(cell.indexOf('[') + 1, -1);
|
|
150
163
|
if (inner.includes('['))
|
|
@@ -156,13 +169,253 @@ const keyValue = (cell, w) => {
|
|
|
156
169
|
value += coef;
|
|
157
170
|
else if (name in w)
|
|
158
171
|
value += coef * w[name];
|
|
159
|
-
else
|
|
172
|
+
else if (name.includes('['))
|
|
160
173
|
return undefined;
|
|
161
174
|
}
|
|
162
175
|
return value;
|
|
163
176
|
};
|
|
164
|
-
function
|
|
177
|
+
function pairingOf(m) {
|
|
178
|
+
const inputs = new Set(m.inputs);
|
|
179
|
+
const lin = (e, k, out) => (e.op === 'const' ? (out.set('1', (out.get('1') ?? 0) + k * e.value), true) : e.op === 'var' ? inputs.has(e.name) && (out.set(e.name, (out.get(e.name) ?? 0) + k), true) : e.op === 'add' ? lin(e.a, k, out) && lin(e.b, k, out) : e.op === 'mul' ? lin(e.a, k * e.k, out) : false);
|
|
180
|
+
let found;
|
|
181
|
+
const each = new Set(Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [w.each] : [])));
|
|
182
|
+
const consider = (key) => {
|
|
183
|
+
if (found)
|
|
184
|
+
return;
|
|
185
|
+
const l = new Map();
|
|
186
|
+
if (!lin(key, 1, l))
|
|
187
|
+
return;
|
|
188
|
+
const vs = [...l].filter(([v, c]) => v !== '1' && c);
|
|
189
|
+
if (vs.length !== 2)
|
|
190
|
+
return;
|
|
191
|
+
const [[a, ca], [b, cb]] = vs[0][1] >= vs[1][1] ? [vs[0], vs[1]] : [vs[1], vs[0]];
|
|
192
|
+
if (cb !== 1 || ca < 2)
|
|
193
|
+
return;
|
|
194
|
+
const conj = (c) => (c.op === 'and' ? c.xs.flatMap(conj) : [c]), names = (c) => [...JSON.stringify(c).matchAll(/"name":"([^"]+)"/g)].map(q => q[1]);
|
|
195
|
+
const own = m.assume ? conj(m.assume).filter(c => names(c).length && names(c).every(v => v === a || v === b)) : [];
|
|
196
|
+
found = { n: ca, c: l.get('1') ?? 0, frame: substC({ op: 'and', xs: own }, { vars: { [a]: x(KEY), [b]: x(KEY2) }, maps: {}, flags: {} }) };
|
|
197
|
+
};
|
|
198
|
+
const visit = (t) => {
|
|
199
|
+
if (!t || typeof t !== 'object')
|
|
200
|
+
return;
|
|
201
|
+
if (Array.isArray(t)) {
|
|
202
|
+
t.forEach(visit);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const o = t;
|
|
206
|
+
if (o.op === 'get' && o.key && m.maps && o.map in m.maps)
|
|
207
|
+
consider(o.key);
|
|
208
|
+
if (o.op === '=' && o.a?.op === 'var' && each.has(o.a.name) && o.b)
|
|
209
|
+
consider(o.b);
|
|
210
|
+
for (const v of Object.values(o))
|
|
211
|
+
if (typeof v === 'object')
|
|
212
|
+
visit(v);
|
|
213
|
+
};
|
|
214
|
+
visit([m.step, m.assume]);
|
|
215
|
+
return found;
|
|
216
|
+
}
|
|
217
|
+
// The products of two of `names` a machine's terms (its step, flags, assumption) and these conditions multiply, a
|
|
218
|
+
// product of sums read as its monomials ((top + 2)·window: top·window), each pair of factors once, in order.
|
|
219
|
+
function monomialsOf(m, cs, names) {
|
|
220
|
+
const out = new Map();
|
|
221
|
+
const vars = (e, acc) => {
|
|
222
|
+
if (e.op === 'var')
|
|
223
|
+
acc.add(e.name);
|
|
224
|
+
else if (e.op === 'add' || e.op === 'sub' || e.op === 'min' || e.op === 'max') {
|
|
225
|
+
vars(e.a, acc);
|
|
226
|
+
vars(e.b, acc);
|
|
227
|
+
}
|
|
228
|
+
else if (e.op === 'mul')
|
|
229
|
+
vars(e.a, acc);
|
|
230
|
+
return acc;
|
|
231
|
+
};
|
|
232
|
+
const visit = (t) => {
|
|
233
|
+
if (!t || typeof t !== 'object')
|
|
234
|
+
return;
|
|
235
|
+
if (Array.isArray(t)) {
|
|
236
|
+
t.forEach(visit);
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
const o = t;
|
|
240
|
+
if (o.op === 'prod' && o.a && o.b)
|
|
241
|
+
for (const u of vars(o.a, new Set()))
|
|
242
|
+
for (const w of vars(o.b, new Set()))
|
|
243
|
+
if (names.has(u) && names.has(w)) {
|
|
244
|
+
const p = [u, w].sort();
|
|
245
|
+
out.set(p.join('*'), p);
|
|
246
|
+
}
|
|
247
|
+
for (const val of Object.values(o))
|
|
248
|
+
if (typeof val === 'object')
|
|
249
|
+
visit(val);
|
|
250
|
+
};
|
|
251
|
+
visit([m.state, m.step, m.assume, cs]);
|
|
252
|
+
return [...out.values()].slice(0, 8);
|
|
253
|
+
}
|
|
254
|
+
// The directions of the states a step breaks a law from (its preimage, made linear): each comparison a law makes, read
|
|
255
|
+
// after the step through each branch of the step's terms (an if's two sides, max's and min's each, a ∸ b as a − b, a
|
|
256
|
+
// map's written value or its old one), and a step law's as it reads; the request's values in it eliminated against the
|
|
257
|
+
// step's own comparisons (its flags, its assumption, its terms' conditions, the step laws' `when`), Fourier–Motzkin, one
|
|
258
|
+
// value at a time, twice at most; what reads the state and params alone (a cell at any key as the cell) is a direction.
|
|
259
|
+
// So "executes at t0 + now ≥ ReadyAt[id]" with "executes needs Ts[id] ≤ t0 + now" gives ReadyAt[k] − Ts[k], and "the
|
|
260
|
+
// timer drops a client with Reset ≤ now" with "a tick comes at now ≥ lastTick + windowMs" gives Reset[k] − lastTick −
|
|
261
|
+
// windowMs: what a bound must hold of for the step to keep the law, beside the rule's own comparisons.
|
|
262
|
+
function preimages(m, laws, stepLaws, atoms, coords) {
|
|
263
|
+
const cap = 256, inputs = new Set(m.inputs), maps = new Set(Object.keys(m.maps ?? {}));
|
|
264
|
+
const termOf = new Map(atoms.flatMap(a => (a.term ? [[JSON.stringify(a.term), a.parts[0][0]]] : [])));
|
|
265
|
+
const plus = (a, b, k = 1) => { const o = new Map(a); for (const [v, c] of b)
|
|
266
|
+
o.set(v, (o.get(v) ?? 0) + k * c); return o; };
|
|
267
|
+
// (branches deduplicated, at most `cap` a term)
|
|
268
|
+
const uniq = (ls) => [...new Map(ls.map(l => [JSON.stringify([...l].filter(([, c]) => c).sort((p, q) => (p[0] < q[0] ? -1 : 1))), l])).values()].slice(0, cap);
|
|
269
|
+
const cross = (xs, ys, k) => uniq(xs.flatMap(a => ys.map(b => plus(a, b, k))));
|
|
270
|
+
// (`post`: names read after the step, through its terms; a step law's primed names are so too)
|
|
271
|
+
const linE = (e, post) => {
|
|
272
|
+
const t = termOf.size && e.op !== 'var' && e.op !== 'const' ? termOf.get(JSON.stringify(e)) : undefined;
|
|
273
|
+
if (t && !post)
|
|
274
|
+
return [new Map([[t, 1]])];
|
|
275
|
+
switch (e.op) {
|
|
276
|
+
case 'const': return [new Map([['1', e.value]])];
|
|
277
|
+
case 'var': {
|
|
278
|
+
const primed = e.name.endsWith("'") ? e.name.slice(0, -1) : undefined;
|
|
279
|
+
if (primed !== undefined && primed in m.state)
|
|
280
|
+
return linE(m.step.state?.[primed] ?? x(primed), false);
|
|
281
|
+
if (post && e.name in m.state)
|
|
282
|
+
return linE(m.step.state?.[e.name] ?? e, false);
|
|
283
|
+
return [new Map([[e.name, 1]])];
|
|
284
|
+
}
|
|
285
|
+
case 'add': return cross(linE(e.a, post), linE(e.b, post), 1);
|
|
286
|
+
case 'sub': return uniq([...cross(linE(e.a, post), linE(e.b, post), -1), new Map()]);
|
|
287
|
+
case 'mul': return linE(e.a, post).map(l => new Map([...l].map(([v, c]) => [v, c * e.k])));
|
|
288
|
+
case 'min':
|
|
289
|
+
case 'max': return uniq([...linE(e.a, post), ...linE(e.b, post)]);
|
|
290
|
+
case 'if': return uniq([...linE(e.then, post), ...linE(e.else, post)]);
|
|
291
|
+
case 'prod': return [];
|
|
292
|
+
case 'get': {
|
|
293
|
+
const name = e.map.endsWith("'") && maps.has(e.map.slice(0, -1)) ? e.map.slice(0, -1) : e.map;
|
|
294
|
+
if (!maps.has(name))
|
|
295
|
+
return [];
|
|
296
|
+
const w = (post || name !== e.map) ? m.step.maps?.[name] : undefined;
|
|
297
|
+
// (the cell as it was first: a step writes few)
|
|
298
|
+
if (w)
|
|
299
|
+
return uniq([new Map([[name, 1]]), ...linE(w.value, false)]);
|
|
300
|
+
return [new Map([[name, 1]])];
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
const flags = {};
|
|
305
|
+
for (const [f, c] of Object.entries(m.step.flags ?? {}))
|
|
306
|
+
if (c.op !== 'all')
|
|
307
|
+
flags[f] = substC(c, { vars: {}, maps: {}, flags });
|
|
308
|
+
const inline = (c) => substC(c, { vars: {}, maps: {}, flags });
|
|
309
|
+
const atomsOfC = (c, post, out) => {
|
|
310
|
+
if (c.op === 'and' || c.op === 'or') {
|
|
311
|
+
c.xs.forEach(y => atomsOfC(y, post, out));
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
if (c.op === 'not') {
|
|
315
|
+
atomsOfC(c.x, post, out);
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (c.op !== '<' && c.op !== '<=' && c.op !== '=')
|
|
319
|
+
return;
|
|
320
|
+
for (const a of linE(c.a, post))
|
|
321
|
+
for (const b of linE(c.b, post))
|
|
322
|
+
if (out.length < 1000)
|
|
323
|
+
out.push(plus(a, b, -1));
|
|
324
|
+
};
|
|
325
|
+
const condsOfE = (e, out) => {
|
|
326
|
+
if (e.op === 'if') {
|
|
327
|
+
atomsOfC(inline(e.c), false, out);
|
|
328
|
+
condsOfE(e.then, out);
|
|
329
|
+
condsOfE(e.else, out);
|
|
330
|
+
}
|
|
331
|
+
else if (e.op === 'add' || e.op === 'sub' || e.op === 'min' || e.op === 'max' || e.op === 'prod') {
|
|
332
|
+
condsOfE(e.a, out);
|
|
333
|
+
condsOfE(e.b, out);
|
|
334
|
+
}
|
|
335
|
+
else if (e.op === 'mul')
|
|
336
|
+
condsOfE(e.a, out);
|
|
337
|
+
};
|
|
338
|
+
// (each law its own: its comparisons, their eliminations and its share of the directions, taken in turn)
|
|
339
|
+
const sources = [], guards = [];
|
|
340
|
+
for (const l of laws) {
|
|
341
|
+
const b = [];
|
|
342
|
+
atomsOfC(inline(l.holds), true, b);
|
|
343
|
+
sources.push(b);
|
|
344
|
+
}
|
|
345
|
+
for (const sl of stepLaws) {
|
|
346
|
+
const b = [];
|
|
347
|
+
atomsOfC(inline(sl.then), false, b);
|
|
348
|
+
sources.push(b);
|
|
349
|
+
for (const w of sl.when === undefined ? [] : Array.isArray(sl.when) ? sl.when : [sl.when])
|
|
350
|
+
atomsOfC(inline(w), false, guards);
|
|
351
|
+
}
|
|
352
|
+
Object.values(flags).forEach(c => atomsOfC(c, false, guards));
|
|
353
|
+
if (m.assume)
|
|
354
|
+
atomsOfC(inline(m.assume), false, guards);
|
|
355
|
+
Object.values(m.step.state ?? {}).forEach(e => condsOfE(e, guards));
|
|
356
|
+
const reads = (l) => [...l].filter(([v, c]) => c && inputs.has(v)).map(([v]) => v);
|
|
357
|
+
const dir = (l) => {
|
|
358
|
+
const coef = [];
|
|
359
|
+
for (const i of coords) {
|
|
360
|
+
const a = atoms[i], [pos, neg] = a.parts, cp = l.get(pos[0]) ?? 0;
|
|
361
|
+
if (neg && (l.get(neg[0]) ?? 0) !== -cp)
|
|
362
|
+
return undefined;
|
|
363
|
+
if (cp)
|
|
364
|
+
coef.push([i, cp]);
|
|
365
|
+
}
|
|
366
|
+
const rest = [...l].filter(([v, c]) => c && v !== '1' && !coef.some(([i]) => atoms[i].parts.some(([q]) => q === v)));
|
|
367
|
+
if (rest.length || coef.length < 2)
|
|
368
|
+
return undefined;
|
|
369
|
+
const g = coef.reduce((acc, [, cc]) => gcd(acc, cc), 0), t = coef.map(([i, cc]) => [i, cc / g]);
|
|
370
|
+
return { coef: t[0][1] > 0 ? t : t.map(([i, cc]) => [i, -cc]), d: 0 };
|
|
371
|
+
};
|
|
372
|
+
const per = sources.map(bad => {
|
|
373
|
+
const found = new Map();
|
|
374
|
+
let front = bad;
|
|
375
|
+
for (let round = 0; round < 3 && front.length; round++) {
|
|
376
|
+
const next = [];
|
|
377
|
+
for (const f of front) {
|
|
378
|
+
const vs = reads(f);
|
|
379
|
+
if (!vs.length) {
|
|
380
|
+
const r = dir(f);
|
|
381
|
+
if (r)
|
|
382
|
+
found.set(JSON.stringify(r.coef), r);
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
if (round === 2)
|
|
386
|
+
continue;
|
|
387
|
+
const v = vs[0];
|
|
388
|
+
for (const g of guards) {
|
|
389
|
+
const gv = g.get(v) ?? 0, fv = f.get(v);
|
|
390
|
+
if (!gv || next.length > 2000)
|
|
391
|
+
continue;
|
|
392
|
+
next.push(plus(new Map([...f].map(([k2, c]) => [k2, c * gv])), g, -fv));
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
front = next;
|
|
396
|
+
}
|
|
397
|
+
return [...found.values()];
|
|
398
|
+
});
|
|
399
|
+
const out = new Map();
|
|
400
|
+
for (let i = 0; per.some(l => i < l.length); i++)
|
|
401
|
+
for (const l of per)
|
|
402
|
+
if (i < l.length)
|
|
403
|
+
out.set(JSON.stringify(l[i].coef), l[i]);
|
|
404
|
+
return [...out.values()];
|
|
405
|
+
}
|
|
406
|
+
function comparisons(m, laws, atoms, coords, more = []) {
|
|
407
|
+
const termOf = new Map(atoms.flatMap(a => (a.term ? [[JSON.stringify(a.term), a.parts[0][0]]] : []))), cellParts = new Set(atoms.flatMap(a => (a.cell ? a.parts.map(([q]) => q) : [])));
|
|
165
408
|
const lin = (e, k, out) => {
|
|
409
|
+
const t = termOf.size && e.op !== 'var' && e.op !== 'const' ? termOf.get(JSON.stringify(e)) : undefined;
|
|
410
|
+
if (t) {
|
|
411
|
+
out.set(t, (out.get(t) ?? 0) + k);
|
|
412
|
+
return true;
|
|
413
|
+
}
|
|
414
|
+
// (a map's cell at any key as the cell: a comparison over cells is one at a key)
|
|
415
|
+
if (e.op === 'get' && cellParts.has(e.map)) {
|
|
416
|
+
out.set(e.map, (out.get(e.map) ?? 0) + k);
|
|
417
|
+
return true;
|
|
418
|
+
}
|
|
166
419
|
if (e.op === 'const') {
|
|
167
420
|
out.set('1', (out.get('1') ?? 0) + k * e.value);
|
|
168
421
|
return true;
|
|
@@ -188,6 +441,27 @@ function comparisons(m, laws, atoms, coords) {
|
|
|
188
441
|
} };
|
|
189
442
|
for (const [v, e] of Object.entries(m.step.state ?? {}))
|
|
190
443
|
leaves(e.op === 'sub' ? e.a : e, v);
|
|
444
|
+
// A request's value a step adds to a state variable (bn + db, the clock moved): beside that variable, with its
|
|
445
|
+
// coefficient, the two read as the variable after the step, a value of the state.
|
|
446
|
+
const incr = new Map();
|
|
447
|
+
const adds = (e, v) => {
|
|
448
|
+
if (e.op === 'if') {
|
|
449
|
+
adds(e.then, v);
|
|
450
|
+
adds(e.else, v);
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
if (e.op !== 'add')
|
|
454
|
+
return;
|
|
455
|
+
for (const [p, q] of [[e.a, e.b], [e.b, e.a]])
|
|
456
|
+
if (p.op === 'var' && p.name === v && q.op === 'var' && m.inputs.includes(q.name)) {
|
|
457
|
+
if (!incr.has(q.name))
|
|
458
|
+
incr.set(q.name, new Set());
|
|
459
|
+
incr.get(q.name).add(v);
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
if (env.GDP_JOIN_CLOCKS !== '0')
|
|
463
|
+
for (const [v, e] of Object.entries(m.step.state ?? {}))
|
|
464
|
+
adds(e, v);
|
|
191
465
|
const found = new Map();
|
|
192
466
|
const visitE = (e) => {
|
|
193
467
|
if (e.op === 'if') {
|
|
@@ -218,6 +492,11 @@ function comparisons(m, laws, atoms, coords) {
|
|
|
218
492
|
const l0 = new Map();
|
|
219
493
|
if (!lin(c.a, 1, l0) || !lin(c.b, -1, l0))
|
|
220
494
|
return;
|
|
495
|
+
for (const [u, vs] of incr) {
|
|
496
|
+
const k = l0.get(u);
|
|
497
|
+
if (k && [...vs].some(v => l0.get(v) === k))
|
|
498
|
+
l0.delete(u);
|
|
499
|
+
}
|
|
221
500
|
const l = new Map();
|
|
222
501
|
for (const [v, k] of l0) {
|
|
223
502
|
const w = inputTo.get(v) ?? v;
|
|
@@ -246,14 +525,19 @@ function comparisons(m, laws, atoms, coords) {
|
|
|
246
525
|
};
|
|
247
526
|
if (m.assume)
|
|
248
527
|
visitC(m.assume);
|
|
528
|
+
Object.values(m.step.flags ?? {}).forEach(visitC);
|
|
249
529
|
Object.values(m.step.state ?? {}).forEach(visitE);
|
|
250
530
|
laws.forEach(l => visitC(l.holds));
|
|
531
|
+
more.forEach(visitC);
|
|
251
532
|
return [...found.values()];
|
|
252
533
|
}
|
|
253
534
|
export function inferLaws(target, laws, stepLaws = [], opts = {}) {
|
|
254
535
|
return quietly(() => withDeadline(clock() + (opts.ms ?? 20000), () => inferLawsSearch(target, laws, stepLaws, opts)));
|
|
255
536
|
}
|
|
256
537
|
function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
538
|
+
// (GDP_INFER_TRACE=2: each phase's progress too, to stderr)
|
|
539
|
+
if (env.GDP_INFER_TRACE === '2' && !opts.progress)
|
|
540
|
+
opts = { ...opts, progress: (phase, info) => globalThis.process.stderr.write(`[infer ${phase}] ${JSON.stringify(info)}\n`) };
|
|
257
541
|
const t0 = performance.now(), ms = opts.ms ?? 20000, wallUntil = t0 + ms, rule = isRule(target) ? target : undefined;
|
|
258
542
|
// The clock the budgets read (counted milliseconds since the start, or wall time where `timed`), and the stop.
|
|
259
543
|
const timed = !!opts.timed, w0 = work.n, used = { tries: 0, rows: 0, evals: 0, watched: 0 };
|
|
@@ -382,9 +666,84 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
382
666
|
add(name, p => m.params.includes(p), true, false);
|
|
383
667
|
for (const name of mapNames)
|
|
384
668
|
add(name, p => mapSet.has(p), false, true);
|
|
669
|
+
// The terms the laws and the step laws read that aren't linear (max(attempts, 1), a ∸ b, a product, a function's
|
|
670
|
+
// value, a choice of two), over the state and params alone: each a value of its own, read at every row, so that a form
|
|
671
|
+
// bounds it as it bounds a variable (the law's own comparison, tightened where the samples say). The largest such
|
|
672
|
+
// terms, not their parts.
|
|
673
|
+
{
|
|
674
|
+
const named = (n) => stateSet.has(n) || m.params.includes(n);
|
|
675
|
+
const okE = (e) => e.op === 'const' || (e.op === 'var' ? named(e.name) : e.op === 'mul' ? okE(e.a) : e.op === 'if' ? okC(e.c) && okE(e.then) && okE(e.else)
|
|
676
|
+
: e.op === 'get' ? !!m.fns?.[e.map] && okE(e.key) : okE(e.a) && okE(e.b));
|
|
677
|
+
const okC = (c) => (c.op === 'and' || c.op === 'or' ? c.xs.every(okC) : c.op === 'not' ? okC(c.x) : c.op === '<' || c.op === '<=' || c.op === '=' ? okE(c.a) && okE(c.b) : false);
|
|
678
|
+
const seenT = new Set();
|
|
679
|
+
const visitE = (e) => {
|
|
680
|
+
if (e.op === 'var' || e.op === 'const')
|
|
681
|
+
return;
|
|
682
|
+
if (e.op !== 'add' && e.op !== 'mul' && okE(e)) {
|
|
683
|
+
const k = JSON.stringify(e);
|
|
684
|
+
if (!seenT.has(k)) {
|
|
685
|
+
seenT.add(k);
|
|
686
|
+
atoms.push({ name: showE(e), parts: [[`$t${seenT.size - 1}`, 1]], param: false, int: false, cell: false, term: e });
|
|
687
|
+
}
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
if (e.op === 'mul')
|
|
691
|
+
visitE(e.a);
|
|
692
|
+
else if (e.op === 'if') {
|
|
693
|
+
visitC(e.c);
|
|
694
|
+
visitE(e.then);
|
|
695
|
+
visitE(e.else);
|
|
696
|
+
}
|
|
697
|
+
else if (e.op === 'get')
|
|
698
|
+
visitE(e.key);
|
|
699
|
+
else {
|
|
700
|
+
visitE(e.a);
|
|
701
|
+
visitE(e.b);
|
|
702
|
+
}
|
|
703
|
+
};
|
|
704
|
+
const visitC = (c) => { if (c.op === 'and' || c.op === 'or')
|
|
705
|
+
c.xs.forEach(visitC);
|
|
706
|
+
else if (c.op === 'not')
|
|
707
|
+
visitC(c.x);
|
|
708
|
+
else if (c.op === '<' || c.op === '<=' || c.op === '=') {
|
|
709
|
+
visitE(c.a);
|
|
710
|
+
visitE(c.b);
|
|
711
|
+
} };
|
|
712
|
+
const lawConds = [...laws.map(l => l.holds), ...stepLaws.flatMap(sl => [sl.then, ...(sl.when === undefined ? [] : Array.isArray(sl.when) ? sl.when : [sl.when])])];
|
|
713
|
+
for (const c of lawConds)
|
|
714
|
+
if (!c.op.startsWith('all'))
|
|
715
|
+
visitC(c);
|
|
716
|
+
// and a product of two naturals the rule, its laws or its step laws multiply (u·w of the state and the params, a
|
|
717
|
+
// monomial as the kernel's arithmetic reads it: (top + 2)·window's top·window), its value its factors' product; a
|
|
718
|
+
// bound over it is linear for the kernel, which multiplies the factors' rows where a goal needs the product's facts
|
|
719
|
+
for (const [u, w] of monomialsOf(m, lawConds, new Set([...scalars, ...m.params].filter(p => !stateSet.has(`${p}$neg`) && !m.params.includes(`${p}$neg`))))) {
|
|
720
|
+
const e = { op: 'prod', a: x(u), b: x(w) }, k = JSON.stringify(e);
|
|
721
|
+
if (!seenT.has(k)) {
|
|
722
|
+
seenT.add(k);
|
|
723
|
+
atoms.push({ name: `${u}·${w}`, parts: [[`$t${seenT.size - 1}`, 1]], param: false, int: false, cell: false, term: e });
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
const termAtoms = atoms.filter(a => a.term);
|
|
728
|
+
// a row's term atoms' values, at its state (a term whose value the interpreter can't take: 0)
|
|
729
|
+
const withTerms = (env, st) => {
|
|
730
|
+
if (!termAtoms.length)
|
|
731
|
+
return env;
|
|
732
|
+
for (const a of termAtoms) {
|
|
733
|
+
try {
|
|
734
|
+
env[a.parts[0][0]] = evalE(a.term, env, st, m);
|
|
735
|
+
}
|
|
736
|
+
catch {
|
|
737
|
+
env[a.parts[0][0]] = 0;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
return env;
|
|
741
|
+
};
|
|
385
742
|
const A = atoms.length, cellAtoms = atoms.flatMap((a, i) => (a.cell ? [i] : []));
|
|
386
743
|
const valueOf = (a, env) => { let s = 0; for (const [p, sign] of a.parts)
|
|
387
744
|
s += sign * (env[a.cell ? AT + p : p] ?? 0); return s; };
|
|
745
|
+
// The pairs' rows (the join's, where the rule composes two keys into one), once the pair atoms are made.
|
|
746
|
+
let pairRowsOf, pairing;
|
|
388
747
|
const cellOf = (st, map, key) => st.maps[map]?.get(key) ?? st.defaults?.[map] ?? m.maps[map];
|
|
389
748
|
// The scalar rows (one per state reached), and the cell rows (one per state and key a map holds, and one fresh key).
|
|
390
749
|
const keysIn = (st) => { const ks = new Set(); for (const c of Object.values(st.maps))
|
|
@@ -394,9 +753,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
394
753
|
if (!mapNames.length)
|
|
395
754
|
return [];
|
|
396
755
|
const ks = keysIn(st), fresh = ks.length ? Math.max(...ks) + 1 : 0;
|
|
397
|
-
return [...ks, fresh].map(k => ({ ...params, ...st.scalars, [K]: k, ...Object.fromEntries(mapNames.map(mp => [AT + mp, cellOf(st, mp, k)])) }));
|
|
756
|
+
return [...ks, fresh].map(k => withTerms({ ...params, ...st.scalars, [K]: k, ...Object.fromEntries(mapNames.map(mp => [AT + mp, cellOf(st, mp, k)])) }, st));
|
|
398
757
|
};
|
|
399
|
-
const rowsS = samples.map(s => ({ ...s.params, ...s.st.scalars }));
|
|
758
|
+
const rowsS = samples.map(s => withTerms({ ...s.params, ...s.st.scalars }, s.st));
|
|
400
759
|
const rowsK = [];
|
|
401
760
|
for (const s of samples) {
|
|
402
761
|
if (rowsK.length > 6000)
|
|
@@ -407,7 +766,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
407
766
|
const kindOf = new Map(kinds.map(([name, k]) => [name, k]));
|
|
408
767
|
const modes = [];
|
|
409
768
|
atoms.forEach((a, i) => {
|
|
410
|
-
if (a.param || a.int)
|
|
769
|
+
if (a.param || a.int || a.term)
|
|
411
770
|
return;
|
|
412
771
|
const k = a.cell ? undefined : kindOf.get(a.name), seenValues = [...new Set(a.cell ? valsK[i] : valsS[i])].sort((p, q) => p - q);
|
|
413
772
|
const decoded = k?.vars(a.name).length === 1 ? k.decode(a.name, { [a.name]: 0 }) : undefined;
|
|
@@ -468,7 +827,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
468
827
|
const NS = rowsS.length, NK = rowsK.length;
|
|
469
828
|
const at = (coef, vals, j) => { let s = 0; for (const [i, c] of coef)
|
|
470
829
|
s += c * vals[i][j]; return s; };
|
|
471
|
-
const keyNots = plain.filter(i => !atoms[i].param && !atoms[i].int);
|
|
830
|
+
const keyNots = plain.filter(i => !atoms[i].param && !atoms[i].int && !atoms[i].term);
|
|
472
831
|
// The guards: the choices first, then yes/nos, then small naturals, at most eight; each shape's largest value per
|
|
473
832
|
// guard in one pass over (at most 1,500 of) the rows. Building candidates takes at most a quarter of the time.
|
|
474
833
|
const guards = [...modes].sort((p, q) => Number(!!q.choice) - Number(!!p.choice) || Number(!!q.bool) - Number(!!p.bool)).slice(0, 8);
|
|
@@ -516,7 +875,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
516
875
|
// by 2, the parity of a sum that two counters keep. No form above states one (no linear bound does).
|
|
517
876
|
// The moduli: the divisors the rule and its laws read, then 2, 3, 4 and the rule's own constants up to 64 (six in all).
|
|
518
877
|
const divisors = [...new Set([...[...divisorsIn([...machineTerms(m), ...laws.map(l => l.holds)])].filter(k => k >= 2 && k <= 1_000_000).sort((p, q) => p - q), 2, 3, 4, ...consts.filter(k => k > 4 && k <= 64)])].slice(0, 6);
|
|
519
|
-
const modAtoms = terms.filter(i => !atoms[i].param && !modeOf(i)?.bool), modShapes = modAtoms.map(i => [[i, 1]]);
|
|
878
|
+
const modAtoms = terms.filter(i => !atoms[i].param && !modeOf(i)?.bool && !atoms[i].term), modShapes = modAtoms.map(i => [[i, 1]]);
|
|
520
879
|
if (modAtoms.length * (modAtoms.length - 1) <= 2000)
|
|
521
880
|
for (const [a, i] of modAtoms.entries())
|
|
522
881
|
for (const j of modAtoms.slice(a + 1))
|
|
@@ -597,8 +956,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
597
956
|
const c = f.coef[0][1];
|
|
598
957
|
return only.values.filter(v => c * v <= f.d);
|
|
599
958
|
};
|
|
600
|
-
|
|
601
|
-
|
|
959
|
+
// (a form about every key says so first)
|
|
960
|
+
const textOf = (f) => (f.cells ? `every k: ${textIn(f)}` : f.pairs ? `every x, y${pairing.frame.op === 'and' && !pairing.frame.xs.length ? '' : ` with ${showC(pairing.frame).replaceAll(KEY2, 'y').replaceAll(KEY, 'x')}`}: ${textIn(f)}` : textIn(f));
|
|
961
|
+
const textIn = (f) => {
|
|
962
|
+
const atText = (g) => (g.hi === undefined ? `${nameOf(g.atom)} is ${shownValue(g.atom, g.value)}` : g.hi === Infinity ? `${g.value} <= ${nameOf(g.atom)}` : `${nameOf(g.atom)} in ${g.value}..${g.hi}`);
|
|
602
963
|
if (f.never)
|
|
603
964
|
return `never ${f.never.map(atText).join(' and ')}`;
|
|
604
965
|
if (f.nevers)
|
|
@@ -606,48 +967,53 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
606
967
|
if (f.cube)
|
|
607
968
|
return `never ${f.cube.map(l => ('at' in l ? atText(l.at) : (({ l: a, r: b }) => `${a} <= ${b}`)(sides({ coef: l.lin.coef, d: l.lin.d, cells: false, size: 0 })))).join(' and ')}`;
|
|
608
969
|
if (f.also)
|
|
609
|
-
return `${f.also.map(atText).join(' and ')} → ${
|
|
970
|
+
return `${f.also.map(atText).join(' and ')} → ${textIn({ ...f, also: undefined })}`;
|
|
610
971
|
if (f.unreachable)
|
|
611
|
-
return `${nameOf(f.unreachable.atom)} is never ${shownValue(f.unreachable.atom, f.unreachable.value)}`;
|
|
972
|
+
return f.unreachable.hi === undefined ? `${nameOf(f.unreachable.atom)} is never ${shownValue(f.unreachable.atom, f.unreachable.value)}` : `never ${atText(f.unreachable)}`;
|
|
612
973
|
if (f.cong)
|
|
613
974
|
return `∃k. ${f.coef.map(([i, c], j) => `${j ? (c > 0 ? ' + ' : ' − ') : c < 0 ? '−' : ''}${nameOf(i)}`).join('')} = ${f.cong.mod}·k${f.cong.rest ? ` + ${f.cong.rest}` : ''}`;
|
|
614
975
|
const { l, r } = sides(f), within = allowedValues(f);
|
|
615
976
|
const body = f.mod ? `${f.coef.map(([i, c], j) => `${c < 0 ? (j ? ' − ' : '−') : j ? ' + ' : ''}${nameOf(i)}`).join('')} mod ${f.mod.k} = ${f.mod.r}` : within ? `${nameOf(f.coef[0][0])} is ${within.map(v => shownValue(f.coef[0][0], v)).join(' or ')}` : `${l} <= ${r}`;
|
|
616
977
|
const under = f.when ? (({ l: wl, r: wr }) => `${wl} <= ${wr} → `)(sides({ coef: f.when.coef, d: f.when.d, cells: false, size: 0 })) : '';
|
|
617
|
-
const guarded = !f.guard ? under + body : 'keyNot' in f.guard ? `k = ${nameOf(f.guard.keyNot)} or ${body}` : `${
|
|
618
|
-
return
|
|
978
|
+
const guarded = !f.guard ? under + body : 'keyNot' in f.guard ? `k = ${nameOf(f.guard.keyNot)} or ${body}` : `${atText(f.guard)} → ${under}${body}`;
|
|
979
|
+
return guarded;
|
|
619
980
|
};
|
|
620
981
|
const sum = (es) => es.reduce((p, q) => plus(p, q), n(0));
|
|
621
982
|
// Each congruence its own witness's name (each may be a ghost of the machine).
|
|
622
983
|
const someNames = new Map(), someName = (f) => { let k = someNames.get(f); if (!k)
|
|
623
984
|
someNames.set(f, (k = `${SOME}${someNames.size}`)); return k; };
|
|
624
|
-
const
|
|
985
|
+
const placeKey = (place) => { if (place < 2)
|
|
986
|
+
return x(place === 0 ? KEY : KEY2); const k = plus(times(pairing.n, x(KEY)), x(KEY2)); return pairing.c ? plus(k, n(pairing.c)) : k; };
|
|
987
|
+
const part = (a, p) => (a.term ?? (a.place !== undefined ? get(p.slice(2, p.lastIndexOf(AT)), placeKey(a.place)) : a.cell ? get(p, x(KEY)) : x(p)));
|
|
625
988
|
const partsOf = (f, sign) => f.coef.flatMap(([i, c]) => atoms[i].parts.filter(([, s]) => s * c * sign > 0).map(([p]) => { const e = part(atoms[i], p); return Math.abs(c) === 1 ? e : times(Math.abs(c), e); }));
|
|
626
989
|
// Σ c·v ≤ d over naturals: the positive parts on the left, the negative ones and d on the right (an integer's
|
|
627
990
|
// negative part goes to the other side of its sign).
|
|
628
991
|
const condOf = (f) => {
|
|
629
992
|
// Not at a value, one-sided where it can be (less splitting for the kernel): a natural not 0 is at least 1, and a
|
|
630
993
|
// yes/no or a choice not at its last value is below it (its kind's law bounds it).
|
|
631
|
-
const notAt = (i, value) => {
|
|
994
|
+
const notAt = (i, value, hi) => {
|
|
632
995
|
const e = part(atoms[i], atoms[i].parts[0][0]), mo = modeOf(i), lastValue = mo?.bool ? 1 : mo?.choice ? mo.choice.length - 1 : undefined;
|
|
996
|
+
// (a level: below its first value, or past its last)
|
|
997
|
+
if (hi !== undefined)
|
|
998
|
+
return any(...(value > 0 ? [atMost(e, n(value - 1))] : []), ...(hi < Infinity ? [atMost(n(hi + 1), e)] : []));
|
|
633
999
|
return value === 0 ? atMost(n(1), e) : value === lastValue ? atMost(e, n(value - 1)) : not(same(e, n(value)));
|
|
634
1000
|
};
|
|
635
1001
|
if (f.never)
|
|
636
|
-
return any(...f.never.map(g => notAt(g.atom, g.value)));
|
|
1002
|
+
return any(...f.never.map(g => notAt(g.atom, g.value, g.hi)));
|
|
637
1003
|
if (f.nevers)
|
|
638
|
-
return all(...f.nevers.map(c => any(...c.map(g => notAt(g.atom, g.value)))));
|
|
1004
|
+
return all(...f.nevers.map(c => any(...c.map(g => notAt(g.atom, g.value, g.hi)))));
|
|
639
1005
|
if (f.cube)
|
|
640
1006
|
return not(all(...f.cube.map(l => ('at' in l ? same(part(atoms[l.at.atom], atoms[l.at.atom].parts[0][0]), n(l.at.value)) : condOf({ coef: l.lin.coef, d: l.lin.d, cells: false, size: 0 })))));
|
|
641
1007
|
if (f.also)
|
|
642
|
-
return any(...f.also.map(g => notAt(g.atom, g.value)), condOf({ ...f, also: undefined }));
|
|
1008
|
+
return any(...f.also.map(g => notAt(g.atom, g.value, g.hi)), condOf({ ...f, also: undefined }));
|
|
643
1009
|
if (f.unreachable)
|
|
644
|
-
return notAt(f.unreachable.atom, f.unreachable.value);
|
|
1010
|
+
return notAt(f.unreachable.atom, f.unreachable.value, f.unreachable.hi);
|
|
645
1011
|
if (f.mod) {
|
|
646
1012
|
// Σ c·v = P − N over naturals (P the positive parts, N the negative ones), whose remainder by k is that of the
|
|
647
1013
|
// natural P + (k − 1)·N.
|
|
648
1014
|
const { k: dk, r } = f.mod, neg = partsOf(f, -1), e = get(modName(dk), sum([...partsOf(f, 1), ...neg.map(t => times(dk - 1, t))]));
|
|
649
1015
|
const body = same(e, n(r));
|
|
650
|
-
return !f.guard ? body : 'keyNot' in f.guard ? any(same(x(KEY), x(atoms[f.guard.keyNot].parts[0][0])), body) : any(notAt(f.guard.atom, f.guard.value), body);
|
|
1016
|
+
return !f.guard ? body : 'keyNot' in f.guard ? any(same(x(KEY), x(atoms[f.guard.keyNot].parts[0][0])), body) : any(notAt(f.guard.atom, f.guard.value, f.guard.hi), body);
|
|
651
1017
|
}
|
|
652
1018
|
// Σ = c·k + r, k = SOME (an integer's two parts where Σ reads an integer or a difference): the negative parts and
|
|
653
1019
|
// c·k's negative part on the other side.
|
|
@@ -658,11 +1024,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
658
1024
|
const lhs = sum([...partsOf(f, 1), ...(f.d < 0 ? [n(-f.d)] : [])]), rhs = sum([...partsOf(f, -1), ...(f.d > 0 ? [n(f.d)] : [])]);
|
|
659
1025
|
// Under a condition Σ ≤ d: its negation, −Σ ≤ −d − 1, or the body.
|
|
660
1026
|
const body = f.when ? any(condOf({ coef: f.when.coef.map(([i, c]) => [i, -c]), d: -f.when.d - 1, cells: false, size: 0 }), atMost(lhs, rhs)) : atMost(lhs, rhs);
|
|
661
|
-
return !f.guard ? body : 'keyNot' in f.guard ? any(same(x(KEY), x(atoms[f.guard.keyNot].parts[0][0])), body) : any(notAt(f.guard.atom, f.guard.value), body);
|
|
1027
|
+
return !f.guard ? body : 'keyNot' in f.guard ? any(same(x(KEY), x(atoms[f.guard.keyNot].parts[0][0])), body) : any(notAt(f.guard.atom, f.guard.value, f.guard.hi), body);
|
|
662
1028
|
};
|
|
663
1029
|
// The builder call, for a rule whose atoms are its own variables (naturals, or integers alone).
|
|
664
1030
|
const sourceOf = (f, text) => {
|
|
665
|
-
if (!rule || f.when || f.mod || f.also || f.never || f.nevers || f.cube)
|
|
1031
|
+
if (!rule || f.when || f.mod || f.also || f.never || f.nevers || f.cube || [...f.coef.map(([i]) => i), ...(f.guard && 'atom' in f.guard ? [f.guard.atom] : [])].some(i => atoms[i].term))
|
|
666
1032
|
return undefined;
|
|
667
1033
|
const used = [...new Set([...f.coef.map(([i]) => i), ...(f.guard ? ['keyNot' in f.guard ? f.guard.keyNot : f.guard.atom] : []), ...(f.unreachable ? [f.unreachable.atom] : [])])];
|
|
668
1034
|
const ints = f.coef.filter(([i]) => atoms[i].int).length;
|
|
@@ -670,11 +1036,12 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
670
1036
|
return undefined;
|
|
671
1037
|
const ref = (i) => (atoms[i].cell ? `${atoms[i].parts[0][0]}.at(k)` : nameOf(i));
|
|
672
1038
|
const val = (i) => { const mo = modeOf(i); return mo?.choice && !atoms[i].cell ? `${ref(i)}.index` : mo?.bool && !atoms[i].cell ? `${ref(i)}.n` : ref(i); };
|
|
673
|
-
const cond = (i, value) => { const mo = modeOf(i);
|
|
1039
|
+
const cond = (i, value, hi) => { const mo = modeOf(i); if (hi !== undefined)
|
|
1040
|
+
return hi === Infinity ? `${ref(i)}.atLeast(${value})` : `${ref(i)}.atLeast(${value}).and(${ref(i)}.atMost(${hi}))`; return mo?.choice && !atoms[i].cell ? `${ref(i)}.is('${mo.choice[value]}')` : mo?.bool && !atoms[i].cell ? (value === 1 ? ref(i) : `${ref(i)}.not()`) : `${ref(i)}.eq(${value})`; };
|
|
674
1041
|
const args = `({${[...new Set(used.map(i => (atoms[i].cell ? atoms[i].parts[0][0] : nameOf(i))))].join(', ')}})`;
|
|
675
1042
|
const wrap = (body) => (f.cells ? `forall(k => ${body})` : body);
|
|
676
1043
|
if (f.unreachable)
|
|
677
|
-
return `r.law('${text}', ${args} => ${cond(f.unreachable.atom, f.unreachable.value)}.not())`;
|
|
1044
|
+
return `r.law('${text}', ${args} => ${cond(f.unreachable.atom, f.unreachable.value, f.unreachable.hi)}.not())`;
|
|
678
1045
|
if (f.cong) {
|
|
679
1046
|
if (f.coef.length !== 1 || f.coef[0][1] !== 1)
|
|
680
1047
|
return undefined;
|
|
@@ -689,7 +1056,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
689
1056
|
};
|
|
690
1057
|
const { left, right } = sides(f);
|
|
691
1058
|
const body = left.length ? `${term(left, Math.max(0, -f.d))}.atMost(${term(right, Math.max(0, f.d))})` : `${term(right, Math.max(0, f.d))}.atLeast(${Math.max(0, -f.d)})`;
|
|
692
|
-
const guarded = !f.guard ? body : 'keyNot' in f.guard ? `k.eq(${nameOf(f.guard.keyNot)}).or(${body})` : `${cond(f.guard.atom, f.guard.value)}.implies(${body})`;
|
|
1059
|
+
const guarded = !f.guard ? body : 'keyNot' in f.guard ? `k.eq(${nameOf(f.guard.keyNot)}).or(${body})` : `${cond(f.guard.atom, f.guard.value, f.guard.hi)}.implies(${body})`;
|
|
693
1060
|
return `r.law('${text}', ${args} => ${wrap(guarded)})`;
|
|
694
1061
|
};
|
|
695
1062
|
// --- evaluating a form ---------------------------------------------------------------------------------------------
|
|
@@ -698,8 +1065,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
698
1065
|
const valuesOf = (env) => {
|
|
699
1066
|
let vs = valuesAt.get(env);
|
|
700
1067
|
if (!vs) {
|
|
701
|
-
|
|
702
|
-
|
|
1068
|
+
const n2 = atoms.length;
|
|
1069
|
+
vs = new Float64Array(n2);
|
|
1070
|
+
for (let i = 0; i < n2; i++)
|
|
703
1071
|
vs[i] = valueOf(atoms[i], env);
|
|
704
1072
|
valuesAt.set(env, vs);
|
|
705
1073
|
}
|
|
@@ -709,15 +1077,15 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
709
1077
|
used.evals++;
|
|
710
1078
|
const vs = valuesOf(env);
|
|
711
1079
|
if (f.never)
|
|
712
|
-
return f.never.some(g => vs[g.atom]
|
|
1080
|
+
return f.never.some(g => off(g, vs[g.atom]));
|
|
713
1081
|
if (f.nevers)
|
|
714
|
-
return f.nevers.every(c => c.some(g => vs[g.atom]
|
|
1082
|
+
return f.nevers.every(c => c.some(g => off(g, vs[g.atom])));
|
|
715
1083
|
if (f.cube)
|
|
716
1084
|
return !f.cube.every(l => ('at' in l ? vs[l.at.atom] === l.at.value : l.lin.coef.reduce((acc, [i, c]) => acc + c * vs[i], 0) <= l.lin.d));
|
|
717
|
-
if (f.also?.some(g => vs[g.atom]
|
|
1085
|
+
if (f.also?.some(g => off(g, vs[g.atom])))
|
|
718
1086
|
return true;
|
|
719
1087
|
if (f.unreachable)
|
|
720
|
-
return vs[f.unreachable.atom]
|
|
1088
|
+
return off(f.unreachable, vs[f.unreachable.atom]);
|
|
721
1089
|
if (f.cong) {
|
|
722
1090
|
let v = 0;
|
|
723
1091
|
for (const [i, c] of f.coef)
|
|
@@ -730,7 +1098,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
730
1098
|
if (env[K] === vs[f.guard.keyNot])
|
|
731
1099
|
return true;
|
|
732
1100
|
}
|
|
733
|
-
else if (vs[f.guard.atom]
|
|
1101
|
+
else if (off(f.guard, vs[f.guard.atom]))
|
|
734
1102
|
return true;
|
|
735
1103
|
}
|
|
736
1104
|
if (f.when) {
|
|
@@ -745,17 +1113,18 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
745
1113
|
s += c * vs[i];
|
|
746
1114
|
return f.mod ? residue(s, f.mod.k) === f.mod.r : s <= f.d;
|
|
747
1115
|
};
|
|
748
|
-
const pointOf = (params, st) => ({ scalar: { ...params, ...st.scalars }, cells: cellRows(params, st) });
|
|
749
|
-
const holdsAt = (f, p) => (f.cells ? p.cells.every(r => holdsRow(f, r)) : holdsRow(f, p.scalar));
|
|
1116
|
+
const pointOf = (params, st) => ({ scalar: withTerms({ ...params, ...st.scalars }, st), cells: cellRows(params, st), ...(pairRowsOf ? { pairs: pairRowsOf(params, st) } : {}) });
|
|
1117
|
+
const holdsAt = (f, p) => (f.pairs ? (p.pairs ?? []).every(r => holdsRow(f, r)) : f.cells ? p.cells.every(r => holdsRow(f, r)) : holdsRow(f, p.scalar));
|
|
750
1118
|
// A kernel witness as a point: its scalars, and a cell row per key it reads a map at.
|
|
751
1119
|
const witnessPoint = (w) => {
|
|
752
1120
|
const scalar = Object.fromEntries([...scalars, ...m.params].map(v => [v, w[v] ?? 0]));
|
|
753
|
-
|
|
1121
|
+
withTerms(scalar, { scalars: scalar, maps: {} });
|
|
1122
|
+
const byKey = new Map(), named = { ...Object.fromEntries([...scalars, ...m.params, ...m.inputs].map(v => [v, 0])), ...w };
|
|
754
1123
|
for (const [name, value] of Object.entries(w)) {
|
|
755
1124
|
const br = name.indexOf('[');
|
|
756
1125
|
if (br < 0 || !name.endsWith(']') || !mapSet.has(name.slice(0, br)))
|
|
757
1126
|
continue;
|
|
758
|
-
const key = keyValue(name,
|
|
1127
|
+
const key = keyValue(name, named);
|
|
759
1128
|
if (key === undefined)
|
|
760
1129
|
continue;
|
|
761
1130
|
const row = byKey.get(key) ?? { ...scalar, [K]: key };
|
|
@@ -764,6 +1133,21 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
764
1133
|
}
|
|
765
1134
|
return { scalar, cells: [...byKey.values()] };
|
|
766
1135
|
};
|
|
1136
|
+
// A kernel witness's map cells, each at the key it names (the others at the map's constant).
|
|
1137
|
+
const mapsOf = (w) => {
|
|
1138
|
+
const out = Object.fromEntries(mapNames.map(mp => [mp, new Map()]));
|
|
1139
|
+
// (a name the model leaves out is 0, as the state's and the request's are read)
|
|
1140
|
+
const named = { ...Object.fromEntries([...scalars, ...m.params, ...m.inputs].map(v => [v, 0])), ...w };
|
|
1141
|
+
for (const [name, value] of Object.entries(w)) {
|
|
1142
|
+
const br = name.indexOf('[');
|
|
1143
|
+
if (br < 0 || !name.endsWith(']') || !mapSet.has(name.slice(0, br)))
|
|
1144
|
+
continue;
|
|
1145
|
+
const key = keyValue(name, named);
|
|
1146
|
+
if (key !== undefined)
|
|
1147
|
+
out[name.slice(0, br)].set(key, value);
|
|
1148
|
+
}
|
|
1149
|
+
return out;
|
|
1150
|
+
};
|
|
767
1151
|
// --- Houdini on the runs' neighbors ----------------------------------------------------------------------------------
|
|
768
1152
|
let alive = forms.slice().sort((p, q) => p.size - q.size).slice(0, maxCandidates);
|
|
769
1153
|
const ctis = [];
|
|
@@ -821,8 +1205,13 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
821
1205
|
// --- the kernel ----------------------------------------------------------------------------------------------------
|
|
822
1206
|
const lawOf = new Map();
|
|
823
1207
|
const someOf = (f) => (!f.cong ? [] : f.coef.some(([i, c]) => atoms[i].int || c < 0) ? [someName(f), `${someName(f)}$neg`] : [someName(f)]);
|
|
824
|
-
const lawFor = (f) => {
|
|
825
|
-
|
|
1208
|
+
const lawFor = (f) => {
|
|
1209
|
+
let l = lawOf.get(f);
|
|
1210
|
+
// (about two keys: where the frame holds of them)
|
|
1211
|
+
if (!l)
|
|
1212
|
+
lawOf.set(f, (l = { name: textOf(f), holds: f.pairs ? any(not(pairing.frame), condOf(f)) : condOf(f), ...(f.cells ? { forall: KEY } : f.pairs ? { forall: KEY, keys: [KEY2] } : {}), ...(f.cong ? { some: someOf(f) } : {}) }));
|
|
1213
|
+
return l;
|
|
1214
|
+
};
|
|
826
1215
|
const names = new Set(given.map(l => l.name));
|
|
827
1216
|
alive = alive.filter(f => !names.has(textOf(f)));
|
|
828
1217
|
let pool = alive.slice(), chosen = [];
|
|
@@ -946,7 +1335,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
946
1335
|
// states short walks from it reach, until the kernel proves them inductive. The caller's laws are then proven with
|
|
947
1336
|
// them assumed, and what their proofs read (and what those read, in turn) is the answer.
|
|
948
1337
|
const pool0 = pool.slice(), ctis0 = ctis.length;
|
|
949
|
-
if (joinOn &&
|
|
1338
|
+
if (joinOn && NS)
|
|
950
1339
|
try {
|
|
951
1340
|
const jT0 = performance.now(), jUntil = Math.min(until, now() + (until - now()) * (opts.join ?? joinShare));
|
|
952
1341
|
// The control state: the choice (loc) and, where they are few, the yes/nos (a program counter in bits), each of its
|
|
@@ -954,9 +1343,83 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
954
1343
|
const jChoice = modes.find(mo => mo.choice && !atoms[mo.atom].cell), bits = modes.filter(mo => mo.bool && !atoms[mo.atom].cell && !atoms[mo.atom].param);
|
|
955
1344
|
const locsReached = jChoice ? new Set(valsS[jChoice.atom]).size : 1;
|
|
956
1345
|
const keyModes = [...(jChoice ? [jChoice] : []), ...(bits.length && bits.length <= joinBits && locsReached * 2 ** bits.length <= joinKeys ? bits : [])];
|
|
957
|
-
const
|
|
958
|
-
|
|
959
|
-
|
|
1346
|
+
const stepConds = stepLaws.flatMap(sl => [sl.then, ...(sl.when === undefined ? [] : Array.isArray(sl.when) ? sl.when : [sl.when])]);
|
|
1347
|
+
const read = new Set([...laws.map(l => l.holds), ...stepConds].flatMap(c => [...JSON.stringify(c).matchAll(/"name":"([^"]+)"/g)].map(q => q[1])));
|
|
1348
|
+
const levelsOf = (cand, vals) => {
|
|
1349
|
+
const cutsOf = new Map();
|
|
1350
|
+
for (const { coef, d } of comparisons(m, laws, atoms, cand, stepConds)) {
|
|
1351
|
+
if (coef.length !== 1)
|
|
1352
|
+
continue;
|
|
1353
|
+
const [i, c] = coef[0], t = c > 0 ? Math.floor(d / c) : Math.ceil(-d / -c) - 1;
|
|
1354
|
+
if (t >= 0 && Number.isSafeInteger(t)) {
|
|
1355
|
+
if (!cutsOf.has(i))
|
|
1356
|
+
cutsOf.set(i, new Set());
|
|
1357
|
+
cutsOf.get(i).add(t);
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
const name = (i) => (atoms[i].cell ? atoms[i].parts[0][0] : atoms[i].name);
|
|
1361
|
+
const order = [...cutsOf.keys()].sort((a, b) => Number(read.has(name(b))) - Number(read.has(name(a))) || cutsOf.get(a).size - cutsOf.get(b).size);
|
|
1362
|
+
return (env.GDP_JOIN_LEVELS === '0' ? [] : order).flatMap(i => {
|
|
1363
|
+
const vs = vals[i], cuts = [...cutsOf.get(i)].filter(t => vs.some(v => v <= t) && vs.some(v => v > t)).sort((a, b) => a - b);
|
|
1364
|
+
return cuts.length ? [{ atom: i, cuts, top: Infinity }] : [];
|
|
1365
|
+
});
|
|
1366
|
+
};
|
|
1367
|
+
const levelOf = (c, v) => { let k = 0; while (k < c.cuts.length && c.cuts[k] < v)
|
|
1368
|
+
k++; return k; };
|
|
1369
|
+
const atOf = (c, level) => {
|
|
1370
|
+
const lo = level === 0 ? 0 : c.cuts[level - 1] + 1, hi = level === c.cuts.length ? c.top : c.cuts[level];
|
|
1371
|
+
return lo === hi ? { atom: c.atom, value: lo } : { atom: c.atom, value: lo, hi };
|
|
1372
|
+
};
|
|
1373
|
+
// The pairs: where the rule composes two keys into one (Link[N·a + b] beside Known[a], Known[b]), the cells at two
|
|
1374
|
+
// keys x and y and at N·x + y, a row per two keys a state holds (or the parts of a composed key it holds, or a fresh
|
|
1375
|
+
// one) that the frame (the assumption's of a and b) allows: their forms laws at every two keys.
|
|
1376
|
+
pairing = mapNames.length ? pairingOf(m) : undefined;
|
|
1377
|
+
const pairAtoms = [], rowsP = [];
|
|
1378
|
+
const cellLevels = pairing ? levelsOf(cellAtoms.filter(i => !atoms[i].int), valsK) : [];
|
|
1379
|
+
if (pairing) {
|
|
1380
|
+
const P = pairing;
|
|
1381
|
+
for (const i of cellAtoms)
|
|
1382
|
+
for (const place of [0, 1, 2]) {
|
|
1383
|
+
const a = atoms[i], keyText = place === 0 ? 'x' : place === 1 ? 'y' : `${P.n}·x + y${P.c ? ` + ${P.c}` : ''}`;
|
|
1384
|
+
pairAtoms.push(atoms.length);
|
|
1385
|
+
atoms.push({ name: `${a.parts[0][0]}[${keyText}]`, parts: a.parts.map(([q, sg]) => [`${AT}${AT}${q}${AT}${place}`, sg]), param: false, int: a.int, cell: false, place });
|
|
1386
|
+
}
|
|
1387
|
+
pairRowsOf = (params, st) => {
|
|
1388
|
+
const ks = new Set();
|
|
1389
|
+
for (const c of Object.values(st.maps))
|
|
1390
|
+
for (const k of c.keys()) {
|
|
1391
|
+
ks.add(k);
|
|
1392
|
+
if (k >= P.c) {
|
|
1393
|
+
ks.add(Math.floor((k - P.c) / P.n));
|
|
1394
|
+
ks.add((k - P.c) % P.n);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
const held = [...ks], fresh = held.length ? Math.max(...held) + 1 : 0, xs = [...held, fresh].slice(0, 24), out = [];
|
|
1398
|
+
for (const kx of xs)
|
|
1399
|
+
for (const ky of xs) {
|
|
1400
|
+
try {
|
|
1401
|
+
if (!evalC(P.frame, { ...params, ...st.scalars, [KEY]: kx, [KEY2]: ky }, st, m))
|
|
1402
|
+
continue;
|
|
1403
|
+
}
|
|
1404
|
+
catch {
|
|
1405
|
+
continue;
|
|
1406
|
+
}
|
|
1407
|
+
const row = { ...params, ...st.scalars, [K]: kx, [K2]: ky };
|
|
1408
|
+
for (const mp of mapNames)
|
|
1409
|
+
for (const [place, key] of [[0, kx], [1, ky], [2, P.n * kx + ky + P.c]])
|
|
1410
|
+
row[`${AT}${AT}${mp}${AT}${place}`] = cellOf(st, mp, key);
|
|
1411
|
+
out.push(withTerms(row, st));
|
|
1412
|
+
}
|
|
1413
|
+
return out;
|
|
1414
|
+
};
|
|
1415
|
+
for (const s2 of samples) {
|
|
1416
|
+
if (rowsP.length > 6000)
|
|
1417
|
+
break;
|
|
1418
|
+
rowsP.push(...pairRowsOf(s2.params, s2.st));
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
// The directions over some values: each value up and down, pairs of them where there are few, the rule's own
|
|
1422
|
+
// comparisons over the state (a guard, the query's condition) and the laws' preimages, each both ways.
|
|
960
1423
|
const directions = (cs) => {
|
|
961
1424
|
const out = [];
|
|
962
1425
|
for (const i of cs)
|
|
@@ -966,8 +1429,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
966
1429
|
for (const j of cs.slice(a2 + 1))
|
|
967
1430
|
for (const [c1, c2] of [[1, 1], [1, -1], [-1, 1], [-1, -1]])
|
|
968
1431
|
out.push([[i, c1], [j, c2]]);
|
|
969
|
-
const known = new Set(out.map(t => JSON.stringify(t)));
|
|
970
|
-
for (const { coef } of comparisons(m, laws, atoms, cs))
|
|
1432
|
+
const known = new Set(out.map(t => JSON.stringify(t))), pre = preimages(m, laws, stepLaws, atoms, cs);
|
|
1433
|
+
for (const { coef } of [...comparisons(m, laws, atoms, cs), ...pre])
|
|
971
1434
|
if (coef.length > 1)
|
|
972
1435
|
for (const u of coef[0][1] > 0 ? [coef, coef.map(([i, c]) => [i, -c])] : []) {
|
|
973
1436
|
const k2 = JSON.stringify(u);
|
|
@@ -978,11 +1441,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
978
1441
|
}
|
|
979
1442
|
return out;
|
|
980
1443
|
};
|
|
981
|
-
const dirs = directions(coords);
|
|
982
1444
|
// Widening with thresholds: a bound a counterexample breaks rises to the next of the rule's constants (their sums and
|
|
983
1445
|
// products the first time, the constants alone after), and past that it is dropped.
|
|
984
1446
|
const fine = bounds, coarse = [...new Set([0, ...consts.flatMap(k => [k, -k])])].sort((p2, q2) => p2 - q2);
|
|
985
|
-
const groups = new Map();
|
|
986
1447
|
const normal = (e) => { let g2 = 0n; for (const x2 of e)
|
|
987
1448
|
g2 = bgcd(g2, x2); if (g2 > 1n)
|
|
988
1449
|
for (let k = 0; k < e.length; k++)
|
|
@@ -991,133 +1452,259 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
991
1452
|
e[k] = -e[k]; return e; };
|
|
992
1453
|
const dirValue = (t, vs) => { let v = 0; for (const [i, c] of t)
|
|
993
1454
|
v += c * vs[i]; return v; };
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
}
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
if (!widen) {
|
|
1018
|
-
grp.hi[k] = v;
|
|
1455
|
+
let joins = 0, neversBroken = 0;
|
|
1456
|
+
// A space of the join: the states (one row each, the scalars), or, for a rule with maps, the cells at a key (a row per
|
|
1457
|
+
// key a state's maps hold and a fresh one: the scalars and that key's cells), its control state, its coordinates
|
|
1458
|
+
// and directions, and per control state the hull and the bounds. A space's forms are laws of the state, or, of the
|
|
1459
|
+
// cells, laws at every key (those that read a cell; the others are the states' space's).
|
|
1460
|
+
const space = (kind) => {
|
|
1461
|
+
const cells = kind === 'cells', pairs = kind === 'pairs';
|
|
1462
|
+
const ctl = keyModes.map(mo => ({ atom: mo.atom, cuts: mo.values.slice(0, -1), top: mo.values.at(-1) }));
|
|
1463
|
+
const exactAtoms = new Set(keyModes.map(mo => mo.atom)), own = cells ? [...plain, ...cellAtoms] : pairs ? [...plain, ...pairAtoms] : plain;
|
|
1464
|
+
// (a pair's cells take their map's cells' levels)
|
|
1465
|
+
const levelable = pairs ? cellLevels.flatMap(c => pairAtoms.filter(i => atoms[i].parts[0][0].slice(2, atoms[i].parts[0][0].lastIndexOf(AT)) === atoms[c.atom].parts[0][0]).map(i => ({ ...c, atom: i })))
|
|
1466
|
+
: levelsOf(own.filter(i => !exactAtoms.has(i) && !atoms[i].int && (!cells || atoms[i].cell)), cells ? valsK : valsS);
|
|
1467
|
+
const coords = own.filter(i => !exactAtoms.has(i)), CN = coords.length, dirs = directions(coords);
|
|
1468
|
+
const groups = new Map();
|
|
1469
|
+
let keyAtoms = ctl.map(c => c.atom);
|
|
1470
|
+
const residual = (e, vs) => { let r = e[CN]; for (let k = 0; k < CN; k++)
|
|
1471
|
+
if (e[k])
|
|
1472
|
+
r += e[k] * BigInt(vs[coords[k]]); return r; };
|
|
1473
|
+
const join = (g, vs, widen, into = groups) => {
|
|
1474
|
+
let grp = into.get(g);
|
|
1475
|
+
if (!grp) {
|
|
1476
|
+
grp = { eqs: coords.map((i, k) => { const e = Array.from({ length: CN + 1 }, () => 0n); e[k] = 1n; e[CN] = -BigInt(vs[i]); return e; }), hi: dirs.map(t => dirValue(t, vs)), raised: dirs.map(() => 0) };
|
|
1477
|
+
into.set(g, grp);
|
|
1019
1478
|
return;
|
|
1020
1479
|
}
|
|
1021
|
-
const
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1480
|
+
const rs = grp.eqs.map(e => residual(e, vs)), nz = rs.flatMap((r, k) => (r !== 0n ? [k] : []));
|
|
1481
|
+
if (nz.length) {
|
|
1482
|
+
const piv = nz.reduce((p2, k) => (grp.eqs[k].filter(x2 => x2 !== 0n).length < grp.eqs[p2].filter(x2 => x2 !== 0n).length ? k : p2)), pe = grp.eqs[piv], pr = rs[piv];
|
|
1483
|
+
for (const k of nz)
|
|
1484
|
+
if (k !== piv)
|
|
1485
|
+
grp.eqs[k] = normal(grp.eqs[k].map((x2, q2) => pr * x2 - rs[k] * pe[q2]));
|
|
1486
|
+
grp.eqs.splice(piv, 1);
|
|
1487
|
+
}
|
|
1488
|
+
dirs.forEach((t, k) => {
|
|
1489
|
+
const v = dirValue(t, vs);
|
|
1490
|
+
if (v <= grp.hi[k])
|
|
1491
|
+
return;
|
|
1492
|
+
if (!widen) {
|
|
1493
|
+
grp.hi[k] = v;
|
|
1494
|
+
return;
|
|
1495
|
+
}
|
|
1496
|
+
const n2 = ++grp.raised[k], up = (n2 === 1 ? fine : coarse).find(b2 => b2 >= v);
|
|
1497
|
+
grp.hi[k] = n2 > joinRaises || up === undefined ? Infinity : up;
|
|
1498
|
+
});
|
|
1499
|
+
joins++;
|
|
1500
|
+
};
|
|
1501
|
+
// an equality of the hull that is a form: at most joinSparse values, small coefficients
|
|
1502
|
+
const emitted = (e) => { let nz = 0; for (let k = 0; k < CN; k++)
|
|
1503
|
+
if (e[k]) {
|
|
1504
|
+
nz++;
|
|
1505
|
+
if (e[k] > BigInt(joinCoef) || e[k] < -BigInt(joinCoef))
|
|
1506
|
+
return false;
|
|
1507
|
+
} return nz > 0 && nz <= joinSparse && Number.isSafeInteger(Number(e[CN])); };
|
|
1508
|
+
const keyOf = (vs) => ctl.map(c => levelOf(c, vs[c.atom])).join(',');
|
|
1509
|
+
const combosOf = () => ctl.reduce((acc, c) => acc.flatMap(k2 => c.cuts.concat(0).map((_, lv) => [...k2, lv])), [[]]);
|
|
1510
|
+
let combos = combosOf();
|
|
1511
|
+
// a control value by its level (as the keys hold it) as the values it stands for
|
|
1512
|
+
const atLevel = (a) => atOf(ctl[keyAtoms.indexOf(a.atom)], a.value);
|
|
1513
|
+
// a point's rows in this space
|
|
1514
|
+
const vecs = (p) => (cells ? p.cells.map(valuesOf) : pairs ? (p.pairs ?? []).map(valuesOf) : [valuesOf(p.scalar)]);
|
|
1515
|
+
const add = (p, widen) => { for (const v of vecs(p))
|
|
1516
|
+
join(keyOf(v), v, widen); };
|
|
1517
|
+
const rows = (cells ? rowsK : pairs ? rowsP : rowsS).map(valuesOf);
|
|
1518
|
+
for (const v of rows)
|
|
1519
|
+
join(keyOf(v), v, false);
|
|
1520
|
+
opts.progress?.('join start', { space: kind, control: ctl.map(c => `${nameOf(c.atom)}:${c.cuts.join('/')}`).join(' '), groups: groups.size, dirs: dirs.length, coords: CN });
|
|
1521
|
+
// The control states no state reached, as fewer and smaller cubes (a program counter in bits: Spacer's clauses there
|
|
1522
|
+
// read two or three of its bits): each cube's values dropped one at a time, the yes/nos first, while it holds at no
|
|
1523
|
+
// control state reached, then the cubes another cube's values include left out. Together they say what the cubes
|
|
1524
|
+
// of every value say (the control state is one reached), but a goal reads fewer of them, and each of them less.
|
|
1525
|
+
const primes = (nev) => {
|
|
1526
|
+
const reachedKeys = [...groups.keys()].map(k2 => k2.split(',').map(Number));
|
|
1527
|
+
const holdsAtSome = (c) => reachedKeys.some(vs => c.every(a => vs[keyAtoms.indexOf(a.atom)] === a.value));
|
|
1528
|
+
const out = [];
|
|
1529
|
+
for (const ats of nev) {
|
|
1530
|
+
let c = ats;
|
|
1531
|
+
for (const a of [...ats.slice(1), ats[0]]) {
|
|
1532
|
+
if (c.length <= 1)
|
|
1533
|
+
break;
|
|
1534
|
+
const fewer = c.filter(b2 => b2 !== a);
|
|
1535
|
+
if (!holdsAtSome(fewer))
|
|
1536
|
+
c = fewer;
|
|
1537
|
+
}
|
|
1538
|
+
out.push(c);
|
|
1539
|
+
}
|
|
1540
|
+
const key2 = (c) => c.map(a => `${a.atom}=${a.value}`).sort().join('&');
|
|
1541
|
+
const uniq = [...new Map(out.map(c => [key2(c), c])).values()].sort((a, b) => a.length - b.length);
|
|
1542
|
+
return uniq.filter((c, i) => !uniq.slice(0, i).some(d => d.every(a => c.some(b2 => b2.atom === a.atom && b2.value === a.value))));
|
|
1543
|
+
};
|
|
1544
|
+
const forms = (push) => {
|
|
1545
|
+
// (of the cells: only what reads one)
|
|
1546
|
+
const keep = (f) => { if (kind === 'state' || [...f.coef.map(([i]) => i), ...(f.guard && 'atom' in f.guard ? [f.guard.atom] : []), ...(f.also ?? []).map(a => a.atom), ...(f.never ?? []).map(a => a.atom), ...(f.unreachable ? [f.unreachable.atom] : []), ...(f.nevers ?? []).flat().map(a => a.atom)].some(i => (pairs ? atoms[i].place !== undefined : atoms[i].cell)))
|
|
1547
|
+
push(pairs ? { ...f, pairs: true } : f); };
|
|
1548
|
+
// (a choice's value no state reached: one form, whatever the yes/nos; the control states no state reached, one form
|
|
1549
|
+
// for all, where there are several: each alone needs the others to be inductive, a goal each where one does)
|
|
1550
|
+
const reachedFirst = new Set([...groups.keys()].map(k2 => k2.split(',')[0])), nev = [];
|
|
1551
|
+
for (const combo of combos) {
|
|
1552
|
+
if (combo.length > 1 && !reachedFirst.has(String(combo[0]))) {
|
|
1553
|
+
if (combo.slice(1).every(v => v === 0))
|
|
1554
|
+
nev.push([{ atom: keyAtoms[0], value: combo[0] }]);
|
|
1555
|
+
continue;
|
|
1556
|
+
}
|
|
1557
|
+
const lv = combo.map((value, k) => ({ atom: keyAtoms[k], value })), ats = lv.map(atLevel), grp = groups.get(combo.join(','));
|
|
1558
|
+
const guard = ats.length ? { guard: ats[0], ...(ats.length > 1 ? { also: ats.slice(1) } : {}) } : {};
|
|
1559
|
+
if (!grp) {
|
|
1560
|
+
if (lv.length)
|
|
1561
|
+
nev.push(lv);
|
|
1562
|
+
continue;
|
|
1563
|
+
}
|
|
1564
|
+
for (const e of grp.eqs) {
|
|
1565
|
+
if (!emitted(e))
|
|
1566
|
+
continue;
|
|
1567
|
+
const coef = [];
|
|
1568
|
+
for (let k = 0; k < CN; k++)
|
|
1569
|
+
if (e[k])
|
|
1570
|
+
coef.push([coords[k], Number(e[k])]);
|
|
1571
|
+
const d = -Number(e[CN]);
|
|
1572
|
+
keep({ coef, d, cells, ...guard, size: 0 });
|
|
1573
|
+
keep({ coef: coef.map(([i, c]) => [i, -c]), d: -d, cells, ...guard, size: 0 });
|
|
1574
|
+
}
|
|
1575
|
+
dirs.forEach((t, k) => {
|
|
1576
|
+
const hi = grp.hi[k];
|
|
1577
|
+
if (!Number.isFinite(hi))
|
|
1578
|
+
return;
|
|
1579
|
+
// constant on the hull (the equalities say it), or a yes/no's own range
|
|
1580
|
+
const neg = dirs.findIndex(u => u.length === t.length && u.every(([i, c], q2) => i === t[q2][0] && c === -t[q2][1]));
|
|
1581
|
+
if (neg >= 0 && grp.hi[neg] === -hi)
|
|
1582
|
+
return;
|
|
1583
|
+
if (t.length === 1 && modeOf(t[0][0])?.bool && (t[0][1] > 0 ? hi >= 1 : hi >= 0))
|
|
1584
|
+
return;
|
|
1585
|
+
keep({ coef: t, d: hi, cells, ...guard, size: 0 });
|
|
1586
|
+
});
|
|
1587
|
+
}
|
|
1588
|
+
// (once broken, each its own form from then on, so that a state joined in changes only the forms that
|
|
1589
|
+
// read its own control state, not every proof that read them all)
|
|
1590
|
+
if (nev.length > 1 && joinNevers && neversBroken < joinNeversBreaks)
|
|
1591
|
+
keep({ coef: [], d: 0, cells, nevers: nev.map(c => c.map(atLevel)), size: 1 });
|
|
1592
|
+
else
|
|
1593
|
+
for (const lvs of joinPrime ? primes(nev) : nev) {
|
|
1594
|
+
const ats = lvs.map(atLevel);
|
|
1595
|
+
keep({ coef: [], d: 0, cells, ...(ats.length > 1 ? { never: ats } : { unreachable: ats[0] }), size: 1 });
|
|
1596
|
+
}
|
|
1597
|
+
};
|
|
1598
|
+
// The control refined on demand (as CEGAR refines its predicates, here read off the rule): a counterexample to a
|
|
1599
|
+
// caller's law that the set allows and nothing rules out lies among the samples of its control state. A level of a
|
|
1600
|
+
// value the rule compares with a constant whose part of those samples and of the states joined in leaves it out
|
|
1601
|
+
// (past its hull or a bound, or with no state there at all) becomes a control value, and every state is joined
|
|
1602
|
+
// again: of those, the one that leaves out the most of the last counterexamples, then the one of fewest levels;
|
|
1603
|
+
// within joinKeys control states.
|
|
1604
|
+
// (2: left out with no state at its level, or by a form that reads what the laws read; 1: by another form; 0: not)
|
|
1605
|
+
const lawCoord = coords.map(i => read.has(atoms[i].cell ? atoms[i].parts[0][0] : atoms[i].name));
|
|
1606
|
+
const lawDir = dirs.map(t => t.some(([i]) => lawCoord[coords.indexOf(i)]));
|
|
1607
|
+
const outOf = (c, p, all) => Math.max(0, ...vecs(p).map(pv => {
|
|
1608
|
+
const key = keyOf(pv), side = all.filter(v => keyOf(v) === key && levelOf(c, v[c.atom]) === levelOf(c, pv[c.atom]));
|
|
1609
|
+
used.rows += all.length;
|
|
1610
|
+
if (!side.length)
|
|
1611
|
+
return 2;
|
|
1612
|
+
const tmp = new Map();
|
|
1613
|
+
for (const v of side)
|
|
1614
|
+
join('', v, false, tmp);
|
|
1615
|
+
const grp = tmp.get('');
|
|
1616
|
+
let out = 0;
|
|
1617
|
+
for (const e of grp.eqs)
|
|
1618
|
+
if (emitted(e) && residual(e, pv) !== 0n)
|
|
1619
|
+
out = Math.max(out, e.some((x2, k) => k < CN && x2 !== 0n && lawCoord[k]) ? 2 : 1);
|
|
1620
|
+
dirs.forEach((t, k) => { if (dirValue(t, pv) > grp.hi[k])
|
|
1621
|
+
out = Math.max(out, lawDir[k] ? 2 : 1); });
|
|
1622
|
+
return out;
|
|
1623
|
+
}));
|
|
1624
|
+
const scored = [];
|
|
1625
|
+
// (the samples' states alone: the states joined in are successors of states the coarser control allowed, which
|
|
1626
|
+
// the finer may not; the join starts again from the samples)
|
|
1627
|
+
const refine = (recent) => {
|
|
1628
|
+
scored.length = 0;
|
|
1629
|
+
const all = rows;
|
|
1630
|
+
let pick, score = 0;
|
|
1631
|
+
for (const c of levelable) {
|
|
1632
|
+
if (keyAtoms.includes(c.atom) || combos.length * (c.cuts.length + 1) > joinKeys)
|
|
1633
|
+
continue;
|
|
1634
|
+
const first = outOf(c, recent[0], all);
|
|
1635
|
+
if (!first)
|
|
1636
|
+
continue;
|
|
1637
|
+
const sc = recent.slice(1).reduce((k, q) => k + outOf(c, q, all), first) * 100 - c.cuts.length;
|
|
1638
|
+
scored.push(`${nameOf(c.atom)}:${sc}`);
|
|
1639
|
+
if (sc > score)
|
|
1640
|
+
(pick = c, score = sc);
|
|
1641
|
+
}
|
|
1642
|
+
if (!pick)
|
|
1643
|
+
return false;
|
|
1644
|
+
ctl.push(pick);
|
|
1645
|
+
keyAtoms = ctl.map(c2 => c2.atom);
|
|
1646
|
+
combos = combosOf();
|
|
1647
|
+
groups.clear();
|
|
1648
|
+
for (const v of all)
|
|
1649
|
+
join(keyOf(v), v, false);
|
|
1650
|
+
return true;
|
|
1651
|
+
};
|
|
1652
|
+
// More directions (a form's own preimage), each bounded per control state by the states there, kept only where they
|
|
1653
|
+
// leave the point out (the bounds already there, widened or not, as they were).
|
|
1654
|
+
const deepen = (more, reached, p) => {
|
|
1655
|
+
const known = new Set(dirs.map(t => JSON.stringify(t))), fresh = more.flatMap(r => [r.coef, r.coef.map(([i, c]) => [i, -c])]).filter(t => !known.has(JSON.stringify(t)) && t.every(([i]) => coords.includes(i)));
|
|
1656
|
+
if (!fresh.length)
|
|
1657
|
+
return false;
|
|
1658
|
+
const his = new Map();
|
|
1659
|
+
for (const v of [...rows, ...reached.flatMap(vecs)]) {
|
|
1660
|
+
const g = keyOf(v), h = his.get(g) ?? fresh.map(() => -Infinity);
|
|
1661
|
+
fresh.forEach((t, k) => { h[k] = Math.max(h[k], dirValue(t, v)); });
|
|
1662
|
+
his.set(g, h);
|
|
1663
|
+
}
|
|
1664
|
+
used.rows += rows.length;
|
|
1665
|
+
if (!vecs(p).some(v => { const h = his.get(keyOf(v)); return !h || fresh.some((t, k) => dirValue(t, v) > h[k]); }))
|
|
1666
|
+
return false;
|
|
1667
|
+
dirs.push(...fresh);
|
|
1668
|
+
lawDir.push(...fresh.map(t => t.some(([i]) => lawCoord[coords.indexOf(i)])));
|
|
1669
|
+
for (const [g, grp] of groups) {
|
|
1670
|
+
const h = his.get(g) ?? fresh.map(() => -Infinity);
|
|
1671
|
+
grp.hi.push(...h);
|
|
1672
|
+
grp.raised.push(...fresh.map(() => 0));
|
|
1673
|
+
}
|
|
1674
|
+
return true;
|
|
1675
|
+
};
|
|
1676
|
+
return { cells, add, forms, refine, deepen, coords, control: () => `${ctl.map(c => nameOf(c.atom)).join(' ')} (${scored.join(' ')})`, groups };
|
|
1025
1677
|
};
|
|
1026
|
-
const
|
|
1027
|
-
const combos = keyModes.reduce((acc, mo) => acc.flatMap(c => mo.values.map(v => [...c, v])), [[]]);
|
|
1028
|
-
for (let j = 0; j < NS; j++)
|
|
1029
|
-
join(keyOf(valsS.map(col => col[j])), valsS.map(col => col[j]), false);
|
|
1030
|
-
let neversBroken = 0;
|
|
1678
|
+
const spaces = [space('state'), ...(mapNames.length && cellAtoms.length ? [space('cells')] : []), ...(rowsP.length ? [space('pairs')] : [])];
|
|
1031
1679
|
const formsNow = () => {
|
|
1032
1680
|
const out = [], seenT = new Set();
|
|
1033
1681
|
const push = (f) => { const t = textOf(f); if (!seenT.has(t) && !names.has(t)) {
|
|
1034
1682
|
seenT.add(t);
|
|
1035
1683
|
out.push(f);
|
|
1036
1684
|
} };
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
const reachedFirst = new Set([...groups.keys()].map(k2 => k2.split(',')[0])), nev = [];
|
|
1040
|
-
for (const combo of combos) {
|
|
1041
|
-
if (combo.length > 1 && !reachedFirst.has(String(combo[0]))) {
|
|
1042
|
-
if (combo.slice(1).every(v => v === 0))
|
|
1043
|
-
nev.push([{ atom: keyAtoms[0], value: combo[0] }]);
|
|
1044
|
-
continue;
|
|
1045
|
-
}
|
|
1046
|
-
const ats = combo.map((value, k) => ({ atom: keyAtoms[k], value })), grp = groups.get(combo.join(','));
|
|
1047
|
-
const guard = ats.length ? { guard: ats[0], ...(ats.length > 1 ? { also: ats.slice(1) } : {}) } : {};
|
|
1048
|
-
if (!grp) {
|
|
1049
|
-
if (ats.length)
|
|
1050
|
-
nev.push(ats);
|
|
1051
|
-
continue;
|
|
1052
|
-
}
|
|
1053
|
-
for (const e of grp.eqs) {
|
|
1054
|
-
const coef = [];
|
|
1055
|
-
for (let k = 0; k < CN; k++)
|
|
1056
|
-
if (e[k])
|
|
1057
|
-
coef.push([coords[k], Number(e[k])]);
|
|
1058
|
-
const d = -Number(e[CN]);
|
|
1059
|
-
if (!coef.length || coef.length > joinSparse || coef.some(([, c]) => Math.abs(c) > joinCoef) || !Number.isSafeInteger(d))
|
|
1060
|
-
continue;
|
|
1061
|
-
push({ coef, d, cells: false, ...guard, size: 0 });
|
|
1062
|
-
push({ coef: coef.map(([i, c]) => [i, -c]), d: -d, cells: false, ...guard, size: 0 });
|
|
1063
|
-
}
|
|
1064
|
-
dirs.forEach((t, k) => {
|
|
1065
|
-
const hi = grp.hi[k];
|
|
1066
|
-
if (!Number.isFinite(hi))
|
|
1067
|
-
return;
|
|
1068
|
-
// constant on the hull (the equalities say it), or a yes/no's own range
|
|
1069
|
-
const neg = dirs.findIndex(u => u.length === t.length && u.every(([i, c], q2) => i === t[q2][0] && c === -t[q2][1]));
|
|
1070
|
-
if (neg >= 0 && grp.hi[neg] === -hi)
|
|
1071
|
-
return;
|
|
1072
|
-
if (t.length === 1 && modeOf(t[0][0])?.bool && (t[0][1] > 0 ? hi >= 1 : hi >= 0))
|
|
1073
|
-
return;
|
|
1074
|
-
push({ coef: t, d: hi, cells: false, ...guard, size: 0 });
|
|
1075
|
-
});
|
|
1076
|
-
}
|
|
1077
|
-
// (once broken, each its own form from then on, so that a state joined in changes only the forms that
|
|
1078
|
-
// read its own control state, not every proof that read them all)
|
|
1079
|
-
if (nev.length > 1 && joinNevers && neversBroken < joinNeversBreaks)
|
|
1080
|
-
push({ coef: [], d: 0, cells: false, nevers: nev, size: 1 });
|
|
1081
|
-
else
|
|
1082
|
-
for (const ats of joinPrime ? primes(nev) : nev)
|
|
1083
|
-
push({ coef: [], d: 0, cells: false, ...(ats.length > 1 ? { never: ats } : { unreachable: ats[0] }), size: 1 });
|
|
1685
|
+
for (const sp of spaces)
|
|
1686
|
+
sp.forms(push);
|
|
1084
1687
|
return out;
|
|
1085
1688
|
};
|
|
1086
|
-
// The control states no state reached, as fewer and smaller cubes (a program counter in bits: Spacer's clauses there
|
|
1087
|
-
// read two or three of its bits): each cube's values dropped one at a time, the yes/nos first, while it holds at no
|
|
1088
|
-
// control state reached, then the cubes another cube's values include left out. Together they say what the cubes
|
|
1089
|
-
// of every value say (the control state is one reached), but a goal reads fewer of them, and each of them less.
|
|
1090
|
-
const primes = (nev) => {
|
|
1091
|
-
const reachedKeys = [...groups.keys()].map(k2 => k2.split(',').map(Number));
|
|
1092
|
-
const holdsAtSome = (c) => reachedKeys.some(vs => c.every(a => vs[keyAtoms.indexOf(a.atom)] === a.value));
|
|
1093
|
-
const out = [];
|
|
1094
|
-
for (const ats of nev) {
|
|
1095
|
-
let c = ats;
|
|
1096
|
-
for (const a of [...ats.slice(1), ats[0]]) {
|
|
1097
|
-
if (c.length <= 1)
|
|
1098
|
-
break;
|
|
1099
|
-
const fewer = c.filter(b2 => b2 !== a);
|
|
1100
|
-
if (!holdsAtSome(fewer))
|
|
1101
|
-
c = fewer;
|
|
1102
|
-
}
|
|
1103
|
-
out.push(c);
|
|
1104
|
-
}
|
|
1105
|
-
const key2 = (c) => c.map(a => `${a.atom}=${a.value}`).sort().join('&');
|
|
1106
|
-
const uniq = [...new Map(out.map(c => [key2(c), c])).values()].sort((a, b) => a.length - b.length);
|
|
1107
|
-
return uniq.filter((c, i) => !uniq.slice(0, i).some(d => d.every(a => c.some(b2 => b2.atom === a.atom && b2.value === a.value))));
|
|
1108
|
-
};
|
|
1109
1689
|
let rounds = 0, why = '', set = [];
|
|
1110
1690
|
const params0 = {};
|
|
1111
1691
|
// Beside the hull, forms of the candidates' that rule out a counterexample to the caller's laws (a state the set
|
|
1112
1692
|
// allows whose successor breaks one): Houdini's, dropped when a counterexample's successor breaks them.
|
|
1113
1693
|
const extras = [], negs = [], reached = [];
|
|
1114
1694
|
let tried = 0;
|
|
1115
|
-
|
|
1695
|
+
// A caller's law broken after a step, or a step law by the step (`pre` and `input` its own).
|
|
1696
|
+
const breaks = (params, st, pre, input) => laws.some(l => { try {
|
|
1116
1697
|
return !evalC(l.holds, params, st, m);
|
|
1117
1698
|
}
|
|
1118
1699
|
catch {
|
|
1119
1700
|
return true;
|
|
1120
|
-
} })
|
|
1701
|
+
} })
|
|
1702
|
+
|| (!!pre && !!input && stepLaws.some(sl => { try {
|
|
1703
|
+
return !watch(m, run, sl, params, 4).step(pre, input, st);
|
|
1704
|
+
}
|
|
1705
|
+
catch {
|
|
1706
|
+
return true;
|
|
1707
|
+
} }));
|
|
1121
1708
|
// A request the rule allows at a state, found by the kernel (a model of the assumption there), some inputs fixed at
|
|
1122
1709
|
// random first; the walks from a counterexample take these where random requests aren't allowed.
|
|
1123
1710
|
const flagless = !Object.keys(m.step.flags ?? {}).length && !!m.assume;
|
|
@@ -1146,14 +1733,15 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
1146
1733
|
// in the set (the set only weakens). A goal's counterexample is a state the set allows: its successor is joined in
|
|
1147
1734
|
// (or, breaking a caller's law, a candidate that rules the state out is added). Every goal of the cone proven, the
|
|
1148
1735
|
// cone is inductive with the caller's laws, and it is the answer.
|
|
1149
|
-
const stood = new Map(), blocked = new Set(), callers = new Set(laws.map(l => l.name));
|
|
1736
|
+
const stood = new Map(), blocked = new Set(), callers = new Set([...laws, ...stepLaws].map(l => l.name));
|
|
1150
1737
|
let cone = [], dropped = 0;
|
|
1738
|
+
const deepened = new Set(), sameAgain = new Map();
|
|
1151
1739
|
// A state reached from one the set allows: joined in, and every extra false there dropped.
|
|
1152
1740
|
const reach = (p2) => {
|
|
1153
1741
|
if (reached.length < 2000)
|
|
1154
1742
|
reached.push(p2);
|
|
1155
|
-
const
|
|
1156
|
-
|
|
1743
|
+
for (const sp of spaces)
|
|
1744
|
+
sp.add(p2, true);
|
|
1157
1745
|
for (let k = extras.length - 1; k >= 0; k--)
|
|
1158
1746
|
if (!holdsAt(extras[k], p2)) {
|
|
1159
1747
|
const f = extras[k];
|
|
@@ -1164,20 +1752,32 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
1164
1752
|
};
|
|
1165
1753
|
// A goal's step with these forms assumed (beside the caller's laws and the kinds'): its tree and the forms it read, or
|
|
1166
1754
|
// the kernel's model.
|
|
1755
|
+
// A goal's hypotheses that are laws, by the law (the facts, the precondition and, for a law's step, the assumption
|
|
1756
|
+
// before them; a law about every key none, at no instances).
|
|
1757
|
+
const lawsFrom = (m0, ls, stepGoal, inst) => {
|
|
1758
|
+
const at = new Map(), mm = plainOf(m0);
|
|
1759
|
+
let h = assumed(mm.facts ?? [], inst).length + (mm.pre ? 1 : 0) + (!stepGoal && mm.assume ? 1 : 0);
|
|
1760
|
+
ls.forEach((l, k) => { for (let q = assumed([l], inst).length; q > 0; q--)
|
|
1761
|
+
at.set(h++, k); });
|
|
1762
|
+
return at;
|
|
1763
|
+
};
|
|
1764
|
+
// (a step law's goal: its step from a state the set allows)
|
|
1765
|
+
const stepLawOf = new Map(stepLaws.map(sl => [sl.name, sl]));
|
|
1167
1766
|
const stepWith = (name, form, ctx) => {
|
|
1168
|
-
const ctxLaws = [...ctx, ...(form ? [form] : [])].map(lawFor), ls = [...given, ...ctxLaws], mm = forLaws(ctxLaws).m;
|
|
1767
|
+
const ctxLaws = [...ctx, ...(form ? [form] : [])].map(lawFor), ls = [...given, ...ctxLaws], mm = forLaws(ctxLaws).m, sl = form ? undefined : stepLawOf.get(name);
|
|
1169
1768
|
const idx = form ? ls.length - 1 : ls.findIndex(l => l.name === name);
|
|
1170
|
-
|
|
1769
|
+
// (a rule with maps: the laws about every key at the instances the prover would read them at)
|
|
1770
|
+
const inst = !mapNames.length ? {} : sl ? stepLawInstances(mm, ls)(sl) : lawInstances(mm, ls, idx);
|
|
1771
|
+
const g = sl ? stepLawObligations(mm, ls, inst, sl)[0] : obligations(mm, ls, { [ls[idx].name]: inst }, idx)[1], lawAt = lawsFrom(mm, ls, !!sl, inst), used = [];
|
|
1772
|
+
const read = (h) => { const k = lawAt.get(h); if (k !== undefined && k >= given.length && k !== idx && !used.includes(ls[k].name))
|
|
1773
|
+
used.push(ls[k].name); };
|
|
1171
1774
|
// First a model alone of the CDCL search (no tree unfolded): refuted, the hypotheses its leaves read are those
|
|
1172
1775
|
// a tree would (the set's proof is the kernel's below, as before); a model is the counterexample; else the prover.
|
|
1173
1776
|
if (joinCore) {
|
|
1174
1777
|
const quick = budgeted(joinQueryMs / 4, until2 => growCdcl(g, new Map(), { nodes: 0, until: until2 }, { model: true, core: true }));
|
|
1175
1778
|
if (!('tree' in quick) && quick.why === REFUTED && quick.core) {
|
|
1176
|
-
for (const h of quick.core)
|
|
1177
|
-
|
|
1178
|
-
if (k >= given.length && k < ls.length && k !== idx)
|
|
1179
|
-
used.push(ls[k].name);
|
|
1180
|
-
}
|
|
1779
|
+
for (const h of quick.core)
|
|
1780
|
+
read(h);
|
|
1181
1781
|
return { used };
|
|
1182
1782
|
}
|
|
1183
1783
|
if (!('tree' in quick) && quick.stuck === 'sat' && quick.witness)
|
|
@@ -1186,14 +1786,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
1186
1786
|
const out = budgeted(joinQueryMs, until2 => grow(g, new Map(), { nodes: 0, until: until2 }));
|
|
1187
1787
|
if (!('tree' in out))
|
|
1188
1788
|
return { stuck: out.stuck, witness: out.stuck === 'sat' ? out.witness : undefined };
|
|
1189
|
-
for (const h of usedHyps(g, out.tree))
|
|
1190
|
-
|
|
1191
|
-
if (k >= given.length && k < ls.length && k !== idx)
|
|
1192
|
-
used.push(ls[k].name);
|
|
1193
|
-
}
|
|
1789
|
+
for (const h of usedHyps(g, out.tree))
|
|
1790
|
+
read(h);
|
|
1194
1791
|
return { used };
|
|
1195
1792
|
};
|
|
1196
|
-
const stateOf = (w) => ({ params: m.params.length ? Object.fromEntries(m.params.map(p => [p, w[p] ?? 0])) : params0, st: { scalars: Object.fromEntries(scalars.map(v => [v, w[v] ?? 0])), maps:
|
|
1793
|
+
const stateOf = (w) => ({ params: m.params.length ? Object.fromEntries(m.params.map(p => [p, w[p] ?? 0])) : params0, st: { scalars: Object.fromEntries(scalars.map(v => [v, w[v] ?? 0])), maps: mapsOf(w) } });
|
|
1197
1794
|
// --- cubes: a point the samples leave out, as literals -------------------------------------------------------------
|
|
1198
1795
|
const ctrl = modes.filter(mo => (mo.choice || mo.bool) && !atoms[mo.atom].cell && !atoms[mo.atom].param).map(mo => mo.atom);
|
|
1199
1796
|
// (the rule's own comparisons first, then each value, then pairs: of two directions that leave out as many samples
|
|
@@ -1232,7 +1829,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
1232
1829
|
sc[p] = Math.max(0, v);
|
|
1233
1830
|
sc[q] = Math.max(0, -v);
|
|
1234
1831
|
}
|
|
1235
|
-
return { scalars: sc, maps:
|
|
1832
|
+
return { scalars: sc, maps: mapsOf(w) };
|
|
1236
1833
|
};
|
|
1237
1834
|
const vecOf = (st) => valuesOf(pointOf({}, st).scalar);
|
|
1238
1835
|
// The cube of a point the samples leave out: its control literals and the rule's own comparisons true there (where
|
|
@@ -1397,7 +1994,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
1397
1994
|
break;
|
|
1398
1995
|
}
|
|
1399
1996
|
const pv = vecOf(r.pre), qv = vecOf(r.post);
|
|
1400
|
-
const ruling = within.filter(f => !ctx.includes(f) && !holdsRow(f, { ...r.pre.scalars }));
|
|
1997
|
+
const ruling = within.filter(f => !f.cells && !ctx.includes(f) && !holdsRow(f, { ...r.pre.scalars }));
|
|
1401
1998
|
if (ruling.length) {
|
|
1402
1999
|
ctx = [...ctx, ...ruling.slice(0, Math.max(joinAdd, ctx.length))];
|
|
1403
2000
|
tries--;
|
|
@@ -1425,6 +2022,15 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
1425
2022
|
}
|
|
1426
2023
|
return made;
|
|
1427
2024
|
};
|
|
2025
|
+
// The control refined on demand (as CEGAR refines its predicates, here read off the rule): a counterexample to a
|
|
2026
|
+
// caller's law that the set allows and nothing rules out lies among the samples of its control state. A level of a
|
|
2027
|
+
// value the rule compares with a constant (the first, of the values the laws read first, whose levels keep the control
|
|
2028
|
+
// states within joinKeys) whose part of those samples and of the states joined in leaves it out (past its hull or a
|
|
2029
|
+
// bound, or with no state there at all) becomes a control value, and every state is joined again.
|
|
2030
|
+
const refine = (p) => { const recent = [p, ...negs.slice(-8)]; used.rows += recent.length; const ok = spaces.some(sp => sp.refine(recent)); if (ok) {
|
|
2031
|
+
stood.clear();
|
|
2032
|
+
reached.length = 0;
|
|
2033
|
+
} return ok; };
|
|
1428
2034
|
for (;;) {
|
|
1429
2035
|
if (now() > jUntil || stop()) {
|
|
1430
2036
|
why = 'time';
|
|
@@ -1436,7 +2042,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
1436
2042
|
for (const [t, used] of stood)
|
|
1437
2043
|
if (used.some(u => !byText.has(u)))
|
|
1438
2044
|
stood.delete(t);
|
|
1439
|
-
const order = laws.map(l => l.name), inOrder = new Set(order);
|
|
2045
|
+
const order = [...laws, ...stepLaws].map(l => l.name), inOrder = new Set(order);
|
|
1440
2046
|
let todo;
|
|
1441
2047
|
for (let q = 0; q < order.length; q++) {
|
|
1442
2048
|
const used = stood.get(order[q]);
|
|
@@ -1526,7 +2132,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
1526
2132
|
opts.progress?.('join', { round: rounds, set: set.length, ms: qms, result: 'outside', goal: todo.slice(0, 60) });
|
|
1527
2133
|
continue;
|
|
1528
2134
|
}
|
|
1529
|
-
if (outside || breaks(params, post)) {
|
|
2135
|
+
if (outside || breaks(params, post, st, input)) {
|
|
1530
2136
|
// the caller's law broken from a state the set allows: a candidate false there and at every state reached, the
|
|
1531
2137
|
// one false at the most such states (then the smallest), or one made from it (fromCti); else its cube blocked,
|
|
1532
2138
|
// as IC3 blocks one. Where no sample holds its control state (the samples say nothing of it) the cube comes first.
|
|
@@ -1544,6 +2150,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
1544
2150
|
};
|
|
1545
2151
|
if (alone && cube())
|
|
1546
2152
|
continue;
|
|
2153
|
+
// (the control refined first, where a level leaves the state out: the samples then say what holds there)
|
|
2154
|
+
if (!outside && refine(pre)) {
|
|
2155
|
+
opts.progress?.('join', { round: rounds, refined: spaces.map(sp => sp.control()).join('; ') });
|
|
2156
|
+
continue;
|
|
2157
|
+
}
|
|
1547
2158
|
const pick = (fs) => { let bestF, score = -Infinity; for (const f of fs) {
|
|
1548
2159
|
if (f.cells || f.cong || extras.includes(f) || blocked.has(textOf(f)) || holdsAt(f, pre) || !reached.every(p2 => holdsAt(f, p2)))
|
|
1549
2160
|
continue;
|
|
@@ -1560,7 +2171,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
1560
2171
|
}
|
|
1561
2172
|
if (next)
|
|
1562
2173
|
tried++;
|
|
1563
|
-
opts.progress?.('join', { round: rounds, set: set.length, ms: qms, target: next ? textOf(next).slice(0, 60) : 'none' });
|
|
2174
|
+
opts.progress?.('join', { round: rounds, set: set.length, ms: qms, target: next ? textOf(next).slice(0, 60) : 'none', ...(next ? {} : { outside: outside ? 1 : 0 }) });
|
|
1564
2175
|
if (!next && !alone && cube())
|
|
1565
2176
|
continue;
|
|
1566
2177
|
if (!next) {
|
|
@@ -1574,10 +2185,30 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
1574
2185
|
// (a model the interpreter reads otherwise, a quotient's term the kernel left free, say: nothing to join, and the
|
|
1575
2186
|
// goal is set aside)
|
|
1576
2187
|
if (!set.some(f => !holdsAt(f, postP))) {
|
|
2188
|
+
// (a caller's goal: asked again, as before; the same counterexample again, a counted search's, has nothing to teach)
|
|
2189
|
+
if (callers.has(todo)) {
|
|
2190
|
+
const wk = JSON.stringify(w);
|
|
2191
|
+
if (sameAgain.get(todo) === wk) {
|
|
2192
|
+
why = 'no violation';
|
|
2193
|
+
break;
|
|
2194
|
+
}
|
|
2195
|
+
sameAgain.set(todo, wk);
|
|
2196
|
+
}
|
|
1577
2197
|
blocked.add(todo);
|
|
1578
2198
|
opts.progress?.('join', { round: rounds, set: set.length, ms: qms, result: 'no violation', goal: todo.slice(0, 60) });
|
|
1579
2199
|
continue;
|
|
1580
2200
|
}
|
|
2201
|
+
// (a form's counterexample: its own preimage's directions first, bounded by the states, where they leave the
|
|
2202
|
+
// state out; else the state it steps to is joined in)
|
|
2203
|
+
if (todoForm && !deepened.has(todo)) {
|
|
2204
|
+
deepened.add(todo);
|
|
2205
|
+
const more = spaces.map(sp => sp.deepen(preimages(m, [lawFor(todoForm)], [], atoms, sp.coords), reached, pre)).some(Boolean);
|
|
2206
|
+
if (more && formsNow().some(f => !holdsAt(f, pre))) {
|
|
2207
|
+
stood.clear();
|
|
2208
|
+
opts.progress?.('join', { round: rounds, deepened: todo.slice(0, 60) });
|
|
2209
|
+
continue;
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
1581
2212
|
const j0 = joins, d0 = dropped;
|
|
1582
2213
|
reach(postP);
|
|
1583
2214
|
// short walks from the state joined: every state they reach is a successor of one the invariant holds at
|
|
@@ -1605,7 +2236,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
1605
2236
|
misses++;
|
|
1606
2237
|
continue;
|
|
1607
2238
|
}
|
|
1608
|
-
if (breaks(params, next))
|
|
2239
|
+
if (breaks(params, next, at, inp))
|
|
1609
2240
|
break;
|
|
1610
2241
|
reach(pointOf(params, next));
|
|
1611
2242
|
at = next;
|