gdp-wired 0.54.2 → 0.55.1

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.
@@ -0,0 +1,286 @@
1
+ // Lean twin: Kern.GroupedSums.grouped_sum_sound (`lean-kernel/GroupedSums.lean`).
2
+ // Parameter-indexed sums over a map's keys (`ParamSumMachine`) combined with fresh
3
+ // observer-key elimination (`sreach_rebind` + `observer_elim`), with zero ghost maps.
4
+ import { atMost, n, not, same, walkOnce, x } from "../core/machine.js";
5
+ import { boundOf, check, checkLaws, mapArities, obligations, own, substC, substE, sumParts, witnessesOf } from "./kernel.js";
6
+ const ZERO = n(0);
7
+ const TRUE_C = atMost(ZERO, ZERO);
8
+ const text = (v) => JSON.stringify(v);
9
+ const eq = (a, b) => text(a) === text(b);
10
+ const safeNat = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
11
+ const plainId = (name) => typeof name === 'string' && name.length > 0 && name !== '1' && !/[*[\],:#?~'⟦⟧⟨⟩|]/.test(name);
12
+ const nullRecord = (entries) => Object.assign(Object.create(null), Object.fromEntries(entries));
13
+ const dTerm = (G, cs) => cs.length ? { op: 'add', a: G(cs[0]), b: dTerm(t => ({ op: 'if', c: same(t, cs[0]), then: ZERO, else: G(t) }), cs.slice(1)) } : ZERO;
14
+ function paramSumTermOk(e, key, params) {
15
+ switch (e.op) {
16
+ case 'var': return params.includes(e.name);
17
+ case 'const': return true;
18
+ case 'get': return e.key.op === 'var' && e.key.name === key;
19
+ case 'mul': return paramSumTermOk(e.a, key, params);
20
+ case 'if': return paramSumCondOk(e.c, key, params) && paramSumTermOk(e.then, key, params) && paramSumTermOk(e.else, key, params);
21
+ case 'add':
22
+ case 'sub':
23
+ case 'min':
24
+ case 'max':
25
+ case 'prod':
26
+ return paramSumTermOk(e.a, key, params) && paramSumTermOk(e.b, key, params);
27
+ case 'tup':
28
+ case 'proj': return false;
29
+ default: return false;
30
+ }
31
+ }
32
+ function paramSumCondOk(c, key, params) {
33
+ if (c.op === 'flag' || c.op === 'all')
34
+ return false;
35
+ if (c.op === 'not')
36
+ return paramSumCondOk(c.x, key, params);
37
+ if (c.op === 'and' || c.op === 'or')
38
+ return c.xs.every(y => paramSumCondOk(y, key, params));
39
+ return paramSumTermOk(c.a, key, params) && paramSumTermOk(c.b, key, params);
40
+ }
41
+ function hasVar(root, name) {
42
+ let found = false;
43
+ walkOnce(root, o => {
44
+ const t = o;
45
+ if (t.op === 'var' && t.name === name)
46
+ found = true;
47
+ });
48
+ return found;
49
+ }
50
+ function hasFlagOrAll(root) {
51
+ let found = false;
52
+ walkOnce(root, o => {
53
+ const t = o;
54
+ if (t.op === 'flag' || t.op === 'all')
55
+ found = true;
56
+ });
57
+ return found;
58
+ }
59
+ function mapsIn(root) {
60
+ const out = new Set();
61
+ walkOnce(root, o => {
62
+ const t = o;
63
+ if (t.op === 'get' && typeof t.map === 'string')
64
+ out.add(t.map);
65
+ });
66
+ return [...out];
67
+ }
68
+ function comparedKeys(t, key, out) {
69
+ if (t.op === '=' && t.a.op === 'var' && t.a.name === key && !hasVar(t.b, key))
70
+ out.set(text(t.b), t.b);
71
+ else if (t.op === '=' && t.b.op === 'var' && t.b.name === key && !hasVar(t.a, key))
72
+ out.set(text(t.a), t.a);
73
+ for (const v of Object.values(t)) {
74
+ if (v && typeof v === 'object')
75
+ (Array.isArray(v) ? v : [v]).forEach(y => comparedKeys(y, key, out));
76
+ }
77
+ }
78
+ export function defaultGroupedCovers(m, term) {
79
+ const out = new Map();
80
+ for (const map of mapsIn(term)) {
81
+ const w = own(m.step.maps ?? {}, map);
82
+ if (!w)
83
+ continue;
84
+ if ('each' in w)
85
+ comparedKeys(w.value, w.each, out);
86
+ else
87
+ out.set(text(w.key), w.key);
88
+ }
89
+ return [...out.values()];
90
+ }
91
+ const pcellLaws = (laws, read, X, ps) => laws.flatMap(l => (l.forall && !l.keys?.length && !ps.includes(l.forall) && paramSumCondOk(l.holds, l.forall, ps)
92
+ && mapsIn(l.holds).every(mp => read.includes(mp))
93
+ ? [substC(l.holds, { vars: { [l.forall]: X }, maps: {}, flags: {} })] : []));
94
+ export function groupedSumTheory(source, law, cert) {
95
+ if (!cert || cert.kind !== 'grouped-sum' || !plainId(cert.observer) || !cert.group || typeof cert.group !== 'object')
96
+ return;
97
+ if (!cert.sums || typeof cert.sums !== 'object' || Array.isArray(cert.sums))
98
+ return;
99
+ const sumEntries = Object.entries(cert.sums);
100
+ if (!sumEntries.length || !Array.isArray(cert.laws) || !cert.laws.length)
101
+ return;
102
+ if (!cert.proof || typeof cert.proof !== 'object'
103
+ || !cert.proof.instances || typeof cert.proof.instances !== 'object' || Array.isArray(cert.proof.instances)
104
+ || !cert.proof.trees || typeof cert.proof.trees !== 'object' || Array.isArray(cert.proof.trees))
105
+ return;
106
+ if (source.history || source.primitiveFailure || Object.keys(source.counts ?? {}).length
107
+ || Object.keys(source.sums ?? {}).length || Object.keys(source.leasts ?? {}).length
108
+ || Object.keys(source.fns ?? {}).length || source.facts?.length)
109
+ return;
110
+ if (law.keys?.length || law.some?.length || law.ex || law.finite !== undefined)
111
+ return;
112
+ if (cert.laws.some(l => l.some?.length || l.ex || l.finite !== undefined))
113
+ return;
114
+ // Reject non-safe naturals and word-division intrinsics (which require WordSReach).
115
+ let unsupported = false;
116
+ walkOnce([source, law, cert.group, cert.sums, cert.laws, cert.proof.instances], o => {
117
+ const t = o;
118
+ if (t.op === 'get' && typeof t.map === 'string' && t.map.startsWith('worddiv$'))
119
+ unsupported = true;
120
+ if (t.op === 'const' && !safeNat(t.value))
121
+ unsupported = true;
122
+ if (t.op === 'mul' && !safeNat(t.k))
123
+ unsupported = true;
124
+ });
125
+ if (unsupported || !Object.values(source.maps ?? {}).every(safeNat))
126
+ return;
127
+ // Existing scope + naturalness checks establish disjoint params/inputs/state/maps/inputMaps/flags/binders,
128
+ // ensuring names absent from sourceNames never occur anywhere in source.
129
+ obligations(source, [law]);
130
+ if (Object.values(mapArities(source, [law])).some(a => a !== 1))
131
+ return;
132
+ const obs = cert.observer;
133
+ const flags = source.step.flags ?? {};
134
+ const sourceNames = new Set([
135
+ ...source.params, ...source.inputs, ...Object.keys(source.state),
136
+ ...Object.keys(source.maps ?? {}), ...(source.inputMaps ?? []),
137
+ ...Object.keys(flags), ...Object.keys(flags).map(f => `?${f}`),
138
+ ...Object.entries(flags).flatMap(([f, c]) => (c.op === 'all' ? [...witnessesOf(f, c), ...boundOf(c)] : [])),
139
+ ...Object.values(source.step.maps ?? {}).flatMap(w => ('each' in w ? [w.each] : [])),
140
+ ]);
141
+ // observerOk source obs, hkey (law.forall !== obs), hgrp (!occE obs grp), hlo (!occC obs law.holds), and flag-free group term.
142
+ if (sourceNames.has(obs) || law.forall === obs || hasVar(cert.group, obs) || hasVar(law.holds, obs) || hasFlagOrAll(cert.group))
143
+ return;
144
+ const sameFlags = nullRecord(Object.keys(flags).map(f => [f, { op: 'flag', name: f }]));
145
+ const inlinedFlags = Object.create(null);
146
+ for (const [f, c] of Object.entries(flags)) {
147
+ inlinedFlags[f] = c.op === 'all' ? same(x(`?${f}`), n(1)) : substC(c, { vars: {}, maps: {}, flags: inlinedFlags });
148
+ }
149
+ const leanSubst = {
150
+ vars: {},
151
+ maps: {},
152
+ flags: nullRecord(Object.entries(inlinedFlags).map(([f, c]) => [
153
+ f, flags[f].op === 'all' ? c : same({ op: 'if', c, then: n(1), else: ZERO }, n(1)),
154
+ ])),
155
+ };
156
+ // Reserve all sum-owned names disjoint from sourceNames, obs, and each other (sghostOk).
157
+ const taken = new Set([...sourceNames, obs]);
158
+ const ghostVars = [];
159
+ for (const [s] of sumEntries) {
160
+ if (!plainId(s))
161
+ return;
162
+ const { flag, x: xv } = sumParts(s);
163
+ const owned = [s, flag, xv, `?${flag}`, `w?${flag}`];
164
+ if (owned.some(nm => taken.has(nm)))
165
+ return;
166
+ for (const nm of owned)
167
+ taken.add(nm);
168
+ ghostVars.push(s, `?${flag}`);
169
+ }
170
+ const steps = Object.create(null);
171
+ const qflags = Object.create(null);
172
+ const zeroSums = Object.create(null);
173
+ const facts = [];
174
+ const initGoals = [];
175
+ const coverGoals = [];
176
+ const decls = [];
177
+ for (const [s, sum] of sumEntries) {
178
+ if (!sum || typeof sum !== 'object' || !plainId(sum.key) || !sum.term || typeof sum.term !== 'object')
179
+ return;
180
+ if (!Array.isArray(sum.params) || new Set(sum.params).size !== sum.params.length)
181
+ return;
182
+ const { flag, x: xv } = sumParts(s);
183
+ if (taken.has(sum.key))
184
+ return;
185
+ // paramImmutable: every p in sum.params must be obs or a declared source parameter.
186
+ // Because taken contains sourceNames ∪ {obs} ∪ sum-owned names and sum.key ∉ taken,
187
+ // p is automatically disjoint from inputs, state, step, flags, qVars, wVars, sums, sum.key, and xv.
188
+ for (const p of sum.params) {
189
+ if (p !== obs && !source.params.includes(p))
190
+ return;
191
+ }
192
+ // gOkEP and summed map checks (scope guarantees source.maps is disjoint from inputMaps and fns).
193
+ if (!paramSumTermOk(sum.term, sum.key, sum.params))
194
+ return;
195
+ const read = mapsIn(sum.term);
196
+ if (!read.every(mp => Object.hasOwn(source.maps ?? {}, mp)))
197
+ return;
198
+ if (sum.covers !== undefined && !Array.isArray(sum.covers))
199
+ return;
200
+ const cs = sum.covers ?? defaultGroupedCovers(source, sum.term);
201
+ if (cs.some(c => !c || typeof c !== 'object' || hasFlagOrAll(c) || hasVar(c, sum.key) || hasVar(c, xv) || ghostVars.some(v => hasVar(c, v))))
202
+ return;
203
+ for (const mp of read) {
204
+ const w = own(source.step.maps ?? {}, mp);
205
+ if (w && !('each' in w) && !cs.some(c => eq(c, w.key)))
206
+ return;
207
+ }
208
+ // S @init goal (GroupedSums.psumStartGoal)
209
+ const atStart = substE(sum.term, {
210
+ vars: {},
211
+ maps: nullRecord(read.map(mp => [mp, () => n(source.maps[mp])])),
212
+ flags: sameFlags,
213
+ });
214
+ initGoals.push({ name: `${s} @init`, hyps: [source.pre ?? TRUE_C, not(same(atStart, ZERO))] });
215
+ // Plain machine definitions (GroupedSums.ParamSumMachine.plain)
216
+ const here = (t) => substE(sum.term, { vars: { [sum.key]: t }, maps: {}, flags: sameFlags });
217
+ const post = (mp) => (k2) => {
218
+ const w = own(source.step.maps ?? {}, mp);
219
+ if (!w)
220
+ return { op: 'get', map: mp, key: k2 };
221
+ if ('each' in w)
222
+ return substE(w.value, { vars: { [w.each]: k2 }, maps: {}, flags: sameFlags });
223
+ return { op: 'if', c: same(k2, w.key), then: w.value, else: { op: 'get', map: mp, key: k2 } };
224
+ };
225
+ const after = (t) => substE(sum.term, { vars: { [sum.key]: t }, maps: nullRecord(read.map(mp => [mp, post(mp)])), flags: sameFlags });
226
+ const S = x(s);
227
+ zeroSums[s] = ZERO;
228
+ steps[s] = { op: 'sub', a: { op: 'add', a: S, b: dTerm(after, cs) }, b: dTerm(here, cs) };
229
+ qflags[flag] = { op: 'all', key: sum.key, c: atMost(dTerm(here, [x(sum.key), ...cs]), S) };
230
+ facts.push({ op: 'and', xs: [atMost(dTerm(here, cs), S), { op: 'flag', name: flag }] });
231
+ // Every-write cover goals (GroupedSums.psumCoverGoal)
232
+ const X = x(xv);
233
+ for (const [mp, w] of Object.entries(source.step.maps ?? {})) {
234
+ if (!('each' in w) || !read.includes(mp))
235
+ continue;
236
+ coverGoals.push({
237
+ name: `${s} @cover ${mp}`,
238
+ hyps: [
239
+ substC(source.assume ?? TRUE_C, leanSubst),
240
+ ...pcellLaws(cert.laws, read, X, sum.params),
241
+ ...cs.map((c) => not(same(X, c))),
242
+ not(same(substE(substE(w.value, leanSubst), { vars: { [w.each]: X }, maps: {}, flags: {} }), { op: 'get', map: mp, key: X })),
243
+ ],
244
+ });
245
+ }
246
+ decls.push({ name: s, key: sum.key, params: sum.params, term: sum.term, covers: cs, flag, x: xv, read });
247
+ }
248
+ // Verify exact guardLaw(law, obs, cert.group) is in cert.laws and avoids all sum ghosts.
249
+ if (ghostVars.some(v => hasVar(cert.group, v)))
250
+ return;
251
+ const expectedGuard = {
252
+ name: law.name,
253
+ ...(law.forall ? { forall: law.forall } : {}),
254
+ holds: { op: 'or', xs: [not(same(cert.group, x(obs))), law.holds] },
255
+ };
256
+ const guardIndex = cert.laws.findIndex(l => eq(l, expectedGuard));
257
+ if (guardIndex < 0)
258
+ return;
259
+ const assumed = facts.reduceRight((acc, f) => ({ op: 'and', xs: [f, acc] }), TRUE_C);
260
+ const plain = {
261
+ ...source,
262
+ params: [...source.params, obs],
263
+ state: { ...source.state, ...zeroSums },
264
+ step: { ...source.step, flags: { ...flags, ...qflags }, state: { ...source.step.state, ...steps } },
265
+ assume: { op: 'and', xs: [source.assume ?? TRUE_C, assumed] },
266
+ };
267
+ return { plain, observer: obs, group: cert.group, decls, initGoals, coverGoals, guardIndex };
268
+ }
269
+ export function checkGroupedSum(source, law, cert) {
270
+ try {
271
+ const t = groupedSumTheory(source, law, cert);
272
+ if (!t)
273
+ return false;
274
+ if (!checkLaws(t.plain, cert.laws, cert.proof))
275
+ return false;
276
+ for (const g of [...t.initGoals, ...t.coverGoals]) {
277
+ const tree = own(cert.proof.trees, g.name);
278
+ if (!tree || !check(g, tree))
279
+ return false;
280
+ }
281
+ return true;
282
+ }
283
+ catch {
284
+ return false;
285
+ }
286
+ }
@@ -9,6 +9,7 @@ import { type Cyclic } from '../kernel/cyclic.js';
9
9
  import { leanLibrary } from './library.js';
10
10
  import type { FiniteSumCertificate } from '../kernel/finite-sum.js';
11
11
  import type { GhostWriteCertificate } from '../kernel/ghost-write.js';
12
+ import type { GroupedSumCertificate } from '../kernel/grouped-sum.js';
12
13
  import type { AggregateKinds } from '../core/aggregate-kinds.js';
13
14
  export { leanLibrary };
14
15
  export type Exported = {
@@ -176,7 +177,11 @@ export declare function smachineToLean(id: string, given: Machine, laws: Law[],
176
177
  simp?: string[];
177
178
  free?: string[];
178
179
  ghosts?: string[];
179
- after?: (ix: (name: string) => number, mx: (name: string) => number, lit: (m: Machine) => string, c: (condition: C) => string) => string;
180
+ after?: (ix: (name: string) => number, mx: (name: string) => number, lit: (m: Machine) => string, c: (condition: C) => string, e: (term: E) => string, enc: (goal: Goal, tree: Tree) => {
181
+ tab: string;
182
+ hyps: string;
183
+ tree: string;
184
+ }) => string;
180
185
  historyTampers?: {
181
186
  what: string;
182
187
  relations: {
@@ -346,7 +351,7 @@ export type LeanItem = {
346
351
  aggregate: {
347
352
  source: Machine;
348
353
  law: Law;
349
- certificate: FiniteSumCertificate | GhostWriteCertificate;
354
+ certificate: FiniteSumCertificate | GhostWriteCertificate | GroupedSumCertificate;
350
355
  kinds?: AggregateKinds;
351
356
  };
352
357
  } | {
@@ -20,6 +20,7 @@ import { countsForReads } from "../core/count-facts.js";
20
20
  import { requireSourceTranslation } from "../core/source-check.js";
21
21
  import { finiteSumToLean } from "./finite-sum-export.js";
22
22
  import { ghostWriteToLean } from "./ghost-write-export.js";
23
+ import { groupedSumToLean } from "./grouped-sum-export.js";
23
24
  export { leanLibrary };
24
25
  // --- to Lean ------------------------------------------------------------------------------------------------------------
25
26
  const varsOf = (c) => [...JSON.stringify(c).matchAll(/"op":"var","name":"([^"]+)"/g)].map(m => m[1]);
@@ -1869,7 +1870,7 @@ theorem ${id}_laws : ∀ ρ M, SReach ${id}_machine ρ M → ∀ e ∈ ${id}_pro
1869
1870
  ${hm ? histBlock() : readable(id, laws, vars, mapNames, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: words ? `Kern.WordReach.WordSReach ${id}_word ρ μ` : `SReach ${id}_machine ρ μ`, call: `${id}_laws ρ μ h`, lit: c, eLit: e, ghosts: !rf && !gm && gv.length > 0, explicitExistentials: new Set((opts.ghostSubst ?? []).map(g => g.law)) })}${sm ? sumsBlock() : ''}${opts.noFacts ? '' : factsProof(id, m, mapNames, vars, opts.simp)}${opts.tamper ? `
1870
1871
  -- TAMPERED: ${opts.tamper.what}. Lean computes the check to false.
1871
1872
  def ${id}_tampered : SMachine := ${lit(opts.tamper.machine)}
1872
- example : checkSMachine ${id}_tampered ${id}_proof = false := by ${checkBy}` : ''}${records.length ? `\n\n${records.join('\n\n')}` : ''}${opts.after ? `\n\n${opts.after(ix, mx, lit, c)}` : ''}`;
1873
+ example : checkSMachine ${id}_tampered ${id}_proof = false := by ${checkBy}` : ''}${records.length ? `\n\n${records.join('\n\n')}` : ''}${opts.after ? `\n\n${opts.after(ix, mx, lit, c, e, enc)}` : ''}`;
1873
1874
  }
1874
1875
  // --- the cyclic certificate's export (GDP_CERT=cyclic) -------------------------------------------------------------
1875
1876
  // By default, or with GDP_CERT=cyclic (core/cyclic.ts's certOn: a covered proof's certificate is its cyclic proof; or toLean's
@@ -2623,7 +2624,9 @@ function toLeanWith(items, opts) {
2623
2624
  const save = checkBy;
2624
2625
  checkBy = 'decide +kernel';
2625
2626
  try {
2626
- parts.push(certificate.kind === 'finite-sum' ? finiteSumToLean(id, source, law, certificate) : ghostWriteToLean(id, source, law, certificate));
2627
+ parts.push(certificate.kind === 'finite-sum' ? finiteSumToLean(id, source, law, certificate)
2628
+ : certificate.kind === 'ghost-write' ? ghostWriteToLean(id, source, law, certificate)
2629
+ : groupedSumToLean(id, source, law, certificate));
2627
2630
  }
2628
2631
  finally {
2629
2632
  checkBy = save;
@@ -2751,8 +2754,9 @@ function toLeanWith(items, opts) {
2751
2754
  // The file the items need: Live.lean for a liveness or a loop, Sets.lean (which imports Steps.lean) for any machine.
2752
2755
  const finiteImport = items.some(item => 'aggregate' in item && item.aggregate.certificate.kind === 'finite-sum') ? 'import FiniteSumComposition\n' : '';
2753
2756
  const ghostImport = items.some(item => 'aggregate' in item && item.aggregate.certificate.kind === 'ghost-write') ? 'import Sums\nimport GhostWriteTransport\nimport GhostSourceViews\n' : '';
2757
+ const groupedImport = items.some(item => 'aggregate' in item && item.aggregate.certificate.kind === 'grouped-sum') ? 'import GroupedSums\n' : '';
2754
2758
  return `import History
2755
- ${finiteImport}${ghostImport}${wordReads(items).length ? 'import WordFacts\nimport WordSMachine\n' : ''}${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'}
2759
+ ${finiteImport}${ghostImport}${groupedImport}${wordReads(items).length ? 'import WordFacts\nimport WordSMachine\n' : ''}${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'}
2756
2760
  open Kern Cert
2757
2761
  set_option maxRecDepth 100000
2758
2762
  set_option maxHeartbeats 0
@@ -0,0 +1,3 @@
1
+ import type { Law, Machine } from '../core/machine.js';
2
+ import { type GroupedSumCertificate } from '../kernel/grouped-sum.js';
3
+ export declare function groupedSumToLean(id: string, source: Machine, law: Law, cert: GroupedSumCertificate): string;
@@ -0,0 +1,82 @@
1
+ import { checkGroupedSum, groupedSumTheory } from "../kernel/grouped-sum.js";
2
+ import { retainedSMachineToLean } from "./emit.js";
3
+ // Replay the retained proof trees verbatim via Kern.GroupedSums.grouped_sum_sound.
4
+ // No proof search runs at export time (`retainedSMachineToLean` pins `retainedOnly` and `decide +kernel`).
5
+ export function groupedSumToLean(id, source, law, cert) {
6
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(id) || !checkGroupedSum(source, law, cert))
7
+ throw new Error('invalid grouped-sum export');
8
+ const { plain, observer, group, decls, initGoals, coverGoals, guardIndex } = groupedSumTheory(source, law, cert);
9
+ const free = [...new Set([
10
+ ...(law.forall ? [law.forall] : []),
11
+ ...decls.flatMap(d => [d.key, d.x, ...d.params]),
12
+ ...[...initGoals, ...coverGoals].flatMap(g => [...JSON.stringify(g.hyps).matchAll(/"op":"var","name":"([^"]+)"/g)].map(m => m[1])),
13
+ ])];
14
+ const body = retainedSMachineToLean('packet', plain, cert.laws, cert.proof, {
15
+ free,
16
+ after: (ix, _mx, lit, cond, expr, enc) => {
17
+ const declLits = decls.map(d => `⟨${ix(d.name)}, ${ix(d.key)}, [${d.params.map(p => String(ix(p))).join(', ')}], ${expr(d.term)}, [${d.covers.map(expr).join(', ')}], ${ix(`?${d.flag}`)}, ${ix(`w?${d.flag}`)}, ${ix(d.x)}⟩`);
18
+ const initLits = initGoals.map(g => {
19
+ const tree = cert.proof.trees[g.name];
20
+ if (!tree)
21
+ throw new Error(`${id}: missing retained init tree for ${g.name}`);
22
+ const encoded = enc(g, tree);
23
+ return `(${encoded.tab}, ${encoded.tree})`;
24
+ });
25
+ const coverByName = new Map(coverGoals.map(g => [g.name, g]));
26
+ const coverLits = decls.map(d => {
27
+ const gs = Object.entries(source.step.maps ?? {}).flatMap(([mp, w]) => {
28
+ if (!('each' in w) || !d.read.includes(mp))
29
+ return [];
30
+ const g = coverByName.get(`${d.name} @cover ${mp}`);
31
+ if (!g)
32
+ throw new Error(`${id}: missing cover goal for ${d.name} @cover ${mp}`);
33
+ return [g];
34
+ });
35
+ return `[${gs.map(g => {
36
+ const tree = cert.proof.trees[g.name];
37
+ if (!tree)
38
+ throw new Error(`${id}: missing retained cover tree for ${g.name}`);
39
+ const encoded = enc(g, tree);
40
+ return `(${encoded.tab}, ${encoded.tree})`;
41
+ }).join(', ')}]`;
42
+ });
43
+ const keyOpt = law.forall ? `some ${ix(law.forall)}` : 'none';
44
+ return `
45
+ def originalMachine : SMachine := ${lit(source)}
46
+ def unchangedLaw : MLaw := ⟨${cond(law.holds)}, ${keyOpt}⟩
47
+ def observer : Nat := ${ix(observer)}
48
+ def groupTerm : E := ${expr(group)}
49
+ def packet_psums : ParamSumMachine := ⟨originalMachine, [${declLits.join(', ')}]⟩
50
+ def packet_inits : List (List VDef × Tree) := [${initLits.join(', ')}]
51
+ def packet_covers : List (List (List VDef × Tree)) := [${coverLits.join(', ')}]
52
+
53
+ theorem packet_shape : packet_psums.plain = packet_machine := by rfl
54
+ theorem packet_pcheck : checkParamSums packet_psums packet_proof packet_inits packet_covers = true := by decide +kernel
55
+ theorem sumGhostChecks : sghostOk packet_psums.ghosts = true := by decide +kernel
56
+ theorem obsOk : observerOk originalMachine observer = true := by decide +kernel
57
+ theorem guardEq : packet_e${guardIndex}.law = guardLaw unchangedLaw observer groupTerm := by rfl
58
+ theorem guardAvoids : avoids packet_psums.ghosts.vars packet_e${guardIndex}.law.holds = true := by decide +kernel
59
+
60
+ theorem original_law (ρ : Nat → Nat) (M : Nat → Nat → Nat)
61
+ (hr : SReach originalMachine ρ M) : unchangedLaw.Holds ρ M :=
62
+ grouped_sum_sound packet_psums packet_proof packet_inits packet_covers
63
+ observer groupTerm unchangedLaw packet_e${guardIndex}
64
+ (packet_shape.symm ▸ packet_check) packet_pcheck sumGhostChecks obsOk
65
+ (by decide +kernel) (by decide +kernel) (by decide +kernel)
66
+ (by simp [packet_proof]) guardEq guardAvoids ρ M hr
67
+ `;
68
+ },
69
+ });
70
+ return `namespace ${id}
71
+ open Kern Cert Classical Kern.GroupedSums
72
+ set_option maxRecDepth 100000
73
+ set_option maxHeartbeats 0
74
+ ${body}
75
+ end ${id}
76
+ #print axioms ${id}.packet_check
77
+ #print axioms ${id}.packet_pcheck
78
+ #print axioms ${id}.sumGhostChecks
79
+ #print axioms ${id}.obsOk
80
+ #print axioms ${id}.original_law
81
+ `;
82
+ }