gdp-wired 0.26.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.
Files changed (44) hide show
  1. package/dist/core/accel.d.ts +24 -0
  2. package/dist/core/accel.js +557 -207
  3. package/dist/core/bmc.d.ts +4 -1
  4. package/dist/core/bmc.js +18 -15
  5. package/dist/core/cycles.d.ts +2 -0
  6. package/dist/core/cycles.js +1 -1
  7. package/dist/core/cyclic.js +17 -10
  8. package/dist/core/data.d.ts +1 -0
  9. package/dist/core/data.js +73 -18
  10. package/dist/core/discover.js +64 -25
  11. package/dist/core/dsl.js +108 -18
  12. package/dist/core/extract-check.d.ts +52 -2
  13. package/dist/core/extract-check.js +155 -104
  14. package/dist/core/extract-read.d.ts +25 -0
  15. package/dist/core/extract-read.js +55 -14
  16. package/dist/core/extract-shapes.js +94 -18
  17. package/dist/core/extract-xstate.js +16 -3
  18. package/dist/core/extract.d.ts +1 -0
  19. package/dist/core/extract.js +16 -8
  20. package/dist/core/fresh.d.ts +9 -0
  21. package/dist/core/fresh.js +91 -0
  22. package/dist/core/infer.d.ts +1 -0
  23. package/dist/core/infer.js +64 -46
  24. package/dist/core/live.d.ts +15 -0
  25. package/dist/core/live.js +317 -0
  26. package/dist/core/machine.js +0 -1
  27. package/dist/core/nonterm.d.ts +3 -1
  28. package/dist/core/nonterm.js +103 -25
  29. package/dist/core/solver.d.ts +21 -0
  30. package/dist/core/solver.js +8 -0
  31. package/dist/core/translate.js +69 -19
  32. package/dist/kernel/cdcl.js +212 -78
  33. package/dist/kernel/kernel.d.ts +17 -1
  34. package/dist/kernel/kernel.js +158 -2
  35. package/dist/kernel/prove.d.ts +30 -4
  36. package/dist/kernel/prove.js +119 -25
  37. package/dist/kernel/reader.d.ts +74 -5
  38. package/dist/kernel/reader.js +531 -75
  39. package/dist/kernel/simplex.d.ts +26 -1
  40. package/dist/kernel/simplex.js +148 -14
  41. package/dist/lean-kernel/emit.d.ts +15 -3
  42. package/dist/lean-kernel/emit.js +144 -12
  43. package/dist/lean-kernel/library.js +1 -1
  44. package/package.json +2 -2
@@ -9,7 +9,8 @@ export type SimplexVerdict = {
9
9
  };
