gdp-wired 0.49.0 → 0.50.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.
- package/README.md +4 -0
- package/dist/core/candidate-seeds.d.ts +25 -0
- package/dist/core/candidate-seeds.js +90 -0
- package/dist/core/chart.js +28 -4
- package/dist/core/cli.js +3 -0
- package/dist/core/compose.js +4 -3
- package/dist/core/count-support.d.ts +1 -0
- package/dist/core/count-support.js +23 -2
- package/dist/core/counted-candidate-seeds.d.ts +12 -0
- package/dist/core/counted-candidate-seeds.js +31 -0
- package/dist/core/counts.js +9 -2
- package/dist/core/dsl-binders.d.ts +15 -0
- package/dist/core/dsl-binders.js +129 -0
- package/dist/core/dsl.d.ts +28 -2
- package/dist/core/dsl.js +147 -52
- package/dist/core/exists.js +2 -1
- package/dist/core/field-laws.js +23 -5
- package/dist/core/infer.js +10 -5
- package/dist/core/laws.js +2 -1
- package/dist/core/lift-cli.d.ts +11 -0
- package/dist/core/lift-cli.js +113 -0
- package/dist/core/proof-output.d.ts +53 -0
- package/dist/core/proof-output.js +38 -0
- package/dist/core/quorum-laws.js +55 -16
- package/dist/kernel/function-instances.d.ts +45 -0
- package/dist/kernel/function-instances.js +460 -0
- package/dist/kernel/prove.d.ts +12 -3
- package/dist/kernel/prove.js +164 -90
- package/dist/lean-kernel/axiom-audit.d.ts +11 -0
- package/dist/lean-kernel/axiom-audit.js +50 -0
- package/dist/lean-kernel/emit.d.ts +25 -2
- package/dist/lean-kernel/emit.js +75 -10
- package/dist/lean-kernel/legacy-family-order.d.ts +1 -0
- package/dist/lean-kernel/legacy-family-order.js +26 -0
- package/dist/lean-kernel/library.js +22 -0
- package/dist/lean-kernel/lift/counted-source-data.d.ts +7 -0
- package/dist/lean-kernel/lift/counted-source-data.js +78 -0
- package/dist/lean-kernel/lift/index.d.ts +82 -0
- package/dist/lean-kernel/lift/index.js +116 -0
- package/dist/lean-kernel/lift/project.d.ts +4 -0
- package/dist/lean-kernel/lift/project.js +15 -0
- package/dist/lean-kernel/lift/proof-capture.d.ts +104 -0
- package/dist/lean-kernel/lift/proof-capture.js +216 -0
- package/dist/lean-kernel/lift/proof-codec.d.ts +28 -0
- package/dist/lean-kernel/lift/proof-codec.js +299 -0
- package/dist/lean-kernel/lift/proof-counted-source.d.ts +16 -0
- package/dist/lean-kernel/lift/proof-counted-source.js +68 -0
- package/dist/lean-kernel/lift/proof-frontier.d.ts +19 -0
- package/dist/lean-kernel/lift/proof-frontier.js +153 -0
- package/dist/lean-kernel/lift/proof-graph.d.ts +17 -0
- package/dist/lean-kernel/lift/proof-graph.js +130 -0
- package/dist/lean-kernel/lift/proof-parts.d.ts +29 -0
- package/dist/lean-kernel/lift/proof-parts.js +131 -0
- package/dist/lean-kernel/lift/proof-prelude.d.ts +2 -0
- package/dist/lean-kernel/lift/proof-prelude.js +38 -0
- package/dist/lean-kernel/lift/proof-witness.d.ts +30 -0
- package/dist/lean-kernel/lift/proof-witness.js +283 -0
- package/dist/lean-kernel/lift/shape.d.ts +5 -0
- package/dist/lean-kernel/lift/shape.js +57 -0
- package/dist/lean-kernel/lift/source-projection.d.ts +16 -0
- package/dist/lean-kernel/lift/source-projection.js +81 -0
- package/dist/lean-kernel/lift/source.d.ts +23 -0
- package/dist/lean-kernel/lift/source.js +111 -0
- package/dist/lean-kernel/lift/witness-alpha.d.ts +9 -0
- package/dist/lean-kernel/lift/witness-alpha.js +31 -0
- package/dist/lean-kernel/lift-legacy.d.ts +58 -0
- package/dist/lean-kernel/lift-legacy.js +84 -0
- package/dist/lean-kernel/lift-names.d.ts +22 -0
- package/dist/lean-kernel/lift-names.js +36 -0
- package/dist/lean-kernel/lift-simulation/index.d.ts +29 -0
- package/dist/lean-kernel/lift-simulation/index.js +352 -0
- package/dist/lean-kernel/lift-simulation/shape.d.ts +41 -0
- package/dist/lean-kernel/lift-simulation/shape.js +173 -0
- package/dist/lean-kernel/lift-special/index.d.ts +36 -0
- package/dist/lean-kernel/lift-special/index.js +241 -0
- package/dist/lean-kernel/lift-special/structural.d.ts +25 -0
- package/dist/lean-kernel/lift-special/structural.js +126 -0
- package/dist/lean-kernel/lift-typed/index.d.ts +35 -0
- package/dist/lean-kernel/lift-typed/index.js +256 -0
- package/dist/lean-kernel/lift-typed/roles.d.ts +17 -0
- package/dist/lean-kernel/lift-typed/roles.js +170 -0
- package/dist/lean-kernel/lift-typed/shape.d.ts +1 -0
- package/dist/lean-kernel/lift-typed/shape.js +12 -0
- package/dist/lean-kernel/lift.d.ts +30 -0
- package/dist/lean-kernel/lift.js +97 -0
- package/package.json +8 -2
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { sumCovers, sumMachine, sumParts } from "../../kernel/kernel.js";
|
|
2
|
+
import { leanProject, retainedSMachineToLean } from "../emit.js";
|
|
3
|
+
import { leanLibrary } from "../library.js";
|
|
4
|
+
import { leanTerms } from "../lean-terms.js";
|
|
5
|
+
import { sourceLeanId, sourceStructure } from "../lift/source.js";
|
|
6
|
+
import { leanSource } from "../lift/project.js";
|
|
7
|
+
import { planRadixSimulation, UnsupportedRadixSimulation } from "./shape.js";
|
|
8
|
+
export { planRadixSimulation, UnsupportedRadixSimulation } from "./shape.js";
|
|
9
|
+
const list = (xs) => '[' + xs.join(', ') + ']';
|
|
10
|
+
const same = (a, b) => sourceStructure(a) === sourceStructure(b);
|
|
11
|
+
const empty = { op: 'and', xs: [] };
|
|
12
|
+
const normalize = (m) => ({ ...m, name: '', relations: undefined, maps: m.maps ?? {}, step: { ...m.step, maps: m.step.maps ?? {}, state: m.step.state ?? {}, flags: m.step.flags ?? {} } });
|
|
13
|
+
function walk(x, f) {
|
|
14
|
+
if (Array.isArray(x)) {
|
|
15
|
+
x.forEach(y => walk(y, f));
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (!x || typeof x !== 'object')
|
|
19
|
+
return;
|
|
20
|
+
const o = x;
|
|
21
|
+
f(o);
|
|
22
|
+
Object.values(o).forEach(y => walk(y, f));
|
|
23
|
+
}
|
|
24
|
+
function key(p, map, e) {
|
|
25
|
+
const layout = p.layouts.find(l => l.map === map);
|
|
26
|
+
if (!layout)
|
|
27
|
+
return rewrite(p, e);
|
|
28
|
+
const parts = (x, n) => {
|
|
29
|
+
if (n === 1)
|
|
30
|
+
return [rewrite(p, x)];
|
|
31
|
+
if (x.op === 'tup')
|
|
32
|
+
return [rewrite(p, x.a), ...parts(x.b, n - 1)];
|
|
33
|
+
if (x.op === 'add' && x.a.op === 'mul' && x.a.k === p.radix)
|
|
34
|
+
return [...parts(x.a.a, n - 1), rewrite(p, x.b)];
|
|
35
|
+
if (n === 3 && x.op === 'add' && x.a.op === 'add' && x.a.a.op === 'mul' && x.a.a.k === p.radix * p.radix && x.a.b.op === 'mul' && x.a.b.k === p.radix)
|
|
36
|
+
return [x.a.a.a, x.a.b.a, x.b].map(y => rewrite(p, y));
|
|
37
|
+
if (x.op === 'const') {
|
|
38
|
+
let v = x.value;
|
|
39
|
+
const ds = [];
|
|
40
|
+
for (let i = 0; i < n - 1; i++) {
|
|
41
|
+
ds.unshift({ op: 'const', value: v % p.radix });
|
|
42
|
+
v = Math.floor(v / p.radix);
|
|
43
|
+
}
|
|
44
|
+
ds.unshift({ op: 'const', value: v });
|
|
45
|
+
return ds;
|
|
46
|
+
}
|
|
47
|
+
throw new UnsupportedRadixSimulation('unsupported packed address syntax in ' + map);
|
|
48
|
+
};
|
|
49
|
+
const tuple = (xs) => xs.length === 1 ? xs[0] : { op: 'tup', a: xs[0], b: tuple(xs.slice(1)) };
|
|
50
|
+
return tuple(parts(e, layout.arity));
|
|
51
|
+
}
|
|
52
|
+
function rewrite(p, x) {
|
|
53
|
+
if (Array.isArray(x))
|
|
54
|
+
return x.map(y => rewrite(p, y));
|
|
55
|
+
if (!x || typeof x !== 'object')
|
|
56
|
+
return x;
|
|
57
|
+
const o = x;
|
|
58
|
+
if ((o.op === '<' || o.op === '<=') && o.b?.op === 'const' && o.b.value === p.radix)
|
|
59
|
+
return empty;
|
|
60
|
+
if (o.op === 'get')
|
|
61
|
+
return { ...o, key: key(p, o.map, o.key) };
|
|
62
|
+
return Object.fromEntries(Object.entries(o).map(([k, v]) => [k, rewrite(p, v)]));
|
|
63
|
+
}
|
|
64
|
+
function targetBase(p) {
|
|
65
|
+
const m = p.sumMachine, base = { ...m, sums: undefined, state: Object.fromEntries(Object.entries(m.state).filter(([n]) => !Object.hasOwn(m.sums ?? {}, n))) };
|
|
66
|
+
const t = rewrite(p, base);
|
|
67
|
+
t.step = { ...t.step, maps: Object.fromEntries(Object.entries(base.step.maps ?? {}).map(([name, w]) => [name, 'each' in w ? { ...w, value: rewrite(p, w.value) } : { ...w, key: key(p, name, w.key), value: rewrite(p, w.value) }])) };
|
|
68
|
+
return t;
|
|
69
|
+
}
|
|
70
|
+
function atoms(x) {
|
|
71
|
+
const out = [];
|
|
72
|
+
walk(x, o => {
|
|
73
|
+
if (o.op === 'flag') {
|
|
74
|
+
out.push(o);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (!['=', '<', '<='].includes(String(o.op)))
|
|
78
|
+
return;
|
|
79
|
+
const c = o;
|
|
80
|
+
// Constant tests reduce directly. Boolean cell tests are discharged by
|
|
81
|
+
// the checked 0-or-1 cases; splitting them again is exponential noise.
|
|
82
|
+
if (c.a.op === 'const' && c.b.op === 'const')
|
|
83
|
+
return;
|
|
84
|
+
if (c.a.op === 'get' && c.b.op === 'const' && (c.b.value === 0 || c.b.value === 1))
|
|
85
|
+
return;
|
|
86
|
+
if (c.b.op === 'get' && c.a.op === 'const' && (c.a.value === 0 || c.a.value === 1))
|
|
87
|
+
return;
|
|
88
|
+
out.push(c);
|
|
89
|
+
});
|
|
90
|
+
return out.filter((c, i) => out.findIndex(d => same(c, d)) === i);
|
|
91
|
+
}
|
|
92
|
+
function reads(x) { const out = []; walk(x, o => { if (o.op === 'get')
|
|
93
|
+
out.push(o); }); return out.filter((c, i) => out.findIndex(d => same(c, d)) === i); }
|
|
94
|
+
/** The caller validates the complete capsule graph and restores its terms
|
|
95
|
+
* exactly once before calling. This function never reads a capsule, restores
|
|
96
|
+
* terms, invokes Lean, searches, or consumes old generated proof files. */
|
|
97
|
+
export function tryRadixSimulation({ id, bundle, providedSourceAST: source, options }) {
|
|
98
|
+
if (id !== sourceLeanId(source.id))
|
|
99
|
+
throw Error('inconsistent full Lean prefix');
|
|
100
|
+
for (const n of [options.maxOutputBytes, options.maxFiles, options.heartbeats, options.recursionDepth])
|
|
101
|
+
if (!Number.isSafeInteger(n) || n < 1)
|
|
102
|
+
throw Error('finite positive generator limits required');
|
|
103
|
+
const p = planRadixSimulation(bundle, source);
|
|
104
|
+
if (!p)
|
|
105
|
+
return null;
|
|
106
|
+
for (const layout of p.layouts)
|
|
107
|
+
if (layout.arity !== 2)
|
|
108
|
+
throw new UnsupportedRadixSimulation('source invariant bridge currently supports binary tuple layouts only');
|
|
109
|
+
for (const m of [source.machine, p.sumMachine])
|
|
110
|
+
if (m.inputMaps?.length || Object.values(m.step.flags ?? {}).some(c => c.op === 'all'))
|
|
111
|
+
throw new UnsupportedRadixSimulation('source/carried or pre-existing quantified flags need a separate simulation');
|
|
112
|
+
for (const layout of p.layouts)
|
|
113
|
+
if (p.sumMachine.step.maps?.[layout.map] && 'each' in p.sumMachine.step.maps[layout.map])
|
|
114
|
+
throw new UnsupportedRadixSimulation('typed whole-map update needs a projection-binder bridge');
|
|
115
|
+
const lowered = sumMachine(p.sumMachine).machine;
|
|
116
|
+
const producerMachine = Object.keys(p.producer.machine.sums ?? {}).length ? sumMachine(p.producer.machine).machine : p.producer.machine;
|
|
117
|
+
if (!same(normalize(lowered), normalize(producerMachine)))
|
|
118
|
+
throw new UnsupportedRadixSimulation('SUM declarations do not regenerate the retained producer machine exactly');
|
|
119
|
+
const target = targetBase(p), sums = Object.entries(p.sumMachine.sums ?? {}), covers = sumCovers(p.sumMachine);
|
|
120
|
+
for (const [n, d] of sums)
|
|
121
|
+
if (d.term.op !== 'get' || d.term.key.op !== 'var' || d.term.key.name !== d.key)
|
|
122
|
+
throw new UnsupportedRadixSimulation('semantic cover emitter currently requires a whole-address cell integrand: ' + n);
|
|
123
|
+
const free = new Set([...source.machine.params, ...source.machine.inputs, ...Object.keys(source.machine.state), ...Object.keys(source.machine.step.flags ?? {}).map(n => '?' + n), ...Object.keys(target.step.flags ?? {}).map(n => '?' + n)]);
|
|
124
|
+
walk([source, p.sumMachine], o => { if (o.op === 'var')
|
|
125
|
+
free.add(o.name); if (o.op === 'flag')
|
|
126
|
+
free.add('?' + String(o.name)); });
|
|
127
|
+
source.laws.forEach(l => { if (l.forall)
|
|
128
|
+
free.add(l.forall); l.keys?.forEach(k => free.add(k)); });
|
|
129
|
+
for (const w of Object.values(source.machine.step.maps ?? {}))
|
|
130
|
+
if ('each' in w)
|
|
131
|
+
free.add(w.each);
|
|
132
|
+
for (const [n, d] of sums) {
|
|
133
|
+
const s = sumParts(n);
|
|
134
|
+
[n, d.key, '?' + s.flag, 'w?' + s.flag, s.x].forEach(v => free.add(v));
|
|
135
|
+
}
|
|
136
|
+
const raw = id + '_retained', defs = id + '_Defs';
|
|
137
|
+
let extra = '', renderC, renderE, ix, mx;
|
|
138
|
+
const emitted = retainedSMachineToLean(raw, producerMachine, p.producer.laws, p.producer.proof, { free: [...free], after: (v, m, lit, c) => {
|
|
139
|
+
ix = v;
|
|
140
|
+
mx = m;
|
|
141
|
+
renderC = x => `(${c(x)})`;
|
|
142
|
+
const vars = [], maps = [];
|
|
143
|
+
for (const name of free)
|
|
144
|
+
vars[v(name)] = name;
|
|
145
|
+
for (const name of Object.keys(producerMachine.maps ?? {}))
|
|
146
|
+
maps[m(name)] = name;
|
|
147
|
+
const terms = leanTerms(vars, maps, id);
|
|
148
|
+
renderE = x => `(${terms.e(x)})`;
|
|
149
|
+
const ds = sums.map(([n, d]) => { const sp = sumParts(n), cells = covers[n].map(e => { const map = d.term.map; return key(p, map, e); }); return `⟨${v(n)}, ${v(d.key)}, ${renderE(d.term)}, ${list(cells.map(renderE))}, ${v('?' + sp.flag)}, ${v('w?' + sp.flag)}, ${v(sp.x)}⟩`; });
|
|
150
|
+
extra = `def ${id}_source : SMachine := ${lit(source.machine)}\ndef ${id}_target_data : SumMachine := ⟨${lit(target)}, ${list(ds)}⟩\n`;
|
|
151
|
+
extra += source.laws.map((l, j) => `def ${id}_source_law${j} : MLaw := ⟨${c(l.holds)}, ${l.forall ? 'some ' + v(l.forall) : 'none'}⟩\ndef ${id}_source_keys${j} : List Nat := ${list((l.keys ?? []).map(v))}`).join('\n') + '\n';
|
|
152
|
+
const oldbase = { ...p.sumMachine, sums: undefined, state: Object.fromEntries(Object.entries(p.sumMachine.state).filter(([n]) => !Object.hasOwn(p.sumMachine.sums ?? {}, n))) };
|
|
153
|
+
extra += `def ${id}_old_sums : SumMachine := ⟨${lit(oldbase)}, ${list(sums.map(([n, d]) => { const sp = sumParts(n); return `⟨${v(n)}, ${v(d.key)}, ${renderE(d.term)}, ${list(covers[n].map(renderE))}, ${v('?' + sp.flag)}, ${v('w?' + sp.flag)}, ${v(sp.x)}⟩`; }))}⟩\n`;
|
|
154
|
+
return '';
|
|
155
|
+
} });
|
|
156
|
+
const cut = emitted.indexOf(`\ntheorem ${raw}_check :`);
|
|
157
|
+
if (cut < 0)
|
|
158
|
+
throw Error('unsupported current retained emission layout');
|
|
159
|
+
const retained = emitted.slice(0, cut);
|
|
160
|
+
const varrefs = [...(retained + extra).matchAll(/\.var (\d+)/g)].map(m => Number(m[1]));
|
|
161
|
+
const freshBase = Math.max(0, ...varrefs, ...[...free].map(ix)) + 1;
|
|
162
|
+
const layoutLit = list(p.layouts.map(l => `(${mx(l.map)}, ${l.arity})`));
|
|
163
|
+
const sumFlags = list(sums.flatMap(([n, d]) => { const l = p.layouts.find(l => l.map === d.term.map); return l ? [`(${ix('?' + sumParts(n).flag)}, ${l.arity})`] : []; }));
|
|
164
|
+
const prefix = (imports) => imports.map(i => 'import ' + i).join('\n') + `\nopen Kern\nset_option maxRecDepth ${options.recursionDepth}\nset_option maxHeartbeats ${options.heartbeats}\n`;
|
|
165
|
+
const project = Object.assign(leanProject('', { name: 'BapaProof' }), leanLibrary);
|
|
166
|
+
for (const n of ['RadixKeySyntax', 'RadixBinderExpansion', 'RadixCertificateTable', 'RadixTupleSyntax', 'CertificateBoundErasure', 'CertificateBooleanCleanup', 'RadixEqualityTree', 'RadixCertificateTransport', 'FiniteSimulation', 'SourceInclusion'])
|
|
167
|
+
project[n + '.lean'] = leanSource(n);
|
|
168
|
+
for (const n of ['RadixSumTransport', 'InvariantSimulation', 'SemanticSums'])
|
|
169
|
+
project[n + '.lean'] = leanSource(n);
|
|
170
|
+
const requiredTheorems = [], printed = (n) => { requiredTheorems.push(n); return '\n#print axioms ' + n + '\n'; };
|
|
171
|
+
project[defs + '.lean'] = prefix(['Lean', 'Sums', 'RadixSumTransport']) + retained + '\n' + extra + `
|
|
172
|
+
def ${id}_plan : Bapa.RadixSumTransport.Plan := ⟨${p.radix}, ${layoutLit}, ${freshBase}, ${sumFlags}⟩
|
|
173
|
+
def ${id}_outcome := Bapa.RadixSumTransport.translate ${id}_plan ${id}_old_sums ${raw}_proof
|
|
174
|
+
def ${id}_created : Bool := match ${id}_outcome with | .ok _ => true | .error _ => false
|
|
175
|
+
def ${id}_derived_proof : List SEntry := match ${id}_outcome with | .ok p => p.2 | .error _ => []
|
|
176
|
+
-- Materialize the closed candidate, rather than exposing the implementation of
|
|
177
|
+
-- its translator in the checked family's type. Reduction is only an untrusted
|
|
178
|
+
-- term producer: the kernel checks both the literal and proof_eq below.
|
|
179
|
+
open Lean Meta Elab Term in
|
|
180
|
+
elab "${id}_literal% " t:term : term => do
|
|
181
|
+
let value ← instantiateMVars (← elabTerm t none)
|
|
182
|
+
withTransparency .all <| Meta.reduce value
|
|
183
|
+
|
|
184
|
+
def ${id}_proof : List SEntry := ${id}_literal% ${id}_derived_proof
|
|
185
|
+
`;
|
|
186
|
+
// A checked family is the complete checker equality, not its semantic
|
|
187
|
+
// consequence. Keep that consequence independently required as well.
|
|
188
|
+
const familyTheorem = id + '_check', semanticLawsTheorem = id + '_semantic_laws';
|
|
189
|
+
project[id + '_Family.lean'] = prefix([defs]) + `theorem ${id}_translation_succeeded : ${id}_created = true := by decide +kernel
|
|
190
|
+
theorem ${id}_translation_target : (Bapa.RadixSumTransport.target ${id}_plan ${id}_old_sums) = .ok ${id}_target_data := by rfl
|
|
191
|
+
theorem ${id}_proof_eq : ${id}_proof = ${id}_derived_proof := by with_unfolding_all rfl
|
|
192
|
+
theorem ${id}_family_size : ${id}_proof.length = ${p.producer.laws.length} := by decide +kernel
|
|
193
|
+
theorem ${id}_check : checkSMachine ${id}_target_data.plain ${id}_proof = true := by decide +kernel
|
|
194
|
+
theorem ${semanticLawsTheorem} : ∀ ρ M, SReach ${id}_target_data.plain ρ M → ∀ e ∈ ${id}_proof, e.Holds ρ M := smachine_sound _ _ ${id}_check
|
|
195
|
+
` + [id + '_translation_succeeded', id + '_translation_target', id + '_proof_eq', id + '_family_size', familyTheorem, semanticLawsTheorem].map(printed).join('');
|
|
196
|
+
// Explicit law snapshots avoid normalizing complete certificate trees in
|
|
197
|
+
// every semantic bridge. Equality remains a separate kernel obligation.
|
|
198
|
+
let shapes = '', fresh = freshBase;
|
|
199
|
+
const expanded = new Map();
|
|
200
|
+
for (let i = 0; i < p.producer.laws.length; i++) {
|
|
201
|
+
const l = p.producer.laws[i], bound = p.booleanEntries.find(b => b.index === i), layout = bound && p.layouts.find(q => q.map === bound.map);
|
|
202
|
+
if (layout && l.forall) {
|
|
203
|
+
expanded.set(i, { first: ix(l.forall), rest: [fresh++] });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
for (const b of p.booleanEntries) {
|
|
207
|
+
const l = p.producer.laws[b.index], e = expanded.get(b.index), keyE = e ? `(.tup (.var ${e.first}) (.var ${e.rest[0]}))` : `(.var ${ix(l.forall)})`;
|
|
208
|
+
shapes += `def ${id}_bound_entry${b.index} : SEntry := ${id}_proof[${b.index}]'(by rw [${id}_family_size]; decide +kernel)
|
|
209
|
+
theorem ${id}_bound_shape${b.index} : ${id}_bound_entry${b.index}.law = ⟨.le (.get ${mx(b.map)} ${keyE}) (.const 1), some ${ix(l.forall)}⟩ ∧ ${id}_bound_entry${b.index}.keys2 = ${list(e?.rest ?? [])} := by constructor <;> rfl
|
|
210
|
+
`;
|
|
211
|
+
shapes += `theorem ${id}_family_bound${b.index} (ρ M) (hl : ∀ e ∈ ${id}_proof, e.Holds ρ M) (k : Nat) : M ${mx(b.map)} k ≤ 1 := by
|
|
212
|
+
have h := hl ${id}_bound_entry${b.index} (List.getElem_mem (by rw [${id}_family_size]; decide +kernel))
|
|
213
|
+
change holdsOver ${id}_bound_entry${b.index}.law M ${id}_bound_entry${b.index}.keys2 ρ at h
|
|
214
|
+
rw [${id}_bound_shape${b.index}.1, ${id}_bound_shape${b.index}.2] at h
|
|
215
|
+
have hk := ${e ? 'h (cun k).2 (cun k).1' : 'h k'}
|
|
216
|
+
simpa [evalC, evalE, upd, cpair_cun] using hk
|
|
217
|
+
` + printed(id + '_bound_shape' + b.index) + printed(id + '_family_bound' + b.index);
|
|
218
|
+
}
|
|
219
|
+
project[id + '_Shapes.lean'] = prefix([id + '_Family']) + shapes;
|
|
220
|
+
const simplify = `${id}_target_data, ${id}_source, everyMaps, writeMaps, lookup, evalC, evalE, upd, withInputs, withCarried, decideFlags, flagSub, applyS, assoc, decideQ`;
|
|
221
|
+
const atomCases = (x, env, start = 0) => atoms(x).map((a, j) => ` all_goals by_cases ha${start + j} : evalC ${env} M ${renderC(a)} = true`).join('\n');
|
|
222
|
+
let semantic = `theorem ${id}_sum_ok : sumOk ${id}_target_data = true := by decide +kernel
|
|
223
|
+
theorem ${id}_sum_ghosts : sghostOk ${id}_target_data.ghosts = true := by decide +kernel
|
|
224
|
+
theorem ${id}_covers : Bapa.SemanticSums.Preserves ${id}_target_data ${id}_proof := by
|
|
225
|
+
intro ρ M hl ι κ ha d hd k hk
|
|
226
|
+
let D := (sView ${id}_target_data.plain ρ M ι κ).1
|
|
227
|
+
clear ha
|
|
228
|
+
simp only [${id}_target_data, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false] at hd
|
|
229
|
+
rcases hd with ${sums.map(() => 'rfl').join(' | ')}
|
|
230
|
+
`;
|
|
231
|
+
sums.forEach(([name, d]) => {
|
|
232
|
+
const mp = d.term.map, w = target.step.maps?.[mp], env = w && 'each' in w ? `(upd D ${ix(w.each)} k)` : 'D';
|
|
233
|
+
semantic += ` · change everyMaps ${id}_target_data.s D M ${mx(mp)} k = M ${mx(mp)} k
|
|
234
|
+
change k ∉ ${list(covers[name].map(e => `evalE D M ${renderE(key(p, mp, e))}`))} at hk
|
|
235
|
+
`;
|
|
236
|
+
const b = p.booleanEntries.find(b => b.map === mp);
|
|
237
|
+
if (b)
|
|
238
|
+
semantic += ` have hb := ${id}_family_bound${b.index} ρ M hl k
|
|
239
|
+
have hz : M ${mx(mp)} k = 0 ∨ M ${mx(mp)} k = 1 := by omega
|
|
240
|
+
rcases hz with hz | hz
|
|
241
|
+
`;
|
|
242
|
+
semantic += atomCases(w, env).replace(/^ /gm, ' ') + '\n' + ` all_goals simp_all [${simplify}]
|
|
243
|
+
`;
|
|
244
|
+
});
|
|
245
|
+
semantic += `theorem ${id}_exact_sums : ∀ ρ M, SReach ${id}_target_data.plain ρ M → ∀ d ∈ ${id}_target_data.sums, IsSum (gAt d.g M) (ρ d.v) :=
|
|
246
|
+
Bapa.SemanticSums.sum_holds _ ${id}_check ${id}_sum_ok ${id}_covers
|
|
247
|
+
theorem ${id}_own_admission : ∀ ρ M, SReach ${id}_target_data.plain ρ M → ∀ ι κ,
|
|
248
|
+
evalC (sView ${id}_target_data.plain ρ M ι κ).1 (sView ${id}_target_data.plain ρ M ι κ).2 ${id}_target_data.plain.f.m.assume =
|
|
249
|
+
evalC (sView ${id}_target_data.plain ρ M ι κ).1 (sView ${id}_target_data.plain ρ M ι κ).2 ${id}_target_data.s.f.m.assume :=
|
|
250
|
+
Bapa.SemanticSums.sum_allowed _ ${id}_check ${id}_sum_ok ${id}_covers
|
|
251
|
+
theorem ${id}_integrands : ${id}_target_data.sums.map (·.g) = ${id}_old_sums.sums.map (·.g) := by rfl
|
|
252
|
+
`;
|
|
253
|
+
// Project only the ghost-independent kind entries; the inferred SUM law
|
|
254
|
+
// itself intentionally mentions sum variables and cannot be projected.
|
|
255
|
+
for (const b of p.booleanEntries) {
|
|
256
|
+
const e = expanded.get(b.index);
|
|
257
|
+
semantic += `theorem ${id}_base_bound${b.index} (ρ M) (hr : SReach ${id}_target_data.s ρ M) (k : Nat) : M ${mx(b.map)} k ≤ 1 := by
|
|
258
|
+
have h := Bapa.SemanticSums.sum_project_laws _ ${id}_sum_ghosts ${id}_proof ${id}_check ${id}_sum_ok ${id}_covers ρ M hr ${id}_bound_entry${b.index} (List.getElem_mem (by rw [${id}_family_size]; decide +kernel)) (by decide +kernel)
|
|
259
|
+
change holdsOver ${id}_bound_entry${b.index}.law M ${id}_bound_entry${b.index}.keys2 ρ at h
|
|
260
|
+
rw [${id}_bound_shape${b.index}.1, ${id}_bound_shape${b.index}.2] at h
|
|
261
|
+
have hk := ${e ? 'h (cun k).2 (cun k).1' : 'h k'}
|
|
262
|
+
simpa [evalC, evalE, upd, cpair_cun] using hk
|
|
263
|
+
`;
|
|
264
|
+
}
|
|
265
|
+
semantic += [id + '_sum_ok', id + '_sum_ghosts', id + '_covers', id + '_exact_sums', id + '_own_admission', id + '_integrands', ...p.booleanEntries.map(b => id + '_base_bound' + b.index)].map(printed).join('');
|
|
266
|
+
project[id + '_Sums.lean'] = prefix([id + '_Shapes', 'SemanticSums']) + semantic;
|
|
267
|
+
// Source templates are syntax-specialized equality proofs, with all cell
|
|
268
|
+
// normalizations guarded by bounds obtained from the target checked family.
|
|
269
|
+
const inv = p.booleanEntries.map(b => `(∀ k, x.2 ${mx(b.map)} k ≤ 1)`).join(' ∧ '), invAt = (b) => 'h' + '.2'.repeat(b) + (b === p.booleanEntries.length - 1 ? '' : '.1');
|
|
270
|
+
let bridge = `def ${id}_Inv (x : Bapa.FiniteSimulation.KState) : Prop := ${inv}
|
|
271
|
+
theorem ${id}_invariant (ρ M) (hr : SReach ${id}_target_data.s ρ M) : ${id}_Inv (ρ,M) := by
|
|
272
|
+
${p.booleanEntries.length > 1 ? 'refine ⟨' + p.booleanEntries.map(() => '?_').join(', ') + '⟩' : ''}
|
|
273
|
+
${p.booleanEntries.map(b => ` ${p.booleanEntries.length > 1 ? '· ' : ''}exact ${id}_base_bound${b.index} ρ M hr`).join('\n')}
|
|
274
|
+
`;
|
|
275
|
+
const fromInv = (x, env) => {
|
|
276
|
+
const rs = reads(x).flatMap(r => { const bi = p.booleanEntries.findIndex(b => b.map === r.map); return bi < 0 ? [] : [{ r, bi }]; });
|
|
277
|
+
return rs.map(({ r, bi }, j) => ` have hb${j} := ${invAt(bi)} (evalE ${env} M ${renderE(r.key)})\n have hz${j} : M ${mx(r.map)} (evalE ${env} M ${renderE(r.key)}) = 0 ∨ M ${mx(r.map)} (evalE ${env} M ${renderE(r.key)}) = 1 := by omega`).join('\n') + '\n' + rs.map((_, j) => ` all_goals rcases hz${j} with hz${j} | hz${j}`).join('\n');
|
|
278
|
+
};
|
|
279
|
+
const mapNames = Object.keys(target.maps ?? {});
|
|
280
|
+
const mapCases = (i, indent) => {
|
|
281
|
+
const name = mapNames[i];
|
|
282
|
+
if (name === undefined)
|
|
283
|
+
return indent + `simp_all [${simplify}]`;
|
|
284
|
+
const w = source.machine.step.maps?.[name], env = w && 'each' in w ? `(upd D ${ix(w.each)} k)` : 'D';
|
|
285
|
+
const branch = [fromInv(w, env), atomCases(w, env), ` all_goals simp_all [${simplify}]`].join('\n').replace(/^ /gm, indent + ' ');
|
|
286
|
+
return indent + `by_cases hm${i} : ${mx(name)} = mp\n` + indent + `· subst mp\n` + branch + '\n' + indent + '·\n' + mapCases(i + 1, indent + ' ');
|
|
287
|
+
};
|
|
288
|
+
const viewFlags = [...new Set([...Object.keys(source.machine.step.flags ?? {}), ...Object.keys(target.step.flags ?? {})])].map(n => ix('?' + n));
|
|
289
|
+
const viewCases = (i, indent) => i === viewFlags.length ? indent + `simp_all [sView, ${simplify}]` :
|
|
290
|
+
indent + `by_cases hv${i} : ${viewFlags[i]} = v\n` + indent + `· subst v\n` + indent + ` simp_all [sView, ${simplify}]\n` + indent + `·\n` + viewCases(i + 1, indent + ' ');
|
|
291
|
+
const inputEnv = `(withInputs ${id}_source.f.m.inputs ρ ι)`;
|
|
292
|
+
bridge += `theorem ${id}_view (ρ M ι κ) (h : ${id}_Inv (ρ,M)) : sView ${id}_source ρ M ι κ = sView ${id}_target_data.s ρ M ι κ := by
|
|
293
|
+
change ${inv.replaceAll('x.2', 'M')} at h
|
|
294
|
+
${fromInv(source.machine.step.flags, inputEnv)}
|
|
295
|
+
all_goals apply Prod.ext
|
|
296
|
+
all_goals first | rfl | (
|
|
297
|
+
funext v
|
|
298
|
+
${viewCases(0, ' ')}
|
|
299
|
+
)
|
|
300
|
+
theorem ${id}_maps (D M) (h : ${id}_Inv (D,M)) : everyMaps ${id}_source D M = everyMaps ${id}_target_data.s D M := by
|
|
301
|
+
change ${inv.replaceAll('x.2', 'M')} at h
|
|
302
|
+
funext mp k
|
|
303
|
+
${mapCases(0, ' ')}
|
|
304
|
+
theorem ${id}_next (ρ M ι κ) (h : ${id}_Inv (ρ,M)) : sNext ${id}_source ρ M ι κ = sNext ${id}_target_data.s ρ M ι κ := by
|
|
305
|
+
unfold sNext
|
|
306
|
+
rw [${id}_view ρ M ι κ h]
|
|
307
|
+
apply Prod.ext
|
|
308
|
+
· rfl
|
|
309
|
+
· apply ${id}_maps
|
|
310
|
+
exact h
|
|
311
|
+
`;
|
|
312
|
+
bridge += `theorem ${id}_restricted : Bapa.InvariantSimulation.RestrictedInclusion ${id}_source ${id}_target_data.s ${id}_Inv where
|
|
313
|
+
initial := by
|
|
314
|
+
rintro x ⟨ρ,M,hm,hp,hf,hpf,rfl⟩
|
|
315
|
+
refine ⟨ρ,M,?_,?_,?_,?_,?_⟩
|
|
316
|
+
· simpa [StartMaps, ${id}_source, ${id}_target_data, and_comm] using hm
|
|
317
|
+
· simpa [${id}_source, ${id}_target_data, evalC, evalE] using hp
|
|
318
|
+
· simpa [${id}_source, ${id}_target_data] using hf
|
|
319
|
+
· simpa [SMachine.PFacts, ${id}_source, ${id}_target_data] using hpf
|
|
320
|
+
· rfl
|
|
321
|
+
admission := by
|
|
322
|
+
intro ρ M ι κ h ha
|
|
323
|
+
rw [${id}_view ρ M ι κ h] at ha
|
|
324
|
+
simp_all [${id}_source, ${id}_target_data, evalC, evalE]
|
|
325
|
+
next := by intro ρ M ι κ h _; exact ${id}_next ρ M ι κ h
|
|
326
|
+
theorem ${id}_simulation : Bapa.FiniteSimulation.SSimulation ${id}_source ${id}_target_data.s (Bapa.InvariantSimulation.Relation ${id}_Inv) := ${id}_restricted.simulation ${id}_invariant
|
|
327
|
+
`;
|
|
328
|
+
const sourceTheorems = source.laws.map((_, j) => id + '_source_law' + j + '_holds');
|
|
329
|
+
source.laws.forEach((l, j) => {
|
|
330
|
+
const n = p.publicLawIndices[j], strong = id + '_public_entry' + j;
|
|
331
|
+
bridge += `def ${strong} : SEntry := ${id}_proof[${n}]'(by rw [${id}_family_size]; decide +kernel)
|
|
332
|
+
theorem ${sourceTheorems[j]} (ρ M) (hr : SReach ${id}_source ρ M) : holdsOver ${id}_source_law${j} M ${id}_source_keys${j} ρ := by
|
|
333
|
+
have ht := ${id}_restricted.sreach ${id}_invariant hr
|
|
334
|
+
have h := Bapa.SemanticSums.sum_project_laws _ ${id}_sum_ghosts ${id}_proof ${id}_check ${id}_sum_ok ${id}_covers ρ M ht ${strong} (List.getElem_mem (by rw [${id}_family_size]; decide +kernel)) (by decide +kernel)
|
|
335
|
+
change holdsOver ${strong}.law M ${strong}.keys2 ρ at h
|
|
336
|
+
have shape : ${strong}.law = ⟨${renderC(rewrite(p, p.producer.laws[n].holds))}, ${l.forall ? 'some ' + ix(l.forall) : 'none'}⟩ ∧ ${strong}.keys2 = ${list((l.keys ?? []).map(ix))} := by constructor <;> rfl
|
|
337
|
+
rw [shape.1, shape.2] at h
|
|
338
|
+
simp only [holdsOver, MLaw.Holds, ${id}_source_law${j}, ${id}_source_keys${j}] at h ⊢
|
|
339
|
+
${[...(l.keys ?? []), ...(l.forall ? [l.forall] : [])].map((_, i) => ` intro k${i}`).join('\n')}
|
|
340
|
+
have hp := h ${[...(l.keys ?? []), ...(l.forall ? [l.forall] : [])].map((_, i) => 'k' + i).join(' ')}
|
|
341
|
+
simp [evalC, evalE, upd] at hp ⊢
|
|
342
|
+
omega
|
|
343
|
+
`;
|
|
344
|
+
});
|
|
345
|
+
bridge += [id + '_invariant', id + '_view', id + '_maps', id + '_next', id + '_restricted', id + '_simulation', ...sourceTheorems].map(printed).join('');
|
|
346
|
+
project['BapaProof.lean'] = prefix([id + '_Sums', 'InvariantSimulation']) + bridge;
|
|
347
|
+
const modules = Object.keys(project).filter(n => n.endsWith('.lean') && n !== 'lakefile.lean').map(n => n.slice(0, -5));
|
|
348
|
+
project['lakefile.lean'] = 'import Lake\nopen Lake DSL\npackage radixsimulation\n@[default_target]\nlean_lib RadixSimulation where\n roots := #[' + modules.map(n => '`' + n).join(', ') + ']\n';
|
|
349
|
+
if (Object.keys(project).length > options.maxFiles || Object.values(project).reduce((n, s) => n + Buffer.byteLength(s), 0) > options.maxOutputBytes)
|
|
350
|
+
throw Error('complete radix simulation project exceeds output budget');
|
|
351
|
+
return { project, familyTheorem, sourceTheorems, publicLawIndices: p.publicLawIndices, requiredTheorems, kind: 'radix-simulation', status: 'EMITTED_NOT_CHECKED', parts: { familySize: p.producer.laws.length, primaryObligations: 2 * p.producer.laws.length }, plan: p };
|
|
352
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Law, Machine } from '../../core/machine.js';
|
|
2
|
+
import type { ProofOutputNode } from '../../core/proof-output.js';
|
|
3
|
+
import type { GenericLiftSource } from '../lift/source.js';
|
|
4
|
+
/** Structural ABI shared by native and historical capsules. No schema or
|
|
5
|
+
* protocol discriminant is used to choose this transport. */
|
|
6
|
+
export type RadixSimulationBundle = {
|
|
7
|
+
original: {
|
|
8
|
+
machine: Machine;
|
|
9
|
+
laws: Law[];
|
|
10
|
+
};
|
|
11
|
+
verdict: {
|
|
12
|
+
proven: boolean;
|
|
13
|
+
checked: boolean;
|
|
14
|
+
};
|
|
15
|
+
proof?: ProofOutputNode;
|
|
16
|
+
final?: unknown;
|
|
17
|
+
};
|
|
18
|
+
export type RadixLayout = {
|
|
19
|
+
map: string;
|
|
20
|
+
arity: number;
|
|
21
|
+
};
|
|
22
|
+
export type RadixShapePlan = {
|
|
23
|
+
radix: number;
|
|
24
|
+
layouts: RadixLayout[];
|
|
25
|
+
producer: Extract<ProofOutputNode, {
|
|
26
|
+
kind: 'usual';
|
|
27
|
+
}>;
|
|
28
|
+
sumMachine: Machine;
|
|
29
|
+
publicLawIndices: number[];
|
|
30
|
+
booleanEntries: {
|
|
31
|
+
map: string;
|
|
32
|
+
index: number;
|
|
33
|
+
}[];
|
|
34
|
+
};
|
|
35
|
+
export declare class UnsupportedRadixSimulation extends Error {
|
|
36
|
+
constructor(message: string);
|
|
37
|
+
}
|
|
38
|
+
/** Data-only shape derivation. A noncandidate returns null. Once packed-key
|
|
39
|
+
* evidence exists, ambiguity or missing proof data is a hard failure, never a
|
|
40
|
+
* fallback to another route or to a fixed-bound theorem. */
|
|
41
|
+
export declare function planRadixSimulation(bundle: RadixSimulationBundle, source: GenericLiftSource): RadixShapePlan | null;
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { sourceStructure } from "../lift/source.js";
|
|
2
|
+
export class UnsupportedRadixSimulation extends Error {
|
|
3
|
+
constructor(message) { super(message); this.name = 'UnsupportedRadixSimulation'; }
|
|
4
|
+
}
|
|
5
|
+
const eq = (a, b) => sourceStructure(a) === sourceStructure(b);
|
|
6
|
+
const fail = (s) => { throw new UnsupportedRadixSimulation(s); };
|
|
7
|
+
const object = (x) => !!x && typeof x === 'object' && !Array.isArray(x);
|
|
8
|
+
function walk(x, f) {
|
|
9
|
+
if (Array.isArray(x)) {
|
|
10
|
+
x.forEach(y => walk(y, f));
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
if (!object(x))
|
|
14
|
+
return;
|
|
15
|
+
f(x);
|
|
16
|
+
Object.values(x).forEach(y => walk(y, f));
|
|
17
|
+
}
|
|
18
|
+
function tupleParts(e) { return e.op === 'tup' ? [e.a, ...tupleParts(e.b)] : [e]; }
|
|
19
|
+
function packed(e) {
|
|
20
|
+
if (e.op !== 'add')
|
|
21
|
+
return null;
|
|
22
|
+
if (e.a.op === 'mul' && Number.isSafeInteger(e.a.k) && e.a.k > 1) {
|
|
23
|
+
const nested = packed(e.a.a);
|
|
24
|
+
if (nested && nested.radix === e.a.k)
|
|
25
|
+
return { radix: e.a.k, parts: [...nested.parts, e.b] };
|
|
26
|
+
return { radix: e.a.k, parts: [e.a.a, e.b] };
|
|
27
|
+
}
|
|
28
|
+
// Historical flattened three-component polynomial.
|
|
29
|
+
if (e.a.op === 'add' && e.a.a.op === 'mul' && e.a.b.op === 'mul' && e.a.a.k === e.a.b.k * e.a.b.k && e.a.b.k > 1)
|
|
30
|
+
return { radix: e.a.b.k, parts: [e.a.a.a, e.a.b.a, e.b] };
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
function keys(m, laws) {
|
|
34
|
+
const result = [];
|
|
35
|
+
walk([m, laws], n => { if (n.op === 'get' && typeof n.map === 'string' && object(n.key))
|
|
36
|
+
result.push({ map: n.map, key: n.key }); });
|
|
37
|
+
for (const [map, w] of Object.entries(m.step.maps ?? {}))
|
|
38
|
+
if ('key' in w)
|
|
39
|
+
result.push({ map, key: w.key });
|
|
40
|
+
return result;
|
|
41
|
+
}
|
|
42
|
+
function plainCondition(c, radix, params) {
|
|
43
|
+
if ((c.op === '<' || c.op === '<=') && (c.b.op === 'const' && c.b.value === radix || c.b.op === 'var' && params.includes(c.b.name)))
|
|
44
|
+
return { op: 'and', xs: [] };
|
|
45
|
+
if (c.op === 'and' || c.op === 'or') {
|
|
46
|
+
const xs = c.xs.map(x => plainCondition(x, radix, params)).flatMap(x => object(x) && x.op === c.op && Array.isArray(x.xs) ? x.xs : [x]);
|
|
47
|
+
const kept = c.op === 'and' ? xs.filter(x => !eq(x, { op: 'and', xs: [] })) : xs;
|
|
48
|
+
return kept.length === 1 ? kept[0] : { op: c.op, xs: kept };
|
|
49
|
+
}
|
|
50
|
+
if (c.op === 'not')
|
|
51
|
+
return { op: 'not', x: plainCondition(c.x, radix, params) };
|
|
52
|
+
return c;
|
|
53
|
+
}
|
|
54
|
+
function booleanBound(l) {
|
|
55
|
+
const c = l.holds;
|
|
56
|
+
if (l.keys?.length || l.some?.length || l.ex || !l.forall || c.op !== '<=' || c.a.op !== 'get' || c.b.op !== 'const' || c.b.value !== 1 || c.a.key.op !== 'var' || c.a.key.name !== l.forall)
|
|
57
|
+
return null;
|
|
58
|
+
return c.a.map;
|
|
59
|
+
}
|
|
60
|
+
/** Data-only shape derivation. A noncandidate returns null. Once packed-key
|
|
61
|
+
* evidence exists, ambiguity or missing proof data is a hard failure, never a
|
|
62
|
+
* fallback to another route or to a fixed-bound theorem. */
|
|
63
|
+
export function planRadixSimulation(bundle, source) {
|
|
64
|
+
if (source.schema !== 'gdp-lift-source/v1')
|
|
65
|
+
throw Error('invalid provided source ABI');
|
|
66
|
+
sourceStructure(source);
|
|
67
|
+
if (!bundle.proof)
|
|
68
|
+
return null;
|
|
69
|
+
const leaves = [], sumSources = [];
|
|
70
|
+
const visited = new Set(), active = new Set();
|
|
71
|
+
let counted = 0;
|
|
72
|
+
const record = (m) => { if (object(m) && object(m.sums) && Object.keys(m.sums).length && object(m.step) && Array.isArray(m.inputs))
|
|
73
|
+
sumSources.push(m); };
|
|
74
|
+
const visit = (n) => {
|
|
75
|
+
if (active.has(n))
|
|
76
|
+
fail('cyclic radix provenance');
|
|
77
|
+
if (visited.has(n))
|
|
78
|
+
return;
|
|
79
|
+
active.add(n);
|
|
80
|
+
if (n.kind === 'derived') {
|
|
81
|
+
if (!n.parents.length || n.parents.some(x => !x))
|
|
82
|
+
fail('incomplete radix provenance');
|
|
83
|
+
if (object(n.context)) {
|
|
84
|
+
record(n.context.original);
|
|
85
|
+
if (object(n.context.original))
|
|
86
|
+
record(n.context.original.machine);
|
|
87
|
+
}
|
|
88
|
+
for (const p of n.parents)
|
|
89
|
+
visit(p);
|
|
90
|
+
}
|
|
91
|
+
else if (n.kind === 'usual') {
|
|
92
|
+
leaves.push(n);
|
|
93
|
+
record(n.machine);
|
|
94
|
+
}
|
|
95
|
+
else if (n.kind === 'counted') {
|
|
96
|
+
counted++;
|
|
97
|
+
}
|
|
98
|
+
active.delete(n);
|
|
99
|
+
visited.add(n);
|
|
100
|
+
};
|
|
101
|
+
visit(bundle.proof);
|
|
102
|
+
record(bundle.original.machine);
|
|
103
|
+
const allKeys = leaves.flatMap(n => keys(n.machine, n.laws));
|
|
104
|
+
const packedKeys = allKeys.flatMap(x => { const p = packed(x.key); return p ? [{ ...x, ...p }] : []; });
|
|
105
|
+
if (!packedKeys.length)
|
|
106
|
+
return null;
|
|
107
|
+
if (!bundle.verdict?.proven || !bundle.verdict.checked)
|
|
108
|
+
fail('unverified radix candidate');
|
|
109
|
+
if (leaves.length !== 1 || counted)
|
|
110
|
+
fail('radix transport needs a unique complete usual producer without counted mixing');
|
|
111
|
+
const producer = leaves[0];
|
|
112
|
+
if (Object.keys(source.machine.sums ?? {}).length)
|
|
113
|
+
fail('provided source SUM semantics are unsupported; refusing to drop declarations');
|
|
114
|
+
for (const m of [source.machine, producer.machine])
|
|
115
|
+
if (m.history || Object.keys(m.counts ?? {}).length || Object.keys(m.fns ?? {}).length || Object.keys(m.leasts ?? {}).length)
|
|
116
|
+
fail('unsupported radix machine extension');
|
|
117
|
+
if (source.machine.facts?.length || producer.machine.facts?.length)
|
|
118
|
+
fail('radix source facts require explicit checked correspondence');
|
|
119
|
+
const radices = [...new Set(packedKeys.map(k => k.radix))];
|
|
120
|
+
if (radices.length !== 1)
|
|
121
|
+
fail('ambiguous packed-key radix');
|
|
122
|
+
const radix = radices[0], layouts = [];
|
|
123
|
+
for (const k of packedKeys) {
|
|
124
|
+
const prior = layouts.find(l => l.map === k.map);
|
|
125
|
+
if (prior && prior.arity !== k.parts.length)
|
|
126
|
+
fail('inconsistent packed-key arity for ' + k.map);
|
|
127
|
+
if (!prior)
|
|
128
|
+
layouts.push({ map: k.map, arity: k.parts.length });
|
|
129
|
+
}
|
|
130
|
+
const sourceKeys = keys(source.machine, source.laws);
|
|
131
|
+
for (const layout of layouts) {
|
|
132
|
+
const typed = sourceKeys.filter(k => k.map === layout.map && k.key.op === 'tup');
|
|
133
|
+
if (!typed.length)
|
|
134
|
+
fail('provided source has no tuple-key evidence for ' + layout.map);
|
|
135
|
+
if (typed.some(k => tupleParts(k.key).length !== layout.arity))
|
|
136
|
+
fail('source tuple-key arity mismatch for ' + layout.map);
|
|
137
|
+
}
|
|
138
|
+
if (!producer.laws.length || new Set(producer.laws.map(l => l.name)).size !== producer.laws.length)
|
|
139
|
+
fail('empty or ambiguous radix family');
|
|
140
|
+
const expected = producer.laws.flatMap(l => [l.name + ' @start', l.name + ' @step']);
|
|
141
|
+
// Primary trees are goal-indexed. Instances are law-indexed and an absent
|
|
142
|
+
// law entry denotes the empty set in the unchanged kernel obligations API.
|
|
143
|
+
if (expected.some(k => !Object.hasOwn(producer.proof.trees, k)))
|
|
144
|
+
fail('missing retained radix primary obligation');
|
|
145
|
+
const uniqueSums = sumSources.filter((m, i) => sumSources.findIndex(q => eq(q, m)) === i);
|
|
146
|
+
// A high-level producer is authoritative. Earlier provenance contexts may
|
|
147
|
+
// use different local row-binder names and are not competing declarations.
|
|
148
|
+
const direct = Object.keys(producer.machine.sums ?? {}).length ? producer.machine : undefined;
|
|
149
|
+
if (!direct && uniqueSums.length !== 1)
|
|
150
|
+
fail(uniqueSums.length ? 'ambiguous high-level SUM declaration source' : 'capsule lacks reconstructible high-level SUM declarations');
|
|
151
|
+
const sumMachine = direct ?? uniqueSums[0];
|
|
152
|
+
for (const [name, d] of Object.entries(sumMachine.sums ?? {})) {
|
|
153
|
+
let unsupported = false;
|
|
154
|
+
walk(d.term, n => { if (n.op === 'get' && (!object(n.key) || n.key.op !== 'var' || n.key.name !== d.key))
|
|
155
|
+
unsupported = true; });
|
|
156
|
+
if (unsupported)
|
|
157
|
+
fail('SUM integrand is not whole-address: ' + name);
|
|
158
|
+
}
|
|
159
|
+
const publicLawIndices = source.laws.map(l => {
|
|
160
|
+
if (l.some?.length || l.ex || l.witness || l.stated || l.finite)
|
|
161
|
+
fail('unsupported radix public law quantification');
|
|
162
|
+
const shape = plainCondition(l.holds, radix, source.machine.params);
|
|
163
|
+
const found = producer.laws.flatMap((p, i) => p.forall === l.forall && eq(p.keys ?? [], l.keys ?? []) && eq(plainCondition(p.holds, radix, []), shape) ? [i] : []);
|
|
164
|
+
if (found.length !== 1)
|
|
165
|
+
fail('missing or ambiguous public-law shape: ' + l.name);
|
|
166
|
+
return found[0];
|
|
167
|
+
});
|
|
168
|
+
const booleanEntries = producer.laws.flatMap((l, index) => { const map = booleanBound(l); return map ? [{ map, index }] : []; });
|
|
169
|
+
for (const layout of layouts)
|
|
170
|
+
if (!booleanEntries.some(e => e.map === layout.map))
|
|
171
|
+
fail('packed map lacks a checked Boolean family entry: ' + layout.map);
|
|
172
|
+
return { radix, layouts, producer, sumMachine, publicLawIndices, booleanEntries };
|
|
173
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type PartOptions } from '../lift/proof-parts.js';
|
|
2
|
+
import type { FamilyBundle } from '../lift/proof-capture.js';
|
|
3
|
+
import { type GenericLiftSource } from '../lift/source.js';
|
|
4
|
+
/** Supplied by the common hash-bound complete-graph loader. This deliberately
|
|
5
|
+
* does not impose a new outer schema on legacy capsules or rewrite identity. */
|
|
6
|
+
export type BoundInclusionBundle = {
|
|
7
|
+
final: Pick<FamilyBundle['final'], 'machine' | 'laws' | 'proof'>;
|
|
8
|
+
verdict?: {
|
|
9
|
+
proven: boolean;
|
|
10
|
+
checked: boolean;
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
export type BoundInclusionInput = {
|
|
14
|
+
id: string;
|
|
15
|
+
bundle: BoundInclusionBundle;
|
|
16
|
+
providedSourceAST: GenericLiftSource;
|
|
17
|
+
options: PartOptions;
|
|
18
|
+
};
|
|
19
|
+
export type BoundInclusionOutput = {
|
|
20
|
+
project: Record<string, string>;
|
|
21
|
+
familyTheorem: string;
|
|
22
|
+
sourceTheorems: string[];
|
|
23
|
+
publicLawIndices: number[];
|
|
24
|
+
requiredTheorems: string[];
|
|
25
|
+
bound: number;
|
|
26
|
+
parts: {
|
|
27
|
+
familySize: number;
|
|
28
|
+
primaryObligations: number;
|
|
29
|
+
};
|
|
30
|
+
kind: 'bound-inclusion';
|
|
31
|
+
};
|
|
32
|
+
/** Call only after complete-graph validation and exact one-time term restoration.
|
|
33
|
+
* Null means no bound-erasure candidate. A candidate that is unsupported or
|
|
34
|
+
* ambiguous throws; callers MUST NOT turn that failure into strategy fallback.
|
|
35
|
+
* Emission is not checking: every returned theorem requires native Lean. */
|
|
36
|
+
export declare function tryEmitBoundInclusion(input: BoundInclusionInput): BoundInclusionOutput | null;
|