gdp-wired 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1091,6 +1091,84 @@ export function loopObligations(l, laws, rank) {
1091
1091
  const m = loopMachine(l), { stay, cover, helps } = livenessParts(m, loopLiveness(l, rank));
1092
1092
  return [...obligations(m, laws, {}), ...[stay, cover, ...helps].map(sl => stepLawObligations(m, laws, {}, sl)[0])];
1093
1093
  }
1094
+ // The closure goal, built as Lean's recurGoal builds it: [set, ¬(while ∧ (assume ∧ set after the body)), each read at the
1095
+ // witnessed request].
1096
+ export function recurGoal(l, r) {
1097
+ const w = { vars: r.wit, maps: {}, flags: {} };
1098
+ return { name: `${l.name} never ends: the set is closed`, hyps: [r.set, { op: 'not', x: { op: 'and', xs: [substC(l.while, w), substC(l.assume ?? trueC, w),
1099
+ substC(substC(r.set, { vars: l.body, maps: {}, flags: {} }), w)] } }] };
1100
+ }
1101
+ // Lean's evalE and evalC over naturals with every map cell 0 (NonTerm.lean's noMaps): exact, never rounded.
1102
+ const natE = (e, env) => {
1103
+ switch (e.op) {
1104
+ case 'var': return env[e.name] ?? 0n;
1105
+ case 'const': return BigInt(e.value);
1106
+ case 'add': return natE(e.a, env) + natE(e.b, env);
1107
+ case 'sub': {
1108
+ const d = natE(e.a, env) - natE(e.b, env);
1109
+ return d > 0n ? d : 0n;
1110
+ }
1111
+ case 'mul': return BigInt(e.k) * natE(e.a, env);
1112
+ case 'prod': return natE(e.a, env) * natE(e.b, env);
1113
+ case 'min': {
1114
+ const a = natE(e.a, env), b = natE(e.b, env);
1115
+ return a < b ? a : b;
1116
+ }
1117
+ case 'max': {
1118
+ const a = natE(e.a, env), b = natE(e.b, env);
1119
+ return a > b ? a : b;
1120
+ }
1121
+ case 'if': return natC(e.c, env) ? natE(e.then, env) : natE(e.else, env);
1122
+ case 'get': return 0n;
1123
+ default: return unreachable(e);
1124
+ }
1125
+ };
1126
+ const natC = (c, env) => {
1127
+ switch (c.op) {
1128
+ case '<=': return natE(c.a, env) <= natE(c.b, env);
1129
+ case '<': return natE(c.a, env) < natE(c.b, env);
1130
+ case '=': return natE(c.a, env) === natE(c.b, env);
1131
+ case 'and': return c.xs.every(x => natC(x, env));
1132
+ case 'or': return c.xs.some(x => natC(x, env));
1133
+ case 'not': return !natC(c.x, env);
1134
+ case 'flag':
1135
+ case 'all': throw new Error('a loop reads no flag');
1136
+ default: return unreachable(c);
1137
+ }
1138
+ };
1139
+ // Lean's checkRecur: the witness sets only inputs; the start meets the precondition; the stem's turns meet `while` and
1140
+ // the assumption, and the state after them is in the set; the closure goal's tree checks. A certificate outside the
1141
+ // language (names the loop doesn't declare, values that aren't naturals, a set reading a turn's input) is refused.
1142
+ export function checkRecur(l, r) {
1143
+ const names = [...l.params, ...l.inputs, ...Object.keys(l.state)], values = (o) => Object.values(o).every(x => Number.isSafeInteger(x) && x >= 0);
1144
+ distinct(l.name, names);
1145
+ for (const name of Object.keys(l.body))
1146
+ if (!(name in l.state))
1147
+ throw new Error(`${l.name}'s body sets ${name}, which isn't in its state`);
1148
+ inScope(`${l.name}'s start`, Object.values(l.state), l.params);
1149
+ inScope(l.name, [...Object.values(l.body), ...(l.assume ? [l.assume] : [])], names);
1150
+ inScope(`${l.name}'s while`, [l.while], [...l.params, ...Object.keys(l.state)]);
1151
+ inScope(`${l.name}'s precondition`, l.pre ? [l.pre] : [], l.params);
1152
+ inScope(`${l.name}'s recurrent set and witness`, [r.set, ...Object.values(r.wit)], [...l.params, ...Object.keys(l.state)]);
1153
+ if (![...Object.values(l.state), ...Object.values(l.body), ...Object.values(r.wit)].every(natural) || ![l.while, r.set, ...(l.pre ? [l.pre] : []), ...(l.assume ? [l.assume] : [])].every(naturalC))
1154
+ throw new Error('outside the kernel');
1155
+ if (!Object.keys(r.start).every(n => l.params.includes(n)) || !values(r.start) || !r.stem.every(t => Object.keys(t).every(n => l.inputs.includes(n)) && values(t)))
1156
+ throw new Error(`${l.name}: a start names params and a stem's turn inputs, each a natural`);
1157
+ if (!Object.keys(r.wit).every(n => l.inputs.includes(n)))
1158
+ return false;
1159
+ let env = Object.fromEntries(names.map(n => [n, BigInt(r.start[n] ?? 0)]));
1160
+ if (!natC(l.pre ?? trueC, env))
1161
+ return false;
1162
+ const apply = (body, at) => ({ ...at, ...Object.fromEntries(Object.entries(body).map(([n, e]) => [n, natE(e, at)])) });
1163
+ env = apply(l.state, env);
1164
+ for (const turn of r.stem) {
1165
+ const at = { ...env, ...Object.fromEntries(l.inputs.map(n => [n, BigInt(turn[n] ?? 0)])) };
1166
+ if (!natC(l.while, at) || !natC(l.assume ?? trueC, at))
1167
+ return false;
1168
+ env = apply(l.body, at);
1169
+ }
1170
+ return natC(r.set, env) && check(recurGoal(l, r), r.tree);
1171
+ }
1094
1172
  // --- progress: laws with "there is a request" ----------------------------------------------------------------------