10
10
  export declare class Simplex {
11
11
  readonly integral: boolean;
12
- constructor(integral?: boolean);
12
+ readonly boundsOnly: boolean;
13
+ constructor(integral?: boolean, boundsOnly?: boolean);
13
14
  private index;
14
15
  private lo;
15
16
  private hi;
@@ -20,12 +21,36 @@ export declare class Simplex {
20
21
  private rows;
21
22
  private colOf;
22
23
  pivots: number;
24
+ private nnzN;
25
+ private at;
26
+ private place;
23
27
  private varOf;
24
28
  private slackOf;
25
29
  load(rows: {
26
30
  lin: Lin;
27
31
  strict?: boolean;
28
32
  }[]): SimplexVerdict;
33
+ private ins;
34
+ private inLo;
35
+ private inHi;
36
+ private falseIn;
37
+ private crossing;
38
+ private moved;
39
+ private movedAt;
40
+ private settles;
41
+ assert(id: number, lin: Lin, strict?: boolean): void;
42
+ retract(id: number): void;
43
+ changes: number;
44
+ private move;
45
+ private vers;
46
+ version(j: number): number;
47
+ value(j: number): number;
48
+ settle(): SimplexVerdict;
49
+ indexOf(name: string): number | undefined;
50
+ low(j: number): number;
51
+ high(j: number): number;
52
+ lowWhy(j: number): number;
53
+ highWhy(j: number): number;
29
54
  private shift;
30
55
  check(maxPivots?: number): SimplexVerdict;
31
56
  private pivot;
@@ -10,7 +10,7 @@
10
10
  // row by its coefficients' divisor gives, which the exact elimination makes as well. Over the rationals (`integral`
11
11
  // false) nothing is rounded, and a strict row's bound is moved in by a hair (1e-7, relative): the floats only pick a
12
12
  // conflict's rows, which the exact elimination then refutes, strictness and all, or doesn't.
13
- import { gcd } from "../core/solver.js";
13
+ import { costs, gcd } from "../core/solver.js";
14
14
  const eps = 1e-9;
15
15
  // A bound's tolerance: relative past 1 (values drift by a few ulps a pivot).
16
16
  const tol = (b) => 1e-7 * Math.max(1, Math.abs(b));
@@ -38,8 +38,11 @@ function formOf(lin) {
38
38
  }
39
39
  export class Simplex {
40
40
  integral;
41
- constructor(integral = true) {
41
+ boundsOnly;
42
+ // `boundsOnly`: only the bounds are kept (assert, retract and their versions; no settle or check).
43
+ constructor(integral = true, boundsOnly = false) {
42
44
  this.integral = integral;
45
+ this.boundsOnly = boundsOnly;
43
46
  }
44
47
  index = new Map();
45
48
  lo = [];
@@ -53,6 +56,18 @@ export class Simplex {
53
56
  rows = [];
54
57
  colOf = [];
55
58
  pivots = 0;
59
+ nnzN = 0;
60
+ at = new WeakMap();
61
+ // (a row's variable and coefficient, kept per form)
62
+ place(lin) {
63
+ let at = this.at.get(lin);
64
+ if (at === undefined) {
65
+ const f = formOf(lin);
66
+ at = f === null ? null : 'single' in f ? { j: this.varOf(f.single), c: f.c } : { j: this.slackOf(f), c: f.g };
67
+ this.at.set(lin, at);
68
+ }
69
+ return at;
70
+ }
56
71
  varOf(name) {
57
72
  let j = this.index.get(name);
58
73
  if (j !== undefined)
@@ -88,6 +103,7 @@ export class Simplex {
88
103
  }
89
104
  const s = this.varOf(f.slack), r = this.rows.length;
90
105
  this.rows.push({ basic: s, coef });
106
+ this.nnzN += coef.size;
91
107
  this.rowOf[s] = r;
92
108
  for (const j of coef.keys())
93
109
  this.colOf[j].add(r);
@@ -136,19 +152,16 @@ export class Simplex {
136
152
  else
137
153
  tighten(j, false, b + d, i);
138
154
  };
139
- for (const [i, r] of rows.entries()) {
140
- const f = formOf(r.lin), k = r.lin['1'] ?? 0;
141
- if (f === null) {
155
+ for (let i = 0; i < rows.length; i++) {
156
+ const r = rows[i], k = r.lin['1'] ?? 0;
157
+ const at = this.place(r.lin);
158
+ if (at === null) {
142
159
  if (k > 0 || (!integral && r.strict && k >= 0))
143
160
  return { kind: 'conflict', rows: [i] };
144
161
  continue;
145
162
  }
146
- if ('single' in f) {
147
- bound(f.c, this.varOf(f.single), k, i, !integral && r.strict);
148
- continue;
149
- }
150
- // g·form + k <= 0
151
- bound(f.g, this.slackOf(f), k, i, !integral && r.strict);
163
+ // c·x + k <= 0 (a slack's: g·form + k <= 0)
164
+ bound(at.c, at.j, k, i, !integral && r.strict);
152
165
  }
153
166
  for (let j = 0; j < this.val.length; j++)
154
167
  if (this.lo[j] > this.hi[j] + eps)
@@ -169,6 +182,125 @@ export class Simplex {
169
182
  }
170
183
  return { kind: 'sat' };
171
184
  }
185
+ // Incremental use, a node's rows as the last node's with some in and some out (kernel/cdcl.ts's search): each row's
186
+ // bound asserted and retracted by an id, a variable's bounds the tightest of those in (the first asserted among
187
+ // equals); `settle` then finds a conflict among them (a constant row that is false, two bounds that cross: the least
188
+ // such variable) or moves each nonbasic value whose bounds changed into them, and `check` goes on as after `load`, a
189
+ // conflict's rows given by their ids. The basic values are computed afresh from their rows every 16 settles.
190
+ ins = new Map();
191
+ inLo = [];
192
+ inHi = [];
193
+ falseIn = new Set();
194
+ crossing = new Set();
195
+ moved = [];
196
+ movedAt = [];
197
+ settles = 0;
198
+ assert(id, lin, strict) {
199
+ const at = this.place(lin), k = lin['1'] ?? 0;
200
+ if (at === null) {
201
+ this.ins.set(id, null);
202
+ if (k > 0 || (!this.integral && strict && k >= 0))
203
+ this.falseIn.add(id);
204
+ return;
205
+ }
206
+ const { j, c } = at, b0 = c > 0 ? -k / c : k / -c, upper = c > 0, d = !this.integral && strict ? 1e-7 * Math.max(1, Math.abs(b0)) : 0;
207
+ const b = this.integral ? (upper ? Math.floor(b0 + eps) : Math.ceil(b0 - eps)) : upper ? b0 - d : b0 + d;
208
+ this.ins.set(id, { j, upper, b });
209
+ ((upper ? this.inHi : this.inLo)[j] ??= []).push([b, id]);
210
+ if (upper ? b < this.hi[j] : b > this.lo[j]) {
211
+ if (upper) {
212
+ this.hi[j] = b;
213
+ this.hiWhy[j] = id;
214
+ }
215
+ else {
216
+ this.lo[j] = b;
217
+ this.loWhy[j] = id;
218
+ }
219
+ this.move(j);
220
+ }
221
+ }
222
+ retract(id) {
223
+ const a = this.ins.get(id);
224
+ this.ins.delete(id);
225
+ if (a === undefined)
226
+ return;
227
+ if (a === null) {
228
+ this.falseIn.delete(id);
229
+ return;
230
+ }
231
+ const { j, upper } = a, list = (upper ? this.inHi : this.inLo)[j];
232
+ list.splice(list.findIndex(x => x[1] === id), 1);
233
+ if ((upper ? this.hiWhy : this.loWhy)[j] !== id)
234
+ return;
235
+ let b = upper ? Infinity : -Infinity, why = -1;
236
+ for (const [x, i] of list)
237
+ if (upper ? x < b : x > b) {
238
+ b = x;
239
+ why = i;
240
+ }
241
+ if (upper) {
242
+ this.hi[j] = b;
243
+ this.hiWhy[j] = why;
244
+ }
245
+ else {
246
+ this.lo[j] = b;
247
+ this.loWhy[j] = why;
248
+ }
249
+ this.move(j);
250
+ }
251
+ // (every change of any bound, counted)
252
+ changes = 0;
253
+ move(j) {
254
+ this.vers[j] = (this.vers[j] ?? 0) + 1;
255
+ this.changes++;
256
+ if (!this.boundsOnly && this.movedAt[j] !== this.settles + 1) {
257
+ this.movedAt[j] = this.settles + 1;
258
+ this.moved.push(j);
259
+ }
260
+ }
261
+ vers = [];
262
+ // How many times a variable's bounds have changed.
263
+ version(j) { return this.vers[j] ?? 0; }
264
+ value(j) { return this.val[j]; }
265
+ settle() {
266
+ for (const id of this.falseIn)
267
+ return { kind: 'conflict', rows: [id] };
268
+ for (const j of this.moved) {
269
+ if (this.lo[j] > this.hi[j] + eps)
270
+ this.crossing.add(j);
271
+ else
272
+ this.crossing.delete(j);
273
+ }
274
+ if (this.crossing.size) {
275
+ let j = Infinity;
276
+ for (const x of this.crossing)
277
+ if (x < j)
278
+ j = x;
279
+ return { kind: 'conflict', rows: [this.loWhy[j], this.hiWhy[j]].filter(x => x >= 0) };
280
+ }
281
+ for (const j of this.moved) {
282
+ if (this.rowOf[j] >= 0)
283
+ continue;
284
+ const x = this.val[j], to = x < this.lo[j] ? this.lo[j] : x > this.hi[j] ? this.hi[j] : x;
285
+ if (to !== x)
286
+ this.shift(j, to - x);
287
+ }
288
+ this.moved = [];
289
+ if (++this.settles % 16 === 0)
290
+ for (const row of this.rows) {
291
+ let value = 0;
292
+ for (const [j, c] of row.coef)
293
+ value += c * this.val[j];
294
+ this.val[row.basic] = value;
295
+ }
296
+ return { kind: 'sat' };
297
+ }
298
+ // A variable's index by name (undefined where no row has read it); its bounds and the ids that give them.
299
+ indexOf(name) { return this.index.get(name); }
300
+ low(j) { return this.lo[j]; }
301
+ high(j) { return this.hi[j]; }
302
+ lowWhy(j) { return this.loWhy[j]; }
303
+ highWhy(j) { return this.hiWhy[j]; }
172
304
  shift(j, d) {
173
305
  this.val[j] += d;
174
306
  for (const r of this.colOf[j]) {
@@ -221,6 +353,7 @@ export class Simplex {
221
353
  ecoef.set(b, 1 / a);
222
354
  for (const j of row.coef.keys())
223
355
  this.colOf[j].delete(r);
356
+ this.nnzN += ecoef.size - row.coef.size;
224
357
  row.basic = e;
225
358
  row.coef = ecoef;
226
359
  this.rowOf[e] = r;
@@ -228,10 +361,11 @@ export class Simplex {
228
361
  for (const j of ecoef.keys())
229
362
  this.colOf[j].add(r);
230
363
  // Every other row reading x_e: substitute.
364
+ costs.pivotRows += this.colOf[e].size;
231
365
  for (const q of [...this.colOf[e]]) {
232
366
  if (q === r)
233
367
  continue;
234
- const other = this.rows[q], c = other.coef.get(e);
368
+ const other = this.rows[q], c = other.coef.get(e), before = other.coef.size;
235
369
  other.coef.delete(e);
236
370
  this.colOf[e].delete(q);
237
371
  for (const [j, d] of ecoef) {
@@ -246,6 +380,7 @@ export class Simplex {
246
380
  other.coef.set(j, x);
247
381
  }
248
382
  }
383
+ this.nnzN += other.coef.size - before;
249
384
  }
250
385
  this.colOf[e].delete(r);
251
386
  for (const j of ecoef.keys())
@@ -265,7 +400,6 @@ export class Simplex {
265
400
  return x <= tol(x);
266
401
  }
267
402
  get size() { return this.rows.length; }
268
- get nnz() { let n = 0; for (const r of this.rows)
269
- n += r.coef.size; return n; }
403
+ get nnz() { return this.nnzN; }
270
404
  get vars() { return this.val.length; }
271
405
  }
@@ -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) {