gdp-wired 0.31.0 → 0.32.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.
Files changed (73) hide show
  1. package/README.md +82 -6
  2. package/dist/core/c/reader.d.ts +86 -0
  3. package/dist/core/c/reader.js +860 -0
  4. package/dist/core/cli.d.ts +66 -0
  5. package/dist/core/cli.js +582 -0
  6. package/dist/core/dsl.d.ts +4 -2
  7. package/dist/core/dsl.js +22 -12
  8. package/dist/core/effect.d.ts +6 -4
  9. package/dist/core/effect.js +48 -10
  10. package/dist/core/ex/harness.exs +177 -0
  11. package/dist/core/ex/json.exs +46 -0
  12. package/dist/core/ex/reader.exs +462 -0
  13. package/dist/core/exists.d.ts +3 -0
  14. package/dist/core/exists.js +3 -1
  15. package/dist/core/extract-c.d.ts +35 -0
  16. package/dist/core/extract-c.js +424 -0
  17. package/dist/core/extract-check.js +27 -6
  18. package/dist/core/extract-ex.d.ts +16 -0
  19. package/dist/core/extract-ex.js +33 -0
  20. package/dist/core/extract-go-check.d.ts +28 -0
  21. package/dist/core/extract-go-check.js +639 -0
  22. package/dist/core/extract-go.d.ts +231 -0
  23. package/dist/core/extract-go.js +1166 -0
  24. package/dist/core/extract-jvm.d.ts +23 -0
  25. package/dist/core/extract-jvm.js +220 -0
  26. package/dist/core/extract-print.js +17 -7
  27. package/dist/core/extract-py.d.ts +15 -0
  28. package/dist/core/extract-py.js +31 -0
  29. package/dist/core/extract-rb.d.ts +17 -0
  30. package/dist/core/extract-rb.js +31 -0
  31. package/dist/core/extract-read.d.ts +20 -0
  32. package/dist/core/extract-read.js +46 -6
  33. package/dist/core/extract-rs.d.ts +12 -0
  34. package/dist/core/extract-rs.js +306 -0
  35. package/dist/core/extract-shapes.d.ts +2 -0
  36. package/dist/core/extract-shapes.js +6 -5
  37. package/dist/core/extract-step.d.ts +806 -0
  38. package/dist/core/extract-step.js +4141 -0
  39. package/dist/core/extract-swift.d.ts +27 -0
  40. package/dist/core/extract-swift.js +484 -0
  41. package/dist/core/extract-xstate.d.ts +10 -3
  42. package/dist/core/extract-xstate.js +50 -4
  43. package/dist/core/extract.d.ts +22 -3
  44. package/dist/core/extract.js +107 -18
  45. package/dist/core/go/go.mod +3 -0
  46. package/dist/core/go/reader.go +901 -0
  47. package/dist/core/infer.js +1770 -52
  48. package/dist/core/jvm/Harness.java +361 -0
  49. package/dist/core/jvm/JavaReader.java +825 -0
  50. package/dist/core/jvm/Jvm.java +332 -0
  51. package/dist/core/jvm/KtReader.java +960 -0
  52. package/dist/core/jvm/Rt.java +10 -0
  53. package/dist/core/laws.d.ts +66 -0
  54. package/dist/core/laws.js +522 -0
  55. package/dist/core/py/harness.py +328 -0
  56. package/dist/core/py/reader.py +447 -0
  57. package/dist/core/rb/harness.rb +233 -0
  58. package/dist/core/rb/reader.rb +375 -0
  59. package/dist/core/rs/Cargo.lock +108 -0
  60. package/dist/core/rs/Cargo.toml +14 -0
  61. package/dist/core/rs/src/main.rs +681 -0
  62. package/dist/core/swift/Harness.swift +124 -0
  63. package/dist/core/swift/Main.swift +34 -0
  64. package/dist/core/swift/Package.swift +13 -0
  65. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
  66. package/dist/kernel/cdcl.js +43 -18
  67. package/dist/kernel/epr.d.ts +35 -0
  68. package/dist/kernel/epr.js +1676 -0
  69. package/dist/kernel/prove.d.ts +44 -0
  70. package/dist/kernel/prove.js +668 -54
  71. package/dist/lean-kernel/emit.d.ts +1 -0
  72. package/dist/lean-kernel/emit.js +21 -4
  73. package/package.json +53 -6