1095
1173
  // "In every reachable state where `when` holds, some request makes `then` true of the step": proven by naming the
1096
1174
  // request (a term per input over the state and params) and proving it allowed (the machine's assumption holds of it)
@@ -1239,3 +1317,235 @@ export function foldObligations(f, laws) {
1239
1317
  const node = step(holds(from(), [...assume, ...laws.flatMap(h => [substC(h.holds, side('l_')), substC(h.holds, side('r_'))])]), { vars: f.node, maps: {} });
1240
1318
  return laws.flatMap(law => [goal(`${law.name} @leaf`, leaf, atEnd(leaf, law.holds)), goal(`${law.name} @node`, node, atEnd(node, law.holds))]);
1241
1319
  }
1320
+ const bgcd = (a, b) => { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b)
1321
+ [a, b] = [b, a % b]; return a; };
1322
+ // Lean's q.num and q.den: the reduced fraction (a denominator <= 0 is no rational).
1323
+ export const ratNorm = (q) => {
1324
+ if (q.den <= 0n)
1325
+ throw new Error('a rational has a positive denominator');
1326
+ const g = bgcd(q.num, q.den) || 1n;
1327
+ return { num: q.num / g, den: q.den / g };
1328
+ };
1329
+ const rscale = (m, r) => ({ cs: new Map(m === 0n ? [] : [...r.cs].map(([x, c]) => [x, m * c])), c: m * r.c });
1330
+ const radd = (a, b) => {
1331
+ const cs = new Map(a.cs);
1332
+ for (const [x, c] of b.cs) {
1333
+ const s = (cs.get(x) ?? 0n) + c;
1334
+ if (s === 0n)
1335
+ cs.delete(x);
1336
+ else
1337
+ cs.set(x, s);
1338
+ }
1339
+ return { cs, c: a.c + b.c };
1340
+ };
1341
+ export const qdif = (a, b) => radd(rscale(b.den, a.row), rscale(-a.den, b.row));
1342
+ // A row as a Lin, its coefficients safe integers (else undefined: a row past 2^53 is not read, so the check is weaker,
1343
+ // never wrong); and its key, as `canon` writes a Lin (zero coefficients dropped: Lean's `same` compares by value).
1344
+ export const qLin = (r) => {
1345
+ const out = {};
1346
+ for (const [x, c] of r.cs) {
1347
+ if (c < -(2n ** 53n) + 1n || c > 2n ** 53n - 1n)
1348
+ return undefined;
1349
+ out[x] = Number(c);
1350
+ }
1351
+ if (r.c !== 0n) {
1352
+ if (r.c < -(2n ** 53n) + 1n || r.c > 2n ** 53n - 1n)
1353
+ return undefined;
1354
+ out['1'] = Number(r.c);
1355
+ }
1356
+ return out;
1357
+ };
1358
+ const linRow = (lin) => {
1359
+ if (!Object.values(lin).every(c => Number.isSafeInteger(c)))
1360
+ return undefined;
1361
+ const cs = new Map();
1362
+ for (const [x, c] of Object.entries(lin))
1363
+ if (x !== '1' && c !== 0)
1364
+ cs.set(x, BigInt(c));
1365
+ return { cs, c: BigInt(lin['1'] ?? 0) };
1366
+ };
1367
+ const rowKey = (r) => { const lin = qLin(r); return lin && canon(lin); };
1368
+ export function qdec(path, r) {
1369
+ if (r.cs.size === 0)
1370
+ return r.c <= 0n;
1371
+ const key = rowKey(r);
1372
+ return key === undefined ? undefined : path.get(key)?.holds;
1373
+ }
1374
+ export function qlinear(e, path) {
1375
+ switch (e.op) {
1376
+ case 'var': return e.name === '1' ? undefined : { row: { cs: new Map([[e.name, 1n]]), c: 0n }, den: 1n };
1377
+ case 'const': {
1378
+ const q = ratNorm(e.q);
1379
+ return { row: { cs: new Map(), c: q.num }, den: q.den };
1380
+ }
1381
+ case 'add':
1382
+ case 'sub': {
1383
+ const a = qlinear(e.a, path), b = qlinear(e.b, path);
1384
+ if (!a || !b)
1385
+ return undefined;
1386
+ return { row: e.op === 'add' ? radd(rscale(b.den, a.row), rscale(a.den, b.row)) : qdif(a, b), den: a.den * b.den };
1387
+ }
1388
+ case 'mul': {
1389
+ const k = ratNorm(e.k), a = qlinear(e.a, path);
1390
+ return a && { row: rscale(k.num, a.row), den: k.den * a.den };
1391
+ }
1392
+ case 'min':
1393
+ case 'max': {
1394
+ const a = qlinear(e.a, path), b = qlinear(e.b, path);
1395
+ if (!a || !b)
1396
+ return undefined;
1397
+ const d = qdec(path, qdif(a, b));
1398
+ return d === undefined ? undefined : (d === (e.op === 'min')) ? a : b;
1399
+ }
1400
+ case 'if': {
1401
+ const t = qtruth(e.c, path);
1402
+ return t === undefined ? undefined : qlinear(t ? e.then : e.else, path);
1403
+ }
1404
+ default: return unreachable(e);
1405
+ }
1406
+ }
1407
+ export function qtruth(c, path) {
1408
+ switch (c.op) {
1409
+ case '<=':
1410
+ case '<':
1411
+ case '=': {
1412
+ const a = qlinear(c.a, path), b = qlinear(c.b, path);
1413
+ if (!a || !b)
1414
+ return undefined;
1415
+ if (c.op === '<=')
1416
+ return qdec(path, qdif(a, b));
1417
+ if (c.op === '<') {
1418
+ const d = qdec(path, qdif(b, a));
1419
+ return d === undefined ? undefined : !d;
1420
+ }
1421
+ const d1 = qdec(path, qdif(a, b)), d2 = qdec(path, qdif(b, a));
1422
+ return d1 === false || d2 === false ? false : d1 === true && d2 === true ? true : undefined;
1423
+ }
1424
+ case 'and':
1425
+ case 'or': {
1426
+ const ta = qtruth(c.a, path), tb = qtruth(c.b, path), dominant = c.op === 'or';
1427
+ return ta === dominant || tb === dominant ? dominant : ta === !dominant && tb === !dominant ? !dominant : undefined;
1428
+ }
1429
+ case 'not': {
1430
+ const t = qtruth(c.x, path);
1431
+ return t === undefined ? undefined : !t;
1432
+ }
1433
+ default: return unreachable(c);
1434
+ }
1435
+ }
1436
+ // The rows (each with its strictness) a hypothesis gives under the path when it has the truth value `pos`.
1437
+ export function qfacts(c, path, pos = true) {
1438
+ switch (c.op) {
1439
+ case 'not': return qfacts(c.x, path, !pos);
1440
+ case 'and':
1441
+ case 'or': {
1442
+ // and when true, or when false: both parts; otherwise the part the other one's truth leaves.
1443
+ if ((c.op === 'and') === pos)
1444
+ return [...qfacts(c.a, path, pos), ...qfacts(c.b, path, pos)];
1445
+ if (qtruth(c.a, path) === !pos)
1446
+ return qfacts(c.b, path, pos);
1447
+ if (qtruth(c.b, path) === !pos)
1448
+ return qfacts(c.a, path, pos);
1449
+ return [];
1450
+ }
1451
+ case '<=':
1452
+ case '<':
1453
+ case '=': {
1454
+ const a = qlinear(c.a, path), b = qlinear(c.b, path);
1455
+ if (!a || !b)
1456
+ return [];
1457
+ if (c.op === '<=')
1458
+ return pos ? [[qdif(a, b), false]] : [[qdif(b, a), true]];
1459
+ if (c.op === '<')
1460
+ return pos ? [[qdif(a, b), true]] : [[qdif(b, a), false]];
1461
+ if (pos)
1462
+ return [[qdif(a, b), false], [qdif(b, a), false]];
1463
+ if (qdec(path, qdif(a, b)) === true)
1464
+ return [[qdif(a, b), true]];
1465
+ if (qdec(path, qdif(b, a)) === true)
1466
+ return [[qdif(b, a), true]];
1467
+ return [];
1468
+ }
1469
+ default: return unreachable(c);
1470
+ }
1471
+ }
1472
+ // A leaf's rows: the path's atoms (l <= 0, or −l < 0), then each hypothesis' facts; a row past 2^53 is left out.
1473
+ export function qLeafRows(goal, path) {
1474
+ const rows = [...[...path.values()].map(a => (a.holds ? [linRow(a.lin), false] : [rscale(-1n, linRow(a.lin)), true])),
1475
+ ...goal.hyps.flatMap(h => qfacts(h, path))];
1476
+ return rows.flatMap(([r, strict]) => { const lin = qLin(r); return lin ? [{ lin, label: '', strict }] : []; });
1477
+ }
1478
+ // A split on a row the path decides already (or a constant one) is refused, as Lean's checkT refuses it.
1479
+ export function checkQTree(goal, tree, path = new Map()) {
1480
+ if ('leaf' in tree)
1481
+ return !tree.products?.length && !tree.squares?.length && checkRefutation(qLeafRows(goal, path), tree.leaf, false);
1482
+ const row = linRow(tree.split), lin = row && qLin(row);
1483
+ if (!row || !lin || qdec(path, row) !== undefined)
1484
+ return false;
1485
+ const key = canon(lin);
1486
+ return checkQTree(goal, tree.yes, new Map(path).set(key, { lin, holds: true })) && checkQTree(goal, tree.no, new Map(path).set(key, { lin, holds: false }));
1487
+ }
1488
+ export const qTrue = { op: '<=', a: { op: 'const', q: { num: 0n, den: 1n } }, b: { op: 'const', q: { num: 0n, den: 1n } } };
1489
+ export function qSubstE(e, s) {
1490
+ switch (e.op) {
1491
+ case 'var': return Object.hasOwn(s, e.name) ? s[e.name] : e;
1492
+ case 'const': return e;
1493
+ case 'mul': return { ...e, a: qSubstE(e.a, s) };
1494
+ case 'if': return { op: 'if', c: qSubstC(e.c, s), then: qSubstE(e.then, s), else: qSubstE(e.else, s) };
1495
+ case 'add':
1496
+ case 'sub':
1497
+ case 'min':
1498
+ case 'max': return { ...e, a: qSubstE(e.a, s), b: qSubstE(e.b, s) };
1499
+ default: return unreachable(e);
1500
+ }
1501
+ }
1502
+ export function qSubstC(c, s) {
1503
+ switch (c.op) {
1504
+ case 'not': return { op: 'not', x: qSubstC(c.x, s) };
1505
+ case 'and':
1506
+ case 'or': return { op: c.op, a: qSubstC(c.a, s), b: qSubstC(c.b, s) };
1507
+ case '<=':
1508
+ case '<':
1509
+ case '=': return { op: c.op, a: qSubstE(c.a, s), b: qSubstE(c.b, s) };
1510
+ default: return unreachable(c);
1511
+ }
1512
+ }
1513
+ export function qOccurs(t, names) {
1514
+ switch (t.op) {
1515
+ case 'var': return names.includes(t.name);
1516
+ case 'const': return false;
1517
+ case 'mul': return qOccurs(t.a, names);
1518
+ case 'not': return qOccurs(t.x, names);
1519
+ case 'if': return qOccurs(t.c, names) || qOccurs(t.then, names) || qOccurs(t.else, names);
1520
+ case 'and':
1521
+ case 'or': return qOccurs(t.a, names) || qOccurs(t.b, names);
1522
+ case 'add':
1523
+ case 'sub':
1524
+ case 'min':
1525
+ case 'max':
1526
+ case '<=':
1527
+ case '<':
1528
+ case '=': return qOccurs(t.a, names) || qOccurs(t.b, names);
1529
+ default: return unreachable(t);
1530
+ }
1531
+ }
1532
+ // startGoal and stepGoal: the law refuted at the start, and after a step from where every law and the request's
1533
+ // assumption hold.
1534
+ export function qObligations(m, laws, law) {
1535
+ const pre = m.pre ?? qTrue, assume = m.assume ?? qTrue;
1536
+ return {
1537
+ start: { name: `${law.name} @start`, hyps: [pre, { op: 'not', x: qSubstC(law.holds, m.state) }] },
1538
+ step: { name: `${law.name} @step`, hyps: [pre, assume, ...laws.map(l => l.holds), { op: 'not', x: qSubstC(law.holds, m.step) }] },
1539
+ };
1540
+ }
1541
+ // checkMachine: the precondition reads no input and no state variable, no law reads an input, and each law's start
1542
+ // and step goals are refuted by its trees.
1543
+ export function checkQMachine(m, laws, trees) {
1544
+ const assigned = [...m.inputs, ...Object.keys(m.state), ...Object.keys(m.step)];
1545
+ if (m.pre && qOccurs(m.pre, assigned))
1546
+ return false;
1547
+ return laws.every(law => {
1548
+ const t = trees[law.name], goals = qObligations(m, laws, law);
1549
+ return !!t && !qOccurs(law.holds, m.inputs) && checkQTree(goals.start, t.start) && checkQTree(goals.step, t.step);
1550
+ });
1551
+ }
@@ -0,0 +1,18 @@
1
+ import { type Lin } from '../core/solver.js';
2
+ import type { Rat } from '../core/q.js';
3
+ import { type Path, type QGoal, type Tree } from './kernel.js';
4
+ export type QOutcome = {
5
+ tree: Tree;
6
+ nodes: number;
7
+ } | {
8
+ stuck: 'sat' | 'unknown';
9
+ witness?: Record<string, number>;
10
+ rational?: Record<string, Rat>;
11
+ path: Path;
12
+ why?: string;
13
+ };
14
+ export declare function openQ(goal: QGoal, path: Path): Lin[];
15
+ export declare function growQ(goal: QGoal, opts?: {
16
+ until?: number;
17
+ maxNodes?: number;
18
+ }): QOutcome;
@@ -0,0 +1,157 @@
1
+ // Untrusted, like prove.ts: the tree search for goals over the rationals (kernel.ts's QGoal). A node reads its rows
2
+ // as the kernel does (qLeafRows); the incremental simplex (simplex.ts, over the rationals) picks a conflict's rows, the
3
+ // elimination (solver.ts, no cut) refutes them exactly, and that derivation is the leaf. A node it can't refute is
4
+ // split on an open atom: a choice a term leaves open (min, max, if), or a comparison a hypothesis needs decided before
5
+ // it gives rows (a disjunction, ≠). With no atom open, every hypothesis' rows say all it says under the path, so the
6
+ // elimination decides the node: refuted, or a model, exact (a counterexample to the goal, checked by evaluation).
7
+ // Linear arithmetic over ℚ is decidable and this search is complete for it: every split is on a finite set of atoms,
8
+ // and each leaf is decided.
9
+ import { solve, work } from "../core/solver.js";
10
+ import { canon, qdec, qdif, qLeafRows, qLin, qlinear, qtruth } from "./kernel.js";
11
+ import { Simplex } from "./simplex.js";
12
+ // The open atoms of a term: its undecided choices (and those inside), and an if's condition's while it is open.
13
+ function openE(e, path, out) {
14
+ switch (e.op) {
15
+ case 'var':
16
+ case 'const': return;
17
+ case 'mul': return openE(e.a, path, out);
18
+ case 'add':
19
+ case 'sub':
20
+ openE(e.a, path, out);
21
+ openE(e.b, path, out);
22
+ return;
23
+ case 'min':
24
+ case 'max': {
25
+ openE(e.a, path, out);
26
+ openE(e.b, path, out);
27
+ const a = qlinear(e.a, path), b = qlinear(e.b, path);
28
+ if (a && b)
29
+ push(qdif(a, b), path, out);
30
+ return;
31
+ }
32
+ case 'if': {
33
+ const t = qtruth(e.c, path);
34
+ if (t === undefined)
35
+ openC(e.c, path, out);
36
+ else
37
+ openE(t ? e.then : e.else, path, out);
38
+ return;
39
+ }
40
+ }
41
+ }
42
+ const push = (row, path, out) => { if (qdec(path, row) === undefined) {
43
+ const lin = qLin(row);
44
+ if (lin)
45
+ out.push(lin);
46
+ } };
47
+ const forms = (c, path) => { const a = qlinear(c.a, path), b = qlinear(c.b, path); return a && b ? [a, b] : undefined; };
48
+ // The atoms that decide a condition's truth.
49
+ function openC(c, path, out) {
50
+ switch (c.op) {
51
+ case 'not': return openC(c.x, path, out);
52
+ case 'and':
53
+ case 'or':
54
+ openC(c.a, path, out);
55
+ openC(c.b, path, out);
56
+ return;
57
+ case '<=':
58
+ case '<':
59
+ case '=': {
60
+ openE(c.a, path, out);
61
+ openE(c.b, path, out);
62
+ const f = forms(c, path);
63
+ if (!f)
64
+ return;
65
+ if (c.op !== '<')
66
+ push(qdif(f[0], f[1]), path, out);
67
+ if (c.op !== '<=')
68
+ push(qdif(f[1], f[0]), path, out);
69
+ }
70
+ }
71
+ }
72
+ // The atoms a hypothesis needs decided before its rows (kernel.ts's qfacts) say all it says: none for a comparison
73
+ // whose terms are decided, both parts of a conjunction, and for a disjunction the atoms that decide its parts.
74
+ function openH(c, path, out, pos = true) {
75
+ switch (c.op) {
76
+ case 'not': return openH(c.x, path, out, !pos);
77
+ case 'and':
78
+ case 'or': {
79
+ if ((c.op === 'and') === pos) {
80
+ openH(c.a, path, out, pos);
81
+ openH(c.b, path, out, pos);
82
+ return;
83
+ }
84
+ if (qtruth(c.a, path) === !pos)
85
+ return openH(c.b, path, out, pos);
86
+ if (qtruth(c.b, path) === !pos)
87
+ return openH(c.a, path, out, pos);
88
+ openC(c.a, path, out);
89
+ openC(c.b, path, out);
90
+ return;
91
+ }
92
+ case '<=':
93
+ case '<':
94
+ case '=': {
95
+ const f = forms(c, path);
96
+ if (!f) {
97
+ openE(c.a, path, out);
98
+ openE(c.b, path, out);
99
+ return;
100
+ }
101
+ if (c.op === '=' && !pos && qdec(path, qdif(f[0], f[1])) !== true && qdec(path, qdif(f[1], f[0])) !== true)
102
+ push(qdif(f[0], f[1]), path, out);
103
+ }
104
+ }
105
+ }
106
+ export function openQ(goal, path) {
107
+ const out = [], last = goal.hyps.length - 1;
108
+ if (last >= 0)
109
+ openH(goal.hyps[last], path, out);
110
+ for (let i = 0; i < last; i++)
111
+ openH(goal.hyps[i], path, out);
112
+ const seen = new Set();
113
+ return out.filter(lin => { const key = canon(lin); return !seen.has(key) && (seen.add(key), true); });
114
+ }
115
+ // A derivation of the rows, by the simplex's conflict (its rows refuted exactly) or else the elimination over all.
116
+ function refute(rows, sx, whole) {
117
+ let lp = sx.load(rows);
118
+ if (lp.kind === 'sat')
119
+ lp = sx.check();
120
+ if (lp.kind === 'conflict') {
121
+ const support = lp.rows.sort((x, y) => x - y), out = solve(support.map(i => rows[i]), 20_000, false);
122
+ if (out.kind === 'refuted')
123
+ return { steps: out.steps.map(s => (s.kind === 'input' ? { ...s, index: support[s.index] } : s)) };
124
+ }
125
+ if (!whole && lp.kind === 'sat')
126
+ return {};
127
+ const verdict = solve(rows, 20_000, false);
128
+ return verdict.kind === 'refuted' ? { steps: verdict.steps } : { verdict };
129
+ }
130
+ export function growQ(goal, opts = {}) {
131
+ const until = opts.until ?? performance.now() + 20_000, maxNodes = opts.maxNodes ?? 100_000;
132
+ let nodes = 0;
133
+ const sx = new Simplex(false);
134
+ const go = (path) => {
135
+ if (++nodes > maxNodes || performance.now() > until)
136
+ return { stuck: 'unknown', path, why: nodes > maxNodes ? 'nodes' : 'time' };
137
+ const rows = qLeafRows(goal, path);
138
+ work.n += 1 + rows.length;
139
+ const open = openQ(goal, path);
140
+ const r = refute(rows, sx, open.length === 0);
141
+ if (r.steps)
142
+ return { tree: { leaf: r.steps }, nodes };
143
+ if (!open.length) {
144
+ const v = r.verdict;
145
+ return v?.kind === 'sat' ? { stuck: 'sat', witness: v.witness, ...(v.rational ? { rational: v.rational } : {}), path } : { stuck: 'unknown', path, why: 'no split' };
146
+ }
147
+ const lin = open[0], key = canon(lin);
148
+ const yes = go(new Map(path).set(key, { lin, holds: true }));
149
+ if (!('tree' in yes))
150
+ return yes;
151
+ const no = go(new Map(path).set(key, { lin, holds: false }));
152
+ if (!('tree' in no))
153
+ return no;
154
+ return { tree: { split: lin, yes: yes.tree, no: no.tree }, nodes };
155
+ };
156
+ return go(new Map());
157
+ }
@@ -8,6 +8,8 @@ export type SimplexVerdict = {
8
8
  kind: 'unknown';
9
9
  };
