gdp-wired 0.23.0 → 0.25.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 (47) hide show
  1. package/README.md +12 -2
  2. package/dist/core/accel.d.ts +44 -0
  3. package/dist/core/accel.js +720 -0
  4. package/dist/core/bmc.d.ts +13 -2
  5. package/dist/core/bmc.js +390 -18
  6. package/dist/core/cycles.d.ts +23 -0
  7. package/dist/core/cycles.js +527 -146
  8. package/dist/core/data.d.ts +17 -0
  9. package/dist/core/data.js +1177 -213
  10. package/dist/core/discover.js +8 -3
  11. package/dist/core/dsl.d.ts +7 -2
  12. package/dist/core/dsl.js +47 -9
  13. package/dist/core/extract-check.d.ts +77 -0
  14. package/dist/core/extract-check.js +785 -0
  15. package/dist/core/extract-ir.d.ts +139 -0
  16. package/dist/core/extract-ir.js +198 -0
  17. package/dist/core/extract-print.d.ts +30 -0
  18. package/dist/core/extract-print.js +426 -0
  19. package/dist/core/extract-read.d.ts +298 -0
  20. package/dist/core/extract-read.js +1298 -0
  21. package/dist/core/extract-shapes.d.ts +13 -0
  22. package/dist/core/extract-shapes.js +993 -0
  23. package/dist/core/extract-xstate.d.ts +34 -0
  24. package/dist/core/extract-xstate.js +320 -0
  25. package/dist/core/extract.d.ts +31 -0
  26. package/dist/core/extract.js +249 -0
  27. package/dist/core/infer.d.ts +1 -0
  28. package/dist/core/infer.js +298 -28
  29. package/dist/core/kind.d.ts +30 -0
  30. package/dist/core/kind.js +81 -0
  31. package/dist/core/nonterm.d.ts +4 -1
  32. package/dist/core/nonterm.js +98 -2
  33. package/dist/core/relation.js +82 -7
  34. package/dist/core/transfer.js +1 -1
  35. package/dist/core/xstate.d.ts +6 -0
  36. package/dist/core/xstate.js +70 -12
  37. package/dist/kernel/cdcl.d.ts +15 -0
  38. package/dist/kernel/cdcl.js +331 -244
  39. package/dist/kernel/kernel.d.ts +15 -0
  40. package/dist/kernel/kernel.js +32 -0
  41. package/dist/kernel/prove.js +20 -7
  42. package/dist/kernel/reader.d.ts +14 -0
  43. package/dist/kernel/reader.js +102 -14
  44. package/dist/lean-kernel/emit.d.ts +28 -1
  45. package/dist/lean-kernel/emit.js +56 -15
  46. package/dist/lean-kernel/library.js +2 -1
  47. package/package.json +12 -3
@@ -148,6 +148,21 @@ export declare function checkStepLaws(m: Machine, laws: Law[], stepLaws: StepLaw
148
148
  trees: Record<string, Tree>;
149
149
  }): boolean;
150
150
  export declare const stepZone: (m: Machine, k: number) => string[];
