gdp-wired 0.50.5 → 0.51.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,167 @@
1
+ export function wordDivisionName(width, part, index) {
2
+ if (![8, 16, 32, 64].includes(width) || !['q', 'r', 'c'].includes(part) || !Number.isSafeInteger(index) ||
3
+ index < (part === 'c' ? 1 : 0) || index > (part === 'c' ? 2 * (width === 8 ? 1 : width / 16) : (width === 8 ? 1 : width / 16) - 1))
4
+ throw new Error('invalid word division name');
5
+ return `worddiv$${width}$${part}$${index}`;
6
+ }
7
+ export function parseWordDivisionName(name) {
8
+ if (typeof name !== 'string')
9
+ return undefined;
10
+ const m = /^worddiv\$(8|16|32|64)\$(q|r|c)\$(0|[1-9][0-9]*)$/.exec(name);
11
+ if (!m)
12
+ return undefined;
13
+ const width = Number(m[1]);
14
+ const part = m[2];
15
+ const index = Number(m[3]);
16
+ const n = width === 8 ? 1 : width / 16;
17
+ return Number.isSafeInteger(index) && (part === 'c' ? index >= 1 && index <= 2 * n : index < n)
18
+ ? { width, part, index } : undefined;
19
+ }
20
+ export function wordDivisionKey(args) {
21
+ if (args.length < 2)
22
+ throw new Error('word division key needs at least two arguments');
23
+ return args.slice(0, -1).reduceRight((b, a) => ({ op: 'tup', a, b }), args[args.length - 1]);
24
+ }
25
+ export function wordDivisionArgs(key, width) {
26
+ if (![8, 16, 32, 64].includes(width))
27
+ return undefined;
28
+ const count = 2 * (width === 8 ? 1 : width / 16);
29
+ const args = [];
30
+ let node = key;
31
+ for (let i = 1; i < count; i++) {
32
+ if (node.op !== 'tup')
33
+ return undefined;
34
+ args.push(node.a);
35
+ node = node.b;
36
+ }
37
+ if (node.op === 'tup')
38
+ return undefined;
39
+ args.push(node);
40
+ return args;
41
+ }
42
+ // Deliberately self-contained: compiled JavaScript embeds this function's source.
43
+ // Inputs are safe natural Numbers; every arithmetic step on word data is BigInt.
44
+ export function wordDivisionValue(width, part, index, values) {
45
+ if (width !== 8 && width !== 16 && width !== 32 && width !== 64)
46
+ throw new Error('invalid word division width');
47
+ const n = width === 8 ? 1 : width / 16;
48
+ if (part !== 'q' && part !== 'r' && part !== 'c')
49
+ throw new Error('invalid word division part');
50
+ if (!Number.isSafeInteger(index) || (part === 'c' ? index < 1 || index > 2 * n : index < 0 || index >= n))
51
+ throw new Error('invalid word division index');
52
+ if (!Array.isArray(values) || values.length !== 2 * n)
53
+ throw new Error('invalid word division arity');
54
+ const base = width === 8 ? 256n : 65536n;
55
+ const digits = [];
56
+ for (const value of values) {
57
+ if (!Number.isSafeInteger(value) || value < 0)
58
+ throw new Error('invalid word division operand');
59
+ digits.push(BigInt(value) % base);
60
+ }
61
+ let a = 0n, b = 0n, power = 1n;
62
+ for (let i = 0; i < n; i++) {
63
+ a += digits[i] * power;
64
+ b += digits[n + i] * power;
65
+ power *= base;
66
+ }
67
+ const q = b === 0n ? 0n : a / b;
68
+ const r = b === 0n ? 0n : a % b;
69
+ if (part === 'q' || part === 'r')
70
+ return Number(((part === 'q' ? q : r) / (base ** BigInt(index))) % base);
71
+ let carry = 0n;
72
+ for (let col = 0; col < index; col++) {
73
+ let total = carry + (col < n ? (r / (base ** BigInt(col))) % base : 0n);
74
+ for (let j = 0; j < n; j++) {
75
+ const k = col - j;
76
+ if (k >= 0 && k < n)
77
+ total += ((q / (base ** BigInt(j))) % base) * digits[n + k];
78
+ }
79
+ carry = total / base;
80
+ }
81
+ return Number(carry);
82
+ }
83
+ // Negative-only memo: skipping a subsequently mutated subtree can only omit
84
+ // optional consequences, never add a stale trusted assumption. Positive facts
85
+ // are always rebuilt from the current syntax. Legacy shared ASTs need no rescan.
86
+ const wordFree = new WeakSet();
87
+ export function wordDivisionFacts(terms) {
88
+ const out = [];
89
+ const seen = new Set();
90
+ const keys = new Set();
91
+ const constant = (value) => ({ op: 'const', value });
92
+ const add = (xs) => xs.reduce((a, b) => ({ op: 'add', a, b }), constant(0));
93
+ const eq = (a, b) => ({ op: '=', a, b });
94
+ const lt = (a, b) => ({ op: '<', a, b });
95
+ const le = (a, b) => ({ op: '<=', a, b });
96
+ const both = (xs) => ({ op: 'and', xs });
97
+ const either = (xs) => ({ op: 'or', xs });
98
+ const digitLex = (a, b, strict) => {
99
+ const alternatives = [];
100
+ for (let i = a.length - 1; i >= 0; i--)
101
+ alternatives.push(both([...a.slice(i + 1).map((x, j) => eq(x, b[i + 1 + j])), lt(a[i], b[i])]));
102
+ if (!strict)
103
+ alternatives.push(both(a.map((x, i) => eq(x, b[i]))));
104
+ return either(alternatives);
105
+ };
106
+ const visit = (value) => {
107
+ if (!value || typeof value !== 'object' || wordFree.has(value))
108
+ return false;
109
+ if (seen.has(value))
110
+ return true; // conservative for shared/cyclic syntax
111
+ seen.add(value);
112
+ let hasWord = false;
113
+ if (!Array.isArray(value)) {
114
+ const node = value;
115
+ if (node.op === 'get' && typeof node.map === 'string') {
116
+ hasWord = node.map.startsWith('worddiv$');
117
+ const spec = parseWordDivisionName(node.map);
118
+ if (spec && node.key && typeof node.key === 'object') {
119
+ const key = node.key;
120
+ const args = wordDivisionArgs(key, spec.width);
121
+ if (args) {
122
+ const tag = `${spec.width}:${JSON.stringify(key)}`;
123
+ if (!keys.has(tag)) {
124
+ keys.add(tag);
125
+ const n = spec.width === 8 ? 1 : spec.width / 16, base = spec.width === 8 ? 256 : 65536;
126
+ const a = args.slice(0, n), b = args.slice(n);
127
+ const get = (part, i) => ({ op: 'get', map: wordDivisionName(spec.width, part, i), key });
128
+ const q = Array.from({ length: n }, (_, i) => get('q', i));
129
+ const r = Array.from({ length: n }, (_, i) => get('r', i));
130
+ const c = Array.from({ length: 2 * n + 1 }, (_, i) => i === 0 ? constant(0) : get('c', i));
131
+ for (const x of [...q, ...r])
132
+ out.push(lt(x, constant(base)));
133
+ for (let i = 1; i <= 2 * n; i++)
134
+ out.push(le(c[i], constant(n * base)));
135
+ const domain = both([...args.map(x => lt(x, constant(base))), either(b.map(x => lt(constant(0), x)))]);
136
+ const guarded = (fact) => { out.push(either([{ op: 'not', x: domain }, fact])); };
137
+ for (let i = 0; i < 2 * n; i++) {
138
+ const columns = [c[i]];
139
+ if (i < n)
140
+ columns.push(r[i]);
141
+ for (let j = 0; j < n; j++)
142
+ if (i - j >= 0 && i - j < n)
143
+ columns.push({ op: 'prod', a: q[j], b: b[i - j] });
144
+ guarded(eq(add(columns), add([i < n ? a[i] : constant(0), { op: 'mul', k: base, a: c[i + 1] }])));
145
+ }
146
+ // Q*B+R=A fits in n digits, so the carry after the LOW n
147
+ // columns is already zero. Waiting until 2n forces elimination
148
+ // through upper columns with unsafe 2^64 certificate products.
149
+ guarded(eq(c[n], constant(0)));
150
+ guarded(digitLex(r, b, true));
151
+ guarded(digitLex(q, a, false));
152
+ const bOne = both([eq(b[0], constant(1)), ...b.slice(1).map(x => eq(x, constant(0)))]);
153
+ guarded(either([{ op: 'not', x: bOne }, both([...q.map((x, i) => eq(x, a[i])), ...r.map(x => eq(x, constant(0)))])]));
154
+ }
155
+ }
156
+ }
157
+ }
158
+ }
159
+ for (const child of Object.values(value))
160
+ hasWord = visit(child) || hasWord;
161
+ if (!hasWord)
162
+ wordFree.add(value);
163
+ return hasWord;
164
+ };
165
+ visit(terms);
166
+ return out;
167
+ }
@@ -1,4 +1,7 @@
1
- import type { C, E, Law, Machine, Recurrence } from '../core/machine.js';
1
+ import { type C, type E, type Law, type Machine, type Recurrence } from '../core/machine.js';
2
+ export { primitiveFunctionLean, toLeanIntegerPrimitive, primitiveSpecimenLean } from './integer-primitives.js';
3
+ export { wordReads, wordDigitLean, wordKeyPartsLean, wordMapOverlayLean } from './word-division-export.js';
4
+ export { q8RangeMachineToLean, wordDigitRangeMachineToLean } from './word-division-lower.js';
2
5
  import { type Lin, type Step } from '../core/solver.js';
