gdp-wired 0.44.0 → 0.45.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 (66) hide show
  1. package/dist/core/c/reader.js +22 -7
  2. package/dist/core/check.js +3 -2
  3. package/dist/core/cli.d.ts +1 -0
  4. package/dist/core/cli.js +136 -6
  5. package/dist/core/counts.d.ts +1 -1
  6. package/dist/core/counts.js +30 -12
  7. package/dist/core/data.d.ts +6 -1
  8. package/dist/core/data.js +894 -152
  9. package/dist/core/dsl.d.ts +2 -0
  10. package/dist/core/dsl.js +88 -10
  11. package/dist/core/effect-prims.js +2 -2
  12. package/dist/core/ex/reader.exs +17 -1
  13. package/dist/core/exists.d.ts +15 -1
  14. package/dist/core/exists.js +263 -41
  15. package/dist/core/extract-c.js +19 -12
  16. package/dist/core/extract-check.d.ts +6 -0
  17. package/dist/core/extract-check.js +49 -3
  18. package/dist/core/extract-ex.js +3 -3
  19. package/dist/core/extract-go-check.js +19 -12
  20. package/dist/core/extract-go.js +20 -5
  21. package/dist/core/extract-jvm.js +63 -14
  22. package/dist/core/extract-print.js +3 -0
  23. package/dist/core/extract-py.js +3 -3
  24. package/dist/core/extract-rb.js +3 -3
  25. package/dist/core/extract-read.d.ts +8 -0
  26. package/dist/core/extract-read.js +55 -0
  27. package/dist/core/extract-rs.js +17 -19
  28. package/dist/core/extract-shapes.js +20 -0
  29. package/dist/core/extract-sol.js +19 -8
  30. package/dist/core/extract-step.d.ts +50 -3
  31. package/dist/core/extract-step.js +289 -58
  32. package/dist/core/extract-swift.js +20 -13
  33. package/dist/core/extract.d.ts +1 -0
  34. package/dist/core/extract.js +27 -2
  35. package/dist/core/fresh.d.ts +2 -2
  36. package/dist/core/fresh.js +7 -3
  37. package/dist/core/go/reader.go +7 -1
  38. package/dist/core/infer.js +115 -42
  39. package/dist/core/jvm/JavaReader.java +10 -2
  40. package/dist/core/jvm/Jvm.java +17 -1
  41. package/dist/core/jvm/KtReader.java +57 -5
  42. package/dist/core/machine.d.ts +1 -2
  43. package/dist/core/machine.js +27 -15
  44. package/dist/core/py/harness.py +77 -11
  45. package/dist/core/py/reader.py +50 -5
  46. package/dist/core/rb/reader.rb +52 -5
  47. package/dist/core/rs/src/main.rs +10 -0
  48. package/dist/core/sol/harness.py +6 -3
  49. package/dist/core/solver.js +5 -4
  50. package/dist/core/system.d.ts +62 -1
  51. package/dist/core/system.js +262 -3
  52. package/dist/core/transfer.js +17 -0
  53. package/dist/core/watch.js +1 -1
  54. package/dist/interchange/check.js +10 -10
  55. package/dist/interchange/format.d.ts +4 -0
  56. package/dist/interchange/format.js +13 -5
  57. package/dist/kernel/cdcl.js +33 -2
  58. package/dist/kernel/epr.js +35 -5
  59. package/dist/kernel/kernel.d.ts +2 -0
  60. package/dist/kernel/kernel.js +67 -40
  61. package/dist/kernel/prove.d.ts +22 -0
  62. package/dist/kernel/prove.js +156 -7
  63. package/dist/lean-kernel/emit.d.ts +9 -3
  64. package/dist/lean-kernel/emit.js +170 -29
  65. package/dist/lean-kernel/library.js +1 -1
  66. package/package.json +2 -2
@@ -13,7 +13,7 @@ import { add, costs, env, k, refuteFast, scale, solve, sub, v, work } from "../c
13
13
  import { checkRefutation } from "../core/check.js";
14
14
  import { allowNode, allowTranslated, certCyclic, certOn, certSearch, stepCertFloor, translateMs, closingInsts, crossCyclic, cyclicOn, cycLog, hasQuantified, loopNodes, machineNodes, proveCyclic, reqTS, searchedStepNodes, skMachine, timedKind, withWitness, translatedProof, uncovered, uncoveredWhy } from "../core/cyclic.js";
15
15
  import { proveSome, someLaws } from "../core/exists.js";
16
- import { growCdcl } from "./cdcl.js";
16
+ import { REFUTED, growCdcl } from "./cdcl.js";
17
17
  import { decide, pastEprCap, patternsOf } from "./epr.js";
18
18
  import { assumed, atomOf, boundOf, canon, canonFlip, columnTerm, decided, factorsOf, isCell, isMonomial, stepZone, check, checkLaws, checkStepLaws, historyMachine, plainOf, substC, substE, leafConstraints, leafConstraintsReusing, reusing, linear, livenessHelpful, livenessParts, strongly, loopMachine, obligations, plainKey, progressObligations, stepLawObligations, trueC, truth, unreachable, witnessesOf, withProducts } from "./kernel.js";
