gdp-wired 0.27.0 → 0.28.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.
@@ -1139,7 +1139,9 @@ const natC = (c, env) => {
1139
1139
  // Lean's checkRecur: the witness sets only inputs; the start meets the precondition; the stem's turns meet `while` and
1140
1140
  // the assumption, and the state after them is in the set; the closure goal's tree checks. A certificate outside the
1141
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) {
1142
+ export function checkRecur(l, r) { return 'cases' in r ? checkRecurCases(l, r) : stemOk(l, r) && check(recurGoal(l, r), r.tree); }
1143
+ // Everything but the closure: the language, the witness's names, the start and the stem.
1144
+ function stemOk(l, r) {
1143
1145
  const names = [...l.params, ...l.inputs, ...Object.keys(l.state)], values = (o) => Object.values(o).every(x => Number.isSafeInteger(x) && x >= 0);
1144
1146
  distinct(l.name, names);
1145
1147
  for (const name of Object.keys(l.body))
@@ -1167,7 +1169,161 @@ export function checkRecur(l, r) {
1167
1169
  return false;
1168
1170
  env = apply(l.body, at);
1169
1171
  }
1170
- return natC(r.set, env) && check(recurGoal(l, r), r.tree);
1172
+ return natC(r.set, env);
1173
+ }
1174
+ const isTC = (c) => c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.a.value <= c.b.value;
1175
+ 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;
1176
+ const kE = (value) => ({ op: 'const', value });
1177
+ // 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,
1178
+ // else the rest that aren't true, and so for or; read through the Lean text, the two give the same terms.
1179
+ const foldMul = (k0, a) => (k0 === 0 ? kE(0) : k0 === 1 ? a : a.op === 'const' ? kE(k0 * a.value) : { op: 'mul', k: k0, a });
1180
+ function foldTerm(e, f, fc) {
1181
+ switch (e.op) {
1182
+ case 'var':
1183
+ case 'const': return e;
1184
+ case 'add': {
1185
+ const a = f(e.a), b = f(e.b);
1186
+ 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 };
1187
+ }
1188
+ case 'sub': {
1189
+ const a = f(e.a), b = f(e.b);
1190
+ 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 };
1191
+ }
1192
+ case 'mul': return foldMul(e.k, f(e.a));
1193
+ case 'min':
1194
+ case 'max': {
1195
+ const a = f(e.a), b = f(e.b);
1196
+ return a.op === 'const' && b.op === 'const' ? kE(Math[e.op](a.value, b.value)) : { op: e.op, a, b };
1197
+ }
1198
+ case 'prod': {
1199
+ const a = f(e.a), b = f(e.b);
1200
+ return a.op === 'const' ? foldMul(a.value, b) : b.op === 'const' ? foldMul(b.value, a) : { op: 'prod', a, b };
1201
+ }
1202
+ case 'if': {
1203
+ const c = fc(e.c);
1204
+ return isTC(c) ? f(e.then) : isFC(c) ? f(e.else) : { op: 'if', c, then: f(e.then), else: f(e.else) };
1205
+ }
1206
+ case 'get': return { op: 'get', map: e.map, key: f(e.key) };
1207
+ default: return unreachable(e);
1208
+ }
1209
+ }
1210
+ function foldCond(c, f, fc) {
1211
+ switch (c.op) {
1212
+ case '<=':
1213
+ case '<':
1214
+ case '=': {
1215
+ const a = f(c.a), b = f(c.b);
1216
+ if (a.op !== 'const' || b.op !== 'const')
1217
+ return { op: c.op, a, b };
1218
+ return (c.op === '<=' ? a.value <= b.value : c.op === '<' ? a.value < b.value : a.value === b.value) ? trueC : falseC;
1219
+ }
1220
+ case 'and':
1221
+ case 'or': {
1222
+ const ys = c.xs.map(fc), stop = c.op === 'and' ? isFC : isTC, unit = c.op === 'and' ? isTC : isFC;
1223
+ if (ys.some(stop))
1224
+ return c.op === 'and' ? falseC : trueC;
1225
+ const zs = ys.filter(y => !unit(y));
1226
+ return zs.length === 0 ? (c.op === 'and' ? trueC : falseC) : zs.length === 1 ? zs[0] : { op: c.op, xs: zs };
1227
+ }
1228
+ case 'not': {
1229
+ const x = fc(c.x);
1230
+ return isTC(x) ? falseC : isFC(x) ? trueC : { op: 'not', x };
1231
+ }
1232
+ case 'flag':
1233
+ case 'all': throw new Error('a loop reads no flag');
1234
+ default: return unreachable(c);
1235
+ }
1236
+ }
1237
+ // Lean's simpC ∘ substC: the variables substituted, then the constants folded, each shared part once (a folder keeps
1238
+ // what it folded, so its terms are folded once for every use).
1239
+ const folder = () => {
1240
+ const me = new WeakMap(), mc = new WeakMap();
1241
+ const f = (e) => { let o = me.get(e); if (!o) {
1242
+ o = foldTerm(e, f, fc);
1243
+ me.set(e, o);
1244
+ } return o; };
1245
+ const fc = (x) => { let o = mc.get(x); if (!o) {
1246
+ o = foldCond(x, f, fc);
1247
+ mc.set(x, o);
1248
+ } return o; };
1249
+ return { f, fc };
1250
+ };
1251
+ const substituter = (vars) => {
1252
+ const me = new WeakMap(), mc = new WeakMap();
1253
+ const se = (e) => {
1254
+ const had = me.get(e);
1255
+ if (had)
1256
+ return had;
1257
+ let o;
1258
+ switch (e.op) {
1259
+ case 'var':
1260
+ o = vars[e.name] ?? e;
1261
+ break;
1262
+ case 'const':
1263
+ o = e;
1264
+ break;
1265
+ case 'mul':
1266
+ o = { op: 'mul', k: e.k, a: se(e.a) };
1267
+ break;
1268
+ case 'if':
1269
+ o = { op: 'if', c: sc(e.c), then: se(e.then), else: se(e.else) };
1270
+ break;
1271
+ case 'get':
1272
+ o = { op: 'get', map: e.map, key: se(e.key) };
1273
+ break;
1274
+ case 'add':
1275
+ case 'sub':
1276
+ case 'min':
1277
+ case 'max':
1278
+ case 'prod':
1279
+ o = { op: e.op, a: se(e.a), b: se(e.b) };
1280
+ break;
1281
+ default: return unreachable(e);
1282
+ }
1283
+ me.set(e, o);
1284
+ return o;
1285
+ };
1286
+ const sc = (c) => {
1287
+ const had = mc.get(c);
1288
+ if (had)
1289
+ return had;
1290
+ if (c.op === 'flag' || c.op === 'all')
1291
+ throw new Error('a loop reads no flag');
1292
+ 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) };
1293
+ mc.set(c, o);
1294
+ return o;
1295
+ };
1296
+ return { se, sc };
1297
+ };
1298
+ export const foldPinned = (c, pins) => folder().fc(substituter(Object.fromEntries(pins.map(([n, x]) => [n, kE(x)]))).sc(c));
1299
+ // The pins as a condition, as Lean's pinC: each variable equal to its value, nested to the right; none: true.
1300
+ export const pinC = (pins) => (pins.length === 0 ? trueC : pins.length === 1 ? { op: '=', a: { op: 'var', name: pins[0][0] }, b: kE(pins[0][1]) }
1301
+ : { op: 'and', xs: [{ op: '=', a: { op: 'var', name: pins[0][0] }, b: kE(pins[0][1]) }, pinC(pins.slice(1))] });
1302
+ 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] } }))] });
1303
+ // Each case's goal, as Lean's caseGoal: its condition at the pins, then the witnessed turn failing, built at the pins
1304
+ // (caseNeg): the witness's terms at the pins and the pins (`w`), the body's terms read there and folded, then `w` (a
1305
+ // state variable's term first); the guard and the assumption read at `w`, the set at those terms, each folded.
1306
+ export function caseGoals(l, r, cases) {
1307
+ return cases.map(({ pins, cond }) => {
1308
+ const { f, fc } = folder(), at = substituter(Object.fromEntries(pins.map(([n, x]) => [n, kE(x)])));
1309
+ 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)])) };
1310
+ const sw = substituter(w), b = { ...w, ...Object.fromEntries(Object.entries(l.body).map(([n, t]) => [n, f(sw.se(t))])) };
1311
+ 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))] } };
1312
+ return { name: `${l.name} never ends: the set is closed where ${pins.map(([n, x]) => `${n} = ${x}`).join(', ')}`, hyps: [foldPinned(cond, pins), neg] };
1313
+ });
1314
+ }
1315
+ // Lean's checkRecurCases: as checkRecur, the closure by its cases.
1316
+ export function checkRecurCases(l, r) {
1317
+ const scope = [...l.params, ...Object.keys(l.state)];
1318
+ for (const c of r.cases) {
1319
+ inScope(`${l.name}'s case`, [c.cond], scope);
1320
+ 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)
1321
+ throw new Error('outside the kernel');
1322
+ }
1323
+ if (!stemOk(l, r) || !check(coverGoal(r), r.cover))
1324
+ return false;
1325
+ const goals = caseGoals(l, r, r.cases);
1326
+ return r.cases.every((c, j) => check(goals[j], c.tree));
1171
1327
  }