3
6
  import { type CountCert, type CountDecl, type CountedGoal, type CountInst, type FrameCut, type MonoCut, type LinCut, type LemmaCut, type Ghosted, type Fold, type Goal, type Instances, type KInduction, type Liveness, type Loop, type Path, type Recur, type RecurCases, type StepLaw, type Tree } from '../kernel/kernel.js';
4
7
  import { proveStepLaws } from '../kernel/prove.js';
@@ -1,3 +1,8 @@
1
+ export { primitiveFunctionLean, toLeanIntegerPrimitive, primitiveSpecimenLean } from "./integer-primitives.js";
2
+ export { wordReads, wordDigitLean, wordKeyPartsLean, wordMapOverlayLean } from "./word-division-export.js";
3
+ // Legacy restricted scalar digit-range convenience lane; generic words use WordSReach below.
4
+ export { q8RangeMachineToLean, wordDigitRangeMachineToLean } from "./word-division-lower.js";
5
+ import { wordReads, wordMachineBridgeLean, wordSchemaMapNames } from "./word-division-export.js";
1
6
  import { atMost, n, not, pointWrite } from "../core/machine.js";
2
7
  import { add, k, scale, sub } from "../core/solver.js";
3
8
  import { framePath, lemmaPath, checkMC, checkCounted, checkCountedLaws, checkLaws, countedGoal, countedObligations, countHyps, mcGoal, postName, boundOf, caseGoals, cellParts, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, sumMachine, sumCovers, sumParts, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessLevels, livenessRanks, strongly, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
@@ -1035,14 +1040,14 @@ export function readable(id, laws, vars, maps, reach) {
1035
1040
  case 'mul': return `(${e.k} * ${t(e.a)})`;
1036
1041
  case 'prod': return `(${t(e.a)} * ${t(e.b)})`;
1037
1042
  case 'min':
1038
- case 'max': return `(${e.op} ${t(e.a)} ${t(e.b)})`;
1043
+ case 'max': return `(${e.op} (${t(e.a)}) (${t(e.b)}))`;
1039
1044
  case 'if': return `(if ${p(e.c)} then ${t(e.then)} else ${t(e.else)})`;
1040
1045
  case 'get': {
1041
1046
  const a = plain ? arithOf(e.map) : undefined;
1042
1047
  return a ? `(${t(e.key)} ${a.op} ${a.k})` : `(μ ${q(e.map)} (${t(e.key)}))`;
1043
1048
  }
1044
- case 'tup': return `(Kern.cpair ${t(e.a)} ${t(e.b)})`;
1045
- case 'proj': return `(Kern.pickP ${e.k} ${t(e.a)})`;
1049
+ case 'tup': return `(Kern.cpair (${t(e.a)}) (${t(e.b)}))`;
1050
+ case 'proj': return `(Kern.pickP ${e.k} (${t(e.a)}))`;
1046
1051
  }
1047
1052
  };
