gdp-wired 0.47.0 → 0.48.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 (170) hide show
  1. package/README.md +15 -4
  2. package/dist/core/carry.d.ts +15 -0
  3. package/dist/core/carry.js +651 -0
  4. package/dist/core/cli.d.ts +3 -1
  5. package/dist/core/cli.js +28 -8
  6. package/dist/core/count-cases.d.ts +24 -0
  7. package/dist/core/count-cases.js +320 -0
  8. package/dist/core/count-cert-grow.d.ts +4 -0
  9. package/dist/core/count-cert-grow.js +37 -0
  10. package/dist/core/count-cert-transport.d.ts +3 -0
  11. package/dist/core/count-cert-transport.js +58 -0
  12. package/dist/core/count-completion.d.ts +9 -0
  13. package/dist/core/count-completion.js +27 -0
  14. package/dist/core/count-cubes.d.ts +8 -0
  15. package/dist/core/count-cubes.js +69 -0
  16. package/dist/core/count-demand.d.ts +37 -0
  17. package/dist/core/count-demand.js +361 -0
  18. package/dist/core/count-facts.d.ts +52 -0
  19. package/dist/core/count-facts.js +247 -0
  20. package/dist/core/count-focus-proof.d.ts +8 -0
  21. package/dist/core/count-focus-proof.js +140 -0
  22. package/dist/core/count-focused.d.ts +22 -0
  23. package/dist/core/count-focused.js +676 -0
  24. package/dist/core/count-ranges.d.ts +5 -0
  25. package/dist/core/count-ranges.js +65 -0
  26. package/dist/core/count-recovery/action-guard.d.ts +5 -0
  27. package/dist/core/count-recovery/action-guard.js +51 -0
  28. package/dist/core/count-recovery/boolean-core.d.ts +16 -0
  29. package/dist/core/count-recovery/boolean-core.js +258 -0
  30. package/dist/core/count-recovery/carried-case.d.ts +2 -0
  31. package/dist/core/count-recovery/carried-case.js +24 -0
  32. package/dist/core/count-recovery/conditional-check-cache.d.ts +23 -0
  33. package/dist/core/count-recovery/conditional-check-cache.js +130 -0
  34. package/dist/core/count-recovery/conditional-cuts.d.ts +6 -0
  35. package/dist/core/count-recovery/conditional-cuts.js +318 -0
  36. package/dist/core/count-recovery/conditional-proof.d.ts +19 -0
  37. package/dist/core/count-recovery/conditional-proof.js +306 -0
  38. package/dist/core/count-recovery/derivability-closure.d.ts +14 -0
  39. package/dist/core/count-recovery/derivability-closure.js +533 -0
  40. package/dist/core/count-recovery/empty-count-source.d.ts +2 -0
  41. package/dist/core/count-recovery/empty-count-source.js +40 -0
  42. package/dist/core/count-recovery/field-bound-lemmas.d.ts +23 -0
  43. package/dist/core/count-recovery/field-bound-lemmas.js +640 -0
  44. package/dist/core/count-recovery/field-case.d.ts +5 -0
  45. package/dist/core/count-recovery/field-case.js +89 -0
  46. package/dist/core/count-recovery/field-demand.d.ts +46 -0
  47. package/dist/core/count-recovery/field-demand.js +47 -0
  48. package/dist/core/count-recovery/field-only.d.ts +3 -0
  49. package/dist/core/count-recovery/field-only.js +18 -0
  50. package/dist/core/count-recovery/fold-path.d.ts +6 -0
  51. package/dist/core/count-recovery/fold-path.js +35 -0
  52. package/dist/core/count-recovery/frame-lemmas.d.ts +9 -0
  53. package/dist/core/count-recovery/frame-lemmas.js +120 -0
  54. package/dist/core/count-recovery/guard-cases.d.ts +12 -0
  55. package/dist/core/count-recovery/guard-cases.js +138 -0
  56. package/dist/core/count-recovery/key-closure.d.ts +14 -0
  57. package/dist/core/count-recovery/key-closure.js +62 -0
  58. package/dist/core/count-recovery/leaf-allowance.d.ts +4 -0
  59. package/dist/core/count-recovery/leaf-allowance.js +7 -0
  60. package/dist/core/count-recovery/lift-count-proxies.d.ts +6 -0
  61. package/dist/core/count-recovery/lift-count-proxies.js +175 -0
  62. package/dist/core/count-recovery/live-dependencies.d.ts +6 -0
  63. package/dist/core/count-recovery/live-dependencies.js +76 -0
  64. package/dist/core/count-recovery/member-inclusions.d.ts +11 -0
  65. package/dist/core/count-recovery/member-inclusions.js +168 -0
  66. package/dist/core/count-recovery/member-premises.d.ts +29 -0
  67. package/dist/core/count-recovery/member-premises.js +114 -0
  68. package/dist/core/count-recovery/natural-cases.d.ts +6 -0
  69. package/dist/core/count-recovery/natural-cases.js +59 -0
  70. package/dist/core/count-recovery/ops.d.ts +6 -0
  71. package/dist/core/count-recovery/ops.js +8 -0
  72. package/dist/core/count-recovery/pre-state-source.d.ts +8 -0
  73. package/dist/core/count-recovery/pre-state-source.js +18 -0
  74. package/dist/core/count-recovery/rebase-path.d.ts +9 -0
  75. package/dist/core/count-recovery/rebase-path.js +70 -0
  76. package/dist/core/count-recovery/rename-proof.d.ts +2 -0
  77. package/dist/core/count-recovery/rename-proof.js +102 -0
  78. package/dist/core/count-recovery/row-cases.d.ts +16 -0
  79. package/dist/core/count-recovery/row-cases.js +291 -0
  80. package/dist/core/count-recovery/scalar-guards.d.ts +7 -0
  81. package/dist/core/count-recovery/scalar-guards.js +291 -0
  82. package/dist/core/count-recovery/source-memo.d.ts +12 -0
  83. package/dist/core/count-recovery/source-memo.js +67 -0
  84. package/dist/core/count-select.d.ts +16 -0
  85. package/dist/core/count-select.js +24 -0
  86. package/dist/core/count-support.d.ts +598 -0
  87. package/dist/core/count-support.js +2080 -0
  88. package/dist/core/count-unions.d.ts +2 -0
  89. package/dist/core/count-unions.js +139 -0
  90. package/dist/core/count-witness-flags.d.ts +9 -0
  91. package/dist/core/count-witness-flags.js +37 -0
  92. package/dist/core/count-write-frames.d.ts +12 -0
  93. package/dist/core/count-write-frames.js +206 -0
  94. package/dist/core/counts.d.ts +20 -2
  95. package/dist/core/counts.js +807 -156
  96. package/dist/core/dsl.d.ts +50 -6
  97. package/dist/core/dsl.js +307 -65
  98. package/dist/core/effect.js +8 -1
  99. package/dist/core/exists.d.ts +1 -1
  100. package/dist/core/exists.js +80 -15
  101. package/dist/core/extract-check.d.ts +7 -1
  102. package/dist/core/extract-check.js +130 -13
  103. package/dist/core/extract-read.d.ts +22 -8
  104. package/dist/core/extract-read.js +29 -11
  105. package/dist/core/extract-shapes.js +122 -41
  106. package/dist/core/extract-standalone.js +53 -9
  107. package/dist/core/extract.js +9 -3
  108. package/dist/core/field-laws.d.ts +2 -0
  109. package/dist/core/field-laws.js +100 -0
  110. package/dist/core/finite-frontiers.d.ts +5 -0
  111. package/dist/core/finite-frontiers.js +116 -0
  112. package/dist/core/finite-houdini.d.ts +52 -0
  113. package/dist/core/finite-houdini.js +460 -0
  114. package/dist/core/finite-model.d.ts +13 -0
  115. package/dist/core/finite-model.js +68 -0
  116. package/dist/core/finite-tiny.d.ts +72 -0
  117. package/dist/core/finite-tiny.js +1052 -0
  118. package/dist/core/infer.d.ts +1 -1
  119. package/dist/core/infer.js +32 -9
  120. package/dist/core/laws.d.ts +2 -1
  121. package/dist/core/laws.js +47 -14
  122. package/dist/core/lemma-cuts.d.ts +38 -0
  123. package/dist/core/lemma-cuts.js +365 -0
  124. package/dist/core/machine.d.ts +39 -2
  125. package/dist/core/machine.js +240 -35
  126. package/dist/core/mutate.d.ts +55 -0
  127. package/dist/core/mutate.js +210 -0
  128. package/dist/core/native-domain.d.ts +6 -0
  129. package/dist/core/native-domain.js +114 -0
  130. package/dist/core/native-law.d.ts +3 -0
  131. package/dist/core/native-law.js +174 -0
  132. package/dist/core/quorum-laws.d.ts +5 -0
  133. package/dist/core/quorum-laws.js +239 -0
  134. package/dist/core/relational.js +10 -2
  135. package/dist/core/relevance.d.ts +4 -0
  136. package/dist/core/relevance.js +79 -0
  137. package/dist/core/runtime-wall.d.ts +3 -0
  138. package/dist/core/runtime-wall.js +4 -0
  139. package/dist/core/sample-step.d.ts +16 -0
  140. package/dist/core/sample-step.js +28 -0
  141. package/dist/core/source-check.d.ts +44 -0
  142. package/dist/core/source-check.js +126 -0
  143. package/dist/core/source-diagnostic.d.ts +1 -0
  144. package/dist/core/source-diagnostic.js +34 -0
  145. package/dist/core/support-budget.d.ts +2 -0
  146. package/dist/core/support-budget.js +6 -0
  147. package/dist/core/system.js +2 -0
  148. package/dist/core/wall.d.ts +6 -0
  149. package/dist/core/wall.js +23 -0
  150. package/dist/core/watch.js +4 -0
  151. package/dist/kernel/cdcl.d.ts +4 -0
  152. package/dist/kernel/cdcl.js +20 -5
  153. package/dist/kernel/kernel.d.ts +10 -0
  154. package/dist/kernel/kernel.js +56 -3
  155. package/dist/kernel/model-sequence.d.ts +2 -2
  156. package/dist/kernel/model-sequence.js +4 -3
  157. package/dist/kernel/model-values.d.ts +2 -0
  158. package/dist/kernel/model-values.js +60 -0
  159. package/dist/kernel/prove.d.ts +10 -0
  160. package/dist/kernel/prove.js +56 -8
  161. package/dist/kernel/prover-rows.d.ts +29 -0
  162. package/dist/kernel/prover-rows.js +114 -0
  163. package/dist/lean-kernel/emit.d.ts +39 -2
  164. package/dist/lean-kernel/emit.js +136 -24
  165. package/dist/lean-kernel/lean-terms.d.ts +1 -0
  166. package/dist/lean-kernel/lean-terms.js +13 -5
  167. package/dist/lean-kernel/library.js +4 -0
  168. package/dist/lean-kernel/qalpha.d.ts +7 -0
  169. package/dist/lean-kernel/qalpha.js +40 -0
  170. package/package.json +5 -1
