gdp-wired 0.52.0 → 0.53.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.
@@ -0,0 +1,74 @@
1
+ // Lean twin: FiniteSumComposition.state_law, restricted to a symbolic prefix,
2
+ // one touched site or a zero-row rebuild, and unit site capacity.
3
+ import { atMost, get, n, not, plus, same, walkOnce, x } from "../core/machine.js";
4
+ import { check, mapArities, obligations, own, substC, substE } from "./kernel.js";
5
+ export const sumLocalGoal = (l) => ({ name: l.name, hyps: [...l.assumptions, not(l.conclusion)] });
6
+ const zero = n(0);
7
+ const safeNat = (x) => typeof x === 'number' && Number.isSafeInteger(x) && x >= 0;
8
+ // The caller supplies the source and claim, not the packet. Only site/field
9
+ // coordinates are proposals. Build the obligations over actual source terms.
10
+ export function finiteSumTheory(m, law, p) {
11
+ const maps = m.maps ?? {}, writes = m.step.maps ?? {}, defaultCell = own(maps, p.map), wr = own(writes, p.map);
12
+ if (m.history || m.primitiveFailure || Object.keys(m.sums ?? {}).length || Object.keys(m.counts ?? {}).length ||
13
+ Object.keys(m.fns ?? {}).length || m.facts?.length || m.inputMaps?.length || m.leasts && Object.keys(m.leasts).length ||
14
+ law.forall !== undefined || law.keys?.length || law.some?.length || law.ex || law.finite !== undefined ||
15
+ !m.assume || Object.keys(maps).length !== 1 || Object.keys(writes).length !== 1 || !safeNat(defaultCell) ||
16
+ !wr || !('each' in wr) || wr.value.op !== 'if' ||
17
+ !m.params.includes(p.bound) || !m.inputs.includes(p.key) || !safeNat(p.offset) || !Array.isArray(p.fields) || !p.fields.length)
18
+ return;
19
+ if (new Set(p.fields.map(f => f.field)).size !== p.fields.length ||
20
+ !p.fields.every(f => safeNat(f.value) && f.value !== defaultCell && own(m.state, f.field) && own(m.step.state ?? {}, f.field)))
21
+ return;
22
+ let unsupported = false;
23
+ walkOnce([m, law.holds], o => {
24
+ const t = o;
25
+ if (t.op === 'all' || t.op === 'get' && t.map?.startsWith('worddiv$') || t.op === 'const' && !safeNat(t.value) || t.op === 'mul' && !safeNat(t.k))
26
+ unsupported = true;
27
+ });
28
+ if (unsupported || (own(mapArities(m, [law]), p.map) ?? 1) !== 1)
29
+ return;
30
+ // Existing scope/natural checks establish disjoint params, inputs, state,
31
+ // flags and source binders. In particular, no step can assign the bound.
32
+ obligations(m, [law]);
33
+ let coordinate = 'agg$coordinate';
34
+ const occupied = JSON.stringify([m, law]);
35
+ while (occupied.includes(coordinate))
36
+ coordinate += '0';
37
+ const flags = Object.create(null);
38
+ for (const [name, c] of Object.entries(m.step.flags ?? {}))
39
+ flags[name] = substC(c, { vars: {}, maps: {}, flags });
40
+ const inline = { vars: {}, maps: {}, flags }, step = m.step.state ?? {};
41
+ const assume = substC(m.assume, inline), bound = x(p.bound), input = x(p.key), j = x(coordinate);
42
+ const point = p.offset ? { op: 'sub', a: input, b: n(p.offset) } : input;
43
+ const addr = (k) => p.offset ? plus(k, n(p.offset)) : k;
44
+ const after = (k) => substE(wr.value, { ...inline, vars: { [wr.each]: k } });
45
+ const reset = substC(wr.value.c, { ...inline, vars: { [wr.each]: input } }), coord = addr(j), atPoint = addr(point);
46
+ const local = (name, assumptions, conclusion) => ({ name, assumptions, conclusion });
47
+ const locals = [
48
+ local('point_inside', [assume], { op: '<', a: point, b: bound }),
49
+ local('other_cells_frame', [assume, not(reset), not(same(j, point))], same(after(coord), get(p.map, coord))),
50
+ local('broadcast_reset', [assume, reset], same(after(coord), n(defaultCell))),
51
+ local('capacity_entails_claim', [atMost(p.fields.map(f => x(f.field)).reduce(plus), bound)], law.holds),
52
+ ];
53
+ const indicator = (value, cell) => ({ op: 'if', c: same(cell, n(value)), then: n(1), else: zero });
54
+ for (const [i, f] of p.fields.entries()) {
55
+ const next = substE(own(step, f.field), inline);
56
+ locals.push(local(`field${i}_init`, [], same(own(m.state, f.field), zero)), local(`field${i}_reset`, [assume, reset], same(next, zero)), local(`field${i}_delta`, [assume, not(reset)], same(plus(next, indicator(f.value, get(p.map, atPoint))), plus(x(f.field), indicator(f.value, after(atPoint))))));
57
+ }
58
+ locals.push(local('disjoint_capacity', [], atMost(p.fields.map(f => indicator(f.value, get(p.map, coord))).reduce(plus), n(1))));
59
+ return { locals, coordinate, point, bound, reset };
60
+ }
61
+ export function checkFiniteSum(m, law, p) {
62
+ try {
63
+ if (p.kind !== 'finite-sum')
64
+ return false;
65
+ const theory = finiteSumTheory(m, law, p.layout);
66
+ return !!theory && Object.keys(p.trees).length === theory.locals.length && theory.locals.every(local => {
67
+ const tree = own(p.trees, local.name);
68
+ return !!tree && check(sumLocalGoal(local), tree);
69
+ });
70
+ }
71
+ catch {
72
+ return false;
73
+ }
74
+ }
@@ -0,0 +1,117 @@
1
+ import { type C, type E, type Law, type Machine } from '../core/machine.js';
2
+ import { type Instances, type Tree } from './kernel.js';
3
+ export type GhostWriteRecipe = {
4
+ ghostMap: string;
5
+ point: E;
6
+ gates: [column: string, value: number][];
7
+ group: string;
8
+ weight: string;
9
+ observer: string;
10
+ };
11
+ export type GhostWriteCertificate = {
12
+ kind: 'ghost-write';
13
+ recipe: GhostWriteRecipe;
14
+ projection: {
15
+ omitMap: string;
16
+ };
17
+ target: Machine;
18
+ laws: Law[];
19
+ pointLaw: string;
20
+ proof: {
21
+ instances: Record<string, Instances>;
22
+ trees: Record<string, Tree>;
23
+ };
24
+ };
25
+ export declare function ghostWriteTheory(source: Machine, law: Law, p: GhostWriteCertificate): {
26
+ orig: {
27
+ params: string[];
28
+ step: {
29
+ flags: Record<string, C>;
30
+ state?: Record<string, E>;
31
+ maps?: Record<string, import("../core/machine.ts").MapUpdate>;
32
+ };
33
+ primitiveFailure?: C;
34
+ name: string;
35
+ inputs: string[];
36
+ state: Record<string, E>;
37
+ maps?: Record<string, number>;
38
+ inputMaps?: string[];
39
+ pre?: C;
40
+ assume?: C;
41
+ history?: import("../core/machine.ts").History;
42
+ sums?: Record<string, import("../core/machine.ts").Sum>;
43
+ counts?: Record<string, import("../core/machine.ts").Counted>;
44
+ fns?: Record<string, import("../core/machine.ts").Fn>;
45
+ facts?: Law[];
46
+ leasts?: Record<string, import("../core/machine.ts").Least>;
47
+ relations?: Record<string, string[]>;
48
+ };
49
+ lift: {
50
+ orig: {
51
+ params: string[];
52
+ step: {
53
+ flags: Record<string, C>;
54
+ state?: Record<string, E>;
55
+ maps?: Record<string, import("../core/machine.ts").MapUpdate>;
56
+ };
57
+ primitiveFailure?: C;
58
+ name: string;
59
+ inputs: string[];
60
+ state: Record<string, E>;
61
+ maps?: Record<string, number>;
62
+ inputMaps?: string[];
63
+ pre?: C;
64
+ assume?: C;
65
+ history?: import("../core/machine.ts").History;
66
+ sums?: Record<string, import("../core/machine.ts").Sum>;
67
+ counts?: Record<string, import("../core/machine.ts").Counted>;
68
+ fns?: Record<string, import("../core/machine.ts").Fn>;
69
+ facts?: Law[];
70
+ leasts?: Record<string, import("../core/machine.ts").Least>;
71
+ relations?: Record<string, string[]>;
72
+ };
73
+ vars: {};
74
+ maps: {
75
+ [x: string]: {
76
+ start: number;
77
+ write: {
78
+ key: E;
79
+ value: E;
80
+ };
81
+ };
82
+ };
83
+ };
84
+ target: {
85
+ state: {
86
+ [x: string]: E;
87
+ };
88
+ sums: {
89
+ [x: string]: {
90
+ term: E;
91
+ key: string;
92
+ };
93
+ };
94
+ primitiveFailure?: C;
95
+ name: string;
96
+ params: string[];
97
+ inputs: string[];
98
+ maps?: Record<string, number>;
99
+ inputMaps?: string[];
100
+ step: {
101
+ flags?: Record<string, C>;
102
+ state?: Record<string, E>;
103
+ maps?: Record<string, import("../core/machine.ts").MapUpdate>;
104
+ };
105
+ pre?: C;
106
+ assume?: C;
107
+ history?: import("../core/machine.ts").History;
108
+ counts?: Record<string, import("../core/machine.ts").Counted>;
109
+ fns?: Record<string, import("../core/machine.ts").Fn>;
110
+ facts?: Law[];
111
+ leasts?: Record<string, import("../core/machine.ts").Least>;
112
+ relations?: Record<string, string[]>;
113
+ };
114
+ laws: Law[];
115
+ publicEntry: number;
116
+ } | undefined;
117
+ export declare function checkGhostWrite(source: Machine, law: Law, p: GhostWriteCertificate): boolean;
@@ -0,0 +1,89 @@
1
+ // Lean twin: GhostWriteTransport.checkedTransport, using the complete original
2
+ // post-row functional. Closed flags and a fresh observer are just views.
3
+ import { get, n, same, walkOnce, x } from "../core/machine.js";
4
+ import { checkLaws, ghostedMachine, ghostedOk, mapArities, obligations, own, sideGoals, substC } from "./kernel.js";
5
+ const text = (x) => JSON.stringify(x);
6
+ const eq = (a, b) => text(a) === text(b);
7
+ const safeNat = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
8
+ const noSub = { vars: {}, maps: {}, flags: {} };
9
+ export function ghostWriteTheory(source, law, p) {
10
+ const r = p.recipe, ghost = r.ghostMap;
11
+ if (p.kind !== 'ghost-write' || Object.keys(p.projection).length !== 1 || p.projection.omitMap !== ghost ||
12
+ !law.forall || law.keys?.length || law.some?.length || law.ex || law.finite !== undefined ||
13
+ source.history || source.primitiveFailure || Object.keys(source.counts ?? {}).length || Object.keys(source.sums ?? {}).length ||
14
+ Object.keys(source.fns ?? {}).length || source.facts?.length || source.inputMaps?.length || Object.keys(source.leasts ?? {}).length)
15
+ return;
16
+ const sums = Object.entries(p.target.sums ?? {});
17
+ if (sums.length !== 1)
18
+ return;
19
+ const [sum, sd] = sums[0], used = text([source, law]);
20
+ const fresh = [r.observer, ghost, sum, sd.key];
21
+ if (new Set(fresh).size !== fresh.length || fresh.some(key => !key || used.includes(text(key))) ||
22
+ !eq(sd, { term: get(ghost, x(sd.key)), key: sd.key }))
23
+ return;
24
+ let unsupported = false;
25
+ walkOnce([source, law.holds, r.point], o => {
26
+ const t = o;
27
+ if (t.op === 'all' || t.op === 'get' && t.map?.startsWith('worddiv$') || t.op === 'const' && !safeNat(t.value) || t.op === 'mul' && !safeNat(t.k))
28
+ unsupported = true;
29
+ });
30
+ if (unsupported)
31
+ return;
32
+ obligations(source, [law]);
33
+ if (!Object.values(source.maps ?? {}).every(safeNat) || Object.values(mapArities(source, [law])).some(n => n !== 1))
34
+ return;
35
+ const written = (name) => { const w = own(source.step.maps ?? {}, name); return w && !('each' in w) ? w : undefined; };
36
+ if (!r.gates.length || !r.gates.every(([map, val]) => safeNat(val) && !!written(map)) || !written(r.group) || !written(r.weight) ||
37
+ !r.gates.some(([map]) => eq(written(map).key, r.point)))
38
+ return;
39
+ const post = (map, key) => {
40
+ const w = written(map);
41
+ return eq(key, w.key) ? w.value :
42
+ { op: 'if', c: same(key, w.key), then: w.value, else: get(map, key) };
43
+ };
44
+ const contribution = (read) => ({ op: 'if',
45
+ c: r.gates.reduceRight((tail, [map, val]) => ({ op: 'and', xs: [same(read(map), n(val)), tail] }), same(read(r.group), x(r.observer))),
46
+ then: read(r.weight), else: n(0) });
47
+ // Match the existing Lean closed-flag view of the same machine. Its dummy
48
+ // binders occur nowhere in the actual body or in the source machine.
49
+ let stem = 'internal$';
50
+ while (text([source, law, fresh]).includes(stem))
51
+ stem += 'a';
52
+ const closed = Object.create(null), inlined = Object.create(null);
53
+ for (const [i, [name, condition]] of Object.entries(source.step.flags ?? {}).entries()) {
54
+ const c = substC(condition, { ...noSub, flags: inlined });
55
+ inlined[name] = c;
56
+ closed[name] = { op: 'all', key: `${stem}${i}`, c };
57
+ }
58
+ const orig = { ...source, params: [...source.params, r.observer], step: { ...source.step, flags: closed } };
59
+ const lift = { orig, vars: {}, maps: { [ghost]: { start: 0, write: { key: r.point, value: contribution(map => post(map, r.point)) } } } };
60
+ if (!ghostedOk(lift))
61
+ return;
62
+ const full = ghostedMachine(lift);
63
+ const target = { ...full, state: { ...full.state, [sum]: n(0) }, sums: { [sum]: { term: get(ghost, x(sd.key)), key: sd.key } } };
64
+ if (!eq(target, p.target))
65
+ return;
66
+ const publicEntry = p.laws.findIndex(l => l.name === law.name), pointEntry = p.laws.findIndex(l => l.name === p.pointLaw);
67
+ if (publicEntry < 0 || pointEntry < 0 || publicEntry === pointEntry)
68
+ return;
69
+ const publicLaw = { name: law.name, holds: substC(law.holds, { ...noSub, vars: { [law.forall]: x(r.observer) } }) };
70
+ const binder = p.laws[pointEntry].forall;
71
+ if (!binder)
72
+ return;
73
+ const rowLaw = { name: p.pointLaw, forall: binder, holds: same(get(ghost, x(binder)), contribution(map => get(map, x(binder)))) };
74
+ if (!eq(publicLaw, p.laws[publicEntry]) || !eq(rowLaw, p.laws[pointEntry]))
75
+ return;
76
+ const laws = p.laws.map((entry, i) => i === publicEntry ? publicLaw : i === pointEntry ? rowLaw : entry);
77
+ if (laws.some(l => l.keys?.length || l.some?.length || l.ex || l.finite !== undefined))
78
+ return;
79
+ return { orig, lift, target, laws, publicEntry };
80
+ }
81
+ export function checkGhostWrite(source, law, p) {
82
+ try {
83
+ const t = ghostWriteTheory(source, law, p);
84
+ return !!t && sideGoals(t.target, t.laws).length === 0 && checkLaws(t.target, t.laws, p.proof);
85
+ }
86
+ catch {
87
+ return false;
88
+ }
89
+ }
@@ -7,6 +7,9 @@ import { type CountCert, type CountDecl, type CountedGoal, type CountInst, type
7
7
  import { proveStepLaws } from '../kernel/prove.js';
8
8
  import { type Cyclic } from '../kernel/cyclic.js';
9
9
  import { leanLibrary } from './library.js';
10
+ import type { FiniteSumCertificate } from '../kernel/finite-sum.js';
11
+ import type { GhostWriteCertificate } from '../kernel/ghost-write.js';
12
+ import type { AggregateKinds } from '../core/aggregate-kinds.js';
10
13
  export { leanLibrary };
11
14
  export type Exported = {
12
15
  name: string;
@@ -338,6 +341,14 @@ export type LeanItem = {
338
341
  k?: number;
339
342
  ms?: number;
340
343
  };
344
+ } | {
345
+ id: string;
346
+ aggregate: {
347
+ source: Machine;
348
+ law: Law;
349
+ certificate: FiniteSumCertificate | GhostWriteCertificate;
350
+ kinds?: AggregateKinds;
351
+ };
341
352
  } | {
342
353
  id: string;
343
354
  countedGoal: CountedGoal;
@@ -18,6 +18,8 @@ import { proveKInduction } from "../core/kind.js";
18
18
  import { quantifiedRenames } from "./qalpha.js";
19
19
  import { countsForReads } from "../core/count-facts.js";
20
20
  import { requireSourceTranslation } from "../core/source-check.js";
21
+ import { finiteSumToLean } from "./finite-sum-export.js";
22
+ import { ghostWriteToLean } from "./ghost-write-export.js";
21
23
  export { leanLibrary };
22
24
  // --- to Lean ------------------------------------------------------------------------------------------------------------
23
25
  const varsOf = (c) => [...JSON.stringify(c).matchAll(/"op":"var","name":"([^"]+)"/g)].map(m => m[1]);
@@ -2553,6 +2555,8 @@ export function toLean(items, opts = {}) {
2553
2555
  requireSourceTranslation(item.machine, [...item.laws, ...(item.stepLaws ?? []), ...(item.liveness ?? [])]);
2554
2556
  else if ('kInduction' in item)
2555
2557
  requireSourceTranslation(item.kInduction.machine, [...item.kInduction.laws, item.kInduction.law]);
2558
+ else if ('aggregate' in item)
2559
+ requireSourceTranslation(item.aggregate.source, [item.aggregate.law]);
2556
2560
  else if ('countedMachine' in item)
2557
2561
  requireSourceTranslation(item.countedMachine, item.laws);
2558
2562
  else if ('refinement' in item) {
@@ -2609,7 +2613,23 @@ function toLeanWith(items, opts) {
2609
2613
  }).join('');
2610
2614
  for (let item of items) {
2611
2615
  const id = ident(item.id), tItem = performance.now();
2612
- if ('countedGoal' in item) {
2616
+ if ('aggregate' in item) {
2617
+ const { source, law, certificate, kinds } = item.aggregate;
2618
+ if (kinds) {
2619
+ const kindId = `${id}_kinds`;
2620
+ parts.push(retainedSMachineToLean(kindId, source, kinds.laws, kinds.proof));
2621
+ theorems.push(`${kindId}_laws`);
2622
+ }
2623
+ const save = checkBy;
2624
+ checkBy = 'decide +kernel';
2625
+ try {
2626
+ parts.push(certificate.kind === 'finite-sum' ? finiteSumToLean(id, source, law, certificate) : ghostWriteToLean(id, source, law, certificate));
2627
+ }
2628
+ finally {
2629
+ checkBy = save;
2630
+ }
2631
+ }
2632
+ else if ('countedGoal' in item) {
2613
2633
  if (!checkCounted(item.countedGoal, item.certificate))
2614
2634
  throw new Error(`${item.id}: counted certificate does not check`);
2615
2635
  parts.push(countedToLean(id, item.countedGoal, item.certificate));
@@ -2729,8 +2749,10 @@ function toLeanWith(items, opts) {
2729
2749
  console.error(`lean item ${item.id}: ${Math.round(performance.now() - tItem)} ms, ${parts.at(-1)?.length ?? 0} bytes`);
2730
2750
  }
2731
2751
  // The file the items need: Live.lean for a liveness or a loop, Sets.lean (which imports Steps.lean) for any machine.
2752
+ const finiteImport = items.some(item => 'aggregate' in item && item.aggregate.certificate.kind === 'finite-sum') ? 'import FiniteSumComposition\n' : '';
2753
+ const ghostImport = items.some(item => 'aggregate' in item && item.aggregate.certificate.kind === 'ghost-write') ? 'import Sums\nimport GhostWriteTransport\nimport GhostSourceViews\n' : '';
2732
2754
  return `import History
2733
- ${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'}
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'}
2734
2756
  open Kern Cert
2735
2757
  set_option maxRecDepth 100000
2736
2758
  set_option maxHeartbeats 0
@@ -0,0 +1,3 @@
1
+ import type { Law, Machine } from '../core/machine.js';
2
+ import { type FiniteSumCertificate } from '../kernel/finite-sum.js';
3
+ export declare function finiteSumToLean(id: string, m: Machine, law: Law, certificate: FiniteSumCertificate): string;
@@ -0,0 +1,163 @@
1
+ import { checkFiniteSum, finiteSumTheory, sumLocalGoal } from "../kernel/finite-sum.js";
2
+ import { encode, machineLit } from "./emit.js";
3
+ import { leanTerms } from "./lean-terms.js";
4
+ // Replay the retained local trees verbatim. Only the syntax-to-semantics
5
+ // adapter is generated; induction/finite addition use the general theorem.
6
+ export function finiteSumToLean(id, m, law, certificate) {
7
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(id) || !checkFiniteSum(m, law, certificate))
8
+ throw Error('invalid finite-sum export');
9
+ const { layout: p, trees } = certificate, { locals, point, coordinate, reset: resetTerm } = finiteSumTheory(m, law, p);
10
+ const write = m.step.maps[p.map];
11
+ if (!('each' in write))
12
+ throw Error('expected broadcast write');
13
+ const names = [...new Set([...m.params, ...m.inputs, ...Object.keys(m.state), ...Object.keys(m.step.flags ?? {}).map(f => `?${f}`), write.each, coordinate])];
14
+ const maps = [p.map], t = leanTerms(names, maps, 'finite-sum');
15
+ const index = (name) => { const i = names.indexOf(name); if (i < 0)
16
+ throw Error(`unknown finite-sum name ${name}`); return i; };
17
+ const mx = (map) => { if (map !== p.map)
18
+ throw Error(`unknown finite-sum map ${map}`); return 0; };
19
+ const certs = locals.map(loc => {
20
+ const goal = sumLocalGoal(loc), cert = encode({ name: loc.name, goal, tree: trees[loc.name] }, false, true, names, maps);
21
+ const hypotheses = loc.assumptions.map((h, i) => ` (h${i} : holdsC env maps (${t.c(h)}))`).join('');
22
+ const cases = goal.hyps.map(() => 'rfl').join(' | ');
23
+ return `def ${loc.name}_goal : Kern.Goal := ⟨${cert.tab}, ${cert.hyps}⟩
24
+ def ${loc.name}_tree : Kern.Tree := ${cert.tree}
25
+ theorem ${loc.name}_check : checkGoal ${loc.name}_goal ${loc.name}_tree = true := by decide +kernel
26
+ theorem checked_${loc.name} (env : Nat → Nat) (maps : Nat → Nat → Nat)${hypotheses} :
27
+ holdsC env maps (${t.c(loc.conclusion)}) := by
28
+ apply Classical.byContradiction
29
+ intro h
30
+ apply sound ${loc.name}_goal ${loc.name}_tree ${loc.name}_check env maps
31
+ intro c hc
32
+ simp only [${loc.name}_goal, List.mem_cons, List.mem_nil_iff, or_false] at hc
33
+ ${goal.hyps.length === 1 ? ' subst c' : ` rcases hc with ${cases}`}
34
+ ${loc.assumptions.map((_, i) => ` · exact (evalC_iff env maps _).2 h${i}\n`).join('')} ${loc.assumptions.length ? '· ' : ''}exact (evalC_iff env maps _).2 h`;
35
+ }).join('\n\n');
36
+ const addr = (v) => p.offset ? `(${v} + ${p.offset})` : v;
37
+ const bound = index(p.bound), defCell = m.maps[p.map], fields = p.fields.map(f => ({ ...f, i: index(f.field) }));
38
+ const indices = fields.map(f => f.i).join(',');
39
+ const tags = fields.map(f => `if i = ${f.i} then ${f.value} else `).join('') + '0';
40
+ const arr = (n) => Array.from({ length: n }, () => 'rfl').join(' | ');
41
+ const sem = 'src, before, applyS, assoc, lookup, evalE, evalC, holdsC, upd, everyMaps, decideFlags, flagSub, withInputs, -List.elem_eq_contains';
42
+ const prev = '(before ρ ι)', next = '(sNext src ρ M ι κ)', shift = `(upd X ${index(coordinate)} j)`;
43
+ const stepvars = '(ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat)';
44
+ const grouping = fields.map(f => `countCell ${f.value} M j`).reduce((a, b) => `(${a} + ${b})`);
45
+ const cap = fields.map(f => `ρ ${f.i}`).reduce((a, b) => `(${a} + ${b})`);
46
+ const start = fields.map((f, i) => ` · have h0 : (applyS src.f.m.init ρ M) ${f.i} = 0 := by
47
+ simpa [${sem}] using checked_field${i}_init ρ M
48
+ exact ⟨h0.trans (sumBelow_zero_fn _).symm, fun j _ => by
49
+ change countCell ${f.value} M j = 0
50
+ simp [countCell, initMap]⟩`).join('\n');
51
+ const reset = fields.map((f, i) => ` · have hz : ρ' ${f.i} = 0 := by
52
+ simp only [ρ', sNext, view_eq, Prod.fst, Prod.snd]
53
+ simpa [X, ${sem}] using checked_field${i}_reset X M ha hr
54
+ exact ⟨hz.trans (sumBelow_zero_fn _).symm, fun j _ => by
55
+ change countCell ${f.value} M' j = 0
56
+ simp [countCell, resetMap]⟩`).join('\n');
57
+ const delta = fields.map((f, i) => ` · have hdelta : ρ' ${f.i} + countCell ${f.value} M q = ρ ${f.i} + countCell ${f.value} M' q := by
58
+ simp only [ρ', M', countCell, sNext, view_eq, Prod.fst, Prod.snd]
59
+ simpa [q, point, X, ${sem}] using checked_field${i}_delta X M ha hr
60
+ simpa [layout, sumOn] using hdelta`).join('\n');
61
+ const resetC = t.c(resetTerm);
62
+ return `namespace ${id}
63
+ open Kern Classical Kern.FiniteSumComposition
64
+ set_option maxRecDepth 30000
65
+ set_option maxHeartbeats 0
66
+ set_option linter.unusedSimpArgs false
67
+
68
+ def src : SMachine := ${machineLit(m, t, index, mx)}
69
+ def original : C := ${t.c(law.holds)}
70
+ def before (ρ ι : Nat → Nat) := withInputs src.f.m.inputs ρ ι
71
+ def point (X : Nat → Nat) (M : Nat → Nat → Nat) := evalE X M (${t.e(point)})
72
+ def countCell (tag : Nat) (M : Nat → Nat → Nat) (j : Nat) : Nat := if M 0 ${addr('j')} = tag then 1 else 0
73
+ def layout : Layout := ⟨[${indices}], fun s => s.1 ${bound}, fun i s => countCell (${tags}) s.2⟩
74
+
75
+ theorem view_eq ${stepvars} : sView src ρ M ι κ = (decideFlags src.f.flags ${prev} M, M) := by
76
+ have hm : withCarried src M κ = M := by funext i j; rfl
77
+ have hv : decideQ src ${prev} M = ${prev} := by funext i; simp [decideQ, src, lookup]
78
+ simp only [sView, hm]
79
+ change (decideFlags src.f.flags (decideQ src ${prev} M) M, M) = _
80
+ rw [hv]
81
+
82
+ theorem assume_eq ${stepvars}
83
+ (h : evalC (sView src ρ M ι κ).1 (sView src ρ M ι κ).2 src.f.m.assume = true) :
84
+ holdsC ${prev} M (${t.c(locals[0].assumptions[0])}) := by
85
+ rw [view_eq] at h
86
+ simpa [${sem}] using h
87
+
88
+ theorem bound_next ${stepvars} : ${next}.1 ${bound} = ρ ${bound} := by
89
+ simp only [sNext, view_eq, Prod.fst, Prod.snd]
90
+ simp [${sem}]
91
+ ${certs}
92
+
93
+ theorem layout_base (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hm : StartMaps src.f.m M) :
94
+ Coupled layout (applyS src.f.m.init ρ M, M) := by
95
+ have initMap (j : Nat) : M 0 j = ${defCell} := hm (0,${defCell}) (by simp [src]) j
96
+ apply rebuilt_coupled layout
97
+ refine ⟨fun _ _ => 0, ?_⟩
98
+ intro i hi
99
+ simp only [layout, List.mem_cons, List.not_mem_nil, or_false] at hi
100
+ rcases hi with ${arr(fields.length)}
101
+ ${start}
102
+
103
+ theorem layout_next ${stepvars}
104
+ (adm : evalC (sView src ρ M ι κ).1 (sView src ρ M ι κ).2 src.f.m.assume = true) :
105
+ StepOK layout (ρ, M) ${next} := by
106
+ let X := before ρ ι
107
+ let N := ρ ${bound}
108
+ let q := point X M
109
+ let ρ' := ${next}.1
110
+ let M' := ${next}.2
111
+ have hn : ρ' ${bound} = N := bound_next ρ M ι κ
112
+ have hb : X ${bound} = N := by rfl
113
+ have ha := assume_eq ρ M ι κ adm
114
+ have hq : q < N := by simpa only [q, point, holdsC, evalE, hb] using checked_point_inside X M ha
115
+ have haAt (j : Nat) : holdsC ${shift} M (${t.c(locals[0].assumptions[0])}) := by
116
+ simpa [holdsC, evalE, upd] using ha
117
+ have hqAt (j : Nat) : point ${shift} M = q := by simp [point, evalE, upd, q]
118
+ refine ⟨hn, ?_⟩
119
+ by_cases hr : holdsC X M (${resetC})
120
+ · have hrAt (j : Nat) : holdsC ${shift} M (${resetC}) := by simpa [holdsC, evalE, upd] using hr
121
+ have resetMap (j : Nat) : M' 0 ${addr('j')} = ${defCell} := by
122
+ have v := checked_broadcast_reset ${shift} M (haAt j) (hrAt j)
123
+ simp only [M', sNext, view_eq, Prod.fst, Prod.snd]
124
+ simpa [X, ${sem}] using v
125
+ refine Or.inr ⟨fun _ _ => 0, ?_⟩
126
+ intro i hi
127
+ simp only [layout, List.mem_cons, List.not_mem_nil, or_false] at hi
128
+ rcases hi with ${arr(fields.length)}
129
+ ${reset}
130
+ · have hrAt (j : Nat) : ¬holdsC ${shift} M (${resetC}) := by simpa [holdsC, evalE, upd] using hr
131
+ have frameMap (j : Nat) (hne : j ≠ q) : M' 0 ${addr('j')} = M 0 ${addr('j')} := by
132
+ have hneq : holdsC ${shift} M (${t.c(locals[1].assumptions[2])}) := by
133
+ change j ≠ point ${shift} M
134
+ rwa [hqAt]
135
+ have v := checked_other_cells_frame ${shift} M (haAt j) (hrAt j) hneq
136
+ simp only [M', sNext, view_eq, Prod.fst, Prod.snd]
137
+ simpa [X, ${sem}] using v
138
+ refine Or.inl ⟨[q], by simp, ?_, ?_⟩
139
+ · simpa [layout, N] using hq
140
+ · intro i hi
141
+ constructor
142
+ · intro j _ hne
143
+ change countCell _ M' j = countCell _ M j
144
+ simp [countCell, frameMap j (by simpa using hne)]
145
+ · simp only [layout, List.mem_cons, List.not_mem_nil, or_false] at hi
146
+ rcases hi with ${arr(fields.length)}
147
+ ${delta}
148
+
149
+ theorem original_law {ρ M} (h : SReach src ρ M) : holdsC ρ M original := by
150
+ apply state_law src layout original (fun _ _ => 1) layout_base layout_next _ _ h
151
+ · rintro ⟨ρ, M⟩ j _
152
+ have v := checked_disjoint_capacity (upd ρ ${index(coordinate)} j) M
153
+ have hc : ${grouping} ≤ 1 := by simpa [countCell, holdsC, evalE, evalC, upd] using v
154
+ simpa [layout, sumOn, Nat.add_assoc] using hc
155
+ · rintro ⟨ρ, M⟩ hcap
156
+ apply checked_capacity_entails_claim
157
+ change ${cap} ≤ ρ ${bound}
158
+ simpa [layout, sumOn, sumBelow_const, Nat.add_assoc] using hcap
159
+
160
+ end ${id}
161
+ #print axioms ${id}.original_law
162
+ `;
163
+ }
@@ -0,0 +1,3 @@
1
+ import type { Law, Machine } from '../core/machine.js';
2
+ import { type GhostWriteCertificate } from '../kernel/ghost-write.js';
3
+ export declare function ghostWriteToLean(id: string, source: Machine, law: Law, p: GhostWriteCertificate): string;
@@ -0,0 +1,81 @@
1
+ import { checkGhostWrite, ghostWriteTheory } from "../kernel/ghost-write.js";
2
+ import { plainOf } from "../kernel/kernel.js";
3
+ import { seedStepProof, smachineToLean } from "./emit.js";
4
+ export function ghostWriteToLean(id, source, law, p) {
5
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(id) || !checkGhostWrite(source, law, p))
6
+ throw Error('invalid ghost-write export');
7
+ const { target, laws, orig, publicEntry } = ghostWriteTheory(source, law, p), r = p.recipe;
8
+ // The exact retained family only. A proof producer is not run at export.
9
+ seedStepProof(plainOf(target), laws, [], { proven: true, checked: true, nodes: 0, leaves: 0, proof: { laws: p.proof, instances: {}, perStep: {}, trees: {} } });
10
+ const body = smachineToLean('packet', target, laws, { free: [law.forall], coverTrees: p.proof.trees, after: (ix, mx, lit, cond) => {
11
+ const binder = Object.entries(orig.step.flags ?? {}).map(([f, a]) => {
12
+ if (a.op !== 'all')
13
+ throw Error('expected closed flag');
14
+ return `if i = ${ix(`?${f}`)} then ${ix(a.key)} else `;
15
+ }).join('') + '0';
16
+ const goal = cond(law.holds), specialization = cond(laws[publicEntry].holds);
17
+ const ghost = mx(r.ghostMap), observer = ix(r.observer);
18
+ const declared = Object.keys(source.maps ?? {}).map(mx).join(',');
19
+ return `
20
+ def originalMachine : SMachine := ${lit(source)}
21
+ def unchangedLaw : MLaw := ⟨${goal}, some ${ix(law.forall)}⟩
22
+ def observer : Nat := ${observer}
23
+ def ghostMap : Nat := ${ghost}
24
+ def closedBinder (i : Nat) : Nat := ${binder}
25
+ def closedSource : SMachine := ${lit(orig)}
26
+ def pointIndex : E := ((packet_sums.s.f.m.writes.find? (fun row => row.1 == ghostMap)).map (fun row => row.2.1)).getD (.const 0)
27
+ def recipe : GhostWrite.Recipe := ⟨pointIndex, [${r.gates.map(([m, v]) => `(${mx(m)}, ${v})`).join(',')}], ${mx(r.group)}, ${mx(r.weight)}, observer⟩
28
+ def sourceMapIds : List Nat := [${declared}]
29
+ def closedPoint : GhostWrite.Point := GhostWrite.completePoint closedSource ghostMap recipe
30
+
31
+ theorem recipeChecks : GhostWrite.Checked closedSource sourceMapIds ghostMap recipe := by
32
+ constructor <;> first | rfl | decide +kernel
33
+
34
+ theorem targetShape : packet_sums.s = (GhostWrite.aug closedSource closedPoint).full := by rfl
35
+ theorem sumGhostChecks : sghostOk packet_sums.ghosts = true := by decide +kernel
36
+ theorem promotionIdentity : closedSource = GhostSourceViews.promote originalMachine closedBinder closedSource.wits := by rfl
37
+
38
+ def specialized : C := ${specialization}
39
+ def projectedLaw (v : GhostWrite.Env × ({m : Nat // m ≠ ghostMap} → GhostWrite.Env)) : Prop :=
40
+ holdsC v.1 (fun m => if h : m ≠ ghostMap then v.2 ⟨m,h⟩ else fun _ => 0) specialized
41
+
42
+ theorem projectedLaw_iff (y : GhostWrite.State) :
43
+ projectedLaw (GhostWrite.projection closedPoint y) ↔ evalC y.1 y.2 specialized = true := by
44
+ unfold projectedLaw
45
+ rw [← evalC_iff]
46
+ change evalC y.1 (fun m => if _ : m ≠ ghostMap then y.2 m else fun _ => 0) specialized = true ↔ _
47
+ have hm : avoidsMaps [ghostMap] specialized = true := by decide +kernel
48
+ rw [congrMC y.1 _ y.2 specialized]
49
+ intro m occurs
50
+ have h : m ≠ ghostMap := by simpa using avoidsMaps_occ hm occurs
51
+ simp [h]
52
+
53
+ theorem original_law (ρ : Nat → Nat) (M : Nat → Nat → Nat)
54
+ (hr : SReach originalMachine ρ M) : unchangedLaw.Holds ρ M := by
55
+ intro k
56
+ have ho := GhostSourceViews.source_rebind originalMachine observer rfl rfl rfl (by decide +kernel) hr k
57
+ have hc : SReach closedSource (upd ρ observer k) M :=
58
+ (GhostSourceViews.candidate_reach closedBinder _ promotionIdentity rfl (by decide +kernel)).mpr ho
59
+ have hinv (y : GhostWrite.State) (hy : SReach packet_sums.s y.1 y.2) :
60
+ projectedLaw (GhostWrite.projection closedPoint y) := by
61
+ apply (projectedLaw_iff y).mpr
62
+ exact sum_project_laws packet_sums sumGhostChecks packet_proof packet_check packet_scheck
63
+ y.1 y.2 hy packet_e${publicEntry} (by simp [packet_proof]) (by decide +kernel)
64
+ have hp := GhostWrite.checkedTransport recipeChecks packet_sums.s targetShape projectedLaw hinv hc
65
+ have hl := (projectedLaw_iff (upd ρ observer k,M)).mp hp
66
+ change evalC (upd ρ ${ix(law.forall)} k) M (${goal}) = true
67
+ simpa [specialized, observer, evalC, evalE, upd] using hl
68
+
69
+ #print axioms packet_check
70
+ #print axioms packet_scheck
71
+ #print axioms recipeChecks
72
+ #print axioms original_law
73
+ `;
74
+ } });
75
+ return `namespace ${id}
76
+ open Kern Cert Classical
77
+ set_option maxRecDepth 100000
78
+ set_option maxHeartbeats 0
79
+ ${body}
80
+ end ${id}\n`;
81
+ }