151
+ export type KInduction = {
152
+ law: Law;
153
+ k: number;
154
+ };
155
+ export declare function kInductionSteps(machine: Machine, kl: KInduction): StepLaw[];
156
+ export declare const kInductionStart: (machine: Machine, kl: KInduction, instances: Instances) => Goal;
157
+ export declare function checkKInduction(m: Machine, laws: Law[], kl: KInduction, proof: {
158
+ laws: {
159
+ instances: Record<string, Instances>;
160
+ trees: Record<string, Tree>;
161
+ };
162
+ instances: Instances;
163
+ perStep?: Record<string, Instances>;
164
+ trees: Record<string, Tree>;
165
+ }): boolean;
151
166
  export type Fold = {
152
167
  name: string;
153
168
  params: string[];
@@ -1298,6 +1298,38 @@ export const stepZone = (m, k) => [
1298
1298
  ...Array.from({ length: k - 1 }, (_, i) => Object.values(laterNames(m, i + 2).vars).map(e => e.name)).flat(),
1299
1299
  ...Array.from({ length: k - 1 }, (_, i) => Object.keys(m.state).map(n => stateName(n, i + 1))).flat(),
1300
1300
  ];
1301
+ export function kInductionSteps(machine, kl) {
1302
+ const m = machine.history ? historyMachine(machine).machine : machine, L = kl.law, k = kl.k;
1303
+ if (L.forall || L.keys?.length || L.some?.length || L.ex)
1304
+ throw new Error(`k-induction of ${L.name}: a law with no key`);
1305
+ if (!Number.isInteger(k) || k < 1 || k > 64)
1306
+ throw new Error(`k-induction of ${L.name}: k is a whole number from 1 to 64`);
1307
+ // (as the twin's checkKInd: the law reads no request's name, flag or witness; the start reads none, nor a state
1308
+ // variable, nor a map; scope below asks the rest)
1309
+ const ext = [...m.inputs, ...quantified(m).flatMap(([f, q]) => [`?${f}`, ...witnessesOf(f, q)]), ...Object.keys(m.step.flags ?? {}).map(f => `?${f}`)];
1310
+ if (mentions(L.holds, ext) || Object.keys(m.state).some(n => ext.includes(n)))
1311
+ throw new Error(`k-induction of ${L.name}: reads a request's name or a flag`);
1312
+ for (const e of Object.values(m.state))
1313
+ if (mentions({ op: '=', a: e, b: e }, [...ext, ...Object.keys(m.state)]) || JSON.stringify(e).includes('"op":"get"'))
1314
+ throw new Error(`k-induction of ${L.name}: a start reads the params alone`);
1315
+ const start = { op: 'and', xs: Object.entries(m.state).map(([n, e]) => ({ op: '=', a: { op: 'var', name: n }, b: e })) };
1316
+ const after = { vars: Object.fromEntries(Object.keys(m.state).map(n => [n, { op: 'var', name: `${n}'` }])), maps: Object.fromEntries(Object.keys(m.maps ?? {}).map(map => [map, (key) => ({ op: 'get', map: `${map}'`, key })])), flags: {} };
1317
+ const then = substC(L.holds, after);
1318
+ return [
1319
+ ...Array.from({ length: k - 1 }, (_, i) => ({ name: `${L.name} @base ${i + 1}`, when: [{ op: 'and', xs: [start, L.holds] }, ...Array.from({ length: i }, () => L.holds)], then, steps: i + 1 })),
1320
+ { name: `${L.name} @k-step`, when: Array.from({ length: k }, () => L.holds), then, steps: k },
1321
+ ];
1322
+ }
1323
+ export const kInductionStart = (machine, kl, instances) => {
1324
+ const m = machine.history ? historyMachine(machine).machine : machine;
1325
+ return obligations(m, [kl.law], { [kl.law.name]: instances })[0];
1326
+ };
1327
+ export function checkKInduction(m, laws, kl, proof) {
1328
+ const steps = kInductionSteps(m, kl), plain = m.history ? historyMachine(m).machine : m;
1329
+ scope(plain, [...laws, kl.law]);
1330
+ const start = kInductionStart(m, kl, proof.perStep?.[`${kl.law.name} @start`] ?? proof.instances);
1331
+ return proof.trees[start.name] !== undefined && check(start, proof.trees[start.name]) && checkStepLaws(m, laws, steps, proof);
1332
+ }
1301
1333
  export function foldObligations(f, laws) {
1302
1334
  if (![...Object.values(f.leaf), ...Object.values(f.node)].every(natural) || !laws.every(law => !law.forall && !law.keys?.length && naturalC(law.holds) && !mentions(law.holds, f.inputs)))
1303
1335
  throw new Error('outside the kernel');
@@ -3,7 +3,7 @@ import { checkRefutation } from "../core/check.js";
3
3
  import { allowNode, allowTranslated, certCyclic, certOn, certSearch, closingInsts, crossCyclic, cyclicOn, cycLog, hasQuantified, loopNodes, machineNodes, proveCyclic, reqTS, searchedStepNodes, skMachine, timedKind, withWitness, translatedProof, uncovered, uncoveredWhy } from "../core/cyclic.js";
4
4
  import { proveSome, someLaws } from "../core/exists.js";
5
5
  import { growCdcl } from "./cdcl.js";
6
- import { assumed, atomOf, boundOf, canon, canonFlip, columnTerm, decided, factorsOf, isCell, isMonomial, stepZone, check, checkLaws, checkStepLaws, historyMachine, leafConstraints, leafConstraintsReusing, reusing, linear, livenessHelpful, livenessParts, loopMachine, obligations, plainKey, progressObligations, stepLawObligations, trueC, truth, unreachable, witnessesOf, withProducts } from "./kernel.js";
6
+ import { assumed, atomOf, boundOf, canon, canonFlip, columnTerm, decided, factorsOf, isCell, isMonomial, stepZone, check, checkLaws, checkStepLaws, historyMachine, substC, substE, leafConstraints, leafConstraintsReusing, reusing, linear, livenessHelpful, livenessParts, loopMachine, obligations, plainKey, progressObligations, stepLawObligations, trueC, truth, unreachable, witnessesOf, withProducts } from "./kernel.js";
7
7
  // The atoms the path leaves open, in evaluation order: deciding any of them makes progress.
8
8
  function openE(e, path, out) {
9
9
  switch (e.op) {
@@ -88,11 +88,13 @@ export function openCells(rows, path) {
88
88
  const names = [...new Set(rows.flatMap(r => Object.keys(r.lin)))].filter(isCell);
89
89
  const out = [];
90
90
  const keyText = (n) => n.slice(n.indexOf('[') + 1, -1);
91
- for (const [i, p] of names.entries())
92
- for (const q of names.slice(i + 1)) {
93
- if (p.slice(0, p.indexOf('[')) !== q.slice(0, q.indexOf('[')))
91
+ // (each name's map and key read once: the pairs are quadratic in the names)
92
+ const maps = names.map(n => n.slice(0, n.indexOf('['))), keys = names.map(n => parse(keyText(n)));
93
+ for (let i = 0; i < names.length; i++)
94
+ for (let j = i + 1; j < names.length; j++) {
95
+ if (maps[i] !== maps[j])
94
96
  continue;
95
- const d = sub(parse(keyText(p)), parse(keyText(q)));
97
+ const d = sub(keys[i], keys[j]);
96
98
  if (pairedKeys.skip && Object.keys(d).some(isMonomial))
97
99
  continue;
98
100
  const dec = (lin) => path.get(canon(lin))?.holds ?? (path.has(canonFlip(lin)) ? !path.get(canonFlip(lin)).holds : undefined);
@@ -977,7 +979,18 @@ function readKeys(m, laws) {
977
979
  }
978
980
  for (const l of laws.filter(l => !l.forall))
979
981
  inC(l.holds);
980
- return [...out.values()];
982
+ return keysInlined(m, [...out.values()]);
983
+ }
984
+ // Keys as the kernel's goals read them: a key that reads a flag (a map read at `when(flag, a, b)` in the step) with the
985
+ // flag's condition in its place (kernel.ts's updateOf inlines them so), since an instance is a term over the frame and
986
+ // names no flag. A quantified flag reads as its 0/1 variable ?f, as the goals read it.
987
+ function keysInlined(m, keys) {
988
+ if (!keys.some(e => JSON.stringify(e).includes('"op":"flag"')))
989
+ return keys;
990
+ const flags = {};
991
+ for (const [f, c] of Object.entries(m.step.flags ?? {}))
992
+ flags[f] = c.op === 'all' ? { op: '=', a: { op: 'var', name: `?${f}` }, b: { op: 'const', value: 1 } } : substC(c, { vars: {}, maps: {}, flags });
993
+ return [...new Map(keys.map(e => substE(e, { vars: {}, maps: {}, flags })).map(e => [JSON.stringify(e), e])).values()];
981
994
  }
982
995
  const shifts = (m) => Object.values(m.step.maps ?? {}).some(w => 'each' in w && !plainKey(w.value, w.each));
983
996
  // The keys some goals read a map at.
@@ -1556,7 +1569,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base) {
1556
1569
  // stepZone), so a k-step law drops the keys that read one; but a flag that holds at every key holds at a later step's
1557
1570
  // key too: where these instances don't prove it, each flag at its own witness at every step is tried (keptAcross).
1558
1571
  const shared = [...readKeys(plain, laws), ...witnesses(plain)], named = [...laws, ...(plain.facts ?? [])], reads = shifts(plain) || laws.some(l => l.keys?.length) || pairFlags(plain);
1559
- const own = (sl) => [...[sl.then, ...(sl.when === undefined ? [] : Array.isArray(sl.when) ? sl.when : [sl.when])].flatMap(readKeysC),
1572
+ const own = (sl) => [...keysInlined(plain, [sl.then, ...(sl.when === undefined ? [] : Array.isArray(sl.when) ? sl.when : [sl.when])].flatMap(readKeysC)),
1560
1573
  ...[sl.forall, ...(sl.keys ?? [])].flatMap(key => (key ? [{ op: 'var', name: key }] : []))];
1561
1574
  const perStep = {};
1562
1575
  for (const sl of stepLaws) {
@@ -51,8 +51,20 @@ export declare class Reader {
51
51
  private ls;
52
52
  private ts;
53
53
  private fs;
54
+ private os;
54
55
  constructor(goal: Goal, trail: Trail);
55
56
  begin(): void;
57
+ private up;
58
+ private byAtom;
59
+ private clean;
60
+ private frame;
61
+ private factKeys;
62
+ private openKeys;
63
+ private lastUp;
64
+ private read;
65
+ private readAtom;
66
+ private within;
67
+ touch(name: string): void;
56
68
  private ok;
57
69
  private kept;
58
70
  private units;
@@ -61,8 +73,10 @@ export declare class Reader {
61
73
  t: boolean | undefined;
62
74
  };
63
75
  linear(e: E): LV;
76
+ private linear0;
64
77
  private atoms;
65
78
  truth(c: C): TV;
79
+ private truth0;
66
80
  private factsOf;
67
81
  facts(i: number): FV;
68
82
  termRows(name: string): Row[];
@@ -36,6 +36,8 @@ function same(site, owner, a, b, c, make) {
36
36
  m.set(owner, { a, b, c, out });
37
37
  return out;
38
38
  }
39
+ // GDP_READER_CLEAN=0: values with an open read found again at every node, as before (for comparing).
40
+ const keepClean = globalThis.process?.env?.GDP_READER_CLEAN !== '0';
39
41
  export class Reader {
40
42
  goal;
41
43
  trail;
@@ -45,16 +47,71 @@ export class Reader {
45
47
  ls = new Map();
46
48
  ts = new Map();
47
49
  fs = [];
50
+ os = [];
48
51
  constructor(goal, trail) {
49
52
  this.goal = goal;
50
53
  this.trail = trail;
51
54
  }
52
- // A new node: values with an open read are found again.
55
+ // A new node: values with an open read are found again, unless nothing they read has changed.
53
56
  begin() { this.node++; }
54
- ok(x) {
55
- if (x.node === this.node)
57
+ // The reads: a value's key (its term, condition, or a hypothesis' facts or open atoms) → the keys of the values that
58
+ // read it; an atom's name → the keys of the values that read it. A clean key's value stands.
59
+ up = new Map();
60
+ byAtom = new Map();
61
+ clean = new Set();
62
+ frame;
63
+ factKeys = [];
64
+ openKeys = [];
65
+ lastUp = new WeakMap();
66
+ read(key) {
67
+ if (!this.frame || this.lastUp.get(key) === this.frame)
68
+ return;
69
+ this.lastUp.set(key, this.frame);
70
+ let s = this.up.get(key);
71
+ if (!s)
72
+ this.up.set(key, (s = new Set()));
73
+ s.add(this.frame);
74
+ }
75
+ readAtom(name) {
76
+ if (!this.frame)
77
+ return;
78
+ let s = this.byAtom.get(name);
79
+ if (!s)
80
+ this.byAtom.set(name, (s = new Set()));
81
+ s.add(this.frame);
82
+ }
83
+ within(key, f) {
84
+ const was = this.frame;
85
+ this.frame = key;
86
+ try {
87
+ return f();
88
+ }
89
+ finally {
90
+ this.frame = was;
91
+ }
92
+ }
93
+ // The trail changed at this atom (decided, or taken back): every value that read it, and every reader of those, all
94
+ // the way up (a value kept as final reads below it values that are not clean).
95
+ touch(name) {
96
+ const todo = [...(this.byAtom.get(name) ?? [])], seen = new Set();
97
+ while (todo.length) {
98
+ const key = todo.pop();
99
+ if (seen.has(key))
100
+ continue;
101
+ seen.add(key);
102
+ this.clean.delete(key);
103
+ for (const p of this.up.get(key) ?? [])
104
+ todo.push(p);
105
+ }
106
+ }
107
+ ok(x, key) {
108
+ if ((keepClean && this.clean.has(key)) || x.node === this.node)
109
+ return true;
110
+ if (x.fin && (x.pos < 0 || (x.pos < this.trail.size() && this.trail.stamp(x.pos) === x.stamp))) {
111
+ this.clean.add(key);
56
112
  return true;
57
- return x.fin && (x.pos < 0 || (x.pos < this.trail.size() && this.trail.stamp(x.pos) === x.stamp));
113
+ }
114
+ return false;
58
115
  }
59
116
  kept(r) { return { pos: r.pos, stamp: r.pos < 0 ? 0 : this.trail.stamp(r.pos), node: this.node }; }
60
117
  units = new Map();
@@ -73,7 +130,10 @@ export class Reader {
73
130
  let names = namePair.get(lin);
74
131
  if (!names)
75
132
  namePair.set(lin, (names = [canon(lin), canonFlip(lin)]));
76
- const [a, f] = names, x = this.trail.get(a);
133
+ const [a, f] = names;
134
+ this.readAtom(a);
135
+ this.readAtom(f);
136
+ const x = this.trail.get(a);
77
137
  if (x && x.val !== undefined)
78
138
  return { t: x.val, w: this.unit(a), pos: x.at, fin: true };
79
139
  const y = this.trail.get(f);
@@ -82,9 +142,13 @@ export class Reader {
82
142
  return { t: undefined, w: none, pos: -1, fin: false };
83
143
  }
84
144
  linear(e) {
145
+ this.read(e);
85
146
  const had = this.ls.get(e);
86
- if (had && this.ok(had))
147
+ if (had && this.ok(had, e))
87
148
  return had;
149
+ return this.within(e, () => this.linear0(e));
150
+ }
151
+ linear0(e) {
88
152
  let lin, r = R0;
89
153
  switch (e.op) {
90
154
  case 'var':
@@ -152,6 +216,7 @@ export class Reader {
152
216
  // (an open value's reason is what its decided parts need: only the column's own value is open)
153
217
  const out = { lin, w: r.w, fin: r.fin, ...this.kept(r) };
154
218
  this.ls.set(e, out);
219
+ this.clean.add(e);
155
220
  return out;
156
221
  }
157
222
  atoms(c) {
@@ -170,9 +235,13 @@ export class Reader {
170
235
  return { ...atoms, r };
171
236
  }
172
237
  truth(c) {
238
+ this.read(c);
173
239
  const had = this.ts.get(c);
174
- if (had && this.ok(had))
240
+ if (had && this.ok(had, c))
175
241
  return had;
242
+ return this.within(c, () => this.truth0(c));
243
+ }
244
+ truth0(c) {
176
245
  let t, r;
177
246
  switch (c.op) {
178
247
  case 'flag': throw new Error('flags are inlined before the kernel sees them');
@@ -241,6 +310,7 @@ export class Reader {
241
310
  // once the column's choice is decided, so a value through an open term is found again at each node).
242
311
  const out = { t, w: r.w, fin: t !== undefined && r.fin, ...this.kept(r) };
243
312
  this.ts.set(c, out);
313
+ this.clean.add(c);
244
314
  return out;
245
315
  }
246
316
  // kernel.ts's facts, each row with its reason; final when nothing it read is open.
@@ -316,13 +386,18 @@ export class Reader {
316
386
  }
317
387
  }
318
388
  facts(i) {
389
+ const key = (this.factKeys[i] ??= {});
390
+ this.read(key);
319
391
  const had = this.fs[i];
320
- if (had && this.ok(had))
392
+ if (had && this.ok(had, key))
321
393
  return had;
322
- const rows = [], r = this.factsOf(this.goal.hyps[i], true, rows);
323
- const out = { rows, fin: r.fin, ...this.kept(r) };
324
- this.fs[i] = out;
325
- return out;
394
+ return this.within(key, () => {
395
+ const rows = [], r = this.factsOf(this.goal.hyps[i], true, rows);
396
+ const out = { rows, fin: r.fin, ...this.kept(r) };
397
+ this.fs[i] = out;
398
+ this.clean.add(key);
399
+ return out;
400
+ });
326
401
  }
327
402
  // kernel.ts's termRows, each row with its reason (the forms made again only when a part's form is a new object).
328
403
  termRows(name) {
@@ -429,9 +504,22 @@ export class Reader {
429
504
  }
430
505
  // prove.ts's open atoms of a hypothesis (openH), in its order; none for a hypothesis whose facts are final.
431
506
  open(i, out) {
432
- if (this.facts(i).fin)
507
+ const key = (this.openKeys[i] ??= {}), had = this.os[i];
508
+ if (had && ((keepClean && this.clean.has(key)) || had.node === this.node)) {
509
+ for (const lin of had.lins)
510
+ out.push(lin);
433
511
  return;
434
- this.openH(this.goal.hyps[i], out, true);
512
+ }
513
+ const lins = this.within(key, () => {
514
+ const mine = [];
515
+ if (!this.facts(i).fin)
516
+ this.openH(this.goal.hyps[i], mine, true);
517
+ return mine;
518
+ });
519
+ this.os[i] = { lins, node: this.node };
520
+ this.clean.add(key);
521
+ for (const lin of lins)
522
+ out.push(lin);
435
523
  }
436
524
  openE(e, out) {
437
525
  switch (e.op) {
@@ -1,6 +1,7 @@
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 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 StepLaw, type Tree } from '../kernel/kernel.js';
4
+ import { proveStepLaws } from '../kernel/prove.js';
4
5
  import { type Cyclic } from '../kernel/cyclic.js';
5
6
  import { leanLibrary } from './library.js';
6
7
  export { leanLibrary };
@@ -78,6 +79,21 @@ export declare function machineLit(mm: Machine, t: {
78
79
  e: (x: E) => string;
79
80
  c: (x: C) => string;
80
81
  }, ix: (name: string) => number, mx: (name: string) => number): string;
82
+ export type KindLean = {
83
+ kl: KInduction;
84
+ start: {
85
+ goal: Goal;
86
+ tree: Tree;
87
+ inst: Instances;
88
+ };
89
+ tampers?: {
90
+ what: string;
91
+ k: number;
92
+ base: number[];
93
+ law?: C;
94
+ expect: boolean;
95
+ }[];
96
+ };
81
97
  export declare function smachineToLean(id: string, given: Machine, laws: Law[], opts?: {
82
98
  stepLaws?: StepLaw[];
83
99
  liveness?: Liveness[];
@@ -112,7 +128,9 @@ export declare function smachineToLean(id: string, given: Machine, laws: Law[],
112
128
  };
113
129
  };
114
130
  noFacts?: boolean;
131
+ kind?: KindLean;
115
132
  }): string;
133
+ export declare const seedStepProof: (m: Machine, laws: Law[], stepLaws: StepLaw[], r: ReturnType<typeof proveStepLaws>) => void;
116
134
  export declare const cyclicCerts: () => boolean;
117
135
  export declare const certReport: {
118
136
  cyclic: string[];
@@ -199,6 +217,15 @@ export type LeanItem = {
199
217
  id: string;
200
218
  fold: Fold;
201
219
  laws: Law[];
220
+ } | {
221
+ id: string;
222
+ kInduction: {
223
+ machine: Machine;
224
+ laws: Law[];
225
+ law: Law;
226
+ k?: number;
227
+ ms?: number;
228
+ };
202
229
  } | {
203
230
  id: string;
204
231
  goal: Goal;
@@ -1,12 +1,13 @@
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, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessRanks, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.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";
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";
7
7
  import { descentGoal, mainGoal, premiseGoal } from "../kernel/cyclic.js";
8
8
  import { allowNode, certMs, closingInsts, reqTS, withWitness, foldNodes, certMode, quietly, uncoveredWhy, hasQuantified, kWhens, machineNodes, proveCyclic, routeOf, searchedStepNodes, skMachine, stepLawNodes, tBack, tSub } from "../core/cyclic.js";
9
9
  import { leanLibrary } from "./library.js";
10
+ import { proveKInduction } from "../core/kind.js";
10
11
  export { leanLibrary };
11
12
  // --- to Lean ------------------------------------------------------------------------------------------------------------
12
13
  const varsOf = (c) => [...JSON.stringify(c).matchAll(/"op":"var","name":"([^"]+)"/g)].map(m => m[1]);
@@ -818,15 +819,13 @@ export function smachineToLean(id, given, laws, opts = {}) {
818
819
  const m = hplain ? hplain.machine : given;
819
820
  const claims = [];
820
821
  const claimSteps = () => claims.flatMap(cl => cl.steps);
821
- // The machine's own step laws, one step or k (Sets.lean's skstep_sound).
822
- if (!rf)
823
- stepLaws.forEach((sl, j) => claims.push({ steps: [sl], allows: [], render: h => {
824
- const { pr, inst } = h.step(sl), kk = sl.steps ?? 1;
825
- const whens = sl.when === undefined ? [] : Array.isArray(sl.when) ? sl.when : [sl.when];
826
- const ren = Array.from({ length: kk }, (_, s2) => (s2 === 0 ? '[]' : list(ext.map(v => `(${ix(v)}, ${ix(`${v}@${s2 + 1}`)})`))));
827
- const mren = Array.from({ length: kk }, (_, s2) => (s2 === 0 ? '[]' : list(carried.map(mp => `(${mx(mp)}, ${mx(`${mp}@${s2 + 1}`)})`))));
828
- return `-- Step law${kk > 1 ? ` over ${kk} steps` : ''}: ${sl.name}
829
- def ${id}_step${j} : SKStep := ⟨⟨${list(Array.from({ length: kk }, (_, s2) => (whens[s2] ? c(inline(whens[s2])) : TRUE)))},
822
+ // A step law's SKStep literal: its whens, then, the names its later requests and states are read by, its proof.
823
+ const skLit = (h, sl) => {
824
+ const { pr, inst } = h.step(sl), kk = sl.steps ?? 1;
825
+ const whens = sl.when === undefined ? [] : Array.isArray(sl.when) ? sl.when : [sl.when];
826
+ const ren = Array.from({ length: kk }, (_, s2) => (s2 === 0 ? '[]' : list(ext.map(v => `(${ix(v)}, ${ix(`${v}@${s2 + 1}`)})`))));
827
+ const mren = Array.from({ length: kk }, (_, s2) => (s2 === 0 ? '[]' : list(carried.map(mp => `(${mx(mp)}, ${mx(`${mp}@${s2 + 1}`)})`))));
828
+ return `⟨⟨${list(Array.from({ length: kk }, (_, s2) => (whens[s2] ? c(inline(whens[s2])) : TRUE)))},
830
829
  ${c(inline(sl.then))},
831
830
  ${list(ren)},
832
831
  ${list(Object.keys(m.state).map(s2 => `(${ix(s2)}, ${ix(`${s2}'`)})`))},
@@ -839,10 +838,39 @@ def ${id}_step${j} : SKStep := ⟨⟨${list(Array.from({ length: kk }, (_, s2) =
839
838
  ${list(pinsts(inst))},
840
839
  ${list(pfinsts(inst))},
841
840
  ${pr.hyps},
842
- ${list(Array.from({ length: kk - 1 }, (_, s2) => list(Object.keys(m.state).map(n2 => `(${ix(n2)}, ${ix(stateName(n2, s2 + 1))})`))))}⟩
841
+ ${list(Array.from({ length: kk - 1 }, (_, s2) => list(Object.keys(m.state).map(n2 => `(${ix(n2)}, ${ix(stateName(n2, s2 + 1))})`))))}⟩`;
842
+ };
843
+ // The machine's own step laws, one step or k (Sets.lean's skstep_sound).
844
+ if (!rf)
845
+ stepLaws.forEach((sl, j) => claims.push({ steps: [sl], allows: [], render: h => `-- Step law${(sl.steps ?? 1) > 1 ? ` over ${sl.steps} steps` : ''}: ${sl.name}
846
+ def ${id}_step${j} : SKStep := ${skLit(h, sl)}
843
847
  theorem ${id}_step${j}_holds : SKStepHolds ${id}_machine ${id}_step${j} :=
844
- skstep_sound ${id}_machine ${id}_proof ${id}_step${j} ${id}_check (by ${checkBy})`;
845
- } }));
848
+ skstep_sound ${id}_machine ${id}_proof ${id}_step${j} ${id}_check (by ${checkBy})` }));
849
+ // k-induction (KInd.lean's kind_sound): Lean builds each base goal's and the step's whens and then from the law; the
850
+ // trees, instances and names are the k-step laws' kernel.ts made (kInductionSteps), the start goal's tree its own.
851
+ const kd = opts.kind;
852
+ if (kd) {
853
+ const kSteps = kInductionSteps(m, kd.kl);
854
+ claims.push({ steps: kSteps, allows: [], render: h => {
855
+ const st = enc(kd.start.goal, kd.start.tree), kid = `${id}_kind`, k = kd.kl.k, base = kSteps.slice(0, -1);
856
+ const lit = (law, k2, bases) => `⟨${c(law)}, ${k2},
857
+ ${list(Object.keys(m.state).map(s2 => `(${ix(s2)}, ${ix(`${s2}'`)})`))},
858
+ ${list(Object.keys(m.maps ?? {}).map(mp => `(${mx(mp)}, ${mx(`${mp}'`)})`))},
859
+ ${list(finsts(kd.start.inst))},
860
+ ${list(pfinsts(kd.start.inst))},
861
+ (${st.tab}, ${st.hyps}, ${st.tree}),
862
+ ${list(bases.map(sl => skLit(h, sl)))},
863
+ ${skLit(h, kSteps.at(-1))}⟩`;
864
+ return `-- k-induction, k = ${k}: ${kd.kl.law.name}
865
+ def ${kid} : KInd := ${lit(kd.kl.law.holds, k, base)}
866
+ theorem ${kid}_check : checkKInd ${id}_machine ${id}_proof ${kid} = true := by ${checkBy}
867
+ /-- ${kd.kl.law.name}, by k-induction (k = ${k}): it holds in every reachable state. -/
868
+ theorem ${kid}_holds : ∀ ρ M, SReach ${id}_machine ρ M → evalC ρ M ${kid}.law = true :=
869
+ kind_sound ${id}_machine ${id}_proof ${kid} ${id}_check ${kid}_check${(kd.tampers ?? []).map(t => `
870
+ -- TAMPERED: ${t.what}. Lean computes the check to ${t.expect}, kernel.ts's answer.
871
+ example : checkKInd ${id}_machine ${id}_proof ${lit(t.law ?? kd.kl.law.holds, t.k, t.base.map(j => base[j]))} = ${t.expect} := by ${checkBy}`).join('')}`;
872
+ } });
873
+ }
846
874
  // A refinement (Refine.lean's SRefined): its step law, that the spec stutters or allows the request it is sent; srefines
847
875
  // says what the whole means.
848
876
  if (rf)
@@ -982,7 +1010,7 @@ theorem ${id}_orig_laws : ∀ ρ M, SReach ${id}_ghosted.orig ρ M → ∀ e ∈
982
1010
  })]));
983
1011
  const allowGoals = [...allowed.values()].flatMap(a => (a ? [a.out.goal] : []));
984
1012
  const named = machineNames(m, laws, allSteps, stepLaws, { ...opts, ...(hm ? { record: hm.history.record } : {}) });
985
- const vars = [...new Set([...named.vars, ...[...goalsL, ...goalsS, ...allowGoals, ...(hplain?.goals ?? [])].flatMap(g => g.hyps.flatMap(varsOf))])];
1013
+ const vars = [...new Set([...named.vars, ...[...goalsL, ...goalsS, ...allowGoals, ...(hplain?.goals ?? []), ...(opts.kind ? [opts.kind.start.goal] : [])].flatMap(g => g.hyps.flatMap(varsOf))])];
986
1014
  const mapNames = [...new Set([...named.maps, ...[...JSON.stringify([...goalsL, ...goalsS, ...allowGoals]).matchAll(/"op":"get","map":"([^"]+)"/g)].map(x2 => x2[1])])];
987
1015
  const enc = (g, tree) => encode({ name: `${id}: ${g.name}`, goal: g, tree }, false, true, vars, mapNames);
988
1016
  const { e, c } = leanTerms(vars, mapNames, id);
@@ -1114,6 +1142,8 @@ function proveStepLawsOnce(m, laws, stepLaws) {
1114
1142
  usualMade.set(key, r);
1115
1143
  return r;
1116
1144
  }
1145
+ // A proof made elsewhere (core/kind.ts's k-induction search), as the one the export reads for these step laws.
1146
+ export const seedStepProof = (m, laws, stepLaws, r) => { usualMade.set(JSON.stringify([m, laws, stepLaws]), r); };
1117
1147
  const envOf = () => globalThis.process?.env;
1118
1148
  export const cyclicCerts = certMode;
1119
1149
  let certsOn = false, cycTexts = 0;
@@ -1801,6 +1831,17 @@ function toLeanWith(items, opts) {
1801
1831
  // A datatype law's theorem is in a namespace of the item's (its datatypes and functions are named as declared).
1802
1832
  ...(item.after ? (ts => (item.data ? ts.slice(-1).map(t => `${id}.${t}`) : ts))([...item.after(() => 0, () => 0).matchAll(/^theorem (\S+)/gm)].map(x2 => x2[1])) : []));
1803
1833
  }
1834
+ else if ('kInduction' in item) {
1835
+ const { machine: m, laws, law, k, ms } = item.kInduction;
1836
+ const f = proveKInduction(m, laws, law, { ms: ms ?? 30_000, from: k ?? 1, to: k ?? 64 });
1837
+ if (!f.proven || !f.checked || !f.proof || !f.kl)
1838
+ throw new Error(`${item.id}: not proven by k-induction (${f.why ?? ''})`);
1839
+ const plain = m.history ? historyMachine(m).machine : m;
1840
+ seedStepProof(plain, f.laws, kInductionSteps(m, f.kl), { proven: true, checked: true, nodes: 0, leaves: 0, proof: f.proof });
1841
+ const start = kInductionStart(m, f.kl, {});
1842
+ parts.push(`-- ${item.id}\n${recurDefs(plain)}${smachineToLean(id, plain, f.laws, { kind: { kl: f.kl, start: { goal: start, tree: f.proof.trees[start.name], inst: {} } } })}`);
1843
+ theorems.push(`${id}_laws`, `${id}_kind_holds`);
1844
+ }
1804
1845
  else if ('fold' in item) {
1805
1846
  const cyc = certsOn ? cycFoldToLean(id, item.fold, item.laws) : undefined;
1806
1847
  if (cyc && 'text' in cyc)
@@ -1821,7 +1862,7 @@ function toLeanWith(items, opts) {
1821
1862
  }
1822
1863
  // The file the items need: Live.lean for a liveness or a loop, Sets.lean (which imports Steps.lean) for any machine.
1823
1864
  return `import History
1824
- ${items.some(item => 'neverEnds' in item) ? 'import NonTerm\n' : ''}${cycTexts ? 'import BridgeRules\n' : ''}${items.some(item => 'cyclic' in item) ? (items.some(item => 'cyclic' in item && (item.bridge || item.recur || item.fold)) ? 'import Bridge\n' : 'import Cyclic\n') : ''}${items.some(item => 'cyclic' in item && item.data) ? 'import Data\n' : ''}import ${items.some(item => 'refinement' in item) ? 'Refine' : items.some(item => 'machine' in item && (item.ghosts?.length || item.laws.some(l => l.some?.length))) ? 'Ghost' : items.some(item => ('machine' in item && item.liveness?.length) || 'loop' in item) ? 'Live' : items.some(item => 'machine' in item) ? 'Sets' : 'Steps'}
1865
+ ${items.some(item => 'neverEnds' in item) ? 'import NonTerm\n' : ''}${items.some(item => 'kInduction' in item) ? 'import KInd\n' : ''}${cycTexts ? 'import BridgeRules\n' : ''}${items.some(item => 'cyclic' in item) ? (items.some(item => 'cyclic' in item && (item.bridge || item.recur || item.fold)) ? 'import Bridge\n' : 'import Cyclic\n') : ''}${items.some(item => 'cyclic' in item && item.data) ? 'import Data\n' : ''}import ${items.some(item => 'refinement' in item) ? 'Refine' : items.some(item => 'machine' in item && (item.ghosts?.length || item.laws.some(l => l.some?.length))) ? 'Ghost' : items.some(item => ('machine' in item && item.liveness?.length) || 'loop' in item) ? 'Live' : items.some(item => 'machine' in item) ? 'Sets' : 'Steps'}
1825
1866
  open Kern Cert
1826
1867
  set_option maxRecDepth 100000
1827
1868
  set_option maxHeartbeats 0