19
19
  // The atoms the path leaves open, in evaluation order: deciding any of them makes progress.
@@ -466,8 +466,150 @@ function eprFirst(goal, budget, whole = true, late = () => pastWall() || pastEpr
466
466
  eprScope.busy = false;
467
467
  }
468
468
  }
469
+ // Wide goals (GDP_WIDE hypotheses or more, a law at every tuple of a goal's keys, a step's every write, and
470
+ // GDP_WIDE_TERMS terms): each node of the search reads every hypothesis' rows, so a goal of a thousand reaches neither a
471
+ // tree nor a model within its budget, though its refutation reads one or two and a model of a few is often a model of
472
+ // all. Grown first over a part: the conclusion, then the hypotheses a model of the part breaks (the model read as a
473
+ // state: each cell at its key's value, any other name 0), those sharing a cell with the part first, the part doubled a
474
+ // round. A model that breaks none is the goal's (every hypothesis holds at it); a tree is widened to the goal (`widen`),
475
+ // which the kernel checks as any; a model-only query's refutation is the part's, its core the part's hypotheses. Within
476
+ // a share of the goal's budget, each round within what the whole's search would spend on as many nodes; anything else
477
+ // leaves the goal as before. Untrusted.
478
+ const wideAt = Number(env.GDP_WIDE ?? 256), wideTerms = Number(env.GDP_WIDE_TERMS ?? 40_000), wideShare = Number(env.GDP_WIDE_SHARE ?? 0.25), wideTrace = !!env.GDP_WIDE_TRACE;
479
+ let wideBusy = false;
480
+ // (while a part is grown: whether a point holds every hypothesis of the part, read as a state; a node's point that does is
481
+ // the part's model, whatever atoms are still open, and the whole's if it breaks none of the rest)
482
+ export const wideScope = {};
483
+ export const wideStats = { goals: 0, trees: 0, models: 0, rounds: 0 };
484
+ export const wideHook = {};
485
+ const cellsIn = (c) => { const out = new Set(); walkOnce(c, o => { const x = o; if (x.op === 'get')
486
+ out.add(`${x.map}${JSON.stringify(x.key)}`); }); return out; };
487
+ // (the hypotheses a model breaks among `ids` (all where none are given), the model read as a state, the conclusion first;
488
+ // `first`: the first one broken alone)
489
+ export const brokenOf = (goal) => {
490
+ const maps = new Set();
491
+ walkOnce(goal.hyps, o => { const x = o; if (x.op === 'get' && typeof x.map === 'string')
492
+ maps.add(x.map); });
493
+ const mm = { maps: Object.fromEntries([...maps].map(mp => [mp, 0])) };
494
+ return (w0, ids = goal.hyps.map((_, i) => i), first = false) => {
495
+ // (a term column's value is its term's at the point, not the point's own where its choice is open: each cell is put
496
+ // at its key's value with the columns so read, twice, as a column's term may read a cell)
497
+ const w = { ...w0 }, at = new Proxy(w, { get: (t, q) => t[q] ?? 0 }), out = [];
498
+ let st = { scalars: {}, maps: {} };
499
+ for (let pass = 0; pass < 3; pass++) {
500
+ if (pass)
501
+ for (const n in w) {
502
+ const e = n.startsWith('⟦') ? columnTerm(n) : undefined;
503
+ if (e)
504
+ try {
505
+ w[n] = evalE(e, at, st, mm);
506
+ }
507
+ catch { /* left */ }
508
+ }
509
+ st = { scalars: {}, maps: Object.fromEntries([...maps].map(mp => [mp, new Map()])) };
510
+ for (const [cell, value] of Object.entries(w)) {
511
+ const br = cell.indexOf('['), key = br > 0 && cell.endsWith(']') && st.maps[cell.slice(0, br)] ? keyValue(cell, w) : undefined;
512
+ if (key !== undefined)
513
+ st.maps[cell.slice(0, br)].set(key, value);
514
+ }
515
+ }
516
+ for (let q = ids.length - 1; q >= 0 && !(first && out.length); q--) {
517
+ const i = ids[q];
518
+ let ok = false;
519
+ try {
520
+ ok = evalC(goal.hyps[i], at, st, mm);
521
+ }
522
+ catch { /* broken */ }
523
+ if (!ok)
524
+ out.push(i);
525
+ }
526
+ return out.reverse();
527
+ };
528
+ };
529
+ // (`ask`: how a part is asked, a tree wanted by default; kernel/cdcl.ts's model-only queries ask for a model or a
530
+ // refutation, whose core is the part's hypotheses, the whole's by index)
531
+ // (and its terms, each shared part once, past GDP_WIDE_TERMS: what each node of the whole goal's search reads, where the
532
+ // search is costly; under it the whole is asked as before, its model the search's own, which the engine's join reads)
533
+ const termsSeen = new WeakMap();
534
+ const termsOf = (goal) => { let n = termsSeen.get(goal); if (n === undefined) {
535
+ n = 0;
536
+ walkOnce(goal.hyps, () => { n++; });
537
+ termsSeen.set(goal, n);
538
+ } return n; };
539
+ export const wideFor = (goal) => !wideBusy && goal.hyps.length >= wideAt && termsOf(goal) >= wideTerms;
540
+ export function growWide(goal, budget, ask = (g, until) => grow(g, new Map(), { nodes: 0, until })) {
541
+ const hyps = goal.hyps, last = hyps.length - 1, broken = brokenOf(goal), now = clock(), w = fullWork();
542
+ const end = withinDeadline(budget.until ?? Infinity), span = wideShare * (end - now), room = wideShare * (workCap - w), until = now + span;
543
+ const part = new Set([last]), near = new Set(cellsIn(hyps[last])), cells = new Map();
544
+ const cellsAt = (i) => { let c = cells.get(i); if (!c)
545
+ cells.set(i, (c = cellsIn(hyps[i]))); return c; };
546
+ const take = (i) => { part.add(i); for (const x of cellsAt(i))
547
+ near.add(x); };
548
+ wideBusy = true;
549
+ wideStats.goals++;
550
+ try {
551
+ while (!late(until)) {
552
+ wideStats.rounds++;
553
+ // (a part's own budget: what the whole's search spends on as many nodes, four times over (a node of the part reads
554
+ // that much less), at least a sixteenth of the share: a part that a small budget doesn't settle leaves the goal)
555
+ const ids = [...part].sort((a, b) => a - b), g = { name: goal.name, hyps: ids.map(i => hyps[i]) }, f = Math.max(1 / 16, Math.min(1, 4 * part.size / hyps.length));
556
+ const t0 = performance.now(), at = clock();
557
+ wideScope.judge = w => !broken(w, ids, true).length;
558
+ let out;
559
+ try {
560
+ out = withWork(Math.min(w + room, fullWork() + f * room), () => ask(g, Math.min(until, at + f * span)));
561
+ }
562
+ finally {
563
+ wideScope.judge = undefined;
564
+ }
565
+ wideHook.on?.(g, out);
566
+ if (wideTrace)
567
+ console.error(`[wide] ${goal.name.slice(0, 40)}: part ${g.hyps.length} of ${hyps.length}, ${'tree' in out ? 'tree' : out.stuck} in ${Math.round(performance.now() - t0)} ms${'tree' in out ? '' : ` ${out.why?.slice(0, 50) ?? ''}`}`);
568
+ if ('tree' in out) {
569
+ const tree = withWork(w + room, () => withDeadline(until, () => widen(g, goal, out.tree)));
570
+ if (tree)
571
+ wideStats.trees++;
572
+ return tree && { tree, nodes: out.nodes };
573
+ }
574
+ if (out.why === REFUTED)
575
+ return { ...out, ...(out.core ? { core: out.core.map(i => ids[i]) } : {}) };
576
+ if (out.stuck !== 'sat' || !out.witness)
577
+ return undefined;
578
+ const bad = broken(out.witness);
579
+ if (wideTrace)
580
+ console.error(`[wide] breaks ${bad.length}${bad.length ? `: ${bad.slice(0, 12).join(' ')}` : ''}`);
581
+ if (!bad.length) {
582
+ wideStats.models++;
583
+ return { ...out, path: new Map() };
584
+ }
585
+ const more = bad.filter(i => !part.has(i)), size = part.size;
586
+ if (!more.length || 2 * size > hyps.length)
587
+ return undefined;
588
+ // (what the model breaks, those sharing a cell with the part first; then, to twice the part, the hypotheses that share
589
+ // one, then any, in the goal's order: the rounds are as many as the doublings to the part that settles the goal)
590
+ const shared = (i) => [...cellsAt(i)].some(x => near.has(x));
591
+ more.sort((a, b) => Number(shared(b)) - Number(shared(a)));
592
+ for (const i of more.slice(0, Math.max(16, size)))
593
+ take(i);
594
+ for (const any of [false, true])
595
+ for (let i = 0; i < last && part.size < 2 * size; i++)
596
+ if (!part.has(i) && (any || shared(i)))
597
+ take(i);
598
+ }
599
+ return undefined;
600
+ }
601
+ finally {
602
+ wideBusy = false;
603
+ }
604
+ }
469
605
  function growRoot(goal, path, budget) {
470
- if (eprScope.patterns && !eprScope.busy && !path.size && !budget.nodes) {
606
+ if (!path.size && !budget.nodes && wideFor(goal)) {
607
+ const out = growWide(goal, budget);
608
+ if (out)
609
+ return out;
610
+ }
611
+ // (not for a wide goal's part: its abstraction's search reads no judge, and the whole goal is decided by it after)
612
+ if (eprScope.patterns && !eprScope.busy && !wideBusy && !path.size && !budget.nodes) {
471
613
  const out = eprFirst(goal, budget);
472
614
  if (out)
473
615
  return out;
@@ -555,6 +697,8 @@ function growPlain(goal, path, budget) {
555
697
  const verdict = next && rows.length > 60 ? solveP(rows, 2 * rows.length) : solveP(rows);
556
698
  if (verdict.kind === 'refuted')
557
699
  return { tree: leafOf(verdict.steps), nodes: budget.nodes };
700
+ if (next && wideScope.judge && verdict.kind === 'sat' && wideScope.judge(verdict.witness))
701
+ return { stuck: 'sat', witness: verdict.witness, path };
558
702
  // Before a split, the rows the plain search sets aside (those reading a term column) by their Farkas rows: an open
559
703
  // choice's bounds (min(a, c) ≤ c) often refute the case whichever way the choice goes, so its cases need no split.
560
704
  if (next && !columns && full.length > rows.length) {
@@ -1088,7 +1232,7 @@ function withCuts(goal, path, budget) {
1088
1232
  const chain = [];
1089
1233
  let at = new Map(path);
1090
1234
  for (const { n, e } of columns) {
1091
- if (pastWall())
1235
+ if (late(budget.until ?? Infinity))
1092
1236
  return undefined;
1093
1237
  if (e.op !== 'if')
1094
1238
  continue;
@@ -1099,7 +1243,7 @@ function withCuts(goal, path, budget) {
1099
1243
  const id = canon(lemma);
1100
1244
  if (at.has(id) || Object.keys(lemma).every(key => key === '1'))
1101
1245
  continue;
1102
- const no = growFocused(goal, new Map(at).set(id, { lin: lemma, holds: false }), focus, { nodes: 0 });
1246
+ const no = growFocused(goal, new Map(at).set(id, { lin: lemma, holds: false }), focus, { nodes: 0, until: budget.until });
1103
1247
  if ('tree' in no) {
1104
1248
  chain.push({ split: lemma, no: no.tree });
1105
1249
  at = new Map(at).set(id, { lin: lemma, holds: true });
@@ -1127,11 +1271,16 @@ function topAtoms(c, path) {
1127
1271
  const atoms = c.op === '<=' ? [sub(a, b)] : c.op === '<' ? [add(sub(a, b), k(1))] : [sub(a, b), sub(b, a)];
1128
1272
  return atoms.filter(l => Object.keys(l).some(key => key !== '1') && !path.has(canon(l)) && !path.has(canonFlip(l)));
1129
1273
  }
1130
- // A refutation that splits only on these atoms (a cut's failing side), within a small budget.
1274
+ // A refutation that splits only on these atoms (a cut's failing side), within a small budget and the goal's end (past
1275
+ // it the goal is left unknown whatever the cuts find: the search after them stops at its first node).
1131
1276
  function growFocused(goal, path, focus, budget, near = focus) {
1132
- if (++budget.nodes > 64 || pastWall())
1277
+ if (++budget.nodes > 64 || late(budget.until ?? Infinity))
1133
1278
  return { stuck: 'unknown', path };
1134
- const verdict = solveNear(leafConstraints(goal, path), [...near, ...[...path.values()].slice(-1).map(a => a.lin)]);
1279
+ // (each node reads its whole leaf, counted as growPlain counts a node's rows)
1280
+ const leaf = leafConstraints(goal, path);
1281
+ work.n += 1 + leaf.length;
1282
+ costs.plainRows += leaf.length;
1283
+ const verdict = solveNear(leaf, [...near, ...[...path.values()].slice(-1).map(a => a.lin)]);
1135
1284
  if (verdict.kind === 'refuted')
1136
1285
  return { tree: { leaf: verdict.steps }, nodes: budget.nodes };
1137
1286
  const split = focus.find(l => !path.has(canon(l)) && !path.has(canonFlip(l)));
@@ -53,13 +53,14 @@ export declare function neverEndsToLean(id: string, l: Loop, r: Recur, tampered?
53
53
  recur: Recur;
54
54
  }[]): string;
55
55
  export declare function neverEndsCasesToLean(id: string, l: Loop, r: RecurCases): string;
56
- export declare function recurCasesLean(id: string, l: Loop): {
56
+ export declare function recurCasesLean(id: string, l: Loop, share?: boolean): {
57
57
  vars: string[];
58
58
  loop: string;
59
- recur: (r: RecurCases) => string;
59
+ recur: (r: RecurCases, names?: string[]) => string;
60
+ caseLit: (r: RecurCases, j: number) => string;
60
61
  defs: string;
61
62
  };
62
- export declare function recurLean(id: string, l: Loop, fallback: Recur | undefined): {
63
+ export declare function recurLean(id: string, l: Loop, fallback: Recur | undefined, share?: boolean): {
63
64
  vars: string[];
64
65
  loop: string;
65
66
  recur: (r: Recur) => string;
@@ -142,6 +143,11 @@ export declare function smachineToLean(id: string, given: Machine, laws: Law[],
142
143
  at: E;
143
144
  as: string;
144
145
  }[];
146
+ ghostSubst?: {
147
+ law: string;
148
+ body: C;
149
+ sub: Record<string, E>;
150
+ }[];
145
151
  refined?: {
146
152
  impl: Machine;
147
153
  spec: Machine;
@@ -530,15 +530,16 @@ export function loopToLean(id, l, laws, rank, tamper) {
530
530
  export function neverEndsToLean(id, l, r, tampered = []) {
531
531
  if (!checkRecur(l, r))
532
532
  throw new Error(`${id}: the certificate does not check`);
533
- const { vars, loop, recur, defs } = recurLean(id, l, r);
533
+ const { vars, loop, recur, defs } = recurLean(id, l, r, true), d = dataDef();
534
534
  return `-- ${l.name}: a run that never ends (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')})
535
- ${defs ? `${defs}\n` : ''}def ${id}_loop : Loop := ${loop}
536
- def ${id}_recur : Recur := ${recur(r)}
535
+ ${defs ? `${defs}\n` : ''}${d} ${id}_loop : Loop := ${loop}
536
+ ${d} ${id}_recur : Recur := ${recur(r)}
537
537
  /-- ${l.name} never ends: for some params meeting its precondition, a run of turns from the start goes on forever. -/
538
538
  theorem ${id}_never_ends : NeverEnds ${id}_loop :=
539
- never_ends_of ${id}_loop ${id}_recur (by ${checkBy})${tampered.map((t, j) => `
539
+ never_ends_of ${id}_loop ${id}_recur (by
540
+ ${checkInParts('checkRecur', [])})${tampered.map((t, j) => `
540
541
  -- TAMPERED: ${t.what}. Lean computes the check to false.
541
- def ${id}_tampered${j} : Recur := ${recur(t.recur)}
542
+ ${d} ${id}_tampered${j} : Recur := ${recur(t.recur)}
542
543
  example : checkRecur ${id}_loop ${id}_tampered${j} = false := by ${checkBy}`).join('')}`;
543
544
  }
544
545
  // 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
@@ -546,17 +547,32 @@ example : checkRecur ${id}_loop ${id}_tampered${j} = false := by ${checkBy}`).jo
546
547
  export function neverEndsCasesToLean(id, l, r) {
547
548
  if (!checkRecurCases(l, r))
548
549
  throw new Error(`${id}: the certificate does not check`);
549
- const { vars, loop, recur, defs } = recurCasesLean(id, l);
550
+ const { vars, loop, recur, caseLit, defs } = recurCasesLean(id, l, true), d = dataDef();
551
+ const names = r.cases.map((_, j) => `${id}_case${j}`);
550
552
  return `-- ${l.name}: a run that never ends, closed by ${r.cases.length} cases (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')})
551
- ${defs ? `${defs}\n` : ''}def ${id}_loop : Loop := ${loop}
552
- def ${id}_recur : RecurCases := ${recur(r)}
553
+ ${defs ? `${defs}\n` : ''}${d} ${id}_loop : Loop := ${loop}
554
+ ${names.map((n, j) => `${d} ${n} : List (Nat × Nat) × C × Cert := ${caseLit(r, j)}\n`).join('')}${d} ${id}_recur : RecurCases := ${recur(r, names)}
553
555
  /-- ${l.name} never ends: for some params meeting its precondition, a run of turns from the start goes on forever. -/
554
556
  theorem ${id}_never_ends : NeverEnds ${id}_loop :=
555
- never_ends_of_cases ${id}_loop ${id}_recur (by ${checkBy})`;
557
+ never_ends_of_cases ${id}_loop ${id}_recur (by
558
+ ${checkInParts('checkRecurCases', [`show ${id}_recur.cases = ${list(names)} from rfl`])})`;
559
+ }
560
+ // Definitions that are data: no compiled code for Lean to make (a large loop's terms take its compiler past its
561
+ // recursion limit and many GB), unless native_decide runs them.
562
+ const dataDef = () => checkBy === 'native_decide' ? 'def' : 'noncomputable def';
563
+ // A certificate's check, one part at a time: its definition unfolded into its conjuncts (the cases' list into one per
564
+ // case), each conjunct computed by the kernel on its own (an auxiliary lemma each, so the kernel's caches of one part
565
+ // are gone before the next: a large program's stem and each case's goal, not all of them at once). The same check of
566
+ // the same definitions, only its && split; Lean proves the split.
567
+ function checkInParts(check, rws) {
568
+ return ` rw [${[check, ...rws].join(', ')}]
569
+ simp only [List.all_cons, List.all_nil, Bool.and_true, Bool.and_eq_true]
570
+ repeat' apply And.intro
571
+ all_goals ${checkBy}`;
556
572
  }
557
573
  // A certificate by cases as NonTerm.lean's RecurCases (each tree written against the goal it refutes, else none).
558
- export function recurCasesLean(id, l) {
559
- const { vars, loop, defs } = recurLean(id, l, undefined);
574
+ export function recurCasesLean(id, l, share = false) {
575
+ const { vars, loop, defs } = recurLean(id, l, undefined, share);
560
576
  const { e, c } = leanTerms(vars, [], id);
561
577
  const ix = (name) => { const j = vars.indexOf(name); if (j < 0)
562
578
  throw new Error(`${id}: no variable for ${name}`); return j; };
@@ -572,36 +588,152 @@ export function recurCasesLean(id, l) {
572
588
  const coded = fits ? encode({ name: `${id}: ${goal.name}`, goal, tree }, false, true, vars, [], false, true) : { tab: '[]', tree: '.leafAt [] [] [] []' };
573
589
  return `(${coded.tab}, [], ${coded.tree})`;
574
590
  };
575
- const recur = (r) => `⟨${list(vars.map((_, j) => String(j)))},
576
- ${vals(r.start)},
577
- ${list(r.stem.map(vals))},
591
+ const caseLit = (r, j) => { const k2 = r.cases[j]; return `(${list(k2.pins.map(([n2, x]) => `(${ix(n2)}, ${x})`))}, ${c(k2.cond)}, ${cert(goals(r)[j], k2.tree)})`; };
592
+ // (the cases written in place, or as the names given, one per case)
593
+ const recur = (r, names) => `⟨${domOrder(vars, l, r.set, r.start)},
594
+ ${vals(nonzero(r.start))},
595
+ ${list(r.stem.map(t => vals(nonzero(t))))},
578
596
  ${c(r.set)},
579
597
  ${list(Object.entries(r.wit).map(([name, t]) => `(${ix(name)}, ${e(t)})`))},
580
598
  ${cert(coverGoal(r), r.cover)},
581
- ${list(r.cases.map((k2, j) => `(${list(k2.pins.map(([n2, x]) => `(${ix(n2)}, ${x})`))}, ${c(k2.cond)}, ${cert(goals(r)[j], k2.tree)})`))}⟩`;
599
+ ${list(names ?? r.cases.map((_, j) => caseLit(r, j)))}⟩`;
582
600
  const made = new WeakMap(), goals = (r) => { let g = made.get(r); if (!g)
583
601
  made.set(r, (g = caseGoals(l, r, r.cases))); return g; };
584
- return { vars, loop, recur, defs };
602
+ return { vars, loop, recur, caseLit, defs };
603
+ }
604
+ // A stem's domain and values as Lean reads them fastest. Its values are each looked up in a list: a value 0 is left out
605
+ // (valsEnv reads a value not listed as 0), and so is from the domain a variable no turn, the start or an input writes
606
+ // whose start is 0 (a run's state off the domain is 0 there, as it is anyway: Lean's stem reads the same values). Then
607
+ // the domain in the order the run reads it most: every rule's condition reads the location, so the variables the
608
+ // conditions read come first (most read first, the rest in their order). NonTerm.lean's domOk reads the domain as a set.
609
+ const nonzero = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== 0));
610
+ function domOrder(vars, l, set, start) {
611
+ const reads = new Map();
612
+ const walk = (t, inC) => {
613
+ if (!t || typeof t !== 'object')
614
+ return;
615
+ const o = t;
616
+ if (o.op === 'var' && inC)
617
+ reads.set(o.name, (reads.get(o.name) ?? 0) + 1);
618
+ const c = inC || ['<=', '<', '=', 'and', 'or', 'not'].includes(o.op ?? '');
619
+ for (const v of Object.values(t))
620
+ if (v && typeof v === 'object')
621
+ (Array.isArray(v) ? v : [v]).forEach(x => walk(x, c));
622
+ };
623
+ for (const t of [...Object.values(l.body), l.while, ...(l.assume ? [l.assume] : []), set])
624
+ walk(t, false);
625
+ const written = new Set([...l.inputs, ...Object.keys(l.state), ...Object.keys(l.body), ...Object.keys(nonzero(start))]);
626
+ return list(vars.flatMap((name, j) => (written.has(name) ? [{ j, n: reads.get(name) ?? 0 }] : [])).sort((a, b) => b.n - a.n || a.j - b.j).map(x => String(x.j)));
627
+ }
628
+ // Terms written once each where they recur (recurLean's loops): `count` each term first, then `e` prints a term with
629
+ // each condition or term that has no if in it and recurs (3 uses or more, 24 characters or more) as its name, s<k>,
630
+ // and `defs` gives their definitions (`d`: def or noncomputable def), in the order they were named.
631
+ function sharedTerms(vars, where, plainE) {
632
+ const { c: plainC } = leanTerms(vars, [], where);
633
+ const counts = new Map(), names = new Map(), out = [];
634
+ const ifFree = new WeakMap();
635
+ const free = (t) => {
636
+ const had = ifFree.get(t);
637
+ if (had !== undefined)
638
+ return had;
639
+ const r = t.op === 'if' ? false : Object.values(t).every(v => typeof v !== 'object' || v === null || (Array.isArray(v) ? v.every(x => typeof x !== 'object' || free(x)) : free(v)));
640
+ ifFree.set(t, r);
641
+ return r;
642
+ };
643
+ const isC = (t) => ['<=', '<', '=', 'and', 'or', 'not', 'flag', 'all'].includes(t.op);
644
+ const text = (t) => (isC(t) ? plainC(t) : plainE(t));
645
+ const atomic = (t) => t.op === 'var' || t.op === 'const';
646
+ const count = (t) => {
647
+ if (atomic(t))
648
+ return;
649
+ if (free(t)) {
650
+ const k = text(t);
651
+ counts.set(k, (counts.get(k) ?? 0) + 1);
652
+ return;
653
+ }
654
+ for (const v of Object.values(t))
655
+ if (typeof v === 'object' && v !== null)
656
+ (Array.isArray(v) ? v : [v]).forEach(x => typeof x === 'object' && count(x));
657
+ };
658
+ const named = (t, k) => {
659
+ if (k.length < 24 || (counts.get(k) ?? 0) < 3)
660
+ return undefined;
661
+ let name = names.get(k);
662
+ if (!name) {
663
+ names.set(k, (name = `s${names.size}`));
664
+ out.push(`${isC(t) ? 'C' : 'E'}\u0000${name}\u0000${k}`);
665
+ }
666
+ return name;
667
+ };
668
+ const e = (t) => {
669
+ if (atomic(t))
670
+ return plainE(t);
671
+ if (free(t)) {
672
+ const k = plainE(t);
673
+ return named(t, k) ?? k;
674
+ }
675
+ switch (t.op) {
676
+ case 'mul': return `.mul ${exactNat(t.k)} (${e(t.a)})`;
677
+ case 'add':
678
+ case 'sub':
679
+ case 'min':
680
+ case 'max':
681
+ case 'prod': return `.${t.op} (${e(t.a)}) (${e(t.b)})`;
682
+ case 'if': return `.ite (${c(t.c)}) (${e(t.then)}) (${e(t.else)})`;
683
+ case 'get': return plainE(t);
684
+ }
685
+ };
686
+ const c = (t) => {
687
+ if (free(t)) {
688
+ const k = plainC(t);
689
+ return named(t, k) ?? k;
690
+ }
691
+ switch (t.op) {
692
+ case '<=': return `.le (${e(t.a)}) (${e(t.b)})`;
693
+ case '<': return `.lt (${e(t.a)}) (${e(t.b)})`;
694
+ case '=': return `.eq (${e(t.a)}) (${e(t.b)})`;
695
+ case 'not': return `.not (${c(t.x)})`;
696
+ case 'and':
697
+ case 'or': return t.xs.length === 0 ? plainC(t) : t.xs.map(c).reduceRight((acc, y) => `.${t.op} (${y}) (${acc})`);
698
+ case 'flag':
699
+ case 'all': return plainC(t);
700
+ }
701
+ };
702
+ const defs = (d) => out.map(x => { const [ty, name, k] = x.split('\u0000'); return `${d} ${name} : ${ty} := ${k}`; });
703
+ return { count, e, c, defs };
585
704
  }
586
- // The loop and a certificate as NonTerm.lean's Loop and Recur (the domain every variable; a certificate whose tree
587
- // 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.
705
+ // The loop and a certificate as NonTerm.lean's Loop and Recur (the domain and the values as domOrder and nonzero give
706
+ // them; a certificate whose tree doesn't refute its own goal carries `fallback`'s table and tree, which refutes
707
+ // `fallback`'s). lean-kernel/conformance.ts prints its cases with it. `share`: the loop's recurring terms named
708
+ // (sharedTerms), for an export that writes `defs` out.
588
709
  // (a loop's start and body past 128 variables as definitions of 128 each, appended: Lean elaborates a list literal of
589
710
  // deep terms one level deeper per entry, and pgarch's 690 body terms, each 228 rules deep, pass its recursion limit)
590
- export function recurLean(id, l, fallback) {
711
+ export function recurLean(id, l, fallback, share = false) {
591
712
  const vars = [...l.params, ...l.inputs, ...Object.keys(l.state)];
592
713
  const { e, c } = leanTerms(vars, [], id);
593
714
  const ix = (name) => { const j = vars.indexOf(name); if (j < 0)
594
715
  throw new Error(`${id}: no variable for ${name}`); return j; };
595
716
  const defs = [];
717
+ // A large program's terms are each variable's rules as one chain of ifs, every chain over the same conditions (the
718
+ // locations) and much the same updates: each such term past a few uses written once, as a definition (s<k>, in the
719
+ // namespace <id>_s, with the chains' pieces), and named where it is used. The same terms, as Lean unfolds them.
720
+ const sh = sharedTerms(vars, id, e), ns = `${id}_s`, entries = (o) => Object.entries(o).map(([name, e2]) => `(${ix(name)}, ${sh.e(e2)})`);
721
+ if (share)
722
+ for (const t of [...Object.values(l.state), ...Object.values(l.body)])
723
+ sh.count(t);
724
+ const init = entries(l.state), body = entries(l.body), shared = sh.defs(dataDef());
596
725
  const pieces = (what, xs) => {
597
- if (xs.length <= 128)
726
+ if (xs.length <= 128 && !shared.length)
598
727
  return list(xs);
599
- 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}`; });
600
- return `(${names.join(' ++ ')})`;
728
+ const names = Array.from({ length: Math.ceil(xs.length / 128) }, (_, k) => { defs.push(`${dataDef()} ${what}${k} : List (Nat × E) := ${list(xs.slice(k * 128, k * 128 + 128))}`); return `${ns}.${what}${k}`; });
729
+ return names.length ? `(${names.join(' ++ ')})` : '[]';
601
730
  };
731
+ const loopInit = pieces('init', init), loopBody = pieces('body', body);
732
+ if (defs.length)
733
+ defs.splice(0, 0, `namespace ${ns}`, ...shared), defs.push(`end ${ns}`);
602
734
  const loop = `⟨${list(l.inputs.map(name => String(ix(name))))},
603
- ${pieces('init', Object.entries(l.state).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
604
- ${pieces('body', Object.entries(l.body).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
735
+ ${loopInit},
736
+ ${loopBody},
605
737
  ${c(l.while)},
606
738
  ${l.pre ? c(l.pre) : TRUE},
607
739
  ${l.assume ? c(l.assume) : TRUE}⟩`;
@@ -620,9 +752,9 @@ export function recurLean(id, l, fallback) {
620
752
  // (neither refuting its goal, as a forged certificate's: a leaf with no step, the tree that refutes nothing)
621
753
  const by = fits(rr) ? rr : fallback && fits(fallback) ? fallback : undefined;
622
754
  const coded = by ? enc(by) : { tab: '[]', tree: '.leafAt [] [] [] []' };
623
- return `⟨${list(vars.map((_, j) => String(j)))},
624
- ${vals(rr.start)},
625
- ${list(rr.stem.map(vals))},
755
+ return `⟨${domOrder(vars, l, rr.set, rr.start)},
756
+ ${vals(nonzero(rr.start))},
757
+ ${list(rr.stem.map(t => vals(nonzero(t))))},
626
758
  ${c(rr.set)},
627
759
  ${list(Object.entries(rr.wit).map(([name, t]) => `(${ix(name)}, ${e(t)})`))},
628
760
  (${coded.tab}, [], ${coded.tree})⟩`;
@@ -1233,6 +1365,16 @@ theorem ${id}_some${j} : ∀ ρ M, SReach ${id}_gm.orig ρ M → ∀ v, ∃ val,
1233
1365
  (by ${checkBy}) (by ${checkBy}) (by ${checkBy}) (by ${checkBy})
1234
1366
  have hr : substRC [] (rdW ${mx(fs.map)} ${ix(fs.as)}) ${id}_e${li}.law.holds = ${c(read)} := by ${checkBy}
1235
1367
  rw [hr] at h; exact h`;
1368
+ }).join('')}${(opts.ghostSubst ?? []).map((gs, j) => {
1369
+ const li = laws.findIndex(l => l.name === gs.law), law = laws[li];
1370
+ if (!law)
1371
+ throw new Error(`${id}: ${gs.law}: no such law`);
1372
+ const sigma = list(Object.entries(gs.sub).map(([x, t]) => `(${ix(x)}, ${e(t)})`));
1373
+ return `
1374
+ /-- ${law.name}, read ∃: for every value of its keys, some natural for each of ${Object.keys(gs.sub).join(', ')} (at the ghosts' terms) where its body holds; no ghost read. -/
1375
+ theorem ${id}_ex${j} : ∀ ρ M, SReach ${id}_gm.orig ρ M → ExHolds (${c(gs.body)}) ${id}_e${li}.law.key ${list(Object.keys(gs.sub).map(x => String(ix(x))))} M ${id}_e${li}.keys2 ρ :=
1376
+ forall_some_of_ghostsubst ${id}_gm ${id}_gmOk ${id}_proof ${id}_check ${id}_e${li} (${memOf(li)}) ${sigma} (${c(gs.body)})
1377
+ (by ${checkBy}) (by ${checkBy}) (by ${checkBy})`;
1236
1378
  }).join('')}`;
1237
1379
  } });
1238
1380
  // Ghosts (Ghost.lean's sghost_laws): the laws that read no ghost hold of the machine without its ghosts.
@@ -2293,8 +2435,7 @@ ${cycProofText(id, p, tampered, vars, maps)}${bridge ? `\n${cycBridgeLean(id, p,
2293
2435
  // node's membership, the check and cyclic_sound's theorem; each tampered proof's check computed to false.
2294
2436
  function cycProofText(id, p, tampered, vars, maps) {
2295
2437
  const { e, c } = leanTerms(vars, maps, id);
2296
- // (data, not code: no compiled code for Lean to make, unless native_decide runs it)
2297
- const d = checkBy === 'native_decide' ? 'def' : 'noncomputable def';
2438
+ const d = dataDef();
2298
2439
  const ix = (name) => vars.indexOf(name);
2299
2440
  const facts = list(p.facts.map(f => `⟨${list(f.keys.map(key => String(ix(key))))}, ${c(f.holds)}⟩`));
2300
2441
  // A tampered proof keeps the proof's tables and trees (made for the proof's own goals) under its changed nodes.