10
10
  export declare class Simplex {
11
+ readonly integral: boolean;
12
+ constructor(integral?: boolean);
11
13
  private index;
12
14
  private lo;
13
15
  private hi;
@@ -22,10 +24,12 @@ export declare class Simplex {
22
24
  private slackOf;
23
25
  load(rows: {
24
26
  lin: Lin;
27
+ strict?: boolean;
25
28
  }[]): SimplexVerdict;
26
29
  private shift;
27
30
  check(maxPivots?: number): SimplexVerdict;
28
31
  private pivot;
32
+ holds(lin: Lin): boolean | undefined;
29
33
  get size(): number;
30
34
  get nnz(): number;
31
35
  get vars(): number;
@@ -25,6 +25,10 @@ function formOf(lin) {
25
25
  return out;
26
26
  }
27
27
  export class Simplex {
28
+ integral;
29
+ constructor(integral = true) {
30
+ this.integral = integral;
31
+ }
28
32
  index = new Map();
29
33
  lo = [];
30
34
  hi = [];
@@ -102,27 +106,37 @@ export class Simplex {
102
106
  this.loWhy[j] = why;
103
107
  }
104
108
  };
109
+ const integral = this.integral;
110
+ // c·x + k <= 0: x <= −k/c (c > 0) or x >= k/−c (c < 0); rounded to integers, or over the rationals moved in when
111
+ // strict.
112
+ const bound = (c, j, k, i, strict) => {
113
+ const b = c > 0 ? -k / c : k / -c;
114
+ if (integral) {
115
+ if (c > 0)
116
+ tighten(j, true, Math.floor(b + eps), i);
117
+ else
118
+ tighten(j, false, Math.ceil(b - eps), i);
119
+ return;
120
+ }
121
+ const d = strict ? 1e-7 * Math.max(1, Math.abs(b)) : 0;
122
+ if (c > 0)
123
+ tighten(j, true, b - d, i);
124
+ else
125
+ tighten(j, false, b + d, i);
126
+ };
105
127
  for (const [i, r] of rows.entries()) {
106
128
  const f = formOf(r.lin), k = r.lin['1'] ?? 0;
107
129
  if (f === null) {
108
- if (k > 0)
130
+ if (k > 0 || (!integral && r.strict && k >= 0))
109
131
  return { kind: 'conflict', rows: [i] };
110
132
  continue;
111
133
  }
112
134
  if ('single' in f) {
113
- const j = this.varOf(f.single);
114
- if (f.c > 0)
115
- tighten(j, true, Math.floor(-k / f.c + eps), i);
116
- else
117
- tighten(j, false, Math.ceil(k / -f.c - eps), i);
135
+ bound(f.c, this.varOf(f.single), k, i, !integral && r.strict);
118
136
  continue;
119
137
  }
120
- const s = this.slackOf(f);
121
138
  // g·form + k <= 0
122
- if (f.g > 0)
123
- tighten(s, true, Math.floor(-k / f.g + eps), i);
124
- else
125
- tighten(s, false, Math.ceil(k / -f.g - eps), i);
139
+ bound(f.g, this.slackOf(f), k, i, !integral && r.strict);
126
140
  }
127
141
  for (let j = 0; j < this.val.length; j++)
128
142
  if (this.lo[j] > this.hi[j] + eps)
@@ -225,6 +239,19 @@ export class Simplex {
225
239
  for (const j of ecoef.keys())
226
240
  this.colOf[j].add(r);
227
241
  }
242
+ // Whether a row (lin <= 0) holds at the current point, or undefined where it reads a variable the tableau hasn't met.
243
+ holds(lin) {
244
+ let x = lin['1'] ?? 0;
245
+ for (const key in lin) {
246
+ if (key === '1')
247
+ continue;
248
+ const j = this.index.get(key);
249
+ if (j === undefined)
250
+ return undefined;
251
+ x += lin[key] * this.val[j];
252
+ }
253
+ return x <= tol(x);
254
+ }
228
255
  get size() { return this.rows.length; }
229
256
  get nnz() { let n = 0; for (const r of this.rows)
230
257
  n += r.coef.size; return n; }
@@ -1,6 +1,6 @@
1
1
  import type { C, E, Law, Machine, Recurrence } from '../core/machine.js';
2
2
  import { type Lin, type Step } from '../core/solver.js';
3
- import { type Fold, type Goal, type Instances, type Liveness, type Loop, type Path, type StepLaw, type Tree } from '../kernel/kernel.js';
3
+ import { type Fold, type Goal, type Instances, type Liveness, type Loop, type Path, type Recur, type StepLaw, type Tree } from '../kernel/kernel.js';
4
4
  import { type Cyclic } from '../kernel/cyclic.js';
5
5
  import { leanLibrary } from './library.js';
6
6
  export { leanLibrary };
@@ -33,6 +33,15 @@ export declare function loopToLean(id: string, l: Loop, laws: Law[], rank: E | E
33
33
  what: string;
34
34
  loop: Loop;
35
35
  }): string;
36
+ export declare function neverEndsToLean(id: string, l: Loop, r: Recur, tampered?: {
37
+ what: string;
38
+ recur: Recur;
39
+ }[]): string;
40
+ export declare function recurLean(id: string, l: Loop, fallback: Recur): {
41
+ vars: string[];
42
+ loop: string;
43
+ recur: (r: Recur) => string;
44
+ };
36
45
  export declare function foldToLean(id: string, f: Fold, laws: Law[], extra?: string): string;
37
46
  export declare function readable(id: string, laws: Law[], vars: string[], maps: string[], reach: {
38
47
  binders: string;
@@ -178,6 +187,14 @@ export type LeanItem = {
178
187
  loop: Loop;
179
188
  rank: E | E[];
180
189
  laws?: Law[];
190
+ } | {
191
+ id: string;
192
+ neverEnds: Loop;
193
+ recur: Recur;
194
+ tampered?: {
195
+ what: string;
196
+ recur: Recur;
197
+ }[];
181
198
  } | {
182
199
  id: string;
183
200
  fold: Fold;
@@ -206,6 +223,7 @@ export declare function toLean(items: LeanItem[], opts?: {
206
223
  native?: boolean;
207
224
  cyclic?: boolean;
208
225
  }): string;
226
+ export { rationalsToLean } from './qlean.js';
209
227
  export declare function leanProject(file: string, opts?: {
210
228
  name?: string;
211
229
  }): Record<string, string>;