@@ -0,0 +1,114 @@
1
+ import { env } from "../core/solver.js";
2
+ import { canon, leafConstraintsReusing } from "./kernel.js";
3
+ const originals = new WeakMap(), ids = new WeakMap();
4
+ const nodes = new Map();
5
+ let serial = 0, keyChars = 0;
6
+ export const rowReuseStats = { nodeHits: 0, nodeMisses: 0, goalHits: 0, rowsHits: 0, rowsBuilt: 0, rowsEvicted: 0 };
7
+ const id = (o) => { let n = ids.get(o); if (n === undefined)
8
+ ids.set(o, (n = ++serial)); return n; };
9
+ function intern(value) {
10
+ if (!value || typeof value !== 'object')
11
+ return value;
12
+ const had = originals.get(value);
13
+ if (had)
14
+ return had;
15
+ const values = Array.isArray(value) ? value.map(intern) : Object.fromEntries(Object.entries(value).map(([k, v]) => [k, intern(v)]));
16
+ const ref = (v) => v && typeof v === 'object' ? ['@', id(v)] : typeof v === 'number' && !Number.isFinite(v) ? ['number', String(v)] : ['value', v];
17
+ const key = Array.isArray(values) ? JSON.stringify(['array', values.map(ref)]) : JSON.stringify(['object', Object.entries(values).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, ref(v)])]);
18
+ let out = nodes.get(key);
19
+ if (out)
20
+ rowReuseStats.nodeHits++;
21
+ else {
22
+ if (nodes.size >= 100000 || keyChars + key.length > 32 * 1024 * 1024) {
23
+ nodes.clear();
24
+ keyChars = 0;
25
+ }
26
+ nodes.set(key, (out = values));
27
+ keyChars += key.length;
28
+ rowReuseStats.nodeMisses++;
29
+ }
30
+ originals.set(value, out);
31
+ originals.set(out, out);
32
+ id(out);
33
+ return out;
34
+ }
35
+ const goals = new WeakMap(), goalPool = new Map();
36
+ function sharedGoal(goal) {
37
+ let out = goals.get(goal);
38
+ if (out)
39
+ return out;
40
+ const hyps = goal.hyps.map(c => intern(c)), key = hyps.map(id).join(',');
41
+ out = goalPool.get(key);
42
+ if (out) {
43
+ rowReuseStats.goalHits++;
44
+ goalPool.delete(key);
45
+ }
46
+ else
47
+ out = { name: goal.name, hyps };
48
+ if (goalPool.size >= 128)
49
+ goalPool.delete(goalPool.keys().next().value);
50
+ goalPool.set(key, out);
51
+ goals.set(goal, out);
52
+ return out;
53
+ }
54
+ // This is a retention budget, never a proof/search allowance. Limit row weight
55
+ // as well as entry count: 8192 large leaves can otherwise retain millions of
56
+ // constraints and cause GC stalls in a strict-wall run.
57
+ export class ProverRowsCache {
58
+ maxRows;
59
+ maxEntries;
60
+ entries = new Map();
61
+ kept = 0;
62
+ constructor(maxRows, maxEntries = 8192) {
63
+ this.maxRows = maxRows;
64
+ this.maxEntries = maxEntries;
65
+ if (maxRows !== Infinity && (!Number.isSafeInteger(maxRows) || maxRows < 0) || !Number.isSafeInteger(maxEntries) || maxEntries < 1)
66
+ throw new RangeError('invalid row-cache retention budget');
67
+ }
68
+ get size() { return this.entries.size; }
69
+ get weight() { return this.kept; }
70
+ get(key) {
71
+ const value = this.entries.get(key);
72
+ if (value) {
73
+ this.entries.delete(key);
74
+ this.entries.set(key, value);
75
+ }
76
+ return value;
77
+ }
78
+ set(key, value) {
79
+ const old = this.entries.get(key);
80
+ if (old) {
81
+ this.kept -= old.length;
82
+ this.entries.delete(key);
83
+ }
84
+ if (value.length > this.maxRows)
85
+ return 0;
86
+ let evicted = 0;
87
+ while (this.entries.size >= this.maxEntries || this.kept + value.length > this.maxRows) {
88
+ const first = this.entries.keys().next().value;
89
+ this.kept -= this.entries.get(first).length;
90
+ this.entries.delete(first);
91
+ evicted++;
92
+ }
93
+ this.entries.set(key, value);
94
+ this.kept += value.length;
95
+ return evicted;
96
+ }
97
+ }
98
+ const rows = new ProverRowsCache(env.GDP_ROWS_UNWEIGHTED === '1' ? Infinity : 250000);
99
+ export const rowReuseStorage = () => ({ nodes: nodes.size, keyChars, goals: goalPool.size, rowEntries: rows.size, constraints: rows.weight });
100
+ export function proverRows(goal, path) {
101
+ const shared = sharedGoal(goal);
102
+ // Path ordering matters for input-row indices. Include the actual atom as
103
+ // well as its lookup key, so even malformed key/atom pairs cannot alias.
104
+ const key = JSON.stringify([id(shared), [...path].map(([key, a]) => [key, a.holds, canon(a.lin)])]);
105
+ let out = rows.get(key);
106
+ if (out) {
107
+ rowReuseStats.rowsHits++;
108
+ return out;
109
+ }
110
+ rowReuseStats.rowsBuilt++;
111
+ out = leafConstraintsReusing(shared, path);
112
+ rowReuseStats.rowsEvicted += rows.set(key, out);
113
+ return out;
114
+ }
@@ -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 CountCert, type CountedGoal, type CountInst, type Ghosted, 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';
3
+ import { type CountCert, type CountedGoal, type CountInst, type LemmaCut, type Ghosted, 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,11 @@ 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, reach?: boolean): {
20
+ export declare function encode(ex: Exported, tamper?: boolean, dropStep?: boolean, globalVars?: string[], globalMaps?: string[], slim?: boolean, reach?: boolean, context?: {
21
+ path?: Path;
22
+ lemmas?: LemmaCut[];
23
+ cols?: string[];
24
+ }): {
21
25
  tab: string;
22
26
  tabCols: string[];
23
27
  hyps: string;
@@ -25,11 +29,28 @@ export declare function encode(ex: Exported, tamper?: boolean, dropStep?: boolea
25
29
  cols: string[];
26
30
  c: (t: C) => string;
27
31
  e: (t: E) => string;
32
+ row: (lin: Lin) => string;
28
33
  };
29
34
  export declare function goalToLean(ex: Exported, i: number, tamper?: boolean, dropStep?: boolean): string;
35
+ export declare function encodeCounted(id: string, goal: Goal, cert: {
36
+ tree: Tree;
37
+ lemmas?: LemmaCut[];
38
+ }, vars: string[], maps: string[]): {
39
+ lemmas: string;
40
+ lemmaList: (entries: LemmaCut[]) => string;
41
+ tab: string;
42
+ tabCols: string[];
43
+ hyps: string;
44
+ tree: string;
45
+ cols: string[];
46
+ c: (t: C) => string;
47
+ e: (t: E) => string;
48
+ row: (lin: Lin) => string;
49
+ };
30
50
  export declare function countedToLean(id: string, g: CountedGoal, cert: {
31
51
  insts: CountInst[];
32
52
  tree: Tree;
53
+ lemmas?: LemmaCut[];
33
54
  }, tampered?: {
34
55
  what: string;
35
56
  insts: CountInst[];
@@ -279,6 +300,22 @@ export type LeanItem = {
279
300
  k?: number;
280
301
  ms?: number;
281
302
  };
303
+ } | {
304
+ id: string;
305
+ countedGoal: CountedGoal;
306
+ certificate: {
307
+ insts: CountInst[];
308
+ tree: Tree;
309
+ lemmas?: LemmaCut[];
310
+ };
311
+ } | {
312
+ id: string;
313
+ countedMachine: Machine;
314
+ laws: Law[];
315
+ proof: {
316
+ instances: Record<string, Instances>;
317
+ certs: Record<string, CountCert>;
318
+ };
282
319
  } | {
283
320
  id: string;
284
321
  goal: Goal;
@@ -1,13 +1,14 @@
1
1
  import { atMost, n, not, pointWrite } from "../core/machine.js";
2
2
  import { add, k, scale, sub } from "../core/solver.js";
3
- import { countedGoal, countedObligations, countHyps, mcGoal, postName, boundOf, caseGoals, cellParts, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, sumMachine, sumCovers, sumParts, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessLevels, livenessRanks, strongly, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
3
+ import { lemmaPath, checkCounted, checkCountedLaws, countedGoal, countedObligations, countHyps, mcGoal, postName, boundOf, caseGoals, cellParts, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, sumMachine, sumCovers, sumParts, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessLevels, livenessRanks, strongly, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
4
4
  import { chooseLevels, clock, grow, minimal, proveBuilt, proveLaws, proveSetFast, proveStepLaws, withDeadline } from "../kernel/prove.js";
5
5
  import { refinement, refinementSides } from "../core/compose.js";
6
- import { exactNat, leanSurface, leanTerms } from "./lean-terms.js";
6
+ import { exactNat, leanConnective, 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
10
  import { proveKInduction } from "../core/kind.js";
11
+ import { quantifiedRenames } from "./qalpha.js";
11
12
  export { leanLibrary };
12
13
  // --- to Lean ------------------------------------------------------------------------------------------------------------
13
14
  const varsOf = (c) => [...JSON.stringify(c).matchAll(/"op":"var","name":"([^"]+)"/g)].map(m => m[1]);
@@ -108,7 +109,7 @@ function reachedChoices(goal, leafList) {
108
109
  }
109
110
  return out;
110
111
  }
111
- export function encode(ex, tamper = false, dropStep = true, globalVars, globalMaps, slim = false, reach = false) {
112
+ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMaps, slim = false, reach = false, context = {}) {
112
113
  const { goal, tree } = ex;
113
114
  // `slim`: the table only has the columns Lean reads. Each row a leaf uses has a hint (where Lean looks for it first),
114
115
  // and Lean computes only the hinted hypotheses' linear forms (Kernel.lean's srcRows), so the columns are the
@@ -118,7 +119,10 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
118
119
  // hypotheses, so its table is a few columns, not every choice of the node's facts.
119
120
  // Each leaf with its path and rows, found once (the passes below and the tree's text read them in the same order).
120
121
  const leafList = [];
121
- leaves(tree, new Map(), (leaf, path) => { leafList.push({ leaf, path, base: leafConstraints(goal, path) }); });
122
+ leaves(tree, context.path ?? new Map(), (leaf, path) => {
123
+ const visible = lemmaPath(context.lemmas ?? [], path);
124
+ leafList.push({ leaf, path: visible, base: leafConstraints(goal, visible) });
125
+ });
122
126
  const reads = new Set(), hintTerms = new Set();
123
127
  let whole = !slim;
124
128
  if (slim)
@@ -245,7 +249,7 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
245
249
  place(cell);
246
250
  for (const mono of cellMonos)
247
251
  place(mono);
248
- const cols = [...vars, ...plainMonos, ...[...terms].sort((a, b) => Number(a.slice(1, -1)) - Number(b.slice(1, -1))), ...late];
252
+ const cols = context.cols ?? [...vars, ...plainMonos, ...[...terms].sort((a, b) => Number(a.slice(1, -1)) - Number(b.slice(1, -1))), ...late];
249
253
  const col = new Map(cols.map((name, j) => [name, j]));
250
254
  const maps = globalMaps ?? [...new Set([...[...cells].map(cellMap), ...goal.hyps.flatMap(h => [...JSON.stringify(h).matchAll(/"op":"get","map":"([^"]+)"/g)].map(m => m[1]))])];
251
255
  const dense = (lin) => {
@@ -326,7 +330,7 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
326
330
  if (!src)
327
331
  return '.any';
328
332
  if ('atom' in src)
329
- return `.atom ${path.size - 1 - src.atom}`; // Lean's path has the latest decision first
333
+ return context.path || context.lemmas?.length ? '.any' : `.atom ${path.size - 1 - src.atom}`; // Lean's path has the latest decision first
330
334
  if ('fact' in src)
331
335
  return `.fact ${src.fact}`;
332
336
  const j = 'pair' in src ? pairs.indexOf([...src.pair].sort().join('\n')) : col.get('nat' in src ? src.nat : src.term) ?? -1;
@@ -340,7 +344,7 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
340
344
  const at2 = list(used.map(u => `(${row(rows[u])}, ${hint(base[u].src)})`)), rest = `${list(steps)} ${list(keepEqs.map(j => eqs[j]))} ${list(prods.map(([i, j]) => `(${idx(i)}, ${idx(j)})`))}`;
341
345
  return squares.length ? `.leafSq ${at2} ${list(squares.map(row))} ${rest}` : `.leafAt ${at2} ${rest}`;
342
346
  };
343
- return { tab: list(tab), tabCols: tab, hyps: list(goal.hyps.map(c)), tree: lean(tree), cols, c, e };
347
+ return { tab: list(tab), tabCols: tab, hyps: list(goal.hyps.map(c)), tree: lean(tree), cols, c, e, row };
344
348
  }
345
349
  export function goalToLean(ex, i, tamper = false, dropStep = true) {
346
350
  const { tab, hyps, tree, cols } = encode(ex, tamper, dropStep);
@@ -363,14 +367,96 @@ theorem ${name} : ∀ env maps, ¬ ∀ c ∈ ${name}_goal.hyps, evalC env maps c
363
367
  // certificates Lean computes to false, as kernel.ts refuses them.
364
368
  const varsOfE = (t) => [...JSON.stringify(t).matchAll(/"op":"var","name":"([^"]+)"/g)].map(m => m[1]);
365
369
  const mapsOf = (t) => [...JSON.stringify(t).matchAll(/"op":"get","map":"([^"]+)"/g)].map(m => m[1]);
370
+ // Extra row names may appear only in a lemma. Resolve their column dependencies with the same rules as encode.
371
+ function lemmaNames(lemmas) {
372
+ const vars = new Set(), maps = new Set(), seen = new Set();
373
+ const name = (s) => {
374
+ if (s === '1' || seen.has(s))
375
+ return;
376
+ seen.add(s);
377
+ if (isMonomial(s)) {
378
+ factorsOf(s).forEach(name);
379
+ return;
380
+ }
381
+ if (isCell(s)) {
382
+ maps.add(cellMap(s));
383
+ cellKeys(s).forEach(row);
384
+ return;
385
+ }
386
+ const term = columnTerm(s);
387
+ if (term) {
388
+ varsOfE(term).forEach(v => vars.add(v));
389
+ mapsOf(term).forEach(m => maps.add(m));
390
+ return;
391
+ }
392
+ vars.add(s);
393
+ };
394
+ const row = (r) => Object.keys(r).forEach(name);
395
+ const tree = (t) => {
396
+ if ('split' in t) {
397
+ row(t.split);
398
+ tree(t.yes);
399
+ tree(t.no);
400
+ }
401
+ else
402
+ t.squares?.forEach(row);
403
+ };
404
+ for (const l of lemmas) {
405
+ l.when.forEach(row);
406
+ row(l.cut);
407
+ tree(l.tree);
408
+ }
409
+ return { vars: [...vars], maps: [...maps] };
410
+ }
411
+ // Every independent proof uses one common table, but its own exact slice and initial path. Two passes establish
412
+ // the union of dependency-ordered columns before printing any rows. The old path stays unchanged for no lemmas.
413
+ export function encodeCounted(id, goal, cert, vars, maps) {
414
+ const ls = cert.lemmas ?? [];
415
+ const sources = ls.map((l, i) => {
416
+ const path = new Map();
417
+ let duplicate = 0;
418
+ for (const atom of [{ lin: l.cut, holds: false }, ...l.when.map(lin => ({ lin, holds: true }))]) {
419
+ const key = canon(atom.lin);
420
+ path.set(path.has(key) ? `@${duplicate++}` : key, atom);
421
+ }
422
+ const selected = l.slice === undefined ? goal.hyps : l.slice.map(j => {
423
+ if (!Number.isSafeInteger(j) || j < 0 || j >= goal.hyps.length)
424
+ throw new Error(`${id}: invalid lemma slice`);
425
+ return goal.hyps[j];
426
+ });
427
+ return { ex: { name: `${id}: lemma ${i}`, goal: { ...goal, hyps: selected }, tree: l.tree }, path };
428
+ });
429
+ const main = { name: id, goal, tree: cert.tree };
430
+ const first = encode(main, false, true, vars, maps, false, false, { lemmas: ls });
431
+ if (!ls.length)
432
+ return { ...first, lemmas: '[]', lemmaList: (entries) => {
433
+ if (entries.length)
434
+ throw new Error(`${id}: no source contexts for added lemmas`);
435
+ return '[]';
436
+ } };
437
+ const initial = sources.map(s => encode(s.ex, false, true, vars, maps, false, false, { path: s.path }));
438
+ const cols = [...new Set([first, ...initial].flatMap(e => e.cols))];
439
+ const base = encode(main, false, true, vars, maps, false, false, { lemmas: ls, cols });
440
+ const proofs = sources.map(s => encode(s.ex, false, true, vars, maps, false, false, { path: s.path, cols }));
441
+ const lemmaList = (entries) => list(entries.map((l, i) => {
442
+ const source = sources[i];
443
+ if (!source)
444
+ throw new Error(`${id}: no source context for lemma ${i}`);
445
+ const t = l.tree === ls[i].tree ? proofs[i].tree
446
+ : encode({ ...source.ex, tree: l.tree }, false, true, vars, maps, false, false, { path: source.path, cols }).tree;
447
+ return `⟨${list(l.when.map(base.row))}, ${base.row(l.cut)}, ${t}, ${l.slice === undefined ? 'none' : `some ${list(l.slice.map(String))}`}⟩`;
448
+ }));
449
+ return { ...base, lemmas: lemmaList(ls), lemmaList };
450
+ }
366
451
  export function countedToLean(id, g, cert, tampered = []) {
367
452
  const goal = countedGoal(g, cert.insts);
368
453
  if (!goal)
369
454
  throw new Error(`${id}: an instance names no count of the goal, or a count of another bound`);
370
- const vars = [...new Set([...goal.hyps.flatMap(varsOf), ...g.counts.flatMap(cn => [cn.v, cn.key, ...varsOfE(cn.below), ...varsOfE(cn.body)]),
455
+ const extra = lemmaNames(cert.lemmas ?? []);
456
+ const vars = [...new Set([...extra.vars, ...goal.hyps.flatMap(varsOf), ...g.counts.flatMap(cn => [cn.v, cn.key, ...varsOfE(cn.below), ...varsOfE(cn.body)]),
371
457
  ...[...cert.insts, ...tampered.flatMap(t => t.insts)].flatMap(i => [i.wit, ...varsOfE(i.below)])])];
372
- const maps = [...new Set([...goal.hyps, ...g.counts.flatMap(cn => [cn.below, cn.body])].flatMap(mapsOf))];
373
- const enc = encode({ name: id, goal, tree: cert.tree }, false, true, vars, maps), { e, c } = enc;
458
+ const maps = [...new Set([...extra.maps, ...[...goal.hyps, ...g.counts.flatMap(cn => [cn.below, cn.body])].flatMap(mapsOf)])];
459
+ const enc = encodeCounted(id, goal, cert, vars, maps), { e, c } = enc;
374
460
  const ix = (name) => vars.indexOf(name);
375
461
  const instsLit = (is) => list(is.map(i => `⟨${ix(i.wit)}, ${e(i.below)}, ${list(i.terms.map(([z, v2]) => `(${int(z)}, ${ix(v2)})`))}, ${int(i.unit)}⟩`));
376
462
  return `-- ${g.name} (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')}; maps ${maps.map((m2, j) => `${j} ${m2}`).join(', ')})
@@ -380,13 +466,14 @@ def ${id}_insts : List CInst := ${instsLit(cert.insts)}
380
466
  def ${id}_tab : List VDef := ${enc.tab}
381
467
  def ${id}_tree : Tree :=
382
468
  ${enc.tree}
469
+ def ${id}_lemmas : List CutLemma := ${enc.lemmas}
383
470
  -- The instances' hypotheses Lean builds are the ones kernel.ts built.
384
471
  example : countHyps ${id}_goal.counts ${id}_insts = some ${list(countHyps(g.counts, cert.insts).map(c))} := by ${checkBy}
385
472
  /-- ${g.name}: no naturals and maps where each count is its sum satisfy the hypotheses. -/
386
473
  theorem ${id} : ∀ ρ M, (∀ cn ∈ ${id}_goal.counts, cn.Holds ρ M) → ¬ ∀ h ∈ ${id}_goal.hyps, evalC ρ M h = true :=
387
- counted_sound ${id}_goal ${id}_insts ${id}_tab ${id}_tree (by ${checkBy})${tampered.map(t => `
474
+ counted_sound ${id}_goal ${id}_insts ${id}_tab ${id}_tree (lemmas := ${id}_lemmas) (by ${checkBy})${tampered.map(t => `
388
475
  -- TAMPERED: ${t.what}. Lean computes the check to false, as kernel.ts refuses it.
389
- example : checkCounted ${id}_goal ${instsLit(t.insts)} ${id}_tab ${id}_tree = false := by ${checkBy}`).join('')}`;
476
+ example : checkCounted ${id}_goal ${instsLit(t.insts)} ${id}_tab ${id}_tree ${id}_lemmas = false := by ${checkBy}`).join('')}`;
390
477
  }
391
478
  // A machine with counts through CountMachine.lean's cmachine_sound: Lean builds the goals and the counts they declare;
392
479
  // each certificate names the kernel's goal's hypotheses (each one Lean builds), the cells it reads, Count.lean's
@@ -397,13 +484,19 @@ export function cmachineToLean(id, m, laws, proof, tampers = []) {
397
484
  const sm = { ...m, counts: undefined, inputMaps: [...(m.inputMaps ?? []), ...counts.map(([cn]) => cn)] };
398
485
  const named = machineNames(sm, laws, [], [], {});
399
486
  const allCerts = [proof.certs, ...tampers.map(t => t.certs)];
487
+ const extra = allCerts.flatMap(cs => Object.values(cs).map(k => lemmaNames(k.lemmas ?? [])));
400
488
  const goals = obl.map(o => { const g = mcGoal(o.goal.hyps, o.decls, proof.certs[o.goal.name]); if (!g)
401
489
  throw new Error(`${id}: ${o.goal.name}: a read of no count`); return g; });
402
490
  const certVars = allCerts.flatMap(cs => Object.values(cs).flatMap(k => [...k.reads.flatMap(r => [r[0], ...varsOfE(r[2])]), ...k.insts.flatMap(i => [i.wit, ...varsOfE(i.below)]), ...(k.picks ?? []).flatMap(([v2, ks]) => [v2, ...ks.flatMap(varsOfE)])]));
403
- const vars = [...new Set([...named.vars, ...counts.flatMap(([, d]) => [d.j, d.lo ?? d.j, d.key, ...varsOfE(d.below), ...varsOfE(d.body)]), ...laws.map(l => (l.forall ? `${l.forall}#` : '#')),
491
+ const vars = [...new Set([...named.vars, ...extra.flatMap(n => n.vars), ...counts.flatMap(([, d]) => [d.j, d.lo ?? d.j, d.key, ...varsOfE(d.below), ...varsOfE(d.body)]), ...laws.map(l => (l.forall ? `${l.forall}#` : '#')),
404
492
  ...goals.flatMap(g => g.hyps.flatMap(varsOf)), ...certVars])];
405
- const maps = [...new Set([...named.maps, ...counts.flatMap(([cn]) => [cn, postName(cn)]), ...goals.flatMap(g => g.hyps.flatMap(mapsOf)),
493
+ const maps = [...new Set([...named.maps, ...extra.flatMap(n => n.maps), ...counts.flatMap(([cn]) => [cn, postName(cn)]), ...goals.flatMap(g => g.hyps.flatMap(mapsOf)),
406
494
  ...allCerts.flatMap(cs => Object.values(cs).flatMap(k => [...k.reads.map(r => r[1]), ...(k.picks ?? []).flatMap(([, ks]) => ks.flatMap(mapsOf))]))])];
495
+ // Keep the input machine and proof untouched. Only the machine submitted to Lean's
496
+ // checker alpha-renames colliding local binders; QAlpha proves its original semantics.
497
+ const renames = quantifiedRenames(sm, laws, [...vars, ...maps]);
498
+ vars.push(...renames.map(r => r.fresh));
499
+ const checked = renames.length ? `${id}_checkedMachine` : `${id}_machine`;
407
500
  const { e, c } = leanTerms(vars, maps, id);
408
501
  const ix = (name) => { const j = vars.indexOf(name); if (j < 0)
409
502
  throw new Error(`${id}: no variable for ${name}`); return j; };
@@ -429,13 +522,14 @@ export function cmachineToLean(id, m, laws, proof, tampers = []) {
429
522
  const certLit = (name, certs) => {
430
523
  // (a tampered certificate keeps the table and tree of the one it tampers with)
431
524
  const o = obl.find(o2 => o2.goal.name === name), k = certs[name], k0 = proof.certs[name];
432
- const tt = encode({ name: `${id}: ${name}`, goal: mcGoal(o.goal.hyps, o.decls, k0), tree: k0.tree }, false, true, vars, maps);
525
+ const tt = encodeCounted(`${id}: ${name}`, mcGoal(o.goal.hyps, o.decls, k0), k0, vars, maps);
433
526
  return `⟨${list(o.goal.hyps.map(c))},
434
527
  ${list(k.reads.map(r => `(${ix(r[0])}, ${mx(r[1])}, ${e(r[2])})`))},
435
528
  ${list(k.insts.map(i => `⟨${ix(i.wit)}, ${e(i.below)}, ${list(i.terms.map(([z, v2]) => `(${int(z)}, ${ix(v2)})`))}, ${int(i.unit)}⟩`))},
436
529
  ${tt.tab},
437
530
  ${tt.tree},
438
- ${list((k.picks ?? []).map(([v2, ks]) => `(${ix(v2)}, ${list(ks.map(e))})`))}⟩`;
531
+ ${list((k.picks ?? []).map(([v2, ks]) => `(${ix(v2)}, ${list(ks.map(e))})`))},
532
+ ${tt.lemmaList(k.lemmas ?? [])}⟩`;
439
533
  };
440
534
  const entries = (certs) => laws.map(law => {
441
535
  const inst = proof.instances[law.name] ?? {};
@@ -446,15 +540,18 @@ export function cmachineToLean(id, m, laws, proof, tampers = []) {
446
540
  });
447
541
  return `-- ${m.name}: ${laws.map(l => l.name).join('; ')}, with counts ${counts.map(([cn]) => cn).join(', ')}
448
542
  -- (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')}; maps ${maps.map((v2, j) => `${j} ${v2}`).join(', ')})
449
- def ${id}_machine : SMachine := ${machineLit(sm, { e, c }, ix, mx)}
543
+ def ${id}_machine : SMachine := ${machineLit(sm, { e, c }, ix, mx)}${renames.length ? `
544
+ -- Local alpha conversion only; validAll is checked by the generic semantic bridge.
545
+ def ${id}_renames : List QAlpha.Rename := ${list(renames.map(r => `⟨${ix(`?${r.flag}`)}, ${ix(r.old)}, ${ix(r.fresh)}⟩`))}
546
+ def ${id}_checkedMachine : SMachine := QAlpha.renameAll ${id}_machine ${id}_renames` : ''}
450
547
  def ${id}_decls : List CDecl := ${list(counts.map(([cn, d]) => `⟨${mx(cn)}, ${mx(postName(cn))}, ${ix(d.j)}, ${ix(d.key)}, ${e(d.below)}, ${e(d.body)}, ${ix(d.lo ?? d.j)}, ${d.base ?? 0}⟩`))}
451
548
  def ${id}_proof : List CEntry := ${list(entries(proof.certs))}
452
- theorem ${id}_check : checkCMachine ${id}_machine ${id}_decls ${id}_proof = true := by ${checkBy}
549
+ theorem ${id}_check : checkCMachine ${checked} ${id}_decls ${id}_proof = true := by ${checkBy}
453
550
  /-- ${laws.map(l => l.name).join('; ')}: each holds in every reachable state, each count map read as the state's count. -/
454
551
  theorem ${id}_laws : ∀ ρ M, CReach ${id}_machine ${id}_decls ρ M → ∀ ce ∈ ${id}_proof, ce.e.Holds ρ (withCnt ${id}_decls ρ M) :=
455
- cmachine_sound ${id}_machine ${id}_decls ${id}_proof ${id}_check${tampers.map(t => `
552
+ ${renames.length ? `QAlpha.cmachine_sound ${id}_machine ${id}_renames ${id}_decls ${id}_proof (by ${checkBy}) ${id}_check` : `cmachine_sound ${id}_machine ${id}_decls ${id}_proof ${id}_check`}${tampers.map(t => `
456
553
  -- TAMPERED: ${t.what}. Lean computes the check to false, as kernel.ts refuses it.
457
- example : checkCMachine ${id}_machine ${id}_decls ${list(entries(t.certs))} = false := by ${checkBy}`).join('')}`;
554
+ example : checkCMachine ${checked} ${id}_decls ${list(entries(t.certs))} = false := by ${checkBy}`).join('')}`;
458
555
  }
459
556
  // Whole machines through Kern.machine_sound: Lean builds the goals from the machine; the trees are the kernel's.
460
557
  export function machineToLean(id, m, laws, corollary) {
@@ -683,7 +780,7 @@ function sharedTerms(vars, where, plainE) {
683
780
  case '=': return `.eq (${e(t.a)}) (${e(t.b)})`;
684
781
  case 'not': return `.not (${c(t.x)})`;
685
782
  case 'and':
686
- case 'or': return t.xs.length === 0 ? plainC(t) : t.xs.map(c).reduceRight((acc, y) => `.${t.op} (${y}) (${acc})`);
783
+ case 'or': return leanConnective(t.op, t.xs.map(c));
687
784
  case 'flag':
688
785
  case 'all': return plainC(t);
689
786
  }
@@ -987,7 +1084,10 @@ ${laws.map((law, j) => {
987
1084
  return someOf(law, j);
988
1085
  if (JSON.stringify(law.holds).includes('"op":"if"'))
989
1086
  return `-- ${law.name}: its terms read an if, so no plain statement here (${id}_laws holds it)`;
990
- const hyps = arithBinders(law), names = arithIn(law).map(hypName), rw = names.length ? `have hμ : ${statement(law, false)} := hl'\n rw [${names.join(', ')}] at hμ\n exact hμ` : `exact hl'`;
1087
+ const hyps = arithBinders(law), names = arithIn(law).map(hypName);
1088
+ // Proof terms retain neutral Boolean children; surface statements omit them.
1089
+ const surfaceProof = `by simpa [${id}_l${j}, holdsC, evalE, upd] using hl'`;
1090
+ const rw = names.length ? `have hμ : ${statement(law, false)} := ${surfaceProof}\n rw [${names.join(', ')}] at hμ\n exact hμ` : `exact ${surfaceProof}`;
991
1091
  const own = law.keys?.length ? `${reach.have ? reach.have(j) : `have hl : ${id}_e${j}.Holds ρ μ := ${reach.call} ${id}_e${j} (by simp [${id}_proof])`}
992
1092
  have hl' := fun k ${law.keys.map((_, i) => `k${i + 2}`).join(' ')} => (evalC_iff (upd (${law.keys.reduce((acc, key, i) => `upd (${acc}) ${vars.indexOf(key)} k${i + 2}`, 'ρ')}) ${vars.indexOf(law.forall)} k) μ ${id}_l${j}.holds).mp (hl ${law.keys.map((_, i) => `k${i + 2}`).join(' ')} k)
993
1093
  ${rw}` : `${reach.have ? reach.have(j) : `have hl : ${id}_l${j}.Holds ρ μ := ${reach.call} ${id}_e${j} (by simp [${id}_proof])`}
@@ -2268,7 +2368,19 @@ function toLeanWith(items, opts) {
2268
2368
  }).join('');
2269
2369
  for (let item of items) {
2270
2370
  const id = ident(item.id), tItem = performance.now();
2271
- if ('machine' in item) {
2371
+ if ('countedGoal' in item) {
2372
+ if (!checkCounted(item.countedGoal, item.certificate))
2373
+ throw new Error(`${item.id}: counted certificate does not check`);
2374
+ parts.push(countedToLean(id, item.countedGoal, item.certificate));
2375
+ theorems.push(id);
2376
+ }
2377
+ else if ('countedMachine' in item) {
2378
+ if (!checkCountedLaws(item.countedMachine, item.laws, item.proof))
2379
+ throw new Error(`${item.id}: counted machine certificate does not check`);
2380
+ parts.push(cmachineToLean(id, item.countedMachine, item.laws, item.proof));
2381
+ theorems.push(`${id}_laws`);
2382
+ }
2383
+ else if ('machine' in item) {
2272
2384
  // Laws with "there exists" go in as the kernel proved them (core/exists.ts): the machine with the ghosts their
2273
2385
  // witnesses are, each law with its witness terms in place or over its ghosts, each stated again as ∃ (readable).
2274
2386
  if (item.laws.some(l => l.some?.length)) {
@@ -2377,7 +2489,7 @@ function toLeanWith(items, opts) {
2377
2489
  }
2378
2490
  // The file the items need: Live.lean for a liveness or a loop, Sets.lean (which imports Steps.lean) for any machine.
2379
2491
  return `import History
2380
- ${items.some(item => 'machine' in item && item.machine.sums && Object.keys(item.machine.sums).length) ? 'import Sums\n' : ''}${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'}
2492
+ ${items.some(item => 'countedGoal' in item || 'countedMachine' in item) ? 'import QAlpha\n' : ''}${items.some(item => 'machine' in item && item.machine.sums && Object.keys(item.machine.sums).length) ? 'import Sums\n' : ''}${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'}
2381
2493
  open Kern Cert
2382
2494
  set_option maxRecDepth 100000
2383
2495
  set_option maxHeartbeats 0
@@ -1,5 +1,6 @@
1
1
  import { type C, type E } from '../core/machine.js';
2
2
  export declare const exactNat: (x: number) => string;
3
+ export declare function leanConnective(op: 'and' | 'or', xs: readonly string[]): string;
3
4
  export declare function leanTerms(vars: readonly string[], maps: readonly string[], where: string): {
4
5
  e: (t: E) => string;
5
6
  c: (t: C) => string;
@@ -7,6 +7,18 @@ import { unreachable } from "../core/machine.js";
7
7
  // decimal that reads back to it, 10^18 + 128 as 1000000000000000100: Lean would read another number than the kernel and
8
8
  // the runtimes do. terra's review of gen/laneQ.)
9
9
  export const exactNat = (x) => (Number.isSafeInteger(x) ? String(x) : BigInt(x).toString());
10
+ // Keep a singleton's connective: TS facts can close a contradicted disjunction (or a
11
+ // negated conjunction) directly. Erasing its wrapper preserves truth but loses that row.
12
+ // A neutral binary child preserves both truth and that path-sensitive extraction.
13
+ // Semantic/retained-tree checks: research/verify-all/export-shape.lean.
14
+ export function leanConnective(op, xs) {
15
+ const neutral = op === 'and' ? '.le (.const 0) (.const 0)' : '.lt (.const 0) (.const 0)';
16
+ if (!xs.length)
17
+ return neutral;
18
+ if (xs.length === 1)
19
+ return `.${op} (${xs[0]}) (${neutral})`;
20
+ return xs.reduceRight((acc, y) => `.${op} (${y}) (${acc})`);
21
+ }
10
22
  export function leanTerms(vars, maps, where) {
11
23
  const ix = (name) => { const j = vars.indexOf(name); if (j < 0)
12
24
  throw new Error(`${where}: no variable for ${name}`); return j; };
@@ -36,11 +48,7 @@ export function leanTerms(vars, maps, where) {
36
48
  case '=': return `.eq (${e(t.a)}) (${e(t.b)})`;
37
49
  case 'not': return `.not (${c(t.x)})`;
38
50
  case 'and':
39
- case 'or': {
40
- if (t.xs.length === 0)
41
- return t.op === 'and' ? '.le (.const 0) (.const 0)' : '.lt (.const 0) (.const 0)';
42
- return t.xs.map(c).reduceRight((acc, y) => `.${t.op} (${y}) (${acc})`);
43
- }
51
+ case 'or': return leanConnective(t.op, t.xs.map(c));
44
52
  case 'flag': return `.eq (.var ${ix(`?${t.name}`)}) (.const 1)`;
45
53
  case 'all': throw new Error(`${where}: a quantified flag goes to Lean as a flag of its own, not a condition`);
46
54
  default: return unreachable(t);