1172
1328
  // --- progress: laws with "there is a request" ----------------------------------------------------------------------
1173
1329
  // "In every reachable state where `when` holds, some request makes `then` true of the step": proven by naming the
@@ -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 KInduction, type Liveness, type Loop, type Path, type Recur, type StepLaw, type Tree } from '../kernel/kernel.js';
3
+ import { type Fold, type Goal, type Instances, type KInduction, type Liveness, type Loop, type Path, type Recur, type RecurCases, type StepLaw, type Tree } from '../kernel/kernel.js';
4
4
  import { proveStepLaws } from '../kernel/prove.js';
5
5
  import { type Cyclic } from '../kernel/cyclic.js';
6
6
  import { leanLibrary } from './library.js';
@@ -17,7 +17,7 @@ export declare function leaves(t: Tree, path: Path, visit: (t: Tree & {
17
17
  products?: [number, number][];
18
18
  squares?: Lin[];
19
19
  }, path: Path) => void): void;
20
- export declare function encode(ex: Exported, tamper?: boolean, dropStep?: boolean, globalVars?: string[], globalMaps?: string[], slim?: boolean): {
20
+ export declare function encode(ex: Exported, tamper?: boolean, dropStep?: boolean, globalVars?: string[], globalMaps?: string[], slim?: boolean, reach?: boolean): {
21
21
  tab: string;
22
22
  tabCols: string[];
23
23
  hyps: string;
@@ -38,10 +38,18 @@ export declare function neverEndsToLean(id: string, l: Loop, r: Recur, tampered?
38
38
  what: string;
39
39
  recur: Recur;
40
40
  }[]): string;
41
- export declare function recurLean(id: string, l: Loop, fallback: Recur): {
41
+ export declare function neverEndsCasesToLean(id: string, l: Loop, r: RecurCases): string;
42
+ export declare function recurCasesLean(id: string, l: Loop): {
43
+ vars: string[];
44
+ loop: string;
45
+ recur: (r: RecurCases) => string;
46
+ defs: string;
47
+ };
48
+ export declare function recurLean(id: string, l: Loop, fallback: Recur | undefined): {
42
49
  vars: string[];
43
50
  loop: string;
44
51
  recur: (r: Recur) => string;
52
+ defs: string;
45
53
  };
46
54
  export declare function foldToLean(id: string, f: Fold, laws: Law[], extra?: string): string;
47
55
  export declare function readable(id: string, laws: Law[], vars: string[], maps: string[], reach: {
@@ -213,6 +221,10 @@ export type LeanItem = {
213
221
  what: string;
214
222
  recur: Recur;
215
223
  }[];
224
+ } | {
225
+ id: string;
226
+ neverEnds: Loop;
227
+ cases: RecurCases;
216
228
  } | {
217
229
  id: string;
218
230
  fold: Fold;
@@ -1,6 +1,6 @@
1
1
  import { atMost, n, not, pointWrite } from "../core/machine.js";
2
2
  import { add, k, scale, sub } from "../core/solver.js";
3
- import { boundOf, check, checkRecur, recurGoal, canon, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, historyMachine, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessRanks, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
3
+ import { boundOf, caseGoals, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessRanks, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
4
4
  import { grow, minimal, proveBuilt, proveLaws, proveStepLaws, withDeadline } from "../kernel/prove.js";
5
5
  import { refinement, refinementSides } from "../core/compose.js";
6
6
  import { leanSurface, leanTerms } from "./lean-terms.js";
@@ -50,7 +50,81 @@ export function leaves(t, path, visit) {
50
50
  leaves(t.yes, new Map(path).set(id, { lin: t.split, holds: true }), visit);
51
51
  leaves(t.no, new Map(path).set(id, { lin: t.split, holds: false }), visit);
52
52
  }
53
- export function encode(ex, tamper = false, dropStep = true, globalVars, globalMaps, slim = false) {
53
+ // The choices Lean's linear forms look up in the table (Kernel.lean's linear and truth): at each leaf, walking what the
54
+ // leaf's hinted rows make Lean read (a hypothesis's facts, a term column's rows), every ∸, min, max or if the path
55
+ // leaves open, and only an if's branch the path takes. Undefined where a leaf has a row of no hint (Lean then reads every
56
+ // hypothesis's rows, and every term column's).
57
+ function reachedChoices(goal, leafList) {
58
+ const out = new Set();
59
+ for (const { leaf, path, base } of leafList) {
60
+ const n0 = base.length, seen = new Set();
61
+ const walkE = (e) => {
62
+ if (seen.has(e))
63
+ return;
64
+ seen.add(e);
65
+ switch (e.op) {
66
+ case 'var':
67
+ case 'const': return;
68
+ case 'mul': return walkE(e.a);
69
+ case 'get': return walkE(e.key);
70
+ case 'add':
71
+ case 'prod':
72
+ walkE(e.a);
73
+ walkE(e.b);
74
+ return;
75
+ case 'sub':
76
+ case 'min':
77
+ case 'max':
78
+ walkE(e.a);
79
+ walkE(e.b);
80
+ if (linear(e.a, path) && linear(e.b, path) && !decided(e, path))
81
+ out.add(termColumn(e));
82
+ return;
83
+ case 'if': {
84
+ walkC(e.c);
85
+ const t = truth(e.c, path);
86
+ if (t === undefined)
87
+ out.add(termColumn(e));
88
+ else
89
+ walkE(t ? e.then : e.else);
90
+ }
91
+ }
92
+ };
93
+ const walkC = (c) => {
94
+ if (seen.has(c))
95
+ return;
96
+ seen.add(c);
97
+ if (c.op === 'not')
98
+ walkC(c.x);
99
+ else if (c.op === 'and' || c.op === 'or')
100
+ c.xs.forEach(walkC);
101
+ else if (c.op === 'all')
102
+ walkC(c.c);
103
+ else if (c.op !== 'flag') {
104
+ walkE(c.a);
105
+ walkE(c.b);
106
+ }
107
+ };
108
+ for (const i of new Set([...leaf.leaf.flatMap(st => (st.kind === 'input' && st.index < n0 ? [st.index] : [])), ...(leaf.products ?? []).flat().filter(i => i < n0)])) {
109
+ const src = base[i].src;
110
+ if (!src)
111
+ return undefined;
112
+ if ('fact' in src)
113
+ walkC(goal.hyps[src.fact]);
114
+ else if ('term' in src) {
115
+ const t = columnTerm(src.term);
116
+ out.add(src.term);
117
+ walkE(t);
118
+ if (t.op === 'if') {
119
+ walkE(t.then);
120
+ walkE(t.else);
121
+ }
122
+ } // (Lean's termRowsAt reads an if's two branches)
123
+ }
124
+ }
125
+ return out;
126
+ }
127
+ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMaps, slim = false, reach = false) {
54
128
  const { goal, tree } = ex;
55
129
  // `slim`: the table only has the columns Lean reads. Each row a leaf uses has a hint (where Lean looks for it first),
56
130
  // and Lean computes only the hinted hypotheses' linear forms (Kernel.lean's srcRows), so the columns are the
@@ -129,8 +203,15 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
129
203
  else if (typeof val === 'object' && val !== null)
130
204
  choices(val);
131
205
  };
132
- readHyps.forEach(choices);
133
- readTerms.forEach(choices);
206
+ // (`reach`: only the choices Lean's linear forms look up, where they can be found)
207
+ const reachedCols = reach && !slim ? reachedChoices(goal, leafList) : undefined;
208
+ if (reachedCols)
209
+ for (const name of reachedCols)
210
+ terms.add(name);
211
+ else {
212
+ readHyps.forEach(choices);
213
+ readTerms.forEach(choices);
214
+ }
134
215
  const readSubterms = [...readHyps, ...readTerms.map((t) => ({ op: '<=', a: t, b: t }))].flatMap(subterms).filter(e => e.op === 'prod' || e.op === 'get');
135
216
  for (const { leaf, path, base } of leafList) {
136
217
  const n0 = base.length;
@@ -351,9 +432,9 @@ export function loopToLean(id, l, laws, rank, tamper) {
351
432
  export function neverEndsToLean(id, l, r, tampered = []) {
352
433
  if (!checkRecur(l, r))
353
434
  throw new Error(`${id}: the certificate does not check`);
354
- const { vars, loop, recur } = recurLean(id, l, r);
435
+ const { vars, loop, recur, defs } = recurLean(id, l, r);
355
436
  return `-- ${l.name}: a run that never ends (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')})
356
- def ${id}_loop : Loop := ${loop}
437
+ ${defs ? `${defs}\n` : ''}def ${id}_loop : Loop := ${loop}
357
438
  def ${id}_recur : Recur := ${recur(r)}
358
439
  /-- ${l.name} never ends: for some params meeting its precondition, a run of turns from the start goes on forever. -/
359
440
  theorem ${id}_never_ends : NeverEnds ${id}_loop :=
@@ -362,22 +443,73 @@ theorem ${id}_never_ends : NeverEnds ${id}_loop :=
362
443
  def ${id}_tampered${j} : Recur := ${recur(t.recur)}
363
444
  example : checkRecur ${id}_loop ${id}_tampered${j} = false := by ${checkBy}`).join('')}`;
364
445
  }
446
+ // A loop with a run that never ends, its set closed by cases (NonTerm.lean's never_ends_of_cases): the cover's and each
447
+ // case's table and tree, read against the goals Lean builds (the pins substituted, the constants folded).
448
+ export function neverEndsCasesToLean(id, l, r) {
449
+ if (!checkRecurCases(l, r))
450
+ throw new Error(`${id}: the certificate does not check`);
451
+ const { vars, loop, recur, defs } = recurCasesLean(id, l);
452
+ return `-- ${l.name}: a run that never ends, closed by ${r.cases.length} cases (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')})
453
+ ${defs ? `${defs}\n` : ''}def ${id}_loop : Loop := ${loop}
454
+ def ${id}_recur : RecurCases := ${recur(r)}
455
+ /-- ${l.name} never ends: for some params meeting its precondition, a run of turns from the start goes on forever. -/
456
+ theorem ${id}_never_ends : NeverEnds ${id}_loop :=
457
+ never_ends_of_cases ${id}_loop ${id}_recur (by ${checkBy})`;
458
+ }
459
+ // A certificate by cases as NonTerm.lean's RecurCases (each tree written against the goal it refutes, else none).
460
+ export function recurCasesLean(id, l) {
461
+ const { vars, loop, defs } = recurLean(id, l, undefined);
462
+ const { e, c } = leanTerms(vars, [], id);
463
+ const ix = (name) => { const j = vars.indexOf(name); if (j < 0)
464
+ throw new Error(`${id}: no variable for ${name}`); return j; };
465
+ const vals = (o) => list(Object.entries(o).map(([name, v2]) => `(${ix(name)}, ${v2})`));
466
+ const cert = (goal, tree) => {
467
+ let fits = false;
468
+ try {
469
+ fits = check(goal, tree);
470
+ }
471
+ catch {
472
+ fits = false;
473
+ }
474
+ const coded = fits ? encode({ name: `${id}: ${goal.name}`, goal, tree }, false, true, vars, [], false, true) : { tab: '[]', tree: '.leafAt [] [] [] []' };
475
+ return `(${coded.tab}, [], ${coded.tree})`;
476
+ };
477
+ const recur = (r) => `⟨${list(vars.map((_, j) => String(j)))},
478
+ ${vals(r.start)},
479
+ ${list(r.stem.map(vals))},
480
+ ${c(r.set)},
481
+ ${list(Object.entries(r.wit).map(([name, t]) => `(${ix(name)}, ${e(t)})`))},
482
+ ${cert(coverGoal(r), r.cover)},
483
+ ${list(r.cases.map((k2, j) => `(${list(k2.pins.map(([n2, x]) => `(${ix(n2)}, ${x})`))}, ${c(k2.cond)}, ${cert(goals(r)[j], k2.tree)})`))}⟩`;
484
+ const made = new WeakMap(), goals = (r) => { let g = made.get(r); if (!g)
485
+ made.set(r, (g = caseGoals(l, r, r.cases))); return g; };
486
+ return { vars, loop, recur, defs };
487
+ }
365
488
  // The loop and a certificate as NonTerm.lean's Loop and Recur (the domain every variable; a certificate whose tree
366
489
  // doesn't refute its own goal carries `fallback`'s table and tree, which refutes `fallback`'s). lean-kernel/conformance.ts prints its cases with it.
490
+ // (a loop's start and body past 128 variables as definitions of 128 each, appended: Lean elaborates a list literal of
491
+ // deep terms one level deeper per entry, and pgarch's 690 body terms, each 228 rules deep, pass its recursion limit)
367
492
  export function recurLean(id, l, fallback) {
368
493
  const vars = [...l.params, ...l.inputs, ...Object.keys(l.state)];
369
494
  const { e, c } = leanTerms(vars, [], id);
370
495
  const ix = (name) => { const j = vars.indexOf(name); if (j < 0)
371
496
  throw new Error(`${id}: no variable for ${name}`); return j; };
497
+ const defs = [];
498
+ const pieces = (what, xs) => {
499
+ if (xs.length <= 128)
500
+ return list(xs);
501
+ const names = Array.from({ length: Math.ceil(xs.length / 128) }, (_, k) => { defs.push(`def ${id}_${what}${k} : List (Nat × E) := ${list(xs.slice(k * 128, k * 128 + 128))}`); return `${id}_${what}${k}`; });
502
+ return `(${names.join(' ++ ')})`;
503
+ };
372
504
  const loop = `⟨${list(l.inputs.map(name => String(ix(name))))},
373
- ${list(Object.entries(l.state).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
374
- ${list(Object.entries(l.body).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
505
+ ${pieces('init', Object.entries(l.state).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
506
+ ${pieces('body', Object.entries(l.body).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
375
507
  ${c(l.while)},
376
508
  ${l.pre ? c(l.pre) : TRUE},
377
509
  ${l.assume ? c(l.assume) : TRUE}⟩`;
378
510
  const vals = (o) => list(Object.entries(o).map(([name, v]) => `(${ix(name)}, ${v})`));
379
511
  const recur = (rr) => {
380
- const enc = (g) => encode({ name: `${id}: ${l.name} never ends`, goal: recurGoal(l, g), tree: g.tree }, false, true, vars, []);
512
+ const enc = (g) => encode({ name: `${id}: ${l.name} never ends`, goal: recurGoal(l, g), tree: g.tree }, false, true, vars, [], false, true);
381
513
  // The tree is written against the goal it refutes: the certificate's own where kernel.ts's check accepts it there,
382
514
  // else `fallback`'s (which must check), and Lean reads it against the goal it builds from `rr` either way. So every
383
515
  // number written is one kernel.ts's check replayed: integers, every cut dividing its row.
@@ -388,7 +520,7 @@ export function recurLean(id, l, fallback) {
388
520
  return false;
389
521
  } };
390
522
  // (neither refuting its goal, as a forged certificate's: a leaf with no step, the tree that refutes nothing)
391
- const by = fits(rr) ? rr : fits(fallback) ? fallback : undefined;
523
+ const by = fits(rr) ? rr : fallback && fits(fallback) ? fallback : undefined;
392
524
  const coded = by ? enc(by) : { tab: '[]', tree: '.leafAt [] [] [] []' };
393
525
  return `⟨${list(vars.map((_, j) => String(j)))},
394
526
  ${vals(rr.start)},
@@ -397,7 +529,7 @@ export function recurLean(id, l, fallback) {
397
529
  ${list(Object.entries(rr.wit).map(([name, t]) => `(${ix(name)}, ${e(t)})`))},
398
530
  (${coded.tab}, [], ${coded.tree})⟩`;
399
531
  };
400
- return { vars, loop, recur };
532
+ return { vars, loop, recur, defs: defs.join('\n') };
401
533
  }
402
534
  // Folds through Kern.fold_sound: Lean builds the leaf and node goals; the trees are the kernel's.
403
535
  export function foldToLean(id, f, laws, extra = '') {
@@ -1822,7 +1954,7 @@ function toLeanWith(items, opts) {
1822
1954
  theorems.push(`${id}_halts`);
1823
1955
  }
1824
1956
  else if ('neverEnds' in item) {
1825
- parts.push(`-- ${item.id}\n${neverEndsToLean(id, item.neverEnds, item.recur, item.tampered ?? [])}`);
1957
+ parts.push(`-- ${item.id}\n${'cases' in item ? neverEndsCasesToLean(id, item.neverEnds, item.cases) : neverEndsToLean(id, item.neverEnds, item.recur, item.tampered ?? [])}`);
1826
1958
  theorems.push(`${id}_never_ends`);
1827
1959
  }
1828
1960
  else if ('cyclic' in item) {