@@ -0,0 +1,1676 @@
1
+ // Untrusted: a fast decision of EPR-shaped goals (research/protocols/epr/DESIGN.md). The hypotheses read as a
2
+ // propositional abstraction: a composed key (a·N² + b·N + c) the tuple of its parts, compared by the parts' order and
3
+ // equality, never by arithmetic; a few-valued cell a finite variable; an ordered value (an epoch) a term of a total order;
4
+ // anything else an opaque atom. Every clause beside the hypotheses holds in every model of the goal, and finite values are
5
+ // capped above every constant they meet, so unsat here is unsat there. It answers unsat with its core (the hypotheses
6
+ // its refutation read: prove.ts proves the goal over those and widens the tree to the whole, which kernel.ts checks), or
7
+ // a model read back as the kernel's witness and judged on every hypothesis, or nothing.
8
+ import { evalC } from "../core/machine.js";
9
+ import { canon, linear } from "./kernel.js";
10
+ import { konst, plus, solve, times, v as tv } from "../core/solver.js";
11
+ import { Simplex } from "./simplex.js";
12
+ // (a term's text, once per object: the decision asks it of the same terms many times)
13
+ const textsOf = new WeakMap();
14
+ const textOfE = (o) => { let s = textsOf.get(o); if (s === undefined)
15
+ textsOf.set(o, (s = JSON.stringify(o))); return s; };
16
+ // The patterns of a rule: of each map's reads in the step, the assumption, the flags and the laws (not the kinds' laws,
17
+ // whose key is a whole key), the one with the most parts. A read keyed by a write-at-every-key's own name is left out.
18
+ export function patternsOf(m, laws) {
19
+ const out = {};
20
+ const each = new Set(Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [w.each] : [])));
21
+ const scan = (o) => {
22
+ if (!o || typeof o !== 'object')
23
+ return;
24
+ const x = o;
25
+ if (x.op === 'get' && !x.args && !(x.key.op === 'var' && each.has(x.key.name)) && !(m.fns && x.map in m.fns)) {
26
+ const t = tupleOf(x.key);
27
+ if (t && t.coefs.length > (out[x.map]?.length ?? 0))
28
+ out[x.map] = t.coefs;
29
+ }
30
+ for (const y of Object.values(o))
31
+ scan(y);
32
+ };
33
+ scan(m.step);
34
+ scan(m.assume);
35
+ // (a function of one key: [0], its reads parts of the keys they're in, an uninterpreted function of a part)
36
+ for (const f of Object.keys(m.fns ?? {}))
37
+ out[f] = [0];
38
+ for (const l of laws)
39
+ if (!(l.name.startsWith('every ') && l.name.endsWith('of its kind')))
40
+ scan(l.holds);
41
+ return out;
42
+ }
43
+ const T = { k: 'c', b: true }, Fa = { k: 'c', b: false };
44
+ const and = (xs) => { const ys = xs.filter(x => !(x.k === 'c' && x.b)); return ys.some(x => x.k === 'c' && !x.b) ? Fa : ys.length === 0 ? T : ys.length === 1 ? ys[0] : { k: 'and', xs: ys }; };
45
+ const or = (xs) => { const ys = xs.filter(x => !(x.k === 'c' && !x.b)); return ys.some(x => x.k === 'c' && x.b) ? T : ys.length === 0 ? Fa : ys.length === 1 ? ys[0] : { k: 'or', xs: ys }; };
46
+ const not = (x) => (x.k === 'c' ? { k: 'c', b: !x.b } : x.k === 'not' ? x.x : { k: 'not', x });
47
+ // The functions of one key of the goal being decided (patterns [0]): a read f(x) of one at a part is a part, `f(x)`.
48
+ let fnMaps = new Set();
49
+ const partName = (e) => e.op === 'var' ? e.name
50
+ : e.op === 'get' && fnMaps.has(e.map) && !e.args ? (n => (n === undefined ? undefined : `${e.map}(${n})`))(partName(e.key)) : undefined;
51
+ // A key Σ c·x + d as its terms; undefined where it reads anything but parts under constant factors.
52
+ const linTerms = (e, k, out, d) => e.op === 'var' || e.op === 'get' ? (n => n !== undefined && (out.push([n, k]), true))(partName(e)) : e.op === 'const' ? ((d.c += k * e.value), true)
53
+ : e.op === 'mul' ? linTerms(e.a, k * e.k, out, d) : e.op === 'add' ? linTerms(e.a, k, out, d) && linTerms(e.b, k, out, d) : false;
54
+ function tupleOf(e) {
55
+ const ts = [], d = { c: 0 };
56
+ if (!linTerms(e, 1, ts, d) || d.c !== 0 || !ts.length)
57
+ return undefined;
58
+ ts.sort((a, b) => b[1] - a[1]);
59
+ const coefs = ts.map(t => t[1]);
60
+ if (coefs.at(-1) !== 1 || coefs.some((c, i) => i + 1 < coefs.length && (c % coefs[i + 1] !== 0 || c / coefs[i + 1] < 2)))
61
+ return undefined;
62
+ return { coefs, parts: ts.map(t => t[0]), bounds: coefs.map((c, i) => (i === 0 ? undefined : coefs[i - 1] / c)) };
63
+ }
64
+ const sameCoefs = (a, b) => a.length === b.length && a.every((c, i) => c === b[i]);
65
+ // `late`: true past the caller's end, checked between the steps and every 256 conflicts; then unknown.
66
+ // (a probe's hook: each decision with its goal, ms and outcome)
67
+ export const decideHook = {};
68
+ let lastShaped;
69
+ export function decide(goal, patterns, opts = {}) {
70
+ if (!decideHook.on)
71
+ return decide1(goal, patterns, opts);
72
+ const t0 = performance.now(), d = decide1(goal, patterns, opts);
73
+ decideHook.on(goal, d, performance.now() - t0, lastShaped);
74
+ return d;
75
+ }
76
+ function decide1(goal0, patterns, opts = {}) {
77
+ fnMaps = new Set(Object.entries(patterns).filter(([, c]) => c.length === 1 && c[0] === 0).map(([f]) => f));
78
+ const goal = { name: goal0.name, hyps: goal0.hyps.map(liftedKeys) };
79
+ // (a model whose order leaves no room between two near constants: again with the constants between them, below)
80
+ // (a model the read-back breaks: once more without the other goals' theory lemmas, whose history chose that model)
81
+ try {
82
+ const d = decide0(goal, patterns, opts), d2 = 'unknown' in d && d.unknown === noRoom ? decide0(goal, patterns, { ...opts, fill: true }) : d;
83
+ return 'unknown' in d2 && d2.unknown.startsWith(breaks) && lemmaCache.size ? decide0(goal, patterns, { ...opts, fresh: true }) : d2;
84
+ }
85
+ catch (e) {
86
+ if (e === pastEnd)
87
+ return { unknown: 'past the deadline' };
88
+ throw e;
89
+ }
90
+ finally {
91
+ fnMaps = new Set();
92
+ }
93
+ }
94
+ // A read at a key that holds an if (a write at every key read at a ghost's key, M'[c ? w : y]) as the if of the reads at
95
+ // its two keys, M[c ? a : b] = c ? M[a] : M[b] (an if inside the key's sum first lifted to its top), so each is a cell
96
+ // at a tuple; equal terms, so a refutation and a model of one are of the other. At most 8 keys a read.
97
+ const liftMemo = new WeakMap();
98
+ const ifMemo = new WeakMap();
99
+ const hasIf = (o) => {
100
+ if (!o || typeof o !== 'object')
101
+ return false;
102
+ let b = ifMemo.get(o);
103
+ if (b === undefined)
104
+ ifMemo.set(o, (b = o.op === 'if' || Object.values(o).some(hasIf)));
105
+ return b;
106
+ };
107
+ const hoisted = (e) => {
108
+ if (e.op === 'add') {
109
+ const a = hoisted(e.a), b = hoisted(e.b);
110
+ return a.op === 'if' ? { op: 'if', c: a.c, then: hoisted({ ...e, a: a.then, b }), else: hoisted({ ...e, a: a.else, b }) } : b.op === 'if' ? { op: 'if', c: b.c, then: hoisted({ ...e, a, b: b.then }), else: hoisted({ ...e, a, b: b.else }) } : a === e.a && b === e.b ? e : { ...e, a, b };
111
+ }
112
+ if (e.op === 'mul') {
113
+ const a = hoisted(e.a);
114
+ return a.op === 'if' ? { op: 'if', c: a.c, then: hoisted({ ...e, a: a.then }), else: hoisted({ ...e, a: a.else }) } : a === e.a ? e : { ...e, a };
115
+ }
116
+ return e;
117
+ };
118
+ const keysOf = (e) => (e.op === 'if' ? keysOf(e.then) + keysOf(e.else) : 1);
119
+ const liftE = (e) => {
120
+ if (!hasIf(e))
121
+ return e;
122
+ if (e.op === 'get' && !e.args) {
123
+ const key = hoisted(liftE(e.key));
124
+ if (key.op !== 'if' || keysOf(key) > 8)
125
+ return key === e.key ? e : { ...e, key };
126
+ const at = (k) => (k.op === 'if' ? { op: 'if', c: k.c, then: at(k.then), else: at(k.else) } : { ...e, key: k });
127
+ return at(key);
128
+ }
129
+ const out = {};
130
+ let changed = false;
131
+ for (const [k, x] of Object.entries(e)) {
132
+ const y = x && typeof x === 'object' && 'op' in x ? (k === 'c' ? liftC(x) : liftE(x)) : x;
133
+ out[k] = y;
134
+ if (y !== x)
135
+ changed = true;
136
+ }
137
+ return changed ? out : e;
138
+ };
139
+ const liftC = (c) => {
140
+ if (!hasIf(c))
141
+ return c;
142
+ if (c.op === 'and' || c.op === 'or') {
143
+ const xs = c.xs.map(liftC);
144
+ return xs.every((x, i) => x === c.xs[i]) ? c : { ...c, xs };
145
+ }
146
+ if (c.op === 'not') {
147
+ const x = liftC(c.x);
148
+ return x === c.x ? c : { ...c, x };
149
+ }
150
+ if (c.op === 'all') {
151
+ const b = liftC(c.c);
152
+ return b === c.c ? c : { ...c, c: b };
153
+ }
154
+ if (c.op === 'flag')
155
+ return c;
156
+ const a = liftE(c.a), b = liftE(c.b);
157
+ return a === c.a && b === c.b ? c : { ...c, a, b };
158
+ };
159
+ const liftedKeys = (c) => { let x = liftMemo.get(c); if (!x)
160
+ liftMemo.set(c, (x = liftC(c))); return x; };
161
+ // (thrown by `late` checked every 4,096 clauses and hypotheses read: a goal's clauses are quadratic in its terms)
162
+ const pastEnd = new Error('past the deadline');
163
+ // The theory's lemmas, by their atoms' names: each is arithmetic over the terms those names read (a part's value, a cell's
164
+ // at its key), so it holds in every goal that has those atoms, a round's other goals over the same set above all; each
165
+ // goal starts with those it has. At most 20,000, then begun again.
166
+ const lemmaCache = new Map();
167
+ const noRoom = 'no values for the model\'s order', breaks = 'the abstraction\'s model breaks';
168
+ function decide0(goal, patterns, opts) {
169
+ // --- which hypotheses are EPR-shaped: every map read at a key of its map's pattern
170
+ const shaped = goal.hyps.map(h => {
171
+ let ok = true;
172
+ const walk = (o) => {
173
+ if (!ok || !o || typeof o !== 'object')
174
+ return;
175
+ const x = o;
176
+ if (x.op === 'get' && fnMaps.has(x.map)) {
177
+ if (partName(x) === undefined) {
178
+ ok = false;
179
+ return;
180
+ }
181
+ }
182
+ else if (x.op === 'get') {
183
+ const t = x.args ? undefined : tupleOf(x.key), p = patterns[x.map];
184
+ if (!t || !p || !sameCoefs(t.coefs, p)) {
185
+ ok = false;
186
+ return;
187
+ }
188
+ }
189
+ for (const v of Object.values(o))
190
+ walk(v);
191
+ };
192
+ walk(h);
193
+ return ok;
194
+ });
195
+ if (decideHook.on)
196
+ lastShaped = shaped;
197
+ // (the conclusion's reads at keys of any radix shape: one of the wrong sort, Leader[k] <= Msg[k] with Msg a relation of
198
+ // pairs, is a cell of its own, as in a hypothesis)
199
+ const tupled = (o) => { if (!o || typeof o !== 'object')
200
+ return true; const x = o; if (x.op === 'get' && !fnMaps.has(x.map) && (x.args || !tupleOf(x.key)))
201
+ return false; return Object.values(o).every(tupled); };
202
+ if (!shaped.at(-1) && !tupled(goal.hyps.at(-1)))
203
+ return { unknown: 'the conclusion is not EPR-shaped' };
204
+ const hyps = goal.hyps;
205
+ let ticks = 0;
206
+ const tick = () => { if ((++ticks & 4095) === 0 && opts.late?.())
207
+ throw pastEnd; };
208
+ const fits = (map, key) => { const t = tupleOf(key), p = patterns[map]; return t && p && sameCoefs(t.coefs, p) ? t : undefined; };
209
+ // --- names: a part is a name some read's key or a key equality reads; the rest are scalars
210
+ // (each function part once: its reads are many, its congruence pairs of parts)
211
+ const parts = new Set(), fnParts = [], fnSeen = new Set();
212
+ // (the goal's reads and comparisons, gathered in one walk, each shared node once: the walks below read these lists)
213
+ const reads = [], comps = [], seen = new WeakSet();
214
+ const gather = (o) => {
215
+ if (!o || typeof o !== 'object' || seen.has(o))
216
+ return;
217
+ seen.add(o);
218
+ tick();
219
+ const x = o;
220
+ if (x.op === 'get')
221
+ reads.push(o);
222
+ else if ((x.op === '<' || x.op === '<=' || x.op === '=') && x.a)
223
+ comps.push(o);
224
+ for (const v of Object.values(o))
225
+ gather(v);
226
+ };
227
+ hyps.forEach(gather);
228
+ for (const x of reads) {
229
+ if (fnMaps.has(x.map)) {
230
+ const n = partName(x), a = partName(x.key);
231
+ if (n && a) {
232
+ if (!fnSeen.has(n))
233
+ (fnSeen.add(n), fnParts.push({ f: x.map, n, a }));
234
+ parts.add(n);
235
+ parts.add(a);
236
+ }
237
+ }
238
+ else
239
+ fits(x.map, x.key)?.parts.forEach(p => parts.add(p));
240
+ }
241
+ // (and the names of a key equality between tuples of one shape: of several parts, or of one where the other side is a part)
242
+ const eqs = comps.flatMap(c => { if (c.op !== '=')
243
+ return []; const ta = tupleOf(c.a), tb = tupleOf(c.b); return ta && tb && sameCoefs(ta.coefs, tb.coefs) ? [{ ta, tb }] : []; });
244
+ for (let grew = true; grew;) {
245
+ grew = false;
246
+ for (const { ta, tb } of eqs)
247
+ if (ta.parts.length > 1 || [...ta.parts, ...tb.parts].some(x => parts.has(x)))
248
+ for (const x of [...ta.parts, ...tb.parts])
249
+ if (!parts.has(x)) {
250
+ parts.add(x);
251
+ grew = true;
252
+ }
253
+ }
254
+ // exact: a scalar or a cell a hypothesis bounds by a constant (M[t] <= 1, a kind's instance): its values are
255
+ // 0 .. that bound exactly, no "cap or more", so it is compared with any finite term by cases, not ordered (a yes/no
256
+ // that implies another, Leader[x] <= Voted[x]); the hypothesis is the origin of the clause that it takes one of them
257
+ const ordMaps = new Set(), ordScalars = new Set();
258
+ const bounded = new Map();
259
+ const unitWalk = (c, h) => {
260
+ if (!c)
261
+ return;
262
+ if (c.op === 'and') {
263
+ c.xs.forEach(x => unitWalk(x, h));
264
+ return;
265
+ }
266
+ if ((c.op === '<=' || c.op === '<') && c.b.op === 'const' && (c.a.op === 'get' || c.a.op === 'var')) {
267
+ const id = textOfE(c.a), b = c.b.value - (c.op === '<' ? 1 : 0), had = bounded.get(id);
268
+ if (b >= 0 && (!had || b < had.b))
269
+ bounded.set(id, { b, h });
270
+ }
271
+ };
272
+ hyps.forEach((c, h) => unitWalk(c, h));
273
+ // (one compared with a key part, or beside an ordered term, is of that sort: ordered, below, and not exact)
274
+ const exactOf = (e) => (e.op === 'get' ? (!ordMaps.has(e.map) ? bounded.get(textOfE(e)) : undefined) : e.op === 'var' && !parts.has(e.name) && !ordScalars.has(e.name) ? bounded.get(textOfE(e)) : undefined);
275
+ // --- caps: a finite term's values are 0 .. cap, cap above every constant a comparison it is in has (so a larger value
276
+ // decides every comparison the cap does: the terms are naturals with coefficients of one sign)
277
+ const caps = new Map();
278
+ const termKey = (e) => (e.op === 'var' && !parts.has(e.name) ? `s:${e.name}` : e.op === 'get' ? `c:${e.map}` : undefined);
279
+ for (const c of comps) {
280
+ {
281
+ const consts = [], keys = [];
282
+ let ex = 0;
283
+ const w = (e, k) => { if (e.op === 'const')
284
+ consts.push(Math.abs(e.value));
285
+ else if (e.op === 'add')
286
+ (w(e.a, k), w(e.b, k));
287
+ else if (e.op === 'mul')
288
+ w(e.a, k * e.k);
289
+ else if (e.op === 'if')
290
+ (w(e.then, k), w(e.else, k));
291
+ else {
292
+ const x = exactOf(e);
293
+ if (x)
294
+ ex += Math.abs(k) * x.b;
295
+ const t = termKey(e);
296
+ if (t)
297
+ keys.push(t);
298
+ } };
299
+ w(c.a, 1);
300
+ w(c.b, 1);
301
+ // (and past what the exact terms beside can add: x <= Voted[k] with x at its cap is false at every larger x)
302
+ const top = Math.max(1, ...consts) + ex + 1;
303
+ for (const k of keys)
304
+ caps.set(k, Math.max(caps.get(k) ?? 1, top));
305
+ }
306
+ }
307
+ // ordered: a map's cells, or a scalar, compared with another non-constant term (an epoch with a node's epoch: Ivy's
308
+ // total order, `le`), not only with constants (a yes/no, a choice, which stay finite)
309
+ const leaves = (e, k, out) => {
310
+ if (e.op === 'add') {
311
+ leaves(e.a, k, out);
312
+ leaves(e.b, k, out);
313
+ }
314
+ else if (e.op === 'mul')
315
+ leaves(e.a, k * e.k, out);
316
+ else if (e.op === 'if') {
317
+ leaves(e.then, k, out);
318
+ leaves(e.else, k, out);
319
+ }
320
+ else if (e.op !== 'const')
321
+ out.push([e, k]);
322
+ };
323
+ const ofParts = (e) => tupleOf(e)?.parts.every(x => parts.has(x));
324
+ const ordComps = comps.filter(c => !(ofParts(c.a) && ofParts(c.b))).map(c => { const ts = []; leaves(c.a, 1, ts); leaves(c.b, -1, ts); return ts; });
325
+ const ordWalk = (ts) => {
326
+ {
327
+ const hasPart = ts.some(([e]) => (n => n !== undefined && parts.has(n))(partName(e)));
328
+ const nonPart = ts.filter(([e]) => (hasPart || !exactOf(e)) && ((e.op === 'get' && !fnMaps.has(e.map)) || (e.op === 'var' && !parts.has(e.name))));
329
+ // (and every term beside an ordered one in a comparison: one value of the sort, an if-then-else's branches)
330
+ const tn = ts.filter(([e]) => hasPart || !exactOf(e)), mixed = nonPart.length && tn.length > 1 && tn.some(t => t[1] > 0) && tn.some(t => t[1] < 0);
331
+ const beside = nonPart.some(([e]) => (e.op === 'get' && ordMaps.has(e.map)) || (e.op === 'var' && ordScalars.has(e.name)));
332
+ if (mixed || beside)
333
+ for (const [e] of nonPart) {
334
+ if (e.op === 'get' && !ordMaps.has(e.map)) {
335
+ ordMaps.add(e.map);
336
+ grew = true;
337
+ }
338
+ else if (e.op === 'var' && !ordScalars.has(e.name)) {
339
+ ordScalars.add(e.name);
340
+ grew = true;
341
+ }
342
+ }
343
+ }
344
+ };
345
+ let grew = true;
346
+ while (grew) {
347
+ grew = false;
348
+ ordComps.forEach(ts => (tick(), ordWalk(ts)));
349
+ }
350
+ // --- atoms
351
+ const ids = new Map(), names = [''];
352
+ const atom = (key) => { let v = ids.get(key); if (v === undefined) {
353
+ v = names.length;
354
+ ids.set(key, v);
355
+ names.push(key);
356
+ } return { k: 'v', v }; };
357
+ // (the order's and equality's atoms by their two terms, without building their text again: the axioms ask them
358
+ // quadratically and the transitivity cubically)
359
+ const pairAtoms = (tag) => { const byA = new Map(); return (a, b) => { let in2 = byA.get(a); if (!in2)
360
+ byA.set(a, (in2 = new Map())); let f = in2.get(b); if (!f)
361
+ in2.set(b, (f = atom(`${tag} ${a} ${b}`))); return f; }; };
362
+ const eqAt = pairAtoms('eq'), leAt = pairAtoms('le');
363
+ const eq = (x, y) => (x === y ? T : x < y ? eqAt(x, y) : eqAt(y, x));
364
+ // the ordered terms (every part among them), `le a b` a ≤ b
365
+ const ords = new Set(['k:0', ...[...parts].map(x => `p:${x}`)]);
366
+ const le = (a, b) => (a === b ? T : leAt(a, b));
367
+ // a part under a bound, x < c: ¬(c ≤ x) in the order (below), the constant one of its terms
368
+ const ltAt = (x, c) => { if (c <= 0)
369
+ return Fa; ords.add(`k:${c}`); return not(le(`k:${c}`, `p:${x}`)); };
370
+ const fins = new Map(), cellsOf = new Map(), odd = [];
371
+ const finAt = (f, v) => atom(`val ${f.id} ${v}`);
372
+ const finOf = (e) => {
373
+ if ((e.op === 'get' && (ordMaps.has(e.map) || fnMaps.has(e.map))) || (e.op === 'var' && ordScalars.has(e.name)))
374
+ return undefined;
375
+ const ex = exactOf(e), fin = (id, cap) => (ex ? { id, cap: ex.b, exact: ex.h } : { id, cap });
376
+ if (e.op === 'var' && !parts.has(e.name)) {
377
+ const id = `s:${e.name}`;
378
+ let f = fins.get(id);
379
+ if (!f)
380
+ fins.set(id, (f = fin(id, caps.get(id) ?? 1)));
381
+ return f;
382
+ }
383
+ if (e.op === 'get' && !e.args && !fits(e.map, e.key)) {
384
+ const id = `c:${e.map}#${textOfE(e.key)}`;
385
+ let f = fins.get(id);
386
+ if (!f) {
387
+ fins.set(id, (f = fin(id, caps.get(`c:${e.map}`) ?? 1)));
388
+ odd.push({ id, map: e.map, key: e.key });
389
+ }
390
+ return f;
391
+ }
392
+ if (e.op === 'get') {
393
+ const t = tupleOf(e.key), id = `c:${e.map}(${t.parts.join(',')})`;
394
+ let f = fins.get(id);
395
+ if (!f) {
396
+ fins.set(id, (f = fin(id, caps.get(`c:${e.map}`) ?? 1)));
397
+ if (!cellsOf.has(e.map))
398
+ cellsOf.set(e.map, []);
399
+ cellsOf.get(e.map).push({ id, parts: t.parts });
400
+ }
401
+ return f;
402
+ }
403
+ return undefined;
404
+ };
405
+ const keyEqs = [];
406
+ const intervals = [];
407
+ // An ordered term: a part, an ordered scalar, an ordered cell (a tuple's, or one of its own at a key of the wrong
408
+ // sort), a constant; `le a b` is a ≤ b.
409
+ const ordCells = new Map(), ordOdd = [];
410
+ const ordOf = (e) => {
411
+ if (e.op === 'const') {
412
+ const id = `k:${e.value}`;
413
+ ords.add(id);
414
+ return id;
415
+ }
416
+ const pn = partName(e);
417
+ if (pn !== undefined && parts.has(pn)) {
418
+ ords.add(`p:${pn}`);
419
+ return `p:${pn}`;
420
+ }
421
+ if (e.op === 'var') {
422
+ if (ordScalars.has(e.name)) {
423
+ ords.add(`s:${e.name}`);
424
+ return `s:${e.name}`;
425
+ }
426
+ return undefined;
427
+ }
428
+ // (a function read at a key of the wrong sort, idn(64·m + n): a term of the order too, its value the read-back's)
429
+ if (e.op === 'get' && fnMaps.has(e.map)) {
430
+ const id = `c:${e.map}#${textOfE(e.key)}`;
431
+ ords.add(id);
432
+ return id;
433
+ }
434
+ if (e.op === 'get' && ordMaps.has(e.map) && !e.args) {
435
+ const t = fits(e.map, e.key);
436
+ const id = t ? `c:${e.map}(${t.parts.join(',')})` : `c:${e.map}#${textOfE(e.key)}`;
437
+ if (!ords.has(id)) {
438
+ ords.add(id);
439
+ if (t) {
440
+ if (!ordCells.has(e.map))
441
+ ordCells.set(e.map, []);
442
+ ordCells.get(e.map).push({ id, parts: t.parts });
443
+ }
444
+ else
445
+ ordOdd.push({ id, map: e.map, key: e.key });
446
+ }
447
+ return id;
448
+ }
449
+ return undefined;
450
+ };
451
+ // (a value: an ordered term plus a constant, `o`: the ring's n + 1)
452
+ const ordCases = (e) => {
453
+ if (e.op === 'if') {
454
+ const c = lit(e.c), a = ordCases(e.then), b = ordCases(e.else);
455
+ return a && b ? [...a.map(x => ({ ...x, g: and([c, x.g]) })), ...b.map(x => ({ ...x, g: and([not(c), x.g]) }))] : undefined;
456
+ }
457
+ if (e.op === 'add' && e.b.op === 'const') {
458
+ const a = ordCases(e.a);
459
+ return a?.map(x => ({ ...x, o: x.o + e.b.value }));
460
+ }
461
+ if (e.op === 'add' && e.a.op === 'const') {
462
+ const b = ordCases(e.b);
463
+ return b?.map(x => ({ ...x, o: x.o + e.a.value }));
464
+ }
465
+ const t = ordOf(e);
466
+ return t ? [{ g: T, t, o: 0 }] : undefined;
467
+ };
468
+ // t1 − t2 + d ⋈ 0 as order atoms (naturals: t1 < t2 is t1 + 1 ≤ t2), or undefined
469
+ // (a constant side takes the offset: t + d ⋈ k:c is t ⋈ k:(c − d), nothing below 0; t1 = t2 + 1, the successor, is an atom
470
+ // that implies t2 < t1 with no term between, one way only: a gap no term names leaves it unknown)
471
+ const succs = [];
472
+ const ordAtom = (t1, t2, d, op) => {
473
+ const num = (x) => (x.startsWith('k:') ? Number(x.slice(2)) : undefined), n1 = num(t1), n2 = num(t2);
474
+ if (n1 !== undefined && n2 !== undefined) {
475
+ const x = n1 - n2 + d;
476
+ return { k: 'c', b: op === '<' ? x < 0 : op === '<=' ? x <= 0 : x === 0 };
477
+ }
478
+ if (n2 !== undefined && d !== 0) {
479
+ const c = n2 - d;
480
+ if (c < 0)
481
+ return Fa;
482
+ ords.add(`k:${c}`);
483
+ return ordAtom(t1, `k:${c}`, 0, op);
484
+ }
485
+ if (n1 !== undefined && d !== 0) {
486
+ const c = n1 + d;
487
+ if (c < 0)
488
+ return op === '=' ? Fa : T;
489
+ ords.add(`k:${c}`);
490
+ return ordAtom(`k:${c}`, t2, 0, op);
491
+ }
492
+ const D = op === '<' ? d + 1 : d;
493
+ if (op === '=') {
494
+ if (d === 0)
495
+ return and([le(t1, t2), le(t2, t1)]);
496
+ if (Math.abs(d) !== 1)
497
+ return undefined;
498
+ const [lo, hi] = d === -1 ? [t2, t1] : [t1, t2], s = atom(`succ ${lo} ${hi}`);
499
+ succs.push({ s: s.v, lo, hi });
500
+ return s;
501
+ }
502
+ return D === 0 ? le(t1, t2) : D === 1 ? not(le(t2, t1)) : undefined;
503
+ };
504
+ const ordered = (ts, d, op) => {
505
+ let a, b, dd = d;
506
+ if (ts.length === 2 && ts[0][1] === 1 && ts[1][1] === -1)
507
+ [a, b] = [ts[0][0], ts[1][0]];
508
+ else if (ts.length === 2 && ts[0][1] === -1 && ts[1][1] === 1)
509
+ [a, b] = [ts[1][0], ts[0][0]];
510
+ else if (ts.length === 1 && ts[0][1] === 1) {
511
+ a = ts[0][0];
512
+ if (-d < 0)
513
+ return Fa;
514
+ b = { op: 'const', value: -d };
515
+ dd = 0;
516
+ }
517
+ else if (ts.length === 1 && ts[0][1] === -1) {
518
+ b = ts[0][0];
519
+ if (d < 0)
520
+ return op === '<' || op === '<=' ? T : Fa;
521
+ a = { op: 'const', value: d };
522
+ dd = 0;
523
+ }
524
+ else
525
+ return undefined;
526
+ const ca = ordCases(a), cb = ordCases(b);
527
+ if (!ca || !cb || ca.length * cb.length > 256)
528
+ return undefined;
529
+ const out = [];
530
+ for (const x of ca)
531
+ for (const y of cb) {
532
+ const at = ordAtom(x.t, y.t, dd + x.o - y.o, op);
533
+ if (!at)
534
+ return undefined;
535
+ out.push(and([x.g, y.g, at]));
536
+ }
537
+ return or(out);
538
+ };
539
+ const cases = (e) => {
540
+ if (e.op === 'const')
541
+ return [{ g: T, n: e.value }];
542
+ if (e.op === 'if') {
543
+ const c = lit(e.c), a = cases(e.then), b = cases(e.else);
544
+ return a && b ? [...a.map(x => ({ ...x, g: and([c, x.g]) })), ...b.map(x => ({ ...x, g: and([not(c), x.g]) }))] : undefined;
545
+ }
546
+ const f = finOf(e);
547
+ return f ? [{ g: T, f }] : undefined;
548
+ };
549
+ // The comparison's sides as Σ coef·term + const; finite where every term is finite and every coefficient one sign.
550
+ // (a ∸ b is a − b where every term of b is a term of a, at least as often: never truncated, as the terms are naturals)
551
+ const exactSub = (e) => {
552
+ const ta = [], tb = [], da = { c: 0 }, db = { c: 0 };
553
+ if (!linTerms(e.a, 1, ta, da) || !linTerms(e.b, 1, tb, db) || db.c > da.c)
554
+ return false;
555
+ const have = new Map();
556
+ for (const [x, c] of ta)
557
+ have.set(x, (have.get(x) ?? 0) + c);
558
+ return tb.every(([x, c]) => (have.get(x) ?? 0) >= c);
559
+ };
560
+ const sum = (e, k, ts, d) => e.op === 'const' ? ((d.c += k * e.value), true) : e.op === 'add' ? sum(e.a, k, ts, d) && sum(e.b, k, ts, d) : e.op === 'mul' ? sum(e.a, k * e.k, ts, d)
561
+ : e.op === 'sub' && exactSub(e) ? sum(e.a, k, ts, d) && sum(e.b, -k, ts, d) : (ts.push([e, k]), true);
562
+ // (an opaque comparison that reads only key parts and constants: an instance at a key of the wrong sort, harmless; one
563
+ // that reads a scalar or a cell is arithmetic the abstraction can't read: a counter, a sum, a product)
564
+ const foreign = new Set(), opaques = new Map();
565
+ const opaque = (c) => {
566
+ const a = atom(`op ${textOfE(c)}`);
567
+ opaques.set(a.v, c);
568
+ let keyOnly = true;
569
+ const wk = (o) => { if (!keyOnly || !o || typeof o !== 'object')
570
+ return; const x = o; if ((x.op === 'get' && !fnMaps.has(x.map) && !ordMaps.has(x.map)) || (x.op === 'var' && !parts.has(x.name) && !ordScalars.has(x.name))) {
571
+ keyOnly = false;
572
+ return;
573
+ } for (const y of Object.values(o))
574
+ wk(y); };
575
+ wk(c);
576
+ if (!keyOnly)
577
+ foreign.add(a.v);
578
+ return a;
579
+ };
580
+ const comparison = (c) => {
581
+ // a key equality: two tuples of one shape
582
+ if (c.op === '=') {
583
+ const ta = tupleOf(c.a), tb = tupleOf(c.b);
584
+ if (ta && tb && sameCoefs(ta.coefs, tb.coefs) && [...ta.parts, ...tb.parts].every(p => parts.has(p))) {
585
+ const p = opaque(c);
586
+ keyEqs.push({ p, a: ta, b: tb });
587
+ return p;
588
+ }
589
+ }
590
+ const ts = [], d = { c: 0 };
591
+ sum(c.a, 1, ts, d);
592
+ sum(c.b, -1, ts, d);
593
+ // a part under a bound: x < k, x <= k
594
+ if (ts.length === 1 && ts[0][0].op === 'var' && parts.has(ts[0][0].name) && Math.abs(ts[0][1]) === 1 && c.op !== '=') {
595
+ const [[x, s]] = ts, k = -d.c * s; // s·x + d ⋈ 0
596
+ const strict = c.op === '<';
597
+ // s = 1: x + d < 0 → x < −d; x + d <= 0 → x < −d + 1. s = −1: −x + d < 0 → x > d → ¬(x < d + 1); <= : ¬(x < d)
598
+ return s === 1 ? ltAt(x.name, strict ? k : k + 1) : not(ltAt(x.name, strict ? k + 1 : k));
599
+ }
600
+ // a tuple against a prefix of its chain: L <= X (lo), X < L + c (hi), c the prefix's last coefficient
601
+ if (c.op !== '=' && ts.length && ts.every(([e]) => e.op === 'var' && parts.has(e.name))) {
602
+ const merged = new Map();
603
+ for (const [e, k] of ts)
604
+ merged.set(e.name, (merged.get(e.name) ?? 0) + k);
605
+ const pos = [...merged].filter(t => t[1] > 0).sort((a, b) => b[1] - a[1]), neg = [...merged].filter(t => t[1] < 0).map(([x, k]) => [x, -k]).sort((a, b) => b[1] - a[1]);
606
+ const k0 = d.c + (c.op === '<' ? 1 : 0); // the form Σ ≤ 0 over integers: P − Q + k0 ≤ 0
607
+ const chainOf = (ts2) => ts2.map(t => t[1]);
608
+ const isChain = (cs) => cs.length > 0 && cs.every((x, i) => i + 1 >= cs.length || (x % cs[i + 1] === 0 && x / cs[i + 1] >= 2));
609
+ const prefix = (full, pre) => pre.length < full.length && pre.every((x, i) => x === full[i]);
610
+ // lo: L − X ≤ 0, P = L (prefix), Q = X (tuple, ending in 1); hi: X − L − c + 1 ≤ 0, P = X, Q = L
611
+ const lo = k0 === 0 && chainOf(neg).at(-1) === 1 && isChain(chainOf(neg)) && prefix(chainOf(neg), chainOf(pos));
612
+ const hi = chainOf(pos).at(-1) === 1 && isChain(chainOf(pos)) && prefix(chainOf(pos), chainOf(neg)) && neg.length > 0 && k0 === 1 - neg.at(-1)[1];
613
+ if (lo || hi) {
614
+ const X = lo ? neg : pos, L = lo ? pos : neg, a = opaque(c);
615
+ intervals.push({ p: a, kind: lo ? 'lo' : 'hi', X: X.map(t => t[0]), L: L.map(t => t[0]), coefs: chainOf(X) });
616
+ return a;
617
+ }
618
+ }
619
+ // ordered: a term against another, or a constant, one of them an ordered cell or scalar
620
+ {
621
+ const reads = (e) => e.op === 'get' ? ordMaps.has(e.map) || fnMaps.has(e.map) : e.op === 'var' ? ordScalars.has(e.name) || parts.has(e.name) : e.op === 'if' ? reads(e.then) || reads(e.else) : e.op === 'add' ? reads(e.a) || reads(e.b) : false;
622
+ if (ts.some(([e]) => reads(e))) {
623
+ const f = ordered(ts, d.c, c.op);
624
+ if (f)
625
+ return f;
626
+ }
627
+ }
628
+ // finite: every term finite, coefficients of one sign
629
+ // (the terms not exact of one sign, the exact ones of any: a capped term at its cap decides it as any larger value)
630
+ const cs = ts.length ? ts.map(([e]) => cases(e)) : [], loose = ts.filter((_, i) => !cs[i]?.every(y => y.n !== undefined || y.f.exact !== undefined));
631
+ if (ts.length && (loose.every(t => t[1] > 0) || loose.every(t => t[1] < 0))) {
632
+ if (cs.every(Boolean)) {
633
+ const holds = (v) => (c.op === '<' ? v < 0 : c.op === '<=' ? v <= 0 : v === 0);
634
+ const out = [];
635
+ let combos = 0;
636
+ const go = (i, acc, g) => {
637
+ if (++combos > 4096)
638
+ return false;
639
+ if (i === ts.length) {
640
+ if (holds(acc + d.c))
641
+ out.push(and(g));
642
+ return true;
643
+ }
644
+ for (const x of cs[i]) {
645
+ if (x.n !== undefined) {
646
+ if (!go(i + 1, acc + ts[i][1] * x.n, [...g, x.g]))
647
+ return false;
648
+ continue;
649
+ }
650
+ for (let v = 0; v <= x.f.cap; v++)
651
+ if (!go(i + 1, acc + ts[i][1] * v, [...g, x.g, finAt(x.f, v)]))
652
+ return false;
653
+ }
654
+ return true;
655
+ };
656
+ if (go(0, 0, []))
657
+ return or(out);
658
+ }
659
+ }
660
+ if (!ts.length)
661
+ return { k: 'c', b: c.op === '<' ? d.c < 0 : c.op === '<=' ? d.c <= 0 : d.c === 0 };
662
+ return opaque(c);
663
+ };
664
+ const lit = (c) => {
665
+ switch (c.op) {
666
+ case 'and': return and(c.xs.map(lit));
667
+ case 'or': return or(c.xs.map(lit));
668
+ case 'not': return not(lit(c.x));
669
+ case '<':
670
+ case '<=':
671
+ case '=': return comparison(c);
672
+ case 'all':
673
+ case 'flag': return opaque(c);
674
+ }
675
+ };
676
+ const forms = hyps.map(h => (tick(), h ? lit(h) : undefined));
677
+ // the theory: each opaque comparison of key parts, ordered terms and composed keys (a part against 64·e + n, an
678
+ // instance at a key of the wrong sort) as linear arithmetic over the ordered terms, which a model's order is checked
679
+ // against below (each a term of the order, so its axioms hold)
680
+ const tlin = (e) => {
681
+ if (e.op === 'const')
682
+ return konst(e.value);
683
+ if (e.op === 'add') {
684
+ const a = tlin(e.a), b = tlin(e.b);
685
+ return a && b ? plus(a, b) : undefined;
686
+ }
687
+ if (e.op === 'mul') {
688
+ const a = tlin(e.a);
689
+ return a && times(a, e.k);
690
+ }
691
+ const t = ordOf(e);
692
+ return t === undefined ? undefined : t.startsWith('k:') ? konst(Number(t.slice(2))) : tv(t);
693
+ };
694
+ const theory = [...opaques].filter(([x]) => !foreign.has(x)).flatMap(([x, c]) => {
695
+ if (c.op !== '<' && c.op !== '<=' && c.op !== '=')
696
+ return [];
697
+ const a = tlin(c.a), b = tlin(c.b);
698
+ return a && b ? [{ x, op: c.op, d: plus(a, times(b, -1)) }] : [];
699
+ });
700
+ // (an order over many terms is a cubic number of transitivity clauses: past 64 terms they are added lazily, those a
701
+ // model breaks, below; past 512, the totality's pairs alone are too many, and the goal keeps the usual path)
702
+ // (`fill`: the constants between two near ones too, so that discreteness counts the room between them: k:0 < x < y < k:2
703
+ // has none, which the read-back meets)
704
+ if (opts.fill) {
705
+ const cs = [...ords].filter(x => x.startsWith('k:')).map(x => Number(x.slice(2))).sort((a, b) => a - b);
706
+ for (let i = 0; i + 1 < cs.length; i++)
707
+ if (cs[i + 1] - cs[i] <= 4)
708
+ for (let c = cs[i] + 1; c < cs[i + 1]; c++)
709
+ ords.add(`k:${c}`);
710
+ }
711
+ if (ords.size > 512)
712
+ return { unknown: `${ords.size} ordered terms` };
713
+ const lazy = ords.size > 64;
714
+ // --- clauses (literals: +v / −v), each with the hypotheses it stands for
715
+ const clauses = [];
716
+ const add = (lits, from) => { tick(); const s = new Set(lits); for (const l of s)
717
+ if (s.has(-l))
718
+ return; clauses.push({ lits: [...s], from }); };
719
+ let fresh = 0;
720
+ const tseitin = (f, from) => {
721
+ if (f.k === 'v')
722
+ return f.v;
723
+ if (f.k === 'not')
724
+ return -tseitin(f.x, from);
725
+ if (f.k === 'c') {
726
+ const g = ++fresh + 1e6;
727
+ add([f.b ? g : -g], -1);
728
+ return g;
729
+ }
730
+ const ls = f.xs.map(x => tseitin(x, from)), g = ++fresh + 1e6;
731
+ if (f.k === 'and') {
732
+ for (const l of ls)
733
+ add([-g, l], from);
734
+ add([g, ...ls.map(l => -l)], from);
735
+ }
736
+ else {
737
+ add([-g, ...ls], from);
738
+ for (const l of ls)
739
+ add([g, -l], from);
740
+ }
741
+ return g;
742
+ };
743
+ const top = (f, from) => {
744
+ if (f.k === 'and') {
745
+ for (const x of f.xs)
746
+ top(x, from);
747
+ return;
748
+ }
749
+ if (f.k === 'c') {
750
+ if (!f.b)
751
+ add([], from);
752
+ return;
753
+ }
754
+ if (f.k === 'or' && f.xs.every(x => x.k === 'v' || (x.k === 'not' && x.x.k === 'v'))) {
755
+ add(f.xs.map(x => (x.k === 'v' ? x.v : -x.x.v)), from);
756
+ return;
757
+ }
758
+ add([tseitin(f, from)], from);
759
+ };
760
+ forms.forEach((f, i) => { if (f)
761
+ top(f, i); });
762
+ // axioms: congruence of cells; a composed key's injectivity where its parts are under their bounds; one value per finite
763
+ // variable; the order (below), whose transitivity is equality's and the bounds' too
764
+ const v = (f) => (f.k === 'v' ? f.v : f.k === 'not' && f.x.k === 'v' ? -f.x.v : undefined);
765
+ for (const { p, a, b } of keyEqs) {
766
+ const pv = v(p), es = a.parts.map((x, i) => eq(x, b.parts[i]));
767
+ // equal parts: equal keys, always; equal keys with every part but the top under its bound: equal parts
768
+ add([...es.map(e => (e.k === 'v' ? -e.v : 0)).filter(Boolean), pv], -1);
769
+ const bounded = a.bounds.flatMap((bd, i) => (bd === undefined ? [] : [v(ltAt(a.parts[i], bd)), v(ltAt(b.parts[i], bd))]));
770
+ for (const e of es)
771
+ if (e.k === 'v')
772
+ add([-pv, ...bounded.map(l => -l), e.v], -1);
773
+ }
774
+ // an interval of a prefix: equal prefixes give lo always and hi where X's low parts are under their bounds; lo and hi
775
+ // with every part of X and L but the top under its bound give equal prefixes (a pair of one X and one L)
776
+ const baseOf = (coefs, i) => coefs[i - 1] / coefs[i];
777
+ const pairs = new Map();
778
+ for (const iv of intervals) {
779
+ const pe = iv.L.map((y, i) => eq(iv.X[i], y)), pv = v(iv.p);
780
+ const lowBounded = iv.X.flatMap((x, i) => (i >= iv.L.length ? [v(ltAt(x, baseOf(iv.coefs, i)))] : []));
781
+ add([...pe.filter(e => e.k === 'v').map(e => -e.v), ...(iv.kind === 'hi' ? lowBounded.map(l => -l) : []), pv], -1);
782
+ const key = `${iv.X.join(',')}|${iv.L.join(',')}`, pr = pairs.get(key) ?? { X: iv.X, L: iv.L, coefs: iv.coefs };
783
+ pr[iv.kind] = pv;
784
+ pairs.set(key, pr);
785
+ }
786
+ for (const pr of pairs.values()) {
787
+ if (pr.lo === undefined || pr.hi === undefined)
788
+ continue;
789
+ const bounded = [...pr.X.flatMap((x, i) => (i ? [v(ltAt(x, baseOf(pr.coefs, i)))] : [])), ...pr.L.flatMap((y, i) => (i ? [v(ltAt(y, baseOf(pr.coefs, i)))] : []))];
790
+ for (const [i, y] of pr.L.entries()) {
791
+ const e = eq(pr.X[i], y);
792
+ if (e.k === 'v')
793
+ add([-pr.lo, -pr.hi, ...bounded.map(l => -l), e.v], -1);
794
+ }
795
+ }
796
+ for (const [, cells] of cellsOf)
797
+ for (let i = 0; i < cells.length; i++)
798
+ for (let j = i + 1; j < cells.length; j++) {
799
+ const a = cells[i], b = cells[j], es = a.parts.map((x, k) => v(eq(x, b.parts[k])));
800
+ const fa = fins.get(a.id), fb = fins.get(b.id), cap = Math.max(fa.cap, fb.cap);
801
+ for (let val = 0; val <= cap; val++) {
802
+ const la = val <= fa.cap ? v(finAt(fa, val)) : undefined, lb = val <= fb.cap ? v(finAt(fb, val)) : undefined;
803
+ const pre = es.filter((e) => e !== undefined).map(e => -e);
804
+ if (la !== undefined)
805
+ add([...pre, -la, ...(lb !== undefined ? [lb] : [])], -1);
806
+ if (lb !== undefined)
807
+ add([...pre, -lb, ...(la !== undefined ? [la] : [])], -1);
808
+ }
809
+ }
810
+ // the order: total, transitive, discrete, the constants in their order, every term at least 0, a part's equality its
811
+ // order both ways, equal tuples equal ordered cells
812
+ {
813
+ const os = [...ords], num = (x) => (x.startsWith('k:') ? Number(x.slice(2)) : undefined);
814
+ for (let i = 0; i < os.length; i++)
815
+ for (let j = i + 1; j < os.length; j++) {
816
+ const a = os[i], b = os[j], na = num(a), nb = num(b);
817
+ add([v(le(a, b)), v(le(b, a))], -1);
818
+ if (na !== undefined && nb !== undefined) {
819
+ add([na <= nb ? v(le(a, b)) : -v(le(a, b))], -1);
820
+ add([nb <= na ? v(le(b, a)) : -v(le(b, a))], -1);
821
+ }
822
+ }
823
+ for (const x of os)
824
+ if (x !== 'k:0')
825
+ add([v(le('k:0', x))], -1);
826
+ // (the naturals are discrete: nothing between c and c + 1)
827
+ for (const c of os.map(num).filter((n) => n !== undefined))
828
+ if (ords.has(`k:${c + 1}`))
829
+ for (const x of os)
830
+ if (!x.startsWith('k:'))
831
+ add([v(le(x, `k:${c}`)), v(le(`k:${c + 1}`, x))], -1);
832
+ if (!lazy)
833
+ for (const a of os)
834
+ for (const b of os)
835
+ if (a !== b)
836
+ for (const c of os)
837
+ if (c !== a && c !== b)
838
+ add([-v(le(a, b)), -v(le(b, c)), v(le(a, c))], -1);
839
+ const ordParts = os.filter(x => x.startsWith('p:')).map(x => x.slice(2));
840
+ for (let i = 0; i < ordParts.length; i++)
841
+ for (let j = i + 1; j < ordParts.length; j++) {
842
+ const x = ordParts[i], y = ordParts[j], e = v(eq(x, y)), a = v(le(`p:${x}`, `p:${y}`)), b = v(le(`p:${y}`, `p:${x}`));
843
+ add([-e, a], -1);
844
+ add([-e, b], -1);
845
+ add([e, -a, -b], -1);
846
+ }
847
+ // a function's reads at equal parts are equal (Ackermann); a successor has nothing between it and its predecessor
848
+ for (let i = 0; i < fnParts.length; i++)
849
+ for (let j = i + 1; j < fnParts.length; j++) {
850
+ const x = fnParts[i], y = fnParts[j];
851
+ if (x.f === y.f && x.n !== y.n) {
852
+ const a = v(eq(x.a, y.a)), b = v(eq(x.n, y.n));
853
+ if (a !== undefined && b !== undefined)
854
+ add([-a, b], -1);
855
+ }
856
+ }
857
+ for (const { s, lo, hi } of succs) {
858
+ add([-s, -v(le(hi, lo))], -1);
859
+ for (const z of ords)
860
+ if (z !== lo && z !== hi)
861
+ add([-s, v(le(z, lo)), v(le(hi, z))], -1);
862
+ }
863
+ for (const [, cells] of ordCells)
864
+ for (let i = 0; i < cells.length; i++)
865
+ for (let j = i + 1; j < cells.length; j++) {
866
+ const a = cells[i], b = cells[j], pre = a.parts.map((x, k) => v(eq(x, b.parts[k]))).filter((e) => e !== undefined).map(e => -e);
867
+ add([...pre, v(le(a.id, b.id))], -1);
868
+ add([...pre, v(le(b.id, a.id))], -1);
869
+ }
870
+ }
871
+ for (const f of fins.values()) {
872
+ const ls = Array.from({ length: f.cap + 1 }, (_, val) => v(finAt(f, val)));
873
+ add(ls, f.exact ?? -1);
874
+ for (let i = 0; i < ls.length; i++)
875
+ for (let j = i + 1; j < ls.length; j++)
876
+ add([-ls[i], -ls[j]], -1);
877
+ }
878
+ if (theory.length && !opts.fresh)
879
+ for (const l of lemmaCache.values()) {
880
+ const xs = l.map(([k, b]) => { const x = ids.get(k); return x === undefined ? undefined : b ? x : -x; });
881
+ if (xs.every((x) => x !== undefined))
882
+ add(xs, -1);
883
+ }
884
+ // EPR-shaped: no comparison the abstraction can't read (a counter's arithmetic, a sum, a product) in any hypothesis
885
+ if (opts.exact) {
886
+ const tied = new Set([...keyEqs, ...intervals].map(k => k.p.v));
887
+ const loose = [...foreign].filter(i => !tied.has(i)).length;
888
+ if (loose)
889
+ return { unknown: `${loose} comparisons outside the EPR shape` };
890
+ }
891
+ // --- the search
892
+ // (a finite variable at 0 first: models with the least values, which break the fewest laws at keys nothing names)
893
+ const first = new Set([...fins.values()].map(f => v(finAt(f, 0))));
894
+ if (opts.late?.())
895
+ return { unknown: 'past the deadline' };
896
+ // (lazily: the transitivity a model breaks, added and the search again, at most 4,096 a round and 16 rounds; as each
897
+ // holds in every model, a refutation stays one)
898
+ // (one solver, the lemmas added to it: the search goes on from what it learned)
899
+ // (the order's atoms and the theory's comparisons keep the phase of the last model: a lemma then moves the next model
900
+ // as little as it must, not to the search's first choices again)
901
+ const kept = new Set([...ids].filter(([k]) => k.startsWith('le ')).map(([, x]) => x).concat(theory.map(t => t.x)));
902
+ let solver = cdclSolver(clauses, first, kept);
903
+ const lemma = (lits) => { const n0 = clauses.length; add(lits, -1); if (clauses.length > n0 && !solver.add(clauses.at(-1)))
904
+ solver = cdclSolver(clauses, first, kept); };
905
+ const search = () => {
906
+ let o = solver.solve(opts.conflicts ?? 200_000, opts.late);
907
+ for (let round = 0; lazy && o?.sat; round++) {
908
+ const m = o.model, os = [...ords], at = (a, b) => a === b || m[v(le(a, b))] === true, broken = [];
909
+ for (const a of os)
910
+ for (const b of os)
911
+ if (a !== b && at(a, b))
912
+ for (const c of os)
913
+ if (c !== a && c !== b && at(b, c) && !at(a, c) && broken.length < 4096)
914
+ broken.push([-v(le(a, b)), -v(le(b, c)), v(le(a, c))]);
915
+ if (!broken.length)
916
+ break;
917
+ if (round === 16 || opts.late?.())
918
+ return 'the order\'s transitivity, lazily, did not settle';
919
+ for (const c of broken)
920
+ lemma(c);
921
+ o = solver.solve(opts.conflicts ?? 200_000, opts.late);
922
+ }
923
+ return o;
924
+ };
925
+ // (the model's order, its groups of equal terms in order: the read-back's and the theory's)
926
+ const groupsOf = (m) => {
927
+ const leq = (a, b) => a === b || m[v(le(a, b))] === true;
928
+ const os = [...ords].sort((a, b) => (leq(a, b) && !leq(b, a) ? -1 : leq(b, a) && !leq(a, b) ? 1 : 0)), groups = [];
929
+ for (let i = 0; i < os.length;) {
930
+ let j = i;
931
+ while (j < os.length && leq(os[j], os[i]) && leq(os[i], os[j]))
932
+ j++;
933
+ groups.push(os.slice(i, j));
934
+ i = j;
935
+ }
936
+ return groups;
937
+ };
938
+ // The theory's check of a model: its order (each group's terms equal, each group below the next, a successor the next
939
+ // value), every ordered term a natural, each theory comparison as the model has it, solved over the integers. Sat: the
940
+ // values, the read-back's; refuted: the model's literals its refutation reads, whose negation holds in every model (a
941
+ // theory lemma, DPLL(T)'s), added and the search again.
942
+ // (first over the theory's own terms, each pair as the model orders it, so that a lemma names them alone; then every
943
+ // term, the model's order as its groups, for the values)
944
+ const theoryTerms = [...new Set(theory.flatMap(t => Object.keys(t.d).filter(x => x !== '1')))];
945
+ // (each comparison's literals: its own and its terms' order, among them and with the constants)
946
+ const feasible = [], locals = [];
947
+ const localOf = (ti, t, ks) => {
948
+ if (locals[ti])
949
+ return locals[ti];
950
+ const xs = Object.keys(t.d).filter(x => x !== '1'), out = [t.x];
951
+ for (let i2 = 0; i2 < xs.length; i2++)
952
+ for (const b of [...xs.slice(i2 + 1), ...ks])
953
+ for (const [p, q] of [[xs[i2], b], [b, xs[i2]]]) {
954
+ const x = v(le(p, q));
955
+ if (x !== undefined)
956
+ out.push(x);
957
+ }
958
+ return (locals[ti] = out);
959
+ };
960
+ const jointLp = new Simplex(true);
961
+ // (each pair's order atoms and its four rows, a ≤ b, b < a, b ≤ a, a < b, made once: the same rows every round, which
962
+ // the simplex knows by their objects)
963
+ const pairs0 = new Map();
964
+ const pairOf = (a, b) => {
965
+ const key = `${a}|${b}`;
966
+ let p = pairs0.get(key);
967
+ if (!p) {
968
+ const T = (t) => (t.startsWith('k:') ? konst(Number(t.slice(2))) : tv(t));
969
+ p = { ab: v(le(a, b)), ba: v(le(b, a)), rows: [plus(T(a), times(T(b), -1)), plus(plus(T(b), konst(1)), times(T(a), -1)), plus(T(b), times(T(a), -1)), plus(plus(T(a), konst(1)), times(T(b), -1))] };
970
+ pairs0.set(key, p);
971
+ }
972
+ return p;
973
+ };
974
+ const theoryCheck = (m) => {
975
+ const T = (t) => (t.startsWith('k:') ? konst(Number(t.slice(2))) : tv(t));
976
+ const theoryRows = (row) => {
977
+ for (const t of theory) {
978
+ const holds = m[t.x] === true;
979
+ if (t.op === '=') {
980
+ if (holds) {
981
+ row(t.d, [t.x]);
982
+ row(times(t.d, -1), [t.x]);
983
+ }
984
+ continue;
985
+ }
986
+ // a − b < 0 is a − b + 1 ≤ 0; its negation b − a ≤ 0; a − b ≤ 0's negation b − a + 1 ≤ 0
987
+ if (holds)
988
+ row(t.op === '<' ? plus(t.d, konst(1)) : t.d, [t.x]);
989
+ else
990
+ row(t.op === '<' ? times(t.d, -1) : plus(times(t.d, -1), konst(1)), [-t.x]);
991
+ }
992
+ };
993
+ const lemmaOf = (r, lits) => {
994
+ if (r.kind !== 'refuted')
995
+ return undefined;
996
+ const used = new Set();
997
+ for (const st of r.steps)
998
+ if (st.kind === 'input')
999
+ for (const l of lits[st.index])
1000
+ used.add(l);
1001
+ return used.size ? [...used].map(l => -l) : undefined;
1002
+ };
1003
+ const pairRows = (row, a, b) => {
1004
+ const p = pairOf(a, b);
1005
+ if (m[p.ab] === true)
1006
+ row(p.rows[0], [p.ab]);
1007
+ else
1008
+ row(p.rows[1], [-p.ab]);
1009
+ if (m[p.ba] === true)
1010
+ row(p.rows[2], [p.ba]);
1011
+ else
1012
+ row(p.rows[3], [-p.ba]);
1013
+ };
1014
+ // (each comparison alone first, with its terms' order and the constants: a lemma of a few literals for each the
1015
+ // model breaks, all of them in one round; one the model reads as an earlier model did, feasible then, not again)
1016
+ {
1017
+ const ks = [...ords].filter(t => t.startsWith('k:')), lemmas = [];
1018
+ for (const [ti, t] of theory.entries()) {
1019
+ const local = localOf(ti, t, ks), seen = (feasible[ti] ??= new Set()), key = local.map(l => (m[l] === true ? '1' : '0')).join('');
1020
+ if (seen.has(key))
1021
+ continue;
1022
+ const rows = [], lits = [], row = (lin, ls) => { rows.push({ lin, label: '' }); lits.push(ls); };
1023
+ const xs = Object.keys(t.d).filter(x => x !== '1');
1024
+ for (const x of xs)
1025
+ row(times(tv(x), -1), []);
1026
+ for (let i2 = 0; i2 < xs.length; i2++) {
1027
+ for (let j = i2 + 1; j < xs.length; j++)
1028
+ pairRows(row, xs[i2], xs[j]);
1029
+ for (const k2 of ks)
1030
+ pairRows(row, xs[i2], k2);
1031
+ }
1032
+ const holds = m[t.x] === true;
1033
+ if (t.op === '=') {
1034
+ if (holds) {
1035
+ row(t.d, [t.x]);
1036
+ row(times(t.d, -1), [t.x]);
1037
+ }
1038
+ else
1039
+ continue;
1040
+ }
1041
+ else if (holds)
1042
+ row(t.op === '<' ? plus(t.d, konst(1)) : t.d, [t.x]);
1043
+ else
1044
+ row(t.op === '<' ? times(t.d, -1) : plus(times(t.d, -1), konst(1)), [-t.x]);
1045
+ const l = lemmaOf(solve(rows), lits);
1046
+ if (l)
1047
+ lemmas.push(l);
1048
+ else
1049
+ seen.add(key);
1050
+ }
1051
+ if (lemmas.length)
1052
+ return { lemmas };
1053
+ }
1054
+ {
1055
+ const rows = [], lits = [], row = (lin, ls) => { rows.push({ lin, label: '' }); lits.push(ls); };
1056
+ // (the pairs of terms one comparison reads, and each with the constants)
1057
+ const ks = [...ords].filter(t => t.startsWith('k:')), pairs = new Map();
1058
+ for (const t of theory) {
1059
+ const xs = Object.keys(t.d).filter(x => x !== '1');
1060
+ for (const a of xs)
1061
+ for (const b of [...xs, ...ks])
1062
+ if (a !== b)
1063
+ pairs.set(a < b ? `${a}|${b}` : `${b}|${a}`, a < b ? [a, b] : [b, a]);
1064
+ }
1065
+ // (with few ordered terms, every pair of them: a refutation through a term no comparison reads, a chain of the
1066
+ // order, is then a lemma of the pairs it needs, not of the whole order)
1067
+ const all = ords.size <= 48 ? [...ords] : [];
1068
+ for (let i2 = 0; i2 < all.length; i2++)
1069
+ for (let j = i2 + 1; j < all.length; j++) {
1070
+ const a = all[i2], b = all[j];
1071
+ if (!(a.startsWith('k:') && b.startsWith('k:')))
1072
+ pairs.set(a < b ? `${a}|${b}` : `${b}|${a}`, a < b ? [a, b] : [b, a]);
1073
+ }
1074
+ for (const t of new Set([...theoryTerms, ...all.filter(x => !x.startsWith('k:'))]))
1075
+ row(times(tv(t), -1), []);
1076
+ for (const [a, b] of pairs.values())
1077
+ pairRows(row, a, b);
1078
+ // (and the successors the model holds among them, n1 = n + 1, both ways: the ring's next node)
1079
+ const tt = new Set([...theoryTerms, ...all]);
1080
+ for (const x of succs)
1081
+ if (m[x.s] && (tt.has(x.lo) || tt.has(x.hi))) {
1082
+ row(plus(T(x.hi), times(plus(T(x.lo), konst(1)), -1)), [x.s]);
1083
+ row(plus(plus(T(x.lo), konst(1)), times(T(x.hi), -1)), [x.s]);
1084
+ for (const y of [x.lo, x.hi])
1085
+ if (!tt.has(y) && !y.startsWith('k:'))
1086
+ row(times(tv(y), -1), []);
1087
+ }
1088
+ theoryRows(row);
1089
+ // (several lemmas a round: each refutation's theory rows set aside, the rest solved again, at most eight)
1090
+ // (each by the simplex first (kernel/simplex.ts, the CDCL search's, its tableau kept from round to round): its
1091
+ // conflict's rows refuted exactly (core/solver.ts), the lemma the literals that refutation reads; no answer, the
1092
+ // first time by elimination over them all, as before; feasible, or a conflict the floats misjudge, no more lemmas)
1093
+ const lemmas = [], off = new Set(), theoryLits = new Set(theory.flatMap(t => [t.x, -t.x]));
1094
+ for (let k = 0; k < 8; k++) {
1095
+ const keep = rows.map((_, i) => i).filter(i => !off.has(i)), sub = keep.map(i => rows[i]), subLits = keep.map(i => lits[i]);
1096
+ let r = jointLp.load(sub);
1097
+ if (r.kind === 'sat')
1098
+ r = jointLp.check();
1099
+ if (r.kind === 'sat')
1100
+ break;
1101
+ const l = r.kind === 'conflict' ? lemmaOf(solve(r.rows.map(i => sub[i])), r.rows.map(i => subLits[i])) : k ? undefined : lemmaOf(solve(sub), subLits);
1102
+ if (!l)
1103
+ break;
1104
+ lemmas.push(l);
1105
+ keep.forEach(i => { if (lits[i].some(x => theoryLits.has(x) && l.includes(-x)))
1106
+ off.add(i); });
1107
+ }
1108
+ if (lemmas.length)
1109
+ return { lemmas };
1110
+ }
1111
+ const rows = [], lits = [], row = (lin, ls) => { rows.push({ lin, label: '' }); lits.push(ls); };
1112
+ const groups = groupsOf(m);
1113
+ for (const t of ords)
1114
+ if (!t.startsWith('k:'))
1115
+ row(times(tv(t), -1), []);
1116
+ for (const [gi, g] of groups.entries()) {
1117
+ for (const t of g.slice(1)) {
1118
+ row(plus(T(t), times(T(g[0]), -1)), [v(le(t, g[0]))]);
1119
+ row(plus(T(g[0]), times(T(t), -1)), [v(le(g[0], t))]);
1120
+ }
1121
+ const h = groups[gi + 1];
1122
+ if (h)
1123
+ row(plus(plus(T(g[0]), konst(1)), times(T(h[0]), -1)), [-v(le(h[0], g[0]))]);
1124
+ }
1125
+ for (const x of succs)
1126
+ if (m[x.s])
1127
+ row(plus(T(x.hi), times(plus(T(x.lo), konst(1)), -1)), [x.s]);
1128
+ theoryRows(row);
1129
+ // (the simplex first, as the joint check: a conflict's rows refuted exactly; its point the values where every term is
1130
+ // a natural there and every row holds exactly, with elimination's (as before) for a read-back they break; else
1131
+ // elimination over them all)
1132
+ let q = jointLp.load(rows);
1133
+ if (q.kind === 'sat')
1134
+ q = jointLp.check();
1135
+ if (q.kind === 'conflict') {
1136
+ const l = lemmaOf(solve(q.rows.map(i => rows[i])), q.rows.map(i => lits[i]));
1137
+ if (l)
1138
+ return { lemmas: [l] };
1139
+ }
1140
+ const exact = () => {
1141
+ const r = solve(rows);
1142
+ if (r.kind === 'sat')
1143
+ return { val: new Map([...ords].map(t => [t, t.startsWith('k:') ? Number(t.slice(2)) : r.witness[t] ?? 0])) };
1144
+ const l = lemmaOf(r, lits);
1145
+ return l && { lemmas: [l] };
1146
+ };
1147
+ if (q.kind === 'sat') {
1148
+ const at = (t) => { const j = jointLp.indexOf(t); return j === undefined ? 0 : jointLp.value(j); };
1149
+ const val = new Map([...ords].map(t => [t, t.startsWith('k:') ? Number(t.slice(2)) : Math.round(at(t))]));
1150
+ const ok = [...ords].every(t => t.startsWith('k:') || (Math.abs(at(t) - val.get(t)) < 1e-6 && val.get(t) >= 0))
1151
+ && rows.every(row => Object.entries(row.lin).reduce((x, [k, c]) => x + c * (k === '1' ? 1 : val.get(k) ?? 0), 0) <= 0);
1152
+ if (ok)
1153
+ return { val, exact };
1154
+ }
1155
+ return exact();
1156
+ };
1157
+ const outcome = (o) => (typeof o === 'string' ? { unknown: o } : o === undefined ? { unknown: 'the conflict budget ran out, or the deadline' }
1158
+ : !o.sat ? { sat: false, core: [...o.core].filter(i => i >= 0).sort((a, b) => a - b) } : { model: o.model });
1159
+ // --- a model, read back: the ordered terms (the parts among them) by the model's order, each composed key the radix
1160
+ // sum of its parts, each cell and scalar its value; then judged on every hypothesis
1161
+ // (the read-back with the theory's values, where it checked the model; where they break a hypothesis, the order's own
1162
+ // grouping, as without one)
1163
+ const finish = (model, theoryVal) => {
1164
+ const val = (l) => model[l] === true;
1165
+ const w = {};
1166
+ for (const f of fins.values()) {
1167
+ let x = 0;
1168
+ for (let val2 = 0; val2 <= f.cap; val2++)
1169
+ if (val(v(finAt(f, val2))))
1170
+ x = val2;
1171
+ if (f.id.startsWith('s:'))
1172
+ w[f.id.slice(2)] = x;
1173
+ }
1174
+ // each group of equal terms the next value, a constant's group its own; odd where there is room before the next constant
1175
+ // (a key of the wrong sort, 2·64·x + y, then meets no cell 64·x' + y), and far apart past every constant (composed keys
1176
+ // of parts above every bound then don't meet)
1177
+ // (where the theory checked the model, its values)
1178
+ const ordVal = theoryVal ?? new Map();
1179
+ if (!theoryVal) {
1180
+ const groups = groupsOf(model);
1181
+ const constOf = (g) => { const cs = [...new Set(g.filter(x => x.startsWith('k:')).map(x => Number(x.slice(2))))]; return cs.length > 1 ? NaN : cs[0]; };
1182
+ // (a successor the model holds, n1 = n + 1, makes its two groups consecutive values: such a chain is one block, its
1183
+ // first group's value the next free one, or its constant's less the steps to it)
1184
+ const groupOf = new Map();
1185
+ groups.forEach((g, i) => g.forEach(t => groupOf.set(t, i)));
1186
+ const tight = new Set(succs.filter(x => val(x.s)).map(x => `${groupOf.get(x.lo)}>${groupOf.get(x.hi)}`));
1187
+ const tied = (i) => tight.has(`${i}>${i + 1}`);
1188
+ let prev = -1, far = 0;
1189
+ for (const [gi, g] of groups.entries()) {
1190
+ const c = constOf(g);
1191
+ if (Number.isNaN(c))
1192
+ return { unknown: 'the model\'s order equates two constants' };
1193
+ let next = Infinity;
1194
+ for (const h of groups.slice(gi + 1)) {
1195
+ const d = constOf(h);
1196
+ if (d !== undefined) {
1197
+ next = d;
1198
+ break;
1199
+ }
1200
+ }
1201
+ let x = c ?? (next === Infinity && prev > 0 ? (1 << 24) * ++far + 997 * far + prev + 13 : prev + 1);
1202
+ if (c === undefined && next !== Infinity && x % 2 === 0 && x + 1 < next)
1203
+ x++;
1204
+ if (c === undefined && gi > 0 && tied(gi - 1))
1205
+ x = prev + 1;
1206
+ else if (c === undefined) {
1207
+ let k = gi;
1208
+ while (tied(k) && constOf(groups[k + 1]) === undefined)
1209
+ k++;
1210
+ const d = tied(k) ? constOf(groups[k + 1]) : undefined;
1211
+ if (d !== undefined)
1212
+ x = d - (k + 1 - gi);
1213
+ }
1214
+ if (x <= prev || x >= next || (gi > 0 && tied(gi - 1) && x !== prev + 1))
1215
+ return { unknown: noRoom };
1216
+ for (const t of g)
1217
+ ordVal.set(t, x);
1218
+ prev = x;
1219
+ }
1220
+ }
1221
+ for (const [t, x] of ordVal)
1222
+ if (t.startsWith('p:') || t.startsWith('s:'))
1223
+ w[t.slice(2)] = x;
1224
+ const maps = new Map();
1225
+ const cellVal = new Map();
1226
+ for (const f of fins.values())
1227
+ if (f.id.startsWith('c:')) {
1228
+ let x = 0;
1229
+ for (let val2 = 0; val2 <= f.cap; val2++)
1230
+ if (val(v(finAt(f, val2))))
1231
+ x = val2;
1232
+ cellVal.set(f.id, x);
1233
+ }
1234
+ for (const [mp, cells] of ordCells)
1235
+ for (const c of cells) {
1236
+ cellVal.set(c.id, ordVal.get(c.id) ?? 0);
1237
+ if (!cellsOf.has(mp))
1238
+ cellsOf.set(mp, []);
1239
+ cellsOf.get(mp).push(c);
1240
+ }
1241
+ for (const o of ordOdd) {
1242
+ cellVal.set(o.id, ordVal.get(o.id) ?? 0);
1243
+ odd.push(o);
1244
+ }
1245
+ // every read of the goal, at its key's value under w: the abstraction's value where it has one, else 0
1246
+ const keyVal = (e) => { const ts = [], d = { c: 0 }; if (!linTerms(e, 1, ts, d))
1247
+ return undefined; let s = d.c; for (const [x, c] of ts) {
1248
+ if (w[x] === undefined)
1249
+ return undefined;
1250
+ s += c * w[x];
1251
+ } return s; };
1252
+ // (each function's table at its parts' values)
1253
+ for (const { f, n, a } of fnParts) {
1254
+ if (!maps.has(f))
1255
+ maps.set(f, new Map());
1256
+ maps.get(f).set(w[a], w[n]);
1257
+ }
1258
+ // (and at a key of the wrong sort, a value of its own past every value the model gives: an injective function's
1259
+ // instance there holds, and a key it is a part of meets no cell of the right sort)
1260
+ let fresh2 = Math.max(0, ...Object.values(w), ...[...maps.values()].flatMap(t => [...t.values()]));
1261
+ // (a key that reads such a read, idn(64·idn(64·m + n) + n): its value from the tables so far, inner reads first)
1262
+ const valueAt = (e) => {
1263
+ if (e.op === 'const')
1264
+ return e.value;
1265
+ if (e.op === 'var')
1266
+ return w[e.name] ?? 0;
1267
+ if (e.op === 'mul') {
1268
+ const a = valueAt(e.a);
1269
+ return a === undefined ? undefined : a * e.k;
1270
+ }
1271
+ if (e.op === 'add') {
1272
+ const a = valueAt(e.a), b = valueAt(e.b);
1273
+ return a === undefined || b === undefined ? undefined : a + b;
1274
+ }
1275
+ if (e.op === 'get' && fnMaps.has(e.map)) {
1276
+ const k = valueAt(e.key);
1277
+ return k === undefined ? undefined : maps.get(e.map)?.get(k);
1278
+ }
1279
+ return undefined;
1280
+ };
1281
+ // (the reads gathered, the inner ones first: each read is gathered before the reads in its key)
1282
+ const fnOdd = (x) => {
1283
+ tick();
1284
+ if (!fnMaps.has(x.map) || partName(x) !== undefined)
1285
+ return;
1286
+ const key = keyVal(x.key) ?? valueAt(x.key), t = maps.get(x.map) ?? new Map();
1287
+ if (key === undefined || t.has(key))
1288
+ return;
1289
+ maps.set(x.map, t.set(key, ordVal.get(`c:${x.map}#${textOfE(x.key)}`) ?? ++fresh2));
1290
+ };
1291
+ [...reads].reverse().forEach(fnOdd);
1292
+ for (const [mp, cells] of cellsOf)
1293
+ for (const c of cells) {
1294
+ const key = c.parts.reduce((s, p, i) => s + w[p] * (patterns[mp][i] ?? 1), 0);
1295
+ if (!maps.has(mp))
1296
+ maps.set(mp, new Map());
1297
+ maps.get(mp).set(key, cellVal.get(c.id));
1298
+ }
1299
+ // (a cell at a key of the wrong sort, where its key falls, unless a cell of the right sort is there: one cell, whose
1300
+ // value the hypotheses are judged with below)
1301
+ for (const o of odd) {
1302
+ const key = keyVal(o.key) ?? valueAt(o.key);
1303
+ if (key === undefined)
1304
+ continue;
1305
+ if (!maps.has(o.map))
1306
+ maps.set(o.map, new Map());
1307
+ if (!maps.get(o.map).has(key))
1308
+ maps.get(o.map).set(key, cellVal.get(o.id));
1309
+ }
1310
+ const allMaps = new Set();
1311
+ for (const x of reads)
1312
+ allMaps.add(x.map);
1313
+ const st = { scalars: {}, maps: Object.fromEntries([...allMaps].map(mp => [mp, maps.get(mp) ?? new Map()])) };
1314
+ const m = { name: goal.name, params: [], inputs: [], state: {}, step: {}, maps: Object.fromEntries([...allMaps].map(mp => [mp, 0])) };
1315
+ const env = new Proxy({ ...w }, { get: (t, q) => t[q] ?? 0 });
1316
+ for (const [i, h] of goal.hyps.entries()) {
1317
+ tick();
1318
+ try {
1319
+ if (!evalC(h, env, st, m)) {
1320
+ return { unknown: `the abstraction's model breaks hypothesis ${i}${shaped[i] ? '' : ' (not EPR-shaped)'}` };
1321
+ }
1322
+ }
1323
+ catch {
1324
+ return { unknown: 'the model could not be read' };
1325
+ }
1326
+ }
1327
+ // the kernel's witness: names, and each cell of the goal by its key's linear form
1328
+ const witness = { ...w };
1329
+ for (const x of reads) {
1330
+ tick();
1331
+ const l = linear(x.key, new Map()), kv = keyVal(x.key);
1332
+ if (l && kv !== undefined)
1333
+ witness[`${x.map}[${canon(l)}]`] = st.maps[x.map]?.get(kv) ?? 0;
1334
+ }
1335
+ // the structure
1336
+ const values = [...new Set([...[...parts].map(x => w[x]), ...[...ordVal].filter(([t]) => !t.startsWith('k:') && !t.includes('#')).map(([, x]) => x)].filter((x) => x !== undefined))].sort((a, b) => a - b), elem = new Map(values.map((x, i) => [x, i]));
1337
+ const diagram = { elements: values.length, parts: {}, scalars: {}, cells: {}, fns: {} };
1338
+ for (const x of [...parts, ...ordScalars].sort())
1339
+ if (w[x] !== undefined)
1340
+ diagram.parts[x] = elem.get(w[x]);
1341
+ for (const f of fins.values())
1342
+ if (f.id.startsWith('s:'))
1343
+ diagram.scalars[f.id.slice(2)] = w[f.id.slice(2)] ?? 0;
1344
+ for (const [mp, cells] of cellsOf) {
1345
+ const seen2 = new Set(), out = [];
1346
+ for (const c of cells) {
1347
+ const at = c.parts.map(x => elem.get(w[x])), id = at.join(','), value = cellVal.get(c.id);
1348
+ if (!seen2.has(id)) {
1349
+ seen2.add(id);
1350
+ out.push({ at, value: ordMaps.has(mp) ? elem.get(value) ?? value : value });
1351
+ }
1352
+ }
1353
+ diagram.cells[mp] = out.sort((a, b) => { for (let i = 0; i < a.at.length; i++)
1354
+ if (a.at[i] !== b.at[i])
1355
+ return a.at[i] - b.at[i]; return 0; });
1356
+ }
1357
+ for (const { f, n, a } of fnParts) {
1358
+ const t = (diagram.fns[f] ??= []), x = elem.get(w[a]);
1359
+ if (!t.some(r => r[0] === x))
1360
+ t.push([x, elem.get(w[n])]);
1361
+ }
1362
+ for (const t of Object.values(diagram.fns))
1363
+ t.sort((a, b) => a[0] - b[0]);
1364
+ return { sat: true, witness, diagram };
1365
+ };
1366
+ // (the order's grouping first, as without a theory; where it breaks a hypothesis, the theory's rounds: lemmas the model
1367
+ // breaks, the search again, until the theory checks a model, its values the read-back's)
1368
+ let cur = outcome(search());
1369
+ if (!('model' in cur))
1370
+ return cur;
1371
+ let done = finish(cur.model, undefined);
1372
+ for (let round = 0; theory.length && 'unknown' in done && round < 256 && !opts.late?.(); round++) {
1373
+ let r = theoryCheck(cur.model);
1374
+ if (!r)
1375
+ break;
1376
+ if ('val' in r) {
1377
+ done = finish(cur.model, r.val);
1378
+ // (the simplex's values breaking it: elimination's)
1379
+ if ('unknown' in done && r.exact) {
1380
+ r = r.exact();
1381
+ if (r && 'val' in r)
1382
+ done = finish(cur.model, r.val);
1383
+ }
1384
+ if (r && !('val' in r)) {
1385
+ for (const l of r.lemmas)
1386
+ lemma(l);
1387
+ cur = outcome(search());
1388
+ if (!('model' in cur))
1389
+ return cur;
1390
+ done = finish(cur.model, undefined);
1391
+ continue;
1392
+ }
1393
+ if ('unknown' in done)
1394
+ done = finish(cur.model, undefined);
1395
+ break;
1396
+ }
1397
+ for (const l of r.lemmas) {
1398
+ lemma(l);
1399
+ const named = l.map((x) => [names[Math.abs(x)], x > 0]), key = named.map(([k, b]) => (b ? '' : '¬') + k).sort().join('|');
1400
+ if (lemmaCache.size > 20_000)
1401
+ lemmaCache.clear();
1402
+ lemmaCache.set(key, named);
1403
+ }
1404
+ cur = outcome(search());
1405
+ if (!('model' in cur))
1406
+ return cur;
1407
+ done = finish(cur.model, undefined);
1408
+ }
1409
+ return done;
1410
+ }
1411
+ function cdcl(input, budget, trueFirst = new Set(), late) {
1412
+ return cdclSolver(input, trueFirst).solve(budget, late);
1413
+ }
1414
+ // The CDCL as a solver clauses can be added to between its answers (a lemma a model breaks, lazily): each added at level
1415
+ // 0, the search again from there with what it learned. `add` false: a clause over a variable it doesn't have.
1416
+ function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1417
+ let n = 0;
1418
+ for (const c of input)
1419
+ for (const l of c.lits)
1420
+ n = Math.max(n, Math.abs(l));
1421
+ const idx = new Map(), back = [0];
1422
+ const vid = (l) => { const a = Math.abs(l); let i = idx.get(a); if (i === undefined) {
1423
+ i = back.length;
1424
+ idx.set(a, i);
1425
+ back.push(a);
1426
+ } return l > 0 ? i : -i; };
1427
+ const cls = input.map(c => ({ lits: c.lits.map(vid), from: new Set([c.from]) }));
1428
+ const nv = back.length, val = new Int8Array(nv), level = new Int32Array(nv), reason = Array(nv), act = new Float64Array(nv);
1429
+ const watch = new Map();
1430
+ const wl = (l) => { let w = watch.get(l); if (!w)
1431
+ watch.set(l, (w = [])); return w; };
1432
+ const valOf = (l) => (val[Math.abs(l)] === 0 ? 0 : (val[Math.abs(l)] > 0) === (l > 0) ? 1 : -1);
1433
+ const trail = [], lim = [];
1434
+ const phase = new Int8Array(nv);
1435
+ const assign = (l, r) => { val[Math.abs(l)] = l > 0 ? 1 : -1; level[Math.abs(l)] = lim.length; reason[Math.abs(l)] = r; trail.push(l); };
1436
+ let qhead = 0, fixed = 'none';
1437
+ const units = [];
1438
+ for (const c of cls) {
1439
+ if (!c.lits.length) {
1440
+ fixed = { sat: false, core: c.from };
1441
+ break;
1442
+ }
1443
+ if (c.lits.length === 1)
1444
+ units.push(c);
1445
+ else {
1446
+ wl(-c.lits[0]).push(c);
1447
+ wl(-c.lits[1]).push(c);
1448
+ }
1449
+ }
1450
+ const coreOf = (c) => {
1451
+ const out = new Set(c.from), seen = new Set(), todo = c.lits.map(Math.abs);
1452
+ while (todo.length) {
1453
+ const x = todo.pop();
1454
+ if (seen.has(x))
1455
+ continue;
1456
+ seen.add(x);
1457
+ const r = reason[x];
1458
+ if (r) {
1459
+ for (const o of r.from)
1460
+ out.add(o);
1461
+ for (const l of r.lits)
1462
+ todo.push(Math.abs(l));
1463
+ }
1464
+ }
1465
+ return out;
1466
+ };
1467
+ for (const u of units) {
1468
+ if (fixed !== 'none')
1469
+ break;
1470
+ const s = valOf(u.lits[0]);
1471
+ if (s < 0) {
1472
+ fixed = { sat: false, core: coreOf(u) };
1473
+ break;
1474
+ }
1475
+ if (s === 0)
1476
+ assign(u.lits[0], u);
1477
+ }
1478
+ const propagate = () => {
1479
+ while (qhead < trail.length) {
1480
+ const l = trail[qhead++], ws = wl(l);
1481
+ for (let i = 0; i < ws.length; i++) {
1482
+ const c = ws[i];
1483
+ if (c.lits[0] === -l) {
1484
+ c.lits[0] = c.lits[1];
1485
+ c.lits[1] = -l;
1486
+ }
1487
+ if (valOf(c.lits[0]) > 0)
1488
+ continue;
1489
+ let moved = false;
1490
+ for (let k = 2; k < c.lits.length; k++)
1491
+ if (valOf(c.lits[k]) >= 0) {
1492
+ const t = c.lits[1];
1493
+ c.lits[1] = c.lits[k];
1494
+ c.lits[k] = t;
1495
+ wl(-c.lits[1]).push(c);
1496
+ ws.splice(i--, 1);
1497
+ moved = true;
1498
+ break;
1499
+ }
1500
+ if (moved)
1501
+ continue;
1502
+ if (valOf(c.lits[0]) < 0) {
1503
+ qhead = trail.length;
1504
+ return c;
1505
+ }
1506
+ assign(c.lits[0], c);
1507
+ }
1508
+ }
1509
+ return undefined;
1510
+ };
1511
+ // (the unassigned variables in a heap, the most active first, ties by the lower index: the choice a scan over them
1512
+ // makes, without the scan; an assigned one is dropped where it surfaces and put back when unassigned)
1513
+ const heap = [], at = new Int32Array(nv).fill(-1);
1514
+ const above = (a, b) => act[a] > act[b] || (act[a] === act[b] && a < b);
1515
+ const up = (i) => { const x = heap[i]; while (i > 0) {
1516
+ const pi = (i - 1) >> 1, y = heap[pi];
1517
+ if (!above(x, y))
1518
+ break;
1519
+ heap[i] = y;
1520
+ at[y] = i;
1521
+ i = pi;
1522
+ } heap[i] = x; at[x] = i; };
1523
+ const down = (i) => { const x = heap[i]; for (;;) {
1524
+ let c = 2 * i + 1;
1525
+ if (c >= heap.length)
1526
+ break;
1527
+ if (c + 1 < heap.length && above(heap[c + 1], heap[c]))
1528
+ c++;
1529
+ if (!above(heap[c], x))
1530
+ break;
1531
+ heap[i] = heap[c];
1532
+ at[heap[i]] = i;
1533
+ i = c;
1534
+ } heap[i] = x; at[x] = i; };
1535
+ const push = (x) => { if (at[x] >= 0)
1536
+ return; heap.push(x); at[x] = heap.length - 1; up(heap.length - 1); };
1537
+ const pop = () => { const x = heap[0], y = heap.pop(); at[x] = -1; if (heap.length) {
1538
+ heap[0] = y;
1539
+ at[y] = 0;
1540
+ down(0);
1541
+ } return x; };
1542
+ for (let x = 1; x < nv; x++)
1543
+ push(x);
1544
+ let inc = 1;
1545
+ const backjump = (bt) => { while (lim.length > bt) {
1546
+ const to = lim.pop();
1547
+ while (trail.length > to) {
1548
+ const x = Math.abs(trail.pop());
1549
+ val[x] = 0;
1550
+ reason[x] = undefined;
1551
+ push(x);
1552
+ }
1553
+ } qhead = Math.min(qhead, trail.length); };
1554
+ const add = (c) => {
1555
+ if (fixed !== 'none' && fixed?.sat === false)
1556
+ return true;
1557
+ if (c.lits.some(l => !idx.has(Math.abs(l))))
1558
+ return false;
1559
+ backjump(0);
1560
+ fixed = 'none';
1561
+ const cl = { lits: c.lits.map(vid), from: new Set([c.from]) };
1562
+ if (cl.lits.some(l => valOf(l) > 0))
1563
+ return true;
1564
+ const open = cl.lits.filter(l => valOf(l) === 0);
1565
+ if (!open.length) {
1566
+ fixed = { sat: false, core: coreOf(cl) };
1567
+ return true;
1568
+ }
1569
+ cl.lits = [...open, ...cl.lits.filter(l => valOf(l) < 0)];
1570
+ if (open.length === 1)
1571
+ assign(open[0], cl);
1572
+ else {
1573
+ wl(-cl.lits[0]).push(cl);
1574
+ wl(-cl.lits[1]).push(cl);
1575
+ }
1576
+ return true;
1577
+ };
1578
+ const solve = (budget, late) => {
1579
+ if (fixed !== 'none')
1580
+ return fixed;
1581
+ let conflicts = 0;
1582
+ for (;;) {
1583
+ const confl = propagate();
1584
+ if (confl) {
1585
+ if (++conflicts > budget || (conflicts % 256 === 0 && late?.()))
1586
+ return undefined;
1587
+ if (!lim.length)
1588
+ return (fixed = { sat: false, core: coreOf(confl) });
1589
+ // first UIP
1590
+ const seen = new Uint8Array(nv), learnt = [], from = new Set(confl.from);
1591
+ let p = 0, cnt = 0, c = confl, ti = trail.length - 1;
1592
+ do {
1593
+ for (const q of c.lits) {
1594
+ if (q === p)
1595
+ continue;
1596
+ const x = Math.abs(q);
1597
+ if (!seen[x] && level[x] > 0) {
1598
+ seen[x] = 1;
1599
+ act[x] = act[x] + inc;
1600
+ if (at[x] >= 0)
1601
+ up(at[x]);
1602
+ if (level[x] === lim.length)
1603
+ cnt++;
1604
+ else
1605
+ learnt.push(q);
1606
+ }
1607
+ else if (!seen[x] && level[x] === 0 && reason[x]) {
1608
+ seen[x] = 1;
1609
+ for (const o of coreOf({ lits: [q], from: new Set() }))
1610
+ from.add(o);
1611
+ }
1612
+ }
1613
+ while (!seen[Math.abs(trail[ti])])
1614
+ ti--;
1615
+ p = trail[ti--];
1616
+ c = reason[Math.abs(p)];
1617
+ if (c)
1618
+ for (const o of c.from)
1619
+ from.add(o);
1620
+ cnt--;
1621
+ } while (cnt > 0);
1622
+ learnt.unshift(-p);
1623
+ inc *= 1.05;
1624
+ let bt = 0, bi = 1;
1625
+ for (let i = 1; i < learnt.length; i++)
1626
+ if (level[Math.abs(learnt[i])] > bt) {
1627
+ bt = level[Math.abs(learnt[i])];
1628
+ bi = i;
1629
+ }
1630
+ if (learnt.length > 1) {
1631
+ const t = learnt[1];
1632
+ learnt[1] = learnt[bi];
1633
+ learnt[bi] = t;
1634
+ }
1635
+ while (lim.length > bt) {
1636
+ const to = lim.pop();
1637
+ while (trail.length > to) {
1638
+ const x = Math.abs(trail.pop());
1639
+ val[x] = 0;
1640
+ reason[x] = undefined;
1641
+ push(x);
1642
+ }
1643
+ }
1644
+ qhead = trail.length;
1645
+ const nc = { lits: learnt, from };
1646
+ if (learnt.length > 1) {
1647
+ wl(-learnt[0]).push(nc);
1648
+ wl(-learnt[1]).push(nc);
1649
+ }
1650
+ assign(learnt[0], nc);
1651
+ continue;
1652
+ }
1653
+ // decide: the most active unassigned variable, false first
1654
+ let best = 0;
1655
+ while (heap.length) {
1656
+ const x = pop();
1657
+ if (val[x] === 0) {
1658
+ best = x;
1659
+ break;
1660
+ }
1661
+ }
1662
+ if (!best) {
1663
+ const model = [];
1664
+ for (let x = 1; x < nv; x++) {
1665
+ model[back[x]] = val[x] > 0;
1666
+ if (keepPhase.has(back[x]))
1667
+ phase[x] = val[x];
1668
+ }
1669
+ return { sat: true, model };
1670
+ }
1671
+ lim.push(trail.length);
1672
+ assign(phase[best] ? phase[best] * best : trueFirst.has(back[best]) ? best : -best);
1673
+ }
1674
+ };
1675
+ return { solve, add };
1676
+ }