1048
1053
  const p = (c) => {
@@ -1401,6 +1406,11 @@ function machineNames(m, laws, allSteps, stepLaws, opts) {
1401
1406
  return { vars, maps };
1402
1407
  }
1403
1408
  export function smachineToLean(id, given, laws, opts = {}) {
1409
+ const words = wordReads([given, laws, opts]).length > 0;
1410
+ // Higher-level temporal/refinement bridges require their own framed-world proof.
1411
+ // Never route them through the arbitrary-map soundness theorem by accident.
1412
+ if (words && (given.history || given.sums || opts.refined || opts.ghosted || opts.ghosts?.length || opts.kind || opts.loop || opts.liveness?.length || opts.tamper || opts.ghostSubst?.length))
1413
+ throw new Error(`${id}: word export supports generic SMachine invariants; this auxiliary bridge needs a concrete-world theorem`);
1404
1414
  const hm = given.history ? { ...given, history: { ...given.history, prune: undefined } } : undefined;
1405
1415
  const hplain = hm ? historyMachine(hm) : undefined, stepLaws = opts.stepLaws ?? [], rf = opts.refined, gv = opts.ghosts ?? [];
1406
1416
  // A machine with sums goes as its plain machine too (kernel.ts's sumMachine), built in Lean (Sums.lean's
@@ -1434,8 +1444,8 @@ export function smachineToLean(id, given, laws, opts = {}) {
1434
1444
  if (!rf)
1435
1445
  stepLaws.forEach((sl, j) => claims.push({ steps: [sl], allows: [], render: h => `-- Step law${(sl.steps ?? 1) > 1 ? ` over ${sl.steps} steps` : ''}: ${sl.name}
1436
1446
  def ${id}_step${j} : SKStep := ${skLit(h, sl)}
1437
- theorem ${id}_step${j}_holds : SKStepHolds ${id}_machine ${id}_step${j} :=
1438
- skstep_sound ${id}_machine ${id}_proof ${id}_step${j} ${id}_check (by ${checkBy})` }));
1447
+ theorem ${id}_step${j}_holds : ${words ? `Kern.WordSMachine.WordSKStepHolds ${id}_word ${id}_step${j}` : `SKStepHolds ${id}_machine ${id}_step${j}`} :=
1448
+ ${words ? `Kern.WordSMachine.word_skstep_sound ${id}_word ${id}_proof ${id}_step${j} ${id}_word_extra ${id}_check ${id}_word_extra_sound (by ${checkBy})` : `skstep_sound ${id}_machine ${id}_proof ${id}_step${j} ${id}_check (by ${checkBy})`}` }));
1439
1449
  // k-induction (KInd.lean's kind_sound): Lean builds each base goal's and the step's whens and then from the law; the
1440
1450
  // trees, instances and names are the k-step laws' kernel.ts made (kInductionSteps), the start goal's tree its own.
1441
1451
  const kd = opts.kind;
@@ -1686,7 +1696,10 @@ theorem ${id}_orig_laws : ∀ ρ M, SReach ${id}_ghosted.orig ρ M → ∀ e ∈
1686
1696
  const named = machineNames(m, laws, allSteps, stepLaws, { ...opts, ...(hm ? { record: hm.history.record } : {}) });
1687
1697
  const sumNames = sm ? Object.entries(sm.sums).flatMap(([s2, sum]) => { const { flag, x } = sumParts(s2); return [s2, sum.key, `?${flag}`, `w?${flag}`, x]; }) : [];
1688
1698
  const vars = [...new Set([...named.vars, ...sumNames, ...[...goalsL, ...goalsS, ...allowGoals, ...(hplain?.goals ?? []), ...covers.flat(), ...(opts.kind ? [opts.kind.start.goal] : [])].flatMap(g => g.hyps.flatMap(varsOf))])];
1689
- const mapNames = [...new Set([...named.maps, ...[...JSON.stringify([...goalsL, ...goalsS, ...allowGoals]).matchAll(/"op":"get","map":"([^"]+)"/g)].map(x2 => x2[1])])];
1699
+ // A computation irrelevant to a proved law is still part of the source machine.
1700
+ // Include its getter namespace and all native schema helpers, not only goal reads.
1701
+ const sourceTerms = words ? [m, laws, allSteps] : [];
1702
+ const mapNames = [...new Set([...named.maps, ...[...JSON.stringify([...goalsL, ...goalsS, ...allowGoals, ...sourceTerms]).matchAll(/"op":"get","map":"([^"]+)"/g)].map(x2 => x2[1]), ...wordSchemaMapNames(sourceTerms)])];
1690
1703
  const enc = (g, tree) => encode({ name: `${id}: ${g.name}`, goal: g, tree }, false, true, vars, mapNames);
1691
1704
  const { e, c } = leanTerms(vars, mapNames, id);
1692
1705
  const ix = (name) => { const j = vars.indexOf(name); if (j < 0)
@@ -1838,10 +1851,14 @@ def ${id}_machine : SMachine := ${id}_hist.plain` : sm ? sumsDef() : lp0 ? `def
1838
1851
  def ${id}_machine : SMachine := ${id}_loop.machine` : `def ${id}_machine : SMachine := ${lit(m)}`}
1839
1852
  ${entries.join('\n')}
1840
1853
  def ${id}_proof : List SEntry := ${list(laws.map((_, j) => `${id}_e${j}`))}
1841
- theorem ${id}_check : checkSMachine ${id}_machine ${id}_proof = true := by ${checkBy}
1854
+ ${words ? `${wordMachineBridgeLean(id, [m, laws, goalsL, goalsS], vars, mapNames)}
1855
+ theorem ${id}_check : Kern.WordSMachine.checkSMachineWithFacts ${id}_machine ${id}_proof ${id}_word_extra = true := by ${checkBy}
1856
+ theorem ${id}_laws : ∀ ρ M, Kern.WordReach.WordSReach ${id}_word ρ M → ∀ e ∈ ${id}_proof, e.Holds ρ M :=
1857
+ Kern.WordSMachine.concrete_smachine_sound ${id}_word ${id}_proof ${id}_word_extra ${id}_check ${id}_word_extra_sound` : `theorem ${id}_check : checkSMachine ${id}_machine ${id}_proof = true := by ${checkBy}
1842
1858
  theorem ${id}_laws : ∀ ρ M, SReach ${id}_machine ρ M → ∀ e ∈ ${id}_proof, e.Holds ρ M :=
1843
- smachine_sound ${id}_machine ${id}_proof ${id}_check
1844
- ${hm ? histBlock() : readable(id, laws, vars, mapNames, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: `${id}_laws ρ μ h`, lit: c, eLit: e, ghosts: !rf && !gm && gv.length > 0, explicitExistentials: new Set((opts.ghostSubst ?? []).map(g => g.law)) })}${sm ? sumsBlock() : ''}${opts.noFacts ? '' : factsProof(id, m, mapNames, vars, opts.simp)}${opts.tamper ? `
1859
+ smachine_sound ${id}_machine ${id}_proof ${id}_check`}
1860
+
1861
+ ${hm ? histBlock() : readable(id, laws, vars, mapNames, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: words ? `Kern.WordReach.WordSReach ${id}_word ρ μ` : `SReach ${id}_machine ρ μ`, call: `${id}_laws ρ μ h`, lit: c, eLit: e, ghosts: !rf && !gm && gv.length > 0, explicitExistentials: new Set((opts.ghostSubst ?? []).map(g => g.law)) })}${sm ? sumsBlock() : ''}${opts.noFacts ? '' : factsProof(id, m, mapNames, vars, opts.simp)}${opts.tamper ? `
1845
1862
  -- TAMPERED: ${opts.tamper.what}. Lean computes the check to false.
1846
1863
  def ${id}_tampered : SMachine := ${lit(opts.tamper.machine)}
1847
1864
  example : checkSMachine ${id}_tampered ${id}_proof = false := by ${checkBy}` : ''}${records.length ? `\n\n${records.join('\n\n')}` : ''}${opts.after ? `\n\n${opts.after(ix, mx, lit, c)}` : ''}`;
@@ -2019,6 +2036,8 @@ function cycMachineProofBy(m, laws, allSteps, allows, r, until) {
2019
2036
  }
2020
2037
  // A machine (with a history, ghosts, a liveness or as a loop's) from one cyclic proof, or why it can't be.
2021
2038
  export function cycMachineToLean(id, given, laws, opts = {}) {
2039
+ if (wordReads([given, laws, opts]).length)
2040
+ return { why: 'word primitives require the concrete SMachine export route' };
2022
2041
  const hm = given.history ? { ...given, history: { ...given.history, prune: undefined } } : undefined;
2023
2042
  const hplain = hm ? historyMachine(hm) : undefined, m = hplain ? hplain.machine : given;
2024
2043
  const stepLaws = opts.stepLaws ?? [], gv = opts.ghosts ?? [], lp0 = opts.loop;
@@ -2502,6 +2521,12 @@ export function hmachineToLean(id, m, laws, tampers = [], corollary) {
2502
2521
  // `cyclic`: each machine, loop and fold the cyclic route covers from cyclic certificates (see cycMachineToLean); defaults
2503
2522
  // to GDP_CERT=cyclic. `certReport` then says which items went which way.
2504
2523
  export function toLean(items, opts = {}) {
2524
+ // Generic intrinsic machines use the same serialized certificates, with every
2525
+ // extra hypothesis constructed and discharged by WordFacts under WordSReach.
2526
+ // Other item kinds need their own concrete-world simulation, never SReach.
2527
+ for (const item of items)
2528
+ if (wordReads(item).length && !('machine' in item))
2529
+ throw new Error('word primitives require the concrete SMachine export route');
2505
2530
  // Admit source-derived models before changing exporter state or emitting any text.
2506
2531
  // Ordinary typed DSL machines have no provenance entry and pass unchanged.
2507
2532
  for (const item of items) {
@@ -2608,7 +2633,7 @@ function toLeanWith(items, opts) {
2608
2633
  // (a machine with sums has no cyclic twin: the usual trees, Sums.lean)
2609
2634
  // (nor a liveness under strong fairness: Live.lean's sleads_sf_soundA reads the usual step laws)
2610
2635
  const sums = !!(m.sums && Object.keys(m.sums).length), sf = (item.liveness ?? []).some(strongly);
2611
- const cyc = certsOn && !sums && !sf ? cycMachineToLean(id, m, item.laws, mopts) : undefined;
2636
+ const cyc = certsOn && !sums && !sf && !wordReads([m, item.laws, item.stepLaws, item.liveness]).length ? cycMachineToLean(id, m, item.laws, mopts) : undefined;
2612
2637
  if (cyc && 'text' in cyc)
2613
2638
  certReport.cyclic.push(item.id);
2614
2639
  else if (cyc)
@@ -2686,7 +2711,7 @@ function toLeanWith(items, opts) {
2686
2711
  }
2687
2712
  // The file the items need: Live.lean for a liveness or a loop, Sets.lean (which imports Steps.lean) for any machine.
2688
2713
  return `import History
2689
- ${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'}
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'}
2690
2715
  open Kern Cert
2691
2716
  set_option maxRecDepth 100000
2692
2717
  set_option maxHeartbeats 0
@@ -0,0 +1,17 @@
1
+ import { type PrimitiveSpec } from '../kernel/integer-primitives.js';
2
+ export type { PrimitiveSpec, PrimitiveResult } from '../kernel/integer-primitives.js';
3
+ /** A Lean term for the complete spec. Runtime validation remains in evaluatePrimitive. */
4
+ export declare function primitiveSpecLean(s: PrimitiveSpec): string;
5
+ /** A closed obligation; Lean computes the result, not a custom arithmetic restatement.
6
+ * `a`/`b` are strict exact decimal strings because specimens can cross JSON.
7
+ * There is no write, check, toolchain invocation, or proof claim in this function.
8
+ */
9
+ export declare function primitiveSpecimenObligation(spec: PrimitiveSpec, a: string, b?: string, name?: string): string;
10
+ /** Symbolic native-typed Lean definition. Each input is Lean's actual UIntN/IntN;
11
+ * arithmetic/division uses IntegerPrimitives' standard BitVec/Int operations.
12
+ * This exports semantics, not a proof of the separate TypeScript limb lowering.
13
+ */
14
+ export declare function primitiveFunctionLean(spec: PrimitiveSpec, name?: string): string;
15
+ export declare function toLeanIntegerPrimitive(spec: PrimitiveSpec, name?: string): string;
16
+ /** Standalone Lean source for a closed native probe; import path expects lean-kernel on LEAN_PATH. */
17
+ export declare function primitiveSpecimenLean(spec: PrimitiveSpec, a: string, b?: string, name?: string): string;
@@ -0,0 +1,81 @@
1
+ // Untrusted serialization only. The native Lean checker independently computes
2
+ // IntegerPrimitives.evaluate against the exact BigInt evaluator's claimed result.
3
+ import { evaluatePrimitive, evaluatePrimitiveReceipt } from "../kernel/integer-primitives.js";
4
+ const intLiteral = (n) => n < 0n ? `(${n.toString(10)})` : n.toString(10);
5
+ const decimal = (n) => {
6
+ if (!/^-?(?:0|[1-9][0-9]*)$/.test(n))
7
+ throw new Error('expected exact decimal integer string');
8
+ return BigInt(n);
9
+ };
10
+ const identifier = (s) => {
11
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(s))
12
+ throw new Error('expected Lean identifier');
13
+ return s;
14
+ };
15
+ const operation = (s) => {
16
+ if (!['add', 'sub', 'mul', 'neg', 'cast', 'div', 'rem'].includes(s))
17
+ throw new Error('invalid operation');
18
+ return `.${s}`;
19
+ };
20
+ const overflow = (s) => {
21
+ if (!['WRAP', 'SATURATE', 'TRAP'].includes(s))
22
+ throw new Error('invalid overflow mode');
23
+ return `.${s}`;
24
+ };
25
+ const division = (s) => {
26
+ if (s === undefined)
27
+ return 'none';
28
+ if (!['FLOOR', 'TRUNCATING', 'EUCLIDEAN'].includes(s))
29
+ throw new Error('invalid division mode');
30
+ return `some .${s}`;
31
+ };
32
+ /** A Lean term for the complete spec. Runtime validation remains in evaluatePrimitive. */
33
+ export function primitiveSpecLean(s) {
34
+ if (![8, 16, 32, 64].includes(s.width) || typeof s.signed !== 'boolean')
35
+ throw new Error('invalid width or signed flag');
36
+ return `{ width := ${s.width}, signed := ${s.signed}, operation := ${operation(s.operation)}, overflow := ${overflow(s.overflow)}, division := ${division(s.division)} }`;
37
+ }
38
+ const errorLean = (reason) => {
39
+ if (reason === 'division by zero')
40
+ return '.error .divisionByZero';
41
+ if (reason === 'overflow')
42
+ return '.error .overflow';
43
+ if (reason === 'a out of bounds' || reason === 'b out of bounds')
44
+ return '.error .invalidInput';
45
+ throw new Error(`cannot serialize primitive failure: ${reason}`);
46
+ };
47
+ const resultLean = (result) => result.ok
48
+ ? `.ok ${intLiteral(result.value)}` : errorLean(result.reason);
49
+ /** A closed obligation; Lean computes the result, not a custom arithmetic restatement.
50
+ * `a`/`b` are strict exact decimal strings because specimens can cross JSON.
51
+ * There is no write, check, toolchain invocation, or proof claim in this function.
52
+ */
53
+ export function primitiveSpecimenObligation(spec, a, b, name = 'integer_primitive_specimen') {
54
+ const left = decimal(a), right = b === undefined ? undefined : decimal(b);
55
+ const result = evaluatePrimitive(spec, left, right);
56
+ const expected = resultLean(result);
57
+ return `theorem ${identifier(name)} : IntegerPrimitives.evaluate (${primitiveSpecLean(spec)}) ${intLiteral(left)} ${right === undefined ? 'none' : `(some ${intLiteral(right)})`} = ${expected} := by decide
58
+ #print axioms ${identifier(name)}`;
59
+ }
60
+ /** Symbolic native-typed Lean definition. Each input is Lean's actual UIntN/IntN;
61
+ * arithmetic/division uses IntegerPrimitives' standard BitVec/Int operations.
62
+ * This exports semantics, not a proof of the separate TypeScript limb lowering.
63
+ */
64
+ export function primitiveFunctionLean(spec, name = 'integer_primitive') {
65
+ const captured = evaluatePrimitiveReceipt(spec, 0n).spec;
66
+ if (!captured)
67
+ throw new Error('invalid primitive spec');
68
+ const native = `${captured.signed ? 'Int' : 'UInt'}${captured.width}`;
69
+ const binary = ['add', 'sub', 'mul', 'div', 'rem'].includes(captured.operation);
70
+ const left = captured.signed ? 'a.toInt' : '(Int.ofNat a.toNat)';
71
+ const right = binary ? `(some ${captured.signed ? 'b.toInt' : '(Int.ofNat b.toNat)'})` : 'none';
72
+ const convert = captured.signed ? `${native}.ofInt z` : `${native}.ofNat z.toNat`;
73
+ return `def ${identifier(name)} (a : ${native})${binary ? ` (b : ${native})` : ''} : Except IntegerPrimitives.Failure ${native} :=\n (IntegerPrimitives.evaluate (${primitiveSpecLean(captured)}) ${left} ${right}).map (fun z => ${convert})\n#print axioms ${identifier(name)}\n`;
74
+ }
75
+ export function toLeanIntegerPrimitive(spec, name = 'integer_primitive') {
76
+ return `import IntegerPrimitives\n\n${primitiveFunctionLean(spec, name)}`;
77
+ }
78
+ /** Standalone Lean source for a closed native probe; import path expects lean-kernel on LEAN_PATH. */
79
+ export function primitiveSpecimenLean(spec, a, b, name = 'integer_primitive_specimen') {
80
+ return `import IntegerPrimitives\n\n${primitiveSpecimenObligation(spec, a, b, name)}\n`;
81
+ }