gdp-wired 0.51.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.
Files changed (89) hide show
  1. package/README.md +2 -2
  2. package/dist/core/accel-refute.d.ts +53 -0
  3. package/dist/core/accel-refute.js +997 -0
  4. package/dist/core/aggregate-kinds.d.ts +10 -0
  5. package/dist/core/aggregate-kinds.js +44 -0
  6. package/dist/core/aggregate-search.d.ts +9 -0
  7. package/dist/core/aggregate-search.js +74 -0
  8. package/dist/core/aggregate-weighted/candidates.d.ts +18 -0
  9. package/dist/core/aggregate-weighted/candidates.js +128 -0
  10. package/dist/core/aggregate-weighted/search.d.ts +17 -0
  11. package/dist/core/aggregate-weighted/search.js +68 -0
  12. package/dist/core/cli.d.ts +2 -0
  13. package/dist/core/cli.js +8 -1
  14. package/dist/core/cycles.d.ts +2 -0
  15. package/dist/core/cycles.js +12 -9
  16. package/dist/core/dsl.d.ts +7 -1
  17. package/dist/core/dsl.js +158 -26
  18. package/dist/core/filtered-sum-candidates.d.ts +17 -0
  19. package/dist/core/filtered-sum-candidates.js +77 -0
  20. package/dist/core/live-support.d.ts +5 -0
  21. package/dist/core/live-support.js +148 -0
  22. package/dist/core/live.js +194 -37
  23. package/dist/core/lockstep.d.ts +5 -0
  24. package/dist/core/lockstep.js +23 -0
  25. package/dist/core/ordered-pair-seeds.d.ts +2 -0
  26. package/dist/core/ordered-pair-seeds.js +109 -0
  27. package/dist/core/proof-output.d.ts +49 -2
  28. package/dist/core/proof-output.js +44 -0
  29. package/dist/core/search-termination.d.ts +4 -0
  30. package/dist/core/search-termination.js +1 -1
  31. package/dist/core/source-check.d.ts +4 -1
  32. package/dist/core/source-check.js +5 -2
  33. package/dist/core/sparse-kind-proof.d.ts +7 -0
  34. package/dist/core/sparse-kind-proof.js +49 -0
  35. package/dist/core/step-seeds.d.ts +46 -0
  36. package/dist/core/step-seeds.js +316 -0
  37. package/dist/kernel/finite-sum.d.ts +31 -0
  38. package/dist/kernel/finite-sum.js +74 -0
  39. package/dist/kernel/ghost-write.d.ts +117 -0
  40. package/dist/kernel/ghost-write.js +89 -0
  41. package/dist/lean-kernel/Cert.lean +222 -0
  42. package/dist/lean-kernel/Count.lean +1568 -0
  43. package/dist/lean-kernel/Ghost.lean +373 -0
  44. package/dist/lean-kernel/GhostMap.lean +426 -0
  45. package/dist/lean-kernel/Kernel.lean +2881 -0
  46. package/dist/lean-kernel/Live.lean +1168 -0
  47. package/dist/lean-kernel/Progress.lean +543 -0
  48. package/dist/lean-kernel/Sets.lean +1975 -0
  49. package/dist/lean-kernel/StepLaw.lean +128 -0
  50. package/dist/lean-kernel/Steps.lean +477 -0
  51. package/dist/lean-kernel/Sums.lean +916 -0
  52. package/dist/lean-kernel/emit.d.ts +15 -0
  53. package/dist/lean-kernel/emit.js +47 -6
  54. package/dist/lean-kernel/finite-sum-export.d.ts +3 -0
  55. package/dist/lean-kernel/finite-sum-export.js +163 -0
  56. package/dist/lean-kernel/ghost-write-export.d.ts +3 -0
  57. package/dist/lean-kernel/ghost-write-export.js +81 -0
  58. package/dist/lean-kernel/lean-aggregate/FiniteFold.lean +44 -0
  59. package/dist/lean-kernel/lean-aggregate/GroupedTransport.lean +308 -0
  60. package/dist/lean-kernel/lean-aggregate/aggregate.d.ts +13 -0
  61. package/dist/lean-kernel/lean-aggregate/aggregate.js +68 -0
  62. package/dist/lean-kernel/lean-aggregate/assets.d.ts +5 -0
  63. package/dist/lean-kernel/lean-aggregate/assets.js +7 -0
  64. package/dist/lean-kernel/lean-aggregate/audit.d.ts +3 -0
  65. package/dist/lean-kernel/lean-aggregate/audit.js +13 -0
  66. package/dist/lean-kernel/lean-aggregate/exact.d.ts +15 -0
  67. package/dist/lean-kernel/lean-aggregate/exact.js +51 -0
  68. package/dist/lean-kernel/lean-aggregate/index.d.ts +19 -0
  69. package/dist/lean-kernel/lean-aggregate/index.js +52 -0
  70. package/dist/lean-kernel/lean-aggregate/point-fold.d.ts +27 -0
  71. package/dist/lean-kernel/lean-aggregate/point-fold.js +79 -0
  72. package/dist/lean-kernel/lean-aggregate/replay-fold.d.ts +2 -0
  73. package/dist/lean-kernel/lean-aggregate/replay-fold.js +163 -0
  74. package/dist/lean-kernel/lean-aggregate/source.d.ts +2 -0
  75. package/dist/lean-kernel/lean-aggregate/source.js +141 -0
  76. package/dist/lean-kernel/lean-aggregate/weighted-flags.d.ts +2 -0
  77. package/dist/lean-kernel/lean-aggregate/weighted-flags.js +26 -0
  78. package/dist/lean-kernel/lean-aggregate/weighted-replay.d.ts +7 -0
  79. package/dist/lean-kernel/lean-aggregate/weighted-replay.js +53 -0
  80. package/dist/lean-kernel/lean-aggregate/weighted-seeded.d.ts +30 -0
  81. package/dist/lean-kernel/lean-aggregate/weighted-seeded.js +64 -0
  82. package/dist/lean-kernel/lean-aggregate/weighted.d.ts +18 -0
  83. package/dist/lean-kernel/lean-aggregate/weighted.js +115 -0
  84. package/dist/lean-kernel/lean-aggregate/worker.d.ts +10 -0
  85. package/dist/lean-kernel/lean-aggregate/worker.js +46 -0
  86. package/dist/lean-kernel/library.js +3 -0
  87. package/dist/lean-kernel/lift-simulation/shape.js +5 -5
  88. package/docs/lean-aggregate.md +29 -0
  89. package/package.json +6 -1
