gdp-wired 0.27.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -25,7 +25,7 @@ import { Reader, namesOf } from "./reader.js";
25
25
  import { Simplex } from "./simplex.js";
26
26
  // A derivation's own inputs: the rows it reads, in order, and the steps renumbered to them.
27
27
  function localize(rows, steps) {
28
- const inputs = [], at = new Map();
28
+ const inputs = [], at = new Map(), from = [];
29
29
  const out = steps.map(st => {
30
30
  if (st.kind !== 'input')
31
31
  return st;
@@ -34,10 +34,11 @@ function localize(rows, steps) {
34
34
  j = inputs.length;
35
35
  at.set(st.index, j);
36
36
  inputs.push(rows[st.index].lin);
37
+ from.push(st.index);
37
38
  }
38
39
  return { ...st, index: j };
39
40
  });
40
- return { inputs, steps: out };
41
+ return { inputs, steps: out, from };
41
42
  }
42
43
  // An atom's variable: the smaller of its canonical text and its flip's (remembered per form).
43
44
  const keyMemo = new WeakMap();
@@ -84,7 +85,7 @@ export function cdclSession(goal, root, opts = {}) {
84
85
  let sx = useLp ? new Simplex() : undefined;
85
86
  const nodes = [], clauses = [], occ = new Map();
86
87
  // (with opts.core: each leaf's hypotheses, by node; the hypothesis each row at this node came from)
87
- const leafHyps = new Map(), wantCore = !!(opts.core && opts.model);
88
+ const leafHyps = new Map(), wantCore = !!(opts.core && opts.model), wantDag = !!(opts.dag && opts.model);
88
89
  const hypsOf = (rs) => {
89
90
  return reader.hypsOf(rs);
90
91
  };
@@ -263,8 +264,8 @@ export function cdclSession(goal, root, opts = {}) {
263
264
  };
264
265
  // A leaf: the decisions of a reason (the root's are every leaf's, below which the tree starts: not literals of its
265
266
  // clause) and a derivation over the rows it reads.
266
- const leafNode = (w, inputs, steps, extra, hyps) => {
267
- nodes.push({ inputs, steps });
267
+ const leafNode = (w, inputs, steps, extra, hyps, src) => {
268
+ nodes.push(src ? { inputs, steps, src } : { inputs, steps });
268
269
  if (hyps)
269
270
  leafHyps.set(nodes.length - 1, hyps);
270
271
  st.leaves++;
@@ -274,6 +275,8 @@ export function cdclSession(goal, root, opts = {}) {
274
275
  lits.set(name, vars.get(name).val);
275
276
  if (extra)
276
277
  lits.set(extra[0], extra[1]);
278
+ if (src)
279
+ nodes.at(-1).lits = [...lits].map(([name, val]) => [vars.get(name).lin, val]);
277
280
  st.coreSize += lits.size;
278
281
  return { lits, node: nodes.length - 1 };
279
282
  };
@@ -286,7 +289,7 @@ export function cdclSession(goal, root, opts = {}) {
286
289
  w.add(name);
287
290
  st.pathSize += trail.length - fixed;
288
291
  const local = localize(rows, steps);
289
- return leafNode(w, local.inputs, local.steps, undefined, wantCore ? hypsOf(steps.flatMap(s => (s.kind === 'input' ? [rows[s.index]] : []))) : undefined);
292
+ return leafNode(w, local.inputs, local.steps, undefined, wantCore ? hypsOf(steps.flatMap(s => (s.kind === 'input' ? [rows[s.index]] : []))) : undefined, wantDag ? local.from.map(i => reader.srcOf(rows[i]) ?? -1) : undefined);
290
293
  }, ms => { st.coreMs += ms; });
291
294
  // Bound propagation's reasons, made when conflict analysis reads them: the atom's bounds (single-variable rows at the
292
295
  // trail then) and its other side refute each other, a leaf at the bounds' reasons with that side decided.
@@ -298,7 +301,7 @@ export function cdclSession(goal, root, opts = {}) {
298
301
  const s = solve(local);
299
302
  if (s.kind !== 'refuted')
300
303
  throw new Error('a bound propagation its bounds do not refute');
301
- const loc = localize(local, s.steps), made = leafNode(b.w, loc.inputs, loc.steps, [b.name, !b.val], b.hyps);
304
+ const loc = localize(local, s.steps), made = leafNode(b.w, loc.inputs, loc.steps, [b.name, !b.val], b.hyps, b.src && loc.from.map(i => b.src[i] ?? -1));
302
305
  c.lits = made.lits;
303
306
  c.node = made.node;
304
307
  }, ms => { st.coreMs += ms; });
@@ -497,7 +500,7 @@ export function cdclSession(goal, root, opts = {}) {
497
500
  for (const n of rowsR[i].w)
498
501
  w.add(n);
499
502
  clauses.push({ lits: new Map([[name, !val]]), node: -1 });
500
- pending.set(clauses.length - 1, { w, used: used.map(i => full[i].lin), name, val, ...(wantCore ? { hyps: hypsOf(used.map(i => rowsR[i])) } : {}) });
503
+ pending.set(clauses.length - 1, { w, used: used.map(i => full[i].lin), name, val, ...(wantCore ? { hyps: hypsOf(used.map(i => rowsR[i])) } : {}), ...(wantDag ? { src: used.map(i => reader.srcOf(rowsR[i]) ?? -1) } : {}) });
501
504
  assign(name, val, clauses.length - 1);
502
505
  forced++;
503
506
  break;
@@ -630,6 +633,8 @@ export function cdclSession(goal, root, opts = {}) {
630
633
  for (;;) {
631
634
  if (!c.lits.size) {
632
635
  if (opts.model) {
636
+ if (wantDag)
637
+ return { stuck: 'unknown', path: new Map(), why: REFUTED, dag: { nodes, top: c.node } };
633
638
  if (!wantCore)
634
639
  return { stuck: 'unknown', path: new Map(), why: REFUTED };
635
640
  // the hypotheses the leaves below the empty clause read (a clause never made into a node, a bound's not yet
@@ -73,6 +73,18 @@ export declare function historyMachine(m: Machine): {
73
73
  machine: Machine;
74
74
  goals: Goal[];
75
75
  };
76
+ export declare const sumParts: (s: string) => {
77
+ flag: string;
78
+ x: string;
79
+ };
80
+ export declare function sumCovers(m: Machine): Record<string, E[]>;
81
+ export declare function sumMachine(m: Machine, given?: Record<string, E[]>): {
82
+ machine: Machine;
83
+ goals: Goal[];
84
+ };
85
+ export declare function sumRuntime(m: Machine): Machine;
86
+ export declare const plainOf: (m: Machine) => Machine;
87
+ export declare const sideGoals: (m: Machine) => Goal[];
76
88
  export declare function obligations(m: Machine, laws: Law[], instances?: Record<string, Instances>, only?: number): Goal[];
77
89
  export declare function checkLaws(m: Machine, laws: Law[], proof: {
78
90
  instances: Record<string, Instances>;
@@ -99,8 +111,24 @@ export type Recur = {
99
111
  tree: Tree;
100
112
  };
101
113
  export declare function recurGoal(l: Loop, r: Pick<Recur, 'set' | 'wit'>): Goal;
102
- export declare function checkRecur(l: Loop, r: Recur): boolean;
103
- export declare function progressObligations(m: Machine, laws: Law[], instances: Instances, p: {
114
+ export declare function checkRecur(l: Loop, r: Recur | RecurCases): boolean;
115
+ export type RecurCases = Omit<Recur, 'tree'> & {
116
+ cover: Tree;
117
+ cases: {
118
+ pins: [string, number][];
119
+ cond: C;
120
+ tree: Tree;
121
+ }[];
122
+ };
123
+ export declare const foldPinned: (c: C, pins: [string, number][]) => C;
124
+ export declare const pinC: (pins: [string, number][]) => C;
125
+ export declare const coverGoal: (r: {
126
+ set: C;
127
+ cases: Pick<RecurCases["cases"][number], "pins" | "cond">[];
128
+ }) => Goal;
129
+ export declare function caseGoals(l: Loop, r: Pick<Recur, 'set' | 'wit'>, cases: Pick<RecurCases['cases'][number], 'pins' | 'cond'>[]): Goal[];
130
+ export declare function checkRecurCases(l: Loop, r: RecurCases): boolean;
131
+ export declare function progressObligations(m0: Machine, laws: Law[], instances: Instances, p: {
104
132
  name: string;
105
133
  when: C;
106
134
  then: C;
@@ -117,7 +145,11 @@ export type Liveness = {
117
145
  rank: E | E[];
118
146
  request?: Record<string, E>;
119
147
  helpful?: Helpful[];
148
+ fairness?: 'weak' | 'strong';
149
+ levels?: number[];
120
150
  };
151
+ export declare const strongly: (l: Liveness) => boolean;
152
+ export declare const livenessLevels: (l: Liveness) => number[];
121
153
  export declare const trueC: C, falseC: C;
122
154
  export declare const livenessRanks: (l: Liveness) => E[];
123
155
  export declare const livenessHelpful: (l: Liveness) => {
@@ -1027,11 +1027,170 @@ export function historyMachine(m) {
1027
1027
  }
1028
1028
  return { machine, goals };
1029
1029
  }
1030
+ // --- sums over a map's keys (Sums.lean) ---------------------------------------------------------------------------
1031
+ // A machine with sums as a plain one, as Sums.lean's SumMachine.plain builds it: each sum S a state variable from 0, after
1032
+ // each step (S + new) ∸ old, where old and new are the term's values at the cover keys (each key once: a key equal to an
1033
+ // earlier one adds 0) before and after the step; conjoined to the assumption, old ≤ S and a quantified flag that holds
1034
+ // at every key k: the term at k and at the cover keys, each once, is at most S. Sound because every sum is exact in every
1035
+ // reachable state (Sums.lean's sum_holds): the term starts 0 at every key, a step changes it at the cover keys alone
1036
+ // (a map it reads written at one key: that key; written at every key: the keys its value compares the bound key with,
1037
+ // each other key kept, the cover goals returned), so the facts hold of every request there (sum_allowed). The cover keys
1038
+ // read no flag (a quantified flag reads none; Lean inlines the rest, here nothing to inline).
1039
+ const ZERO = { op: 'const', value: 0 };
1040
+ const TRUE_C = { op: '<=', a: ZERO, b: ZERO };
1041
+ // Sums.lean's dTermE: G at each listed key, a key equal to an earlier one read as 0.
1042
+ const dTerm = (G, cs) => (cs.length ? { op: 'add', a: G(cs[0]), b: dTerm(t => ({ op: 'if', c: { op: '=', a: t, b: cs[0] }, then: ZERO, else: G(t) }), cs.slice(1)) } : ZERO);
1043
+ // A term over the maps at the key alone (Sums.lean's gOkE): no variable but in a map's key, and that key the variable.
1044
+ const sumTermOk = (e, key) => {
1045
+ switch (e.op) {
1046
+ case 'var': return false;
1047
+ case 'const': return true;
1048
+ case 'get': return e.key.op === 'var' && e.key.name === key;
1049
+ case 'mul': return sumTermOk(e.a, key);
1050
+ case 'if': return sumCondOk(e.c, key) && sumTermOk(e.then, key) && sumTermOk(e.else, key);
1051
+ case 'add':
1052
+ case 'sub':
1053
+ case 'min':
1054
+ case 'max':
1055
+ case 'prod': return sumTermOk(e.a, key) && sumTermOk(e.b, key);
1056
+ default: return unreachable(e);
1057
+ }
1058
+ };
1059
+ const sumCondOk = (c, key) => c.op === 'flag' || c.op === 'all' ? false : c.op === 'not' ? sumCondOk(c.x, key)
1060
+ : c.op === 'and' || c.op === 'or' ? c.xs.every(y => sumCondOk(y, key)) : sumTermOk(c.a, key) && sumTermOk(c.b, key);
1061
+ // The names a sum's parts go by: its quantified flag, the cover goals' key.
1062
+ export const sumParts = (s) => ({ flag: `cells$${s}`, x: `x$${s}` });
1063
+ // The keys a write at every key compares its bound key with (k = t, t not reading k): where else it keeps every cell.
1064
+ function comparedKeys(t, key, out) {
1065
+ if (t.op === '=' && t.a.op === 'var' && t.a.name === key && !readsKey(t.b, key))
1066
+ out.set(JSON.stringify(t.b), t.b);
1067
+ else if (t.op === '=' && t.b.op === 'var' && t.b.name === key && !readsKey(t.a, key))
1068
+ out.set(JSON.stringify(t.a), t.a);
1069
+ for (const x of Object.values(t))
1070
+ if (x && typeof x === 'object')
1071
+ (Array.isArray(x) ? x : [x]).forEach(y => comparedKeys(y, key, out));
1072
+ }
1073
+ // Each sum's cover keys, in the order of the maps its term reads (first read first).
1074
+ export function sumCovers(m) {
1075
+ return Object.fromEntries(Object.entries(m.sums ?? {}).map(([s, sum]) => {
1076
+ const out = new Map();
1077
+ for (const map of [...new Set([...JSON.stringify(sum.term).matchAll(/"op":"get","map":"([^"]+)"/g)].map(x2 => x2[1]))]) {
1078
+ const w = m.step.maps?.[map];
1079
+ if (!w)
1080
+ continue;
1081
+ if ('each' in w)
1082
+ comparedKeys(w.value, w.each, out);
1083
+ else
1084
+ out.set(JSON.stringify(w.key), w.key);
1085
+ }
1086
+ return [s, [...out.values()]];
1087
+ }));
1088
+ }
1089
+ // `given`: each sum's cover keys (core/conformance.ts's tampered twins), else sumCovers'.
1090
+ export function sumMachine(m, given) {
1091
+ const sums = Object.entries(m.sums ?? {});
1092
+ if (!sums.length)
1093
+ return { machine: m, goals: [] };
1094
+ if (m.history)
1095
+ throw new Error(`${m.name}: sums over a map's keys go on a machine without a history`);
1096
+ const covers = given ?? sumCovers(m), flags = m.step.flags ?? {};
1097
+ // (substitutions that leave each flag as it is: Lean reads a flag as its variable in the step's view)
1098
+ const same = Object.fromEntries(Object.keys(flags).map(f => [f, { op: 'flag', name: f }]));
1099
+ // (a sum may be declared in the state, at 0, which no step sets: a state variable the plain machine moves)
1100
+ for (const [s] of sums)
1101
+ if (s in m.state && JSON.stringify(m.state[s]) !== JSON.stringify(ZERO) || s in (m.step.state ?? {}))
1102
+ throw new Error(`${m.name}: the sum ${s} starts at 0 and no step sets it`);
1103
+ // (every name the machine has, as the Lean twin numbers them: a flag f's variable ?f, a quantified flag's witnesses,
1104
+ // the keys writes at every key and quantified flags bind)
1105
+ const names = [...m.params, ...m.inputs, ...Object.keys(m.state).filter(n => !(n in m.sums)), ...Object.keys(m.maps ?? {}), ...(m.inputMaps ?? []), ...Object.keys(m.fns ?? {}),
1106
+ ...Object.keys(flags), ...Object.keys(flags).map(f => `?${f}`), ...Object.entries(flags).flatMap(([f, c]) => (c.op === 'all' ? [...witnessesOf(f, c), ...boundOf(c)] : [])),
1107
+ ...Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [w.each] : []))];
1108
+ const steps = {}, qflags = {}, facts = [], goals = [];
1109
+ for (const [s, sum] of sums) {
1110
+ const { term, key } = sum, { flag, x } = sumParts(s), cs = covers[s];
1111
+ const read = [...new Set([...JSON.stringify(term).matchAll(/"op":"get","map":"([^"]+)"/g)].map(x2 => x2[1]))];
1112
+ const bad = (why) => { throw new Error(`${m.name}: the sum ${s}: ${why}`); };
1113
+ for (const name of [s, key, flag, x]) {
1114
+ plainName(m.name, name);
1115
+ if (names.includes(name) || name in (m.sums ?? {}) && name !== s)
1116
+ bad(`${name} is already a name of the machine`);
1117
+ }
1118
+ if (new Set([s, key, flag, x, `?${flag}`, `w?${flag}`]).size !== 6 || names.includes(`?${flag}`) || names.includes(`w?${flag}`))
1119
+ bad('its names collide');
1120
+ if (!natural(term) || !sumTermOk(term, key))
1121
+ bad(`its term reads the maps at ${key} alone, and no other name`);
1122
+ for (const map of read) {
1123
+ if ((m.inputMaps ?? []).includes(map) || (m.fns ?? {})[map] || !(map in (m.maps ?? {})))
1124
+ bad(`${map} is not a map of the machine's state`);
1125
+ }
1126
+ // 0 where every map holds its start value (Sums.lean's startVal: the term with each read its map's start).
1127
+ const atStart = substE(term, { vars: {}, maps: Object.fromEntries(read.map(map => [map, () => ({ op: 'const', value: m.maps[map] })])), flags: same });
1128
+ if (natE(atStart, {}) !== 0n)
1129
+ bad('its term is not 0 at the start');
1130
+ for (const c of cs)
1131
+ if (JSON.stringify(c).includes('"op":"flag"') || readsKey(c, key) || readsKey(c, x))
1132
+ bad('a key a step writes it at reads a flag');
1133
+ // (Sums.lean's sumOk1: a map the term reads written at one key has that key among the cover keys)
1134
+ for (const map of read) {
1135
+ const w = m.step.maps?.[map];
1136
+ if (w && !('each' in w) && !cs.some(c => JSON.stringify(c) === JSON.stringify(w.key)))
1137
+ bad(`the key ${map} is written at is no cover key`);
1138
+ }
1139
+ const here = (t) => substE(term, { vars: { [key]: t }, maps: {}, flags: same });
1140
+ // A map read after the step, over the step's view (Sums.lean's postRd).
1141
+ const post = (map) => (k2) => {
1142
+ const w = m.step.maps?.[map];
1143
+ if (!w)
1144
+ return { op: 'get', map, key: k2 };
1145
+ if ('each' in w)
1146
+ return substE(w.value, { vars: { [w.each]: k2 }, maps: {}, flags: same });
1147
+ return { op: 'if', c: { op: '=', a: k2, b: w.key }, then: w.value, else: { op: 'get', map, key: k2 } };
1148
+ };
1149
+ const after = (t) => substE(term, { vars: { [key]: t }, maps: Object.fromEntries(read.map(map => [map, post(map)])), flags: same });
1150
+ const S = { op: 'var', name: s };
1151
+ steps[s] = { op: 'sub', a: { op: 'add', a: S, b: dTerm(after, cs) }, b: dTerm(here, cs) };
1152
+ qflags[flag] = { op: 'all', key, c: { op: '<=', a: dTerm(here, [{ op: 'var', name: key }, ...cs]), b: S } };
1153
+ facts.push({ op: 'and', xs: [{ op: '<=', a: dTerm(here, cs), b: S }, { op: 'flag', name: flag }] });
1154
+ // A map it reads written at every key: at a key none of the cover keys is, the write keeps the cell. Built as
1155
+ // Sums.lean's sumCoverGoal builds it (each write at every key in the machine's order, its flags inlined as Lean
1156
+ // inlines them: a flag f read as (if f's condition then 1 else 0) = 1), so the Lean export reads these goals as they are.
1157
+ const lean = { vars: {}, maps: {}, flags: Object.fromEntries(Object.entries(flagsOf(m)).map(([f, c]) => [f, flags[f].op === 'all' ? c
1158
+ : { op: '=', a: { op: 'if', c, then: { op: 'const', value: 1 }, else: ZERO }, b: { op: 'const', value: 1 } }])) };
1159
+ for (const [map, w] of Object.entries(m.step.maps ?? {})) {
1160
+ if (!('each' in w) || !read.includes(map))
1161
+ continue;
1162
+ const X = { op: 'var', name: x };
1163
+ goals.push({ name: `${s} @cover ${map}`, hyps: [substC(m.assume ?? TRUE_C, lean), ...cs.map((c) => ({ op: 'not', x: { op: '=', a: X, b: c } })),
1164
+ { op: 'not', x: { op: '=', a: substE(substE(w.value, lean), { vars: { [w.each]: X }, maps: {}, flags: {} }), b: { op: 'get', map, key: X } } }] });
1165
+ }
1166
+ }
1167
+ // (Sums.lean's sumsC: each sum's facts, then the rest, ending in 0 ≤ 0)
1168
+ const assumed = facts.reduceRight((acc, f) => ({ op: 'and', xs: [f, acc] }), TRUE_C);
1169
+ const machine = {
1170
+ ...m, sums: undefined,
1171
+ state: { ...m.state, ...Object.fromEntries(sums.map(([s]) => [s, ZERO])) },
1172
+ step: { ...m.step, flags: { ...flags, ...qflags }, state: { ...m.step.state, ...steps } },
1173
+ assume: { op: 'and', xs: [m.assume ?? TRUE_C, assumed] },
1174
+ };
1175
+ return { machine, goals };
1176
+ }
1177
+ // The machine the runtimes step: each sum a state variable kept exact by its step, the rule's own assumption.
1178
+ export function sumRuntime(m) {
1179
+ if (!m.sums || !Object.keys(m.sums).length)
1180
+ return m;
1181
+ const { machine } = sumMachine(m);
1182
+ const flags = Object.fromEntries(Object.entries(machine.step.flags ?? {}).filter(([f]) => !Object.keys(m.sums).some(s => sumParts(s).flag === f)));
1183
+ return { ...machine, step: { ...machine.step, flags }, assume: m.assume };
1184
+ }
1185
+ // The plain machine any claim is proven of: with a history kernel.ts's historyMachine's, with sums sumMachine's.
1186
+ export const plainOf = (m) => (m.history ? historyMachine(m).machine : m.sums && Object.keys(m.sums).length ? sumMachine(m).machine : m);
1187
+ // The goals beside a plain machine's own: a history's record goals, the sums' cover goals.
1188
+ export const sideGoals = (m) => (m.history ? historyMachine(m).goals : m.sums && Object.keys(m.sums).length ? sumMachine(m).goals : []);
1030
1189
  // `only`: the goals of that law alone (the prover's instance search asks for one law's at a time).
1031
1190
  export function obligations(m, laws, instances = {}, only) {
1032
- if (m.history) {
1033
- const { machine, goals } = historyMachine(m);
1034
- return [...obligations(machine, laws, instances, only), ...(only === undefined ? goals : [])];
1191
+ if (m.history || (m.sums && Object.keys(m.sums).length)) {
1192
+ const goals = sideGoals(m);
1193
+ return [...obligations(plainOf(m), laws, instances, only), ...(only === undefined ? goals : [])];
1035
1194
  }
1036
1195
  scope(m, laws);
1037
1196
  const ok = [...Object.values(m.state), ...Object.values(m.step.state ?? {}), ...Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [w.value] : [w.key, w.value]))].every(natural)
@@ -1139,7 +1298,9 @@ const natC = (c, env) => {
1139
1298
  // Lean's checkRecur: the witness sets only inputs; the start meets the precondition; the stem's turns meet `while` and
1140
1299
  // the assumption, and the state after them is in the set; the closure goal's tree checks. A certificate outside the
1141
1300
  // 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) {
1301
+ export function checkRecur(l, r) { return 'cases' in r ? checkRecurCases(l, r) : stemOk(l, r) && check(recurGoal(l, r), r.tree); }
1302
+ // Everything but the closure: the language, the witness's names, the start and the stem.
1303
+ function stemOk(l, r) {
1143
1304
  const names = [...l.params, ...l.inputs, ...Object.keys(l.state)], values = (o) => Object.values(o).every(x => Number.isSafeInteger(x) && x >= 0);
1144
1305
  distinct(l.name, names);
1145
1306
  for (const name of Object.keys(l.body))
@@ -1167,14 +1328,171 @@ export function checkRecur(l, r) {
1167
1328
  return false;
1168
1329
  env = apply(l.body, at);
1169
1330
  }
1170
- return natC(r.set, env) && check(recurGoal(l, r), r.tree);
1331
+ return natC(r.set, env);
1332
+ }
1333
+ const isTC = (c) => c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.a.value <= c.b.value;
1334
+ const isFC = (c) => c.op === '<' && c.a.op === 'const' && c.b.op === 'const' ? c.b.value <= c.a.value : c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.b.value < c.a.value;
1335
+ const kE = (value) => ({ op: 'const', value });
1336
+ // Lean's folds, on kernel.ts's terms: an and of several (Lean: each and of two, nested to the right) is false if one is,
1337
+ // else the rest that aren't true, and so for or; read through the Lean text, the two give the same terms.
1338
+ const foldMul = (k0, a) => (k0 === 0 ? kE(0) : k0 === 1 ? a : a.op === 'const' ? kE(k0 * a.value) : { op: 'mul', k: k0, a });
1339
+ function foldTerm(e, f, fc) {
1340
+ switch (e.op) {
1341
+ case 'var':
1342
+ case 'const': return e;
1343
+ case 'add': {
1344
+ const a = f(e.a), b = f(e.b);
1345
+ return a.op === 'const' && a.value === 0 ? b : b.op === 'const' && b.value === 0 ? a : a.op === 'const' && b.op === 'const' ? kE(a.value + b.value) : { op: 'add', a, b };
1346
+ }
1347
+ case 'sub': {
1348
+ const a = f(e.a), b = f(e.b);
1349
+ return b.op === 'const' && b.value === 0 ? a : a.op === 'const' && b.op === 'const' ? kE(Math.max(0, a.value - b.value)) : { op: 'sub', a, b };
1350
+ }
1351
+ case 'mul': return foldMul(e.k, f(e.a));
1352
+ case 'min':
1353
+ case 'max': {
1354
+ const a = f(e.a), b = f(e.b);
1355
+ return a.op === 'const' && b.op === 'const' ? kE(Math[e.op](a.value, b.value)) : { op: e.op, a, b };
1356
+ }
1357
+ case 'prod': {
1358
+ const a = f(e.a), b = f(e.b);
1359
+ return a.op === 'const' ? foldMul(a.value, b) : b.op === 'const' ? foldMul(b.value, a) : { op: 'prod', a, b };
1360
+ }
1361
+ case 'if': {
1362
+ const c = fc(e.c);
1363
+ return isTC(c) ? f(e.then) : isFC(c) ? f(e.else) : { op: 'if', c, then: f(e.then), else: f(e.else) };
1364
+ }
1365
+ case 'get': return { op: 'get', map: e.map, key: f(e.key) };
1366
+ default: return unreachable(e);
1367
+ }
1368
+ }
1369
+ function foldCond(c, f, fc) {
1370
+ switch (c.op) {
1371
+ case '<=':
1372
+ case '<':
1373
+ case '=': {
1374
+ const a = f(c.a), b = f(c.b);
1375
+ if (a.op !== 'const' || b.op !== 'const')
1376
+ return { op: c.op, a, b };
1377
+ return (c.op === '<=' ? a.value <= b.value : c.op === '<' ? a.value < b.value : a.value === b.value) ? trueC : falseC;
1378
+ }
1379
+ case 'and':
1380
+ case 'or': {
1381
+ const ys = c.xs.map(fc), stop = c.op === 'and' ? isFC : isTC, unit = c.op === 'and' ? isTC : isFC;
1382
+ if (ys.some(stop))
1383
+ return c.op === 'and' ? falseC : trueC;
1384
+ const zs = ys.filter(y => !unit(y));
1385
+ return zs.length === 0 ? (c.op === 'and' ? trueC : falseC) : zs.length === 1 ? zs[0] : { op: c.op, xs: zs };
1386
+ }
1387
+ case 'not': {
1388
+ const x = fc(c.x);
1389
+ return isTC(x) ? falseC : isFC(x) ? trueC : { op: 'not', x };
1390
+ }
1391
+ case 'flag':
1392
+ case 'all': throw new Error('a loop reads no flag');
1393
+ default: return unreachable(c);
1394
+ }
1395
+ }
1396
+ // Lean's simpC ∘ substC: the variables substituted, then the constants folded, each shared part once (a folder keeps
1397
+ // what it folded, so its terms are folded once for every use).
1398
+ const folder = () => {
1399
+ const me = new WeakMap(), mc = new WeakMap();
1400
+ const f = (e) => { let o = me.get(e); if (!o) {
1401
+ o = foldTerm(e, f, fc);
1402
+ me.set(e, o);
1403
+ } return o; };
1404
+ const fc = (x) => { let o = mc.get(x); if (!o) {
1405
+ o = foldCond(x, f, fc);
1406
+ mc.set(x, o);
1407
+ } return o; };
1408
+ return { f, fc };
1409
+ };
1410
+ const substituter = (vars) => {
1411
+ const me = new WeakMap(), mc = new WeakMap();
1412
+ const se = (e) => {
1413
+ const had = me.get(e);
1414
+ if (had)
1415
+ return had;
1416
+ let o;
1417
+ switch (e.op) {
1418
+ case 'var':
1419
+ o = vars[e.name] ?? e;
1420
+ break;
1421
+ case 'const':
1422
+ o = e;
1423
+ break;
1424
+ case 'mul':
1425
+ o = { op: 'mul', k: e.k, a: se(e.a) };
1426
+ break;
1427
+ case 'if':
1428
+ o = { op: 'if', c: sc(e.c), then: se(e.then), else: se(e.else) };
1429
+ break;
1430
+ case 'get':
1431
+ o = { op: 'get', map: e.map, key: se(e.key) };
1432
+ break;
1433
+ case 'add':
1434
+ case 'sub':
1435
+ case 'min':
1436
+ case 'max':
1437
+ case 'prod':
1438
+ o = { op: e.op, a: se(e.a), b: se(e.b) };
1439
+ break;
1440
+ default: return unreachable(e);
1441
+ }
1442
+ me.set(e, o);
1443
+ return o;
1444
+ };
1445
+ const sc = (c) => {
1446
+ const had = mc.get(c);
1447
+ if (had)
1448
+ return had;
1449
+ if (c.op === 'flag' || c.op === 'all')
1450
+ throw new Error('a loop reads no flag');
1451
+ const o = c.op === 'not' ? { op: 'not', x: sc(c.x) } : c.op === 'and' || c.op === 'or' ? { op: c.op, xs: c.xs.map(sc) } : { op: c.op, a: se(c.a), b: se(c.b) };
1452
+ mc.set(c, o);
1453
+ return o;
1454
+ };
1455
+ return { se, sc };
1456
+ };
1457
+ export const foldPinned = (c, pins) => folder().fc(substituter(Object.fromEntries(pins.map(([n, x]) => [n, kE(x)]))).sc(c));
1458
+ // The pins as a condition, as Lean's pinC: each variable equal to its value, nested to the right; none: true.
1459
+ export const pinC = (pins) => (pins.length === 0 ? trueC : pins.length === 1 ? { op: '=', a: { op: 'var', name: pins[0][0] }, b: kE(pins[0][1]) }
1460
+ : { op: 'and', xs: [{ op: '=', a: { op: 'var', name: pins[0][0] }, b: kE(pins[0][1]) }, pinC(pins.slice(1))] });
1461
+ export const coverGoal = (r) => ({ name: 'the set is covered by its cases', hyps: [r.set, ...r.cases.map((c) => ({ op: 'not', x: { op: 'and', xs: [pinC(c.pins), c.cond] } }))] });
1462
+ // Each case's goal, as Lean's caseGoal: its condition at the pins, then the witnessed turn failing, built at the pins
1463
+ // (caseNeg): the witness's terms at the pins and the pins (`w`), the body's terms read there and folded, then `w` (a
1464
+ // state variable's term first); the guard and the assumption read at `w`, the set at those terms, each folded.
1465
+ export function caseGoals(l, r, cases) {
1466
+ return cases.map(({ pins, cond }) => {
1467
+ const { f, fc } = folder(), at = substituter(Object.fromEntries(pins.map(([n, x]) => [n, kE(x)])));
1468
+ const w = { ...Object.fromEntries(Object.entries(r.wit).map(([n, t]) => [n, f(at.se(t))])), ...Object.fromEntries(pins.map(([n, x]) => [n, kE(x)])) };
1469
+ const sw = substituter(w), b = { ...w, ...Object.fromEntries(Object.entries(l.body).map(([n, t]) => [n, f(sw.se(t))])) };
1470
+ const neg = { op: 'not', x: { op: 'and', xs: [fc(sw.sc(l.while)), fc(sw.sc(l.assume ?? trueC)), fc(substituter(b).sc(r.set))] } };
1471
+ return { name: `${l.name} never ends: the set is closed where ${pins.map(([n, x]) => `${n} = ${x}`).join(', ')}`, hyps: [foldPinned(cond, pins), neg] };
1472
+ });
1473
+ }
1474
+ // Lean's checkRecurCases: as checkRecur, the closure by its cases.
1475
+ export function checkRecurCases(l, r) {
1476
+ const scope = [...l.params, ...Object.keys(l.state)];
1477
+ for (const c of r.cases) {
1478
+ inScope(`${l.name}'s case`, [c.cond], scope);
1479
+ if (!naturalC(c.cond) || !c.pins.every(([n, x]) => scope.includes(n) && Number.isSafeInteger(x) && x >= 0) || new Set(c.pins.map(([n]) => n)).size < c.pins.length)
1480
+ throw new Error('outside the kernel');
1481
+ }
1482
+ if (!stemOk(l, r) || !check(coverGoal(r), r.cover))
1483
+ return false;
1484
+ const goals = caseGoals(l, r, r.cases);
1485
+ return r.cases.every((c, j) => check(goals[j], c.tree));
1171
1486
  }
1172
1487
  // --- progress: laws with "there is a request" ----------------------------------------------------------------------
1173
1488
  // "In every reachable state where `when` holds, some request makes `then` true of the step": proven by naming the
1174
1489
  // request (a term per input over the state and params) and proving it allowed (the machine's assumption holds of it)
1175
1490
  // and that the step it causes makes `then` hold. `then` reads the state before the step by plain names and after it by
1176
1491
  // primed names (s', and M'[k] as a read of the map named M'). The laws assumed must be proven inductive on their own.
1177
- export function progressObligations(m, laws, instances, p) {
1492
+ // A machine with sums: the request is allowed by the rule's own assumption (the facts its plain machine assumes besides
1493
+ // hold of every request where the sums are exact: Sums.lean's sum_allowed).
1494
+ export function progressObligations(m0, laws, instances, p) {
1495
+ const m = plainOf(m0), own = m0.sums && Object.keys(m0.sums).length ? m0.assume : m.assume;
1178
1496
  if (!m.inputs.every(i => i in p.request) || !Object.values(p.request).every(natural) || mentions(p.when, m.inputs))
1179
1497
  throw new Error('outside the kernel');
1180
1498
  for (const e of Object.values(p.request))
@@ -1188,10 +1506,12 @@ export function progressObligations(m, laws, instances, p) {
1188
1506
  const asked = holds(reading(before, p.request), closing(m, instances));
1189
1507
  const caused = step(asked, updateOf(m));
1190
1508
  return [
1191
- ...(m.assume ? [goal(`${p.name}: the request is allowed`, asked, substC(inlineFlags(m, m.assume), req))] : []),
1509
+ ...(own ? [goal(`${p.name}: the request is allowed`, asked, substC(inlineFlags(m, own), req))] : []),
1192
1510
  goal(`${p.name}: the step it causes`, caused, across(caused, p.then, Object.keys(m.state), Object.keys(m.maps ?? {}), { inputs: p.request, flags })),
1193
1511
  ];
1194
1512
  }
1513
+ export const strongly = (l) => l.fairness === 'strong';
1514
+ export const livenessLevels = (l) => l.levels ?? livenessHelpful(l).map((_, i) => i);
1195
1515
  const zero = { op: 'const', value: 0 };
1196
1516
  export const trueC = { op: '<=', a: zero, b: zero }, falseC = { op: '<', a: zero, b: zero };
1197
1517
  const and2 = (a, b) => ({ op: 'and', xs: [a, b] }), or2 = (a, b) => ({ op: 'or', xs: [a, b] });
@@ -1208,7 +1528,7 @@ export const livenessHelpful = (l) => {
1208
1528
  };
1209
1529
  export function livenessParts(m, l) {
1210
1530
  // A machine with a history as its plain machine (its sums are state, its queries inputs no request names).
1211
- const plain = m.history ? historyMachine(m).machine : m;
1531
+ const plain = plainOf(m);
1212
1532
  const queries = Object.keys(m.history?.queries ?? {}), client = plain.inputs.filter(i => !queries.includes(i));
1213
1533
  const ranks = livenessRanks(l), helpful = livenessHelpful(l);
1214
1534
  if (!ranks.length || !helpful.length)
@@ -1227,6 +1547,18 @@ export function livenessParts(m, l) {
1227
1547
  const after = { vars: Object.fromEntries(Object.keys(plain.state).map(n => [n, { op: 'var', name: `${n}'` }])), maps: Object.fromEntries(Object.keys(plain.maps ?? {}).map(map => [map, (key) => ({ op: 'get', map: `${map}'`, key })])), flags: {} };
1228
1548
  const prime = (c) => substC(c, after), ranks2 = ranks.map(r => substE(r, after)), to2 = prime(l.to);
1229
1549
  const pending = and2(l.from, { op: 'not', x: l.to }), lower = lexLt(ranks2, ranks), regions = helpful.map(h => h.when);
1550
+ if (strongly(l)) {
1551
+ // (Live.lean's liveStaySC and liveHelpThenS: the regions of a higher level, in order)
1552
+ const levels = livenessLevels(l);
1553
+ if (levels.length !== helpful.length || !levels.every(n => Number.isInteger(n) && n >= 0))
1554
+ throw new Error(`liveness ${l.name}: a level, a natural, per helpful request`);
1555
+ return {
1556
+ stay: { name: `${l.name}: each step stays or gets there, the rank never rising`, when: pending, then: and2(or2(prime(l.from), to2), or2(to2, or2(lower, eqs(ranks2, ranks)))) },
1557
+ cover: { name: `${l.name}: some helpful request applies`, when: pending, then: anyOf(regions) },
1558
+ helps: helpful.map((h, i) => ({ name: `${l.name}: helpful request ${i + 1}`, when: and2(pending, and2(h.when, named(Object.entries(h.request)))),
1559
+ then: or2(to2, or2(lower, anyOf(regions.filter((_, j) => levels[i] < levels[j]).map(prime)))) })),
1560
+ };
1561
+ }
1230
1562
  return {
1231
1563
  stay: { name: `${l.name}: each step stays or gets there, the rank kept only with its region`, when: pending,
1232
1564
  then: and2(or2(prime(l.from), to2), or2(to2, or2(lower, and2(eqs(ranks2, ranks), keep(regions, prime))))) },
@@ -1235,7 +1567,7 @@ export function livenessParts(m, l) {
1235
1567
  };
1236
1568
  }
1237
1569
  export function stepLawObligations(machine, laws, instances, sl) {
1238
- const m = machine.history ? historyMachine(machine).machine : machine;
1570
+ const m = plainOf(machine);
1239
1571
  scope(m, laws);
1240
1572
  const k = sl.steps ?? 1;
1241
1573
  // Past 64 the cost is the bound (proving grows about as k³: 64 steps in about 5 s on Modal; Lean checks 32 in about 14 s, 64 in about 47 s).
@@ -1286,7 +1618,7 @@ export function stepLawObligations(machine, laws, instances, sl) {
1286
1618
  const lawsOnly = (inst) => Object.fromEntries(Object.entries(inst).filter(([n]) => !n.startsWith('?')));
1287
1619
  export function checkStepLaws(m, laws, stepLaws, proof) {
1288
1620
  return checkLaws(m, laws, proof.laws) && stepLaws.every(sl => {
1289
- const inst = proof.perStep?.[sl.name] ?? proof.instances, plain = m.history ? historyMachine(m).machine : m;
1621
+ const inst = proof.perStep?.[sl.name] ?? proof.instances, plain = plainOf(m);
1290
1622
  const zone = stepZone(plain, sl.steps ?? 1);
1291
1623
  return [...assumed(laws, inst), ...assumed(plain.facts ?? [], inst), ...closing(plain, lawsOnly(inst))].every(c => !mentions(c, zone))
1292
1624
  && stepLawObligations(m, laws, inst, sl).every(g => proof.trees[g.name] !== undefined && check(g, proof.trees[g.name]));
@@ -1299,7 +1631,7 @@ export const stepZone = (m, k) => [
1299
1631
  ...Array.from({ length: k - 1 }, (_, i) => Object.keys(m.state).map(n => stateName(n, i + 1))).flat(),
1300
1632
  ];
1301
1633
  export function kInductionSteps(machine, kl) {
1302
- const m = machine.history ? historyMachine(machine).machine : machine, L = kl.law, k = kl.k;
1634
+ const m = plainOf(machine), L = kl.law, k = kl.k;
1303
1635
  if (L.forall || L.keys?.length || L.some?.length || L.ex)
1304
1636
  throw new Error(`k-induction of ${L.name}: a law with no key`);
1305
1637
  if (!Number.isInteger(k) || k < 1 || k > 64)
@@ -1321,11 +1653,11 @@ export function kInductionSteps(machine, kl) {
1321
1653
  ];
1322
1654
  }
1323
1655
  export const kInductionStart = (machine, kl, instances) => {
1324
- const m = machine.history ? historyMachine(machine).machine : machine;
1656
+ const m = plainOf(machine);
1325
1657
  return obligations(m, [kl.law], { [kl.law.name]: instances })[0];
1326
1658
  };
1327
1659
  export function checkKInduction(m, laws, kl, proof) {
1328
- const steps = kInductionSteps(m, kl), plain = m.history ? historyMachine(m).machine : m;
1660
+ const steps = kInductionSteps(m, kl), plain = plainOf(m);
1329
1661
  scope(plain, [...laws, kl.law]);
1330
1662
  const start = kInductionStart(m, kl, proof.perStep?.[`${kl.law.name} @start`] ?? proof.instances);
1331
1663
  return proof.trees[start.name] !== undefined && check(start, proof.trees[start.name]) && checkStepLaws(m, laws, steps, proof);
@@ -124,6 +124,7 @@ export declare function proveLaw(m: Machine, laws: Law[], i: number): {
124
124
  stuck: string;
125
125
  witness?: Record<string, number>;
126
126
  };
127
+ export declare function lawInstances(m: Machine, laws: Law[], i: number): Instances;
127
128
  export declare const usualCheck: {
128
129
  on: boolean;
129
130
  };
@@ -153,6 +154,7 @@ export declare function proveStepLaws(given0: Machine, given: Law[], stepLaws: S
153
154
  proof?: StepProof;
154
155
  uncovered?: string[];
155
156
  };
157
+ export declare function stepLawInstances(m: Machine, laws: Law[]): (sl: StepLaw) => Instances;
156
158
  export declare function proveProgress(m: Machine, laws: Law[], p: {
157
159
  name: string;
158
160
  when: C;
@@ -163,9 +165,11 @@ export declare function proveProgress(m: Machine, laws: Law[], p: {
163
165
  trees?: Record<string, Tree>;
164
166
  uncovered?: string;
165
167
  };
166
- export declare function proveLiveness(m: Machine, laws: Law[], l: Liveness): Report & {
168
+ export declare function chooseLevels(m: Machine, laws: Law[], l: Liveness): number[] | undefined;
169
+ export declare function proveLiveness(m: Machine, laws: Law[], given: Liveness): Report & {
167
170
  steps?: ReturnType<typeof proveStepLaws>;
168
171
  uncovered?: string[];
172
+ levels?: number[];
169
173
  };
170
174
  export declare function certLoop(l: Loop, laws: Law[], rank: E | E[], trees: Record<string, Tree>, usualMs?: number): {
171
175
  checked: boolean;