@@ -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;
@@ -234,6 +237,10 @@ export declare function retainedSMachineToLean(id: string, m: Machine, laws: Law
234
237
  instances: Record<string, Instances>;
235
238
  trees: Record<string, Tree>;
236
239
  }, projection?: Pick<NonNullable<Parameters<typeof smachineToLean>[3]>, 'ghosts' | 'ghosted' | 'ghostSubst' | 'forallSome' | 'free' | 'after'>): string;
240
+ export declare function retainedSumMachineToLean(id: string, m: Machine, laws: Law[], proof: {
241
+ instances: Record<string, Instances>;
242
+ trees: Record<string, Tree>;
243
+ }, projection: Pick<NonNullable<Parameters<typeof smachineToLean>[3]>, 'free' | 'after'>): string;
237
244
  export declare const cyclicCerts: () => boolean;
238
245
  export declare const certReport: {
239
246
  cyclic: string[];
@@ -334,6 +341,14 @@ export type LeanItem = {
334
341
  k?: number;
335
342
  ms?: number;
336
343
  };
344
+ } | {
345
+ id: string;
346
+ aggregate: {
347
+ source: Machine;
348
+ law: Law;
349
+ certificate: FiniteSumCertificate | GhostWriteCertificate;
350
+ kinds?: AggregateKinds;
351
+ };
337
352
  } | {
338
353
  id: string;
339
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]);
@@ -1741,8 +1743,14 @@ def ${id}_machine : SMachine := ${id}_sums.plain`;
1741
1743
  // machine's, the laws.
1742
1744
  const sumsBlock = () => {
1743
1745
  const trees = covers.map(gs => list(gs.map(g => {
1744
- const t2 = opts.coverTrees?.[g.name] ?? (() => { const out = grow(g); if (!('tree' in out))
1745
- throw new Error(`${id}: ${g.name} not proven`); return out.tree; })();
1746
+ const t2 = opts.coverTrees?.[g.name] ?? (() => {
1747
+ if (retainedOnly)
1748
+ throw new Error(`${id}: missing retained cover tree for ${g.name}`);
1749
+ const out = grow(g);
1750
+ if (!('tree' in out))
1751
+ throw new Error(`${id}: ${g.name} not proven`);
1752
+ return out.tree;
1753
+ })();
1746
1754
  const x2 = enc(g, t2);
1747
1755
  return `(${x2.tab}, ${x2.tree})`;
1748
1756
  })));
@@ -1934,13 +1942,26 @@ export function retainedSMachineToLean(id, m, laws, proof, projection = {}) {
1934
1942
  retainedShape(id, m, laws);
1935
1943
  if (!checkLaws(m, laws, proof))
1936
1944
  throw new Error('captured usual family does not check');
1945
+ return emitRetainedSMachine(id, m, m, laws, proof, projection);
1946
+ }
1947
+ // Sum machinery and all source transport still check in Lean; this only reuses
1948
+ // the instrumented family's retained local trees and forbids fresh cover search.
1949
+ export function retainedSumMachineToLean(id, m, laws, proof, projection) {
1950
+ if (!m.sums || !Object.keys(m.sums).length || m.history)
1951
+ throw new Error('retained sum export needs a sums machine without history');
1952
+ retainedShape(id, { ...m, sums: undefined }, laws);
1953
+ if (!checkLaws(m, laws, proof))
1954
+ throw new Error('captured sums family does not check');
1955
+ return emitRetainedSMachine(id, m, sumMachine(m).machine, laws, proof, { ...projection, coverTrees: proof.trees });
1956
+ }
1957
+ function emitRetainedSMachine(id, given, plain, laws, proof, options) {
1937
1958
  const old = checkBy, oldRetained = retainedOnly, oldCache = [...usualMade];
1938
1959
  try {
1939
1960
  usualMade.clear();
1940
1961
  retainedOnly = true;
1941
1962
  checkBy = 'decide +kernel';
1942
- seedStepProof(m, laws, [], { proven: true, checked: true, nodes: 0, leaves: 0, proof: { laws: proof, instances: {}, perStep: {}, trees: {} } });
1943
- return smachineToLean(id, m, laws, projection);
1963
+ seedStepProof(plain, laws, [], { proven: true, checked: true, nodes: 0, leaves: 0, proof: { laws: proof, instances: {}, perStep: {}, trees: {} } });
1964
+ return smachineToLean(id, given, laws, options);
1944
1965
  }
1945
1966
  finally {
1946
1967
  usualMade.clear();
@@ -2534,6 +2555,8 @@ export function toLean(items, opts = {}) {
2534
2555
  requireSourceTranslation(item.machine, [...item.laws, ...(item.stepLaws ?? []), ...(item.liveness ?? [])]);
2535
2556
  else if ('kInduction' in item)
2536
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]);
2537
2560
  else if ('countedMachine' in item)
2538
2561
  requireSourceTranslation(item.countedMachine, item.laws);
2539
2562
  else if ('refinement' in item) {
@@ -2590,7 +2613,23 @@ function toLeanWith(items, opts) {
2590
2613
  }).join('');
2591
2614
  for (let item of items) {
2592
2615
  const id = ident(item.id), tItem = performance.now();
2593
- 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) {
2594
2633
  if (!checkCounted(item.countedGoal, item.certificate))
2595
2634
  throw new Error(`${item.id}: counted certificate does not check`);
2596
2635
  parts.push(countedToLean(id, item.countedGoal, item.certificate));
@@ -2710,8 +2749,10 @@ function toLeanWith(items, opts) {
2710
2749
  console.error(`lean item ${item.id}: ${Math.round(performance.now() - tItem)} ms, ${parts.at(-1)?.length ?? 0} bytes`);
2711
2750
  }
2712
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' : '';
2713
2754
  return `import History
2714
- ${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'}
2715
2756
  open Kern Cert
2716
2757
  set_option maxRecDepth 100000
2717
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
+ }
@@ -0,0 +1,44 @@
1
+ import Count
2
+
3
+ /- No new count-checker rule. An ordinary Lean finite-sum theorem composes
4
+ the checked local transition obligations of the research certificate. -/
5
+ namespace FiniteFold
6
+ open Kern
7
+
8
+ theorem spike (n t : Nat) (v : Nat) (ht : t < n) :
9
+ sumBelow (fun k => if k = t then v else 0) n = v := by
10
+ induction n with
11
+ | zero => omega
12
+ | succ n ih =>
13
+ by_cases h : n = t
14
+ · subst t
15
+ have hz : sumBelow (fun k => if k = n then v else 0) n = 0 := by
16
+ calc
17
+ _ = sumBelow (fun _ => 0) n := by
18
+ apply sumBelow_congr
19
+ intro k hk
20
+ simp [Nat.ne_of_lt hk]
21
+ _ = 0 := sumBelow_zero_fn n
22
+ simp [sumBelow, hz]
23
+ · have hn : t < n := by omega
24
+ simp [sumBelow, ih hn, h]
25
+
26
+ theorem point_delta (f g : Nat → Nat) (n t : Nat) (ht : t < n)
27
+ (frame : ∀ k, k < n → k ≠ t → g k = f k) :
28
+ sumBelow g n + f t = sumBelow f n + g t := by
29
+ rw [← spike n t (f t) ht, ← spike n t (g t) ht]
30
+ rw [← sumBelow_add, ← sumBelow_add]
31
+ apply sumBelow_congr n
32
+ intro k hk
33
+ by_cases he : k = t
34
+ · subst k; simp [Nat.add_comm]
35
+ · simp [he, frame k hk he]
36
+
37
+ theorem coupled_change (f g : Nat → Nat) (n t before after : Nat)
38
+ (ht : t < n) (frame : ∀ k, k < n → k ≠ t → g k = f k)
39
+ (old : before = sumBelow f n) (delta : after + f t = before + g t) :
40
+ after = sumBelow g n := by
41
+ have h := point_delta f g n t ht frame
42
+ omega
43
+
44
+ end FiniteFold