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.
@@ -66,6 +66,7 @@ export type C = {
66
66
  finite?: string;
67
67
  };
68
68
  export type Machine = {
69
+ primitiveFailure?: C;
69
70
  name: string;
70
71
  params: string[];
71
72
  inputs: string[];
@@ -8,6 +8,7 @@
8
8
  import { boundOf, crossFree, eachParts, finiteBound, finiteLawBound, historyMachine, tuple, keyTerm, mapArities, plainKey, scope, sumRuntime, tupleParts } from "../kernel/kernel.js";
9
9
  import { add, env, eq, k, le, lt, nat, scale, show, solve, sub, v } from "./solver.js";
10
10
  import { runtimeWall } from "./runtime-wall.js";
11
+ import { parseWordDivisionName, wordDivisionArgs, wordDivisionValue } from "../kernel/word-division.js";
11
12
  import { traceNow } from "./trace-clock.js";
12
13
  import { coreMeter } from "./meter.js";
13
14
  import { observeEval } from "./work-observe.js";
@@ -180,7 +181,7 @@ export function withArithmetic(m, more = [], ks = []) {
180
181
  return { ...m, fns: { ...m.fns, ...fns }, facts: [...(m.facts ?? []), ...facts] };
181
182
  }
182
183
  // Every term and condition a machine holds.
183
- export const machineTerms = (m) => [...Object.values(m.state), ...Object.values(m.step.flags ?? {}), ...Object.values(m.step.state ?? {}),
184
+ export const machineTerms = (m) => [...Object.values(m.state), ...(m.primitiveFailure ? [m.primitiveFailure] : []), ...Object.values(m.step.flags ?? {}), ...Object.values(m.step.state ?? {}),
184
185
  ...Object.values(m.step.maps ?? {}).flatMap(w => ('key' in w ? [w.key, w.value] : [w.value])), ...(m.pre ? [m.pre] : []), ...(m.assume ? [m.assume] : []),
185
186
  ...(m.facts ?? []).map(f => f.holds), ...(m.history ? [m.history.keep, ...Object.values(m.history.sums), ...Object.values(m.history.queries), ...(m.history.relations ?? []).flatMap(r => [r.when, r.holds])] : [])];
186
187
  // A condition at every key, or a value at every key. Where the bound key is read only as a map's key, each key a map
@@ -340,6 +341,13 @@ export function evalE(e, env, st, m) {
340
341
  case 'tup': return cpair(evalE(e.a, env, st, m), evalE(e.b, env, st, m));
341
342
  case 'proj': return cunpair(evalE(e.a, env, st, m))[e.k];
342
343
  case 'get': {
344
+ const intrinsic = parseWordDivisionName(e.map);
345
+ if (intrinsic) {
346
+ const args = wordDivisionArgs(e.key, intrinsic.width);
347
+ if (!args)
348
+ throw new Error(`${e.map} needs a right-nested word division tuple key`);
349
+ return wordDivisionValue(intrinsic.width, intrinsic.part, intrinsic.index, args.map(a => evalE(a, env, st, m)));
350
+ }
343
351
  const fn = m.fns && Object.hasOwn(m.fns, e.map) ? m.fns[e.map] : undefined, args = fn?.call ? pairedArgs(e.key, fn.arity) : undefined;
344
352
  if (args) {
345
353
  const xs = args.map(a => evalE(a, env, st, m));
@@ -377,6 +385,13 @@ const directCall = (d) => {
377
385
  case 'max': return Math.max(value(e.a, env), value(e.b, env));
378
386
  case 'if': return condition(e.c, env) ? value(e.then, env) : value(e.else, env);
379
387
  case 'get': {
388
+ const intrinsic = parseWordDivisionName(e.map);
389
+ if (intrinsic) {
390
+ const args = wordDivisionArgs(e.key, intrinsic.width);
391
+ if (!args)
392
+ throw new Error('invalid compact word-division argument tuple');
393
+ return wordDivisionValue(intrinsic.width, intrinsic.part, intrinsic.index, args.map(a => value(a, env)));
394
+ }
380
395
  const fn = d.uses[e.map], args = pairedArgs(e.key, fn.arity ?? 1);
381
396
  return args ? callOf(fn)(...args.map(a => value(a, env))) : fnOf(fn)(value(e.key, env));
382
397
  }
@@ -561,6 +576,8 @@ function compileENode(e, m) {
561
576
  return (env, st) => cunpair(a(env, st))[k];
562
577
  }
563
578
  case 'get': {
579
+ if (parseWordDivisionName(e.map))
580
+ return (env, st) => evalE(e, env, st, m);
564
581
  const map = e.map, key = compileE(e.key, m);
565
582
  return (env, st) => {
566
583
  const fn = m.fns?.[map];
@@ -924,6 +941,11 @@ export function interpret(m, checkpoint) {
924
941
  env[`?${name}`] = evalC(c, env, st, plain) ? 1 : 0;
925
942
  if (m.assume && !evalC(m.assume, env, st, plain))
926
943
  throw new RangeError(refused(m));
944
+ if (plain.primitiveFailure && evalC(plain.primitiveFailure, env, st, plain)) {
945
+ const error = new RangeError(`${m.name}: fixed-width primitive failed`);
946
+ error.name = 'PrimitiveFailure';
947
+ throw error;
948
+ }
927
949
  const scalars = { ...st.scalars };
928
950
  for (const [name, e] of Object.entries(plain.step.state ?? {}))
929
951
  scalars[name] = evalE(e, env, st, plain);
@@ -1032,6 +1054,13 @@ function compileJsMode(m, persistent, cells) {
1032
1054
  case 'tup': return `$p(${ex(e.a)}, ${ex(e.b)})`;
1033
1055
  case 'proj': return `$u(${ex(e.a)})[${e.k}]`;
1034
1056
  case 'get': {
1057
+ const intrinsic = parseWordDivisionName(e.map);
1058
+ if (intrinsic) {
1059
+ const args = wordDivisionArgs(e.key, intrinsic.width);
1060
+ if (!args)
1061
+ throw new Error(`${e.map} needs a right-nested word division tuple key`);
1062
+ return `$wordDivisionValue(${intrinsic.width}, ${id(intrinsic.part)}, ${intrinsic.index}, [${args.map(ex).join(', ')}])`;
1063
+ }
1035
1064
  const fn = m.fns && Object.hasOwn(m.fns, e.map) ? m.fns[e.map] : undefined, args = fn?.call ? pairedArgs(e.key, fn.arity) : undefined;
1036
1065
  if (args)
1037
1066
  return `$n(fnc${fns.indexOf(e.map)}(${args.map(ex).join(', ')}), ${id(`${e.map}()`)})`;
@@ -1130,7 +1159,7 @@ function compileJsMode(m, persistent, cells) {
1130
1159
  }
1131
1160
  lines.push(...flags.map((name, i) => `const flag${i} = ${cx(plain.step.flags[name])};`),
1132
1161
  // The rule's own assumption, as `allowed` (core/watch.ts) reads it (a history's machine assumes more: its relations).
1133
- ...(m.assume ? [`if (!${cx(m.assume)}) throw new RangeError(${id(refused(m))});`] : []), `const scalars = {...s, ${Object.entries(plain.step.state ?? {}).map(([name, e]) => `${id(name)}: ${ex(e)}`).join(', ')}};`, ...[...sharedBreaks].map(([text, bk]) => `const ${bk} = ${breaksJs(JSON.parse(text))};`), ...writes.map(([name, w], i) => ('each' in w ? `const write${i} = ${every(w, sharedOf(name))};` : `const key${i} = ${ex(w.key)}, value${i} = ${ex(w.value)};`)));
1162
+ ...(m.assume ? [`if (!${cx(m.assume)}) throw new RangeError(${id(refused(m))});`] : []), ...(plain.primitiveFailure ? [`if (${cx(plain.primitiveFailure)}) { const e = new RangeError(${id(`${m.name}: fixed-width primitive failed`)}); e.name = "PrimitiveFailure"; throw e; }`] : []), `const scalars = {...s, ${Object.entries(plain.step.state ?? {}).map(([name, e]) => `${id(name)}: ${ex(e)}`).join(', ')}};`, ...[...sharedBreaks].map(([text, bk]) => `const ${bk} = ${breaksJs(JSON.parse(text))};`), ...writes.map(([name, w], i) => ('each' in w ? `const write${i} = ${every(w, sharedOf(name))};` : `const key${i} = ${ex(w.key)}, value${i} = ${ex(w.value)};`)));
1134
1163
  if (h)
1135
1164
  lines.push(`const keep = ${cx(h.keep)};`);
1136
1165
  if (persistent)
@@ -1173,7 +1202,8 @@ export function step(params, state, input${hasFinite(plain) ? ', $finite = () =>
1173
1202
  }
1174
1203
  `;
1175
1204
  return `// Generated from the machine ${m.name}. step consumes its state: keep the one it returns (fork to branch).
1176
- ${runtimeFor(fnDefs + code)}${fnDefs}${code}`;
1205
+ ${runtimeFor(fnDefs + code)}const $wordDivisionValue = ${wordDivisionValue.toString()};
1206
+ ${fnDefs}${code}`;
1177
1207
  }
1178
1208
  // Generated code as a function. Every caller passes source this library generated from its own terms, or a function's
1179
1209
  // `js` the rule's author wrote (code, as the rule itself is), never data; the lint's implied-eval rule is waived here
@@ -1481,13 +1511,9 @@ function renameKey(lin, from, to) {
1481
1511
  // just need a stronger invariant.
1482
1512
  export function search(m, law, depth = 3, bound = 2) {
1483
1513
  const run = interpret(m);
1484
- const holds = (params, st) => {
1485
- const finite = finiteLawBound(law);
1486
- if (finite)
1487
- return evalC({ op: 'all', key: law.forall, c: law.holds, finite: law.finite }, params, st, m);
1488
- const keys = law.forall ? [...new Set([0, ...Object.values(st.maps).flatMap(cells => [...cells.keys()])])] : [0];
1489
- return keys.every(key => evalC(law.holds, { ...params, ...(law.forall ? { [law.forall]: key } : {}) }, st, m));
1490
- };
1514
+ finiteLawBound(law); // Preserve validation of explicit finite-domain metadata.
1515
+ const condition = law.forall ? { op: 'all', key: law.forall, keys: law.keys, c: law.holds, finite: law.finite } : law.holds;
1516
+ const holds = (params, st) => evalC(condition, params, st, m);
1491
1517
  const tops = new Map();
1492
1518
  const conj = (c) => (c === undefined ? [] : c.op === 'and' ? c.xs.flatMap(conj) : [c]);
1493
1519
  for (const c of [...conj(m.pre), ...conj(m.assume)])
@@ -0,0 +1,38 @@
1
+ export type Width = 8 | 16 | 32 | 64;
2
+ export type OverflowMode = 'WRAP' | 'SATURATE' | 'TRAP';
3
+ export type DivisionMode = 'FLOOR' | 'TRUNCATING' | 'EUCLIDEAN';
4
+ export type PrimitiveOperation = 'add' | 'sub' | 'mul' | 'neg' | 'cast' | 'div' | 'rem';
5
+ export type PrimitiveSpec = {
6
+ width: Width;
7
+ signed: boolean;
8
+ operation: PrimitiveOperation;
9
+ overflow: OverflowMode;
10
+ division?: DivisionMode;
11
+ };
12
+ export type PrimitiveResult = {
13
+ ok: true;
14
+ value: bigint;
15
+ } | {
16
+ ok: false;
17
+ reason: string;
18
+ };
19
+ export type PrimitiveReceipt = {
20
+ spec: PrimitiveSpec | null;
21
+ a: string;
22
+ b?: string;
23
+ result: {
24
+ ok: true;
25
+ value: string;
26
+ } | {
27
+ ok: false;
28
+ reason: string;
29
+ };
30
+ };
31
+ export declare function evaluatePrimitive(spec: PrimitiveSpec, a: bigint, b?: bigint): PrimitiveResult;
32
+ export type WrapCaseCertificate = {
33
+ quotient: bigint;
34
+ residue: bigint;
35
+ value: bigint;
36
+ };
37
+ export declare function checkWrapCase(spec: PrimitiveSpec, a: bigint, b: bigint | undefined, c: WrapCaseCertificate): boolean;
38
+ export declare function evaluatePrimitiveReceipt(spec: PrimitiveSpec, a: bigint, b?: bigint): PrimitiveReceipt;
@@ -0,0 +1,179 @@
1
+ const fail = (reason) => ({ ok: false, reason });
2
+ const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
3
+ const binary = (op) => op === 'add' || op === 'sub' || op === 'mul' || op === 'div' || op === 'rem';
4
+ const dividing = (op) => op === 'div' || op === 'rem';
5
+ function snapshot(spec) {
6
+ if (spec === null || typeof spec !== 'object')
7
+ return { ok: false, reason: 'invalid spec' };
8
+ let s;
9
+ try {
10
+ const proto = Object.getPrototypeOf(spec);
11
+ if (proto !== Object.prototype && proto !== null)
12
+ return { ok: false, reason: 'invalid spec' };
13
+ const ds = Object.getOwnPropertyDescriptors(spec);
14
+ const keys = Reflect.ownKeys(ds);
15
+ if (keys.some(k => typeof k !== 'string'))
16
+ return { ok: false, reason: 'invalid spec' };
17
+ s = Object.create(null);
18
+ for (const k of keys) {
19
+ if (!['width', 'signed', 'operation', 'overflow', 'division'].includes(k))
20
+ return { ok: false, reason: 'unknown spec field' };
21
+ const d = ds[k];
22
+ if (!own(d, 'value'))
23
+ return { ok: false, reason: 'invalid spec' };
24
+ s[k] = d.value;
25
+ }
26
+ }
27
+ catch {
28
+ return { ok: false, reason: 'invalid spec' };
29
+ }
30
+ if (!own(s, 'width') || ![8, 16, 32, 64].includes(s.width))
31
+ return { ok: false, reason: 'invalid width' };
32
+ if (!own(s, 'signed') || typeof s.signed !== 'boolean')
33
+ return { ok: false, reason: 'invalid signed flag' };
34
+ if (!own(s, 'operation') || !['add', 'sub', 'mul', 'neg', 'cast', 'div', 'rem'].includes(s.operation))
35
+ return { ok: false, reason: 'invalid operation' };
36
+ if (!own(s, 'overflow') || !['WRAP', 'SATURATE', 'TRAP'].includes(s.overflow))
37
+ return { ok: false, reason: 'invalid overflow mode' };
38
+ const hasDivision = own(s, 'division');
39
+ if (hasDivision !== dividing(s.operation) ||
40
+ (hasDivision && !['FLOOR', 'TRUNCATING', 'EUCLIDEAN'].includes(s.division)))
41
+ return { ok: false, reason: 'invalid division mode' };
42
+ const clean = { width: s.width, signed: s.signed, operation: s.operation, overflow: s.overflow };
43
+ if (hasDivision)
44
+ clean.division = s.division;
45
+ return { ok: true, spec: clean };
46
+ }
47
+ export function evaluatePrimitive(spec, a, b) {
48
+ const parsed = snapshot(spec);
49
+ return parsed.ok ? evaluateSnapshot(parsed.spec, a, b) : fail(parsed.reason);
50
+ }
51
+ function evaluateSnapshot(spec, a, b) {
52
+ if (typeof a !== 'bigint')
53
+ return fail('a must be bigint');
54
+ const needsB = binary(spec.operation);
55
+ if (needsB ? typeof b !== 'bigint' : b !== undefined)
56
+ return fail(needsB ? 'b must be bigint' : 'unexpected b');
57
+ const bits = BigInt(spec.width);
58
+ const modulus = 1n << bits;
59
+ const min = spec.signed ? -(modulus >> 1n) : 0n;
60
+ const max = spec.signed ? (modulus >> 1n) - 1n : modulus - 1n;
61
+ // Cast is conversion from an unbounded exact integer; other operands are values of this type.
62
+ if (spec.operation !== 'cast' && (a < min || a > max))
63
+ return fail('a out of bounds');
64
+ if (needsB && (b < min || b > max))
65
+ return fail('b out of bounds');
66
+ let raw;
67
+ switch (spec.operation) {
68
+ case 'add':
69
+ raw = a + b;
70
+ break;
71
+ case 'sub':
72
+ raw = a - b;
73
+ break;
74
+ case 'mul':
75
+ raw = a * b;
76
+ break;
77
+ case 'neg':
78
+ raw = -a;
79
+ break;
80
+ case 'cast':
81
+ raw = a;
82
+ break;
83
+ case 'div':
84
+ case 'rem': {
85
+ if (b === 0n)
86
+ return fail('division by zero');
87
+ let q = a / b; // BigInt division truncates towards zero.
88
+ let r = a % b;
89
+ if (spec.division === 'FLOOR' && r !== 0n && ((r < 0n) !== (b < 0n))) {
90
+ q -= 1n;
91
+ r += b;
92
+ }
93
+ else if (spec.division === 'EUCLIDEAN' && r < 0n) {
94
+ const sign = b < 0n ? -1n : 1n;
95
+ q -= sign;
96
+ r += b * sign;
97
+ }
98
+ // Division-pair trap: even rem(MIN, -1) fails when its quotient overflows.
99
+ // WRAP/SATURATE still return the exact remainder (zero in that case).
100
+ if (spec.operation === 'rem' && spec.overflow === 'TRAP' && (q < min || q > max))
101
+ return fail('overflow');
102
+ raw = spec.operation === 'div' ? q : r;
103
+ break;
104
+ }
105
+ }
106
+ if (raw >= min && raw <= max)
107
+ return { ok: true, value: raw };
108
+ if (spec.overflow === 'TRAP')
109
+ return fail('overflow');
110
+ if (spec.overflow === 'SATURATE')
111
+ return { ok: true, value: raw < min ? min : max };
112
+ const unsigned = ((raw % modulus) + modulus) % modulus;
113
+ return { ok: true, value: spec.signed && unsigned >= (modulus >> 1n) ? unsigned - modulus : unsigned };
114
+ }
115
+ export function checkWrapCase(spec, a, b, c) {
116
+ const parsed = snapshot(spec);
117
+ if (!parsed.ok)
118
+ return false;
119
+ const s = parsed.spec;
120
+ if (s.overflow !== 'WRAP' || !['add', 'sub', 'mul', 'neg', 'cast'].includes(s.operation))
121
+ return false;
122
+ if (typeof a !== 'bigint' || c === null || typeof c !== 'object')
123
+ return false;
124
+ let q, u, y;
125
+ try {
126
+ if (Object.getPrototypeOf(c) !== Object.prototype && Object.getPrototypeOf(c) !== null)
127
+ return false;
128
+ const ds = Object.getOwnPropertyDescriptors(c);
129
+ if (Reflect.ownKeys(ds).length !== 3 || !['quotient', 'residue', 'value'].every(k => own(ds, k) && own(ds[k], 'value') && typeof ds[k].value === 'bigint'))
130
+ return false;
131
+ q = ds.quotient.value;
132
+ u = ds.residue.value;
133
+ y = ds.value.value;
134
+ }
135
+ catch {
136
+ return false;
137
+ }
138
+ const m = 1n << BigInt(s.width), half = m >> 1n;
139
+ const lo = s.signed ? -half : 0n, hi = s.signed ? half - 1n : m - 1n;
140
+ if (s.operation !== 'cast' && (a < lo || a > hi))
141
+ return false;
142
+ if (binary(s.operation) ? typeof b !== 'bigint' || b < lo || b > hi : b !== undefined)
143
+ return false;
144
+ let raw;
145
+ switch (s.operation) {
146
+ case 'add':
147
+ raw = a + b;
148
+ break;
149
+ case 'sub':
150
+ raw = a - b;
151
+ break;
152
+ case 'mul':
153
+ raw = a * b;
154
+ break;
155
+ case 'neg':
156
+ raw = -a;
157
+ break;
158
+ case 'cast':
159
+ raw = a;
160
+ break;
161
+ case 'div':
162
+ case 'rem': return false;
163
+ }
164
+ return u >= 0n && u < m && raw === q * m + u &&
165
+ y === (s.signed && u >= half ? u - m : u) && y >= lo && y <= hi &&
166
+ raw - y === (q + (s.signed && u >= half ? 1n : 0n)) * m;
167
+ }
168
+ // Valid operands/results cross JSON as exact decimal strings. An invalid supplied
169
+ // operand is explicitly marked <invalid>, never silently changed into an absent one.
170
+ // Diagnostic receipts are not proof certificates and must not be accepted as such.
171
+ export function evaluatePrimitiveReceipt(spec, a, b) {
172
+ const parsed = snapshot(spec);
173
+ const result = parsed.ok ? evaluateSnapshot(parsed.spec, a, b) : fail(parsed.reason);
174
+ return {
175
+ spec: parsed.ok ? parsed.spec : null, a: typeof a === 'bigint' ? a.toString(10) : '<invalid>',
176
+ ...(b === undefined ? {} : { b: typeof b === 'bigint' ? b.toString(10) : '<invalid>' }),
177
+ result: result.ok ? { ok: true, value: result.value.toString(10) } : result,
178
+ };
179
+ }
@@ -16,6 +16,7 @@ export type Tree = {
16
16
  export type Goal = {
17
17
  name: string;
18
18
  hyps: C[];
19
+ wordDivision?: boolean;
19
20
  };
20
21
  export type Path = Map<string, {
21
22
  lin: Lin;
@@ -20,6 +20,7 @@
20
20
  import { checkRefutation } from "../core/check.js";
21
21
  import { observeCheckStep, observeTableCells } from "../core/meter.js";
22
22
  import { admittedLinearSub as rowSub, admittedLinearAdd as rowAdd, admittedLinearScale as rowScale, admittedLinearCopy as rowCopy, admittedLinearVariable as rowVariable, visitLinearCells } from "../core/linear-admission.js";
23
+ import { parseWordDivisionName, wordDivisionArgs, wordDivisionFacts } from "./word-division.js";
23
24
  import { fundedAdd as add, fundedConstant as k, fundedScale as scale, fundedSub as sub, fundedVariable as v, admittedLinearProduct, everyLinearCell } from "../core/linear-admission.js";
24
25
  import { workMap, workFilter, workConcat, workStrings, workJoin, workSlice, workSetArray, workEntries, workJSON, workFlatMap, workArraySlice } from "../core/work-collections.js";
25
26
  import { completeWorkProfile } from "../core/work-profile.js";
@@ -1123,7 +1124,33 @@ const across = (r, c, state, maps, first) => substC(c, {
1123
1124
  maps: Object.fromEntries(maps.map(map => [`${map}'`, (key) => { const f = own(r.at.maps, map); return f ? f(key) : { op: 'get', map, key }; }])),
1124
1125
  flags: first.flags,
1125
1126
  });
1126
- const goal = (name, r, conclusion) => ({ name, hyps: [...r.hyps, { op: 'not', x: conclusion }] });
1127
+ // A plain range/comparison goal does not need convolution hypotheses. Keeping
1128
+ // irrelevant products out avoids eagerly solving nonlinear constraints merely
1129
+ // to prove a digit bound. Omitting valid lemmas can only lose proofs, not invent
1130
+ // one. A reserved helper read is opaque here, even when its arguments compute.
1131
+ const divisionArithmetic = (x, seen = new Set()) => {
1132
+ if (!x || typeof x !== 'object' || seen.has(x))
1133
+ return false;
1134
+ seen.add(x);
1135
+ const t = x;
1136
+ if (t.op === 'get' && typeof t.map === 'string' && parseWordDivisionName(t.map))
1137
+ return false;
1138
+ if (t.op === 'prod' || t.op === 'add' || t.op === 'sub' || t.op === 'mul')
1139
+ return true;
1140
+ return Object.values(x).some(value => divisionArithmetic(value, seen));
1141
+ };
1142
+ const goal = (name, r, conclusion) => {
1143
+ const hyps = [...r.hyps, { op: 'not', x: conclusion }];
1144
+ // These are kernel-generated consequences of the reserved total Nat helpers,
1145
+ // never caller-supplied assumptions. Domain guards preserve invalid-input cases.
1146
+ const facts = wordDivisionFacts(hyps);
1147
+ if (!facts.length)
1148
+ return { name, hyps };
1149
+ const arithmetic = divisionArithmetic(conclusion);
1150
+ const theory = facts.filter(c => arithmetic || !divisionArithmetic(c));
1151
+ // Search treats the final hypothesis as the negated conclusion.
1152
+ return { name, hyps: [...r.hyps, ...theory, { op: 'not', x: conclusion }], wordDivision: true };
1153
+ };
1127
1154
  // A machine's flags as its terms read them (decided before the step, over the frame it starts from): a plain flag its
1128
1155
  // condition (through the flags before it), a quantified flag (one whose condition holds at every key) its 0/1 variable
1129
1156
  // ?f, which `closing` ties to the condition.
@@ -1202,10 +1229,17 @@ function reads(t, out = { vars: new Set(), maps: new Set(), flags: new Set() })
1202
1229
  out.vars.add(t.name);
1203
1230
  break;
1204
1231
  case 'const': break;
1205
- case 'get':
1206
- out.maps.add(t.map);
1232
+ case 'get': {
1233
+ const builtin = parseWordDivisionName(t.map);
1234
+ if (builtin) {
1235
+ if (!wordDivisionArgs(t.key, builtin.width))
1236
+ throw new Error('invalid compact word-division argument tuple');
1237
+ }
1238
+ else
1239
+ out.maps.add(t.map);
1207
1240
  reads(t.key, out);
1208
1241
  break;
1242
+ }
1209
1243
  case 'flag':
1210
1244
  out.flags.add(t.name);
1211
1245
  break;
@@ -1289,6 +1323,11 @@ export function scope(m, laws = []) {
1289
1323
  // (a count map is read as a map the request carries; a law reads the counts of the state, countsScope says which)
1290
1324
  const counts = Object.keys(m.counts ?? {}), carried = [...(m.inputMaps ?? []), ...counts];
1291
1325
  const names = [...m.params, ...m.inputs, ...state];
1326
+ // Intrinsic reads are interpreted before ordinary maps/functions in BOTH
1327
+ // runtimes. A declaration/write in this namespace must never impersonate one.
1328
+ for (const name of [...maps, ...carried, ...fns])
1329
+ if (name.startsWith('worddiv$'))
1330
+ throw new Error('worddiv$ is reserved for compact integer-division helpers');
1292
1331
  distinct(m.name, [...names, ...maps, ...carried, ...fns]);
1293
1332
  for (const name of [...names, ...maps, ...carried, ...fns, ...flags])
1294
1333
  plainName(m.name, name);
@@ -2272,10 +2311,10 @@ export function stepLawObligations(machine, laws, instances, sl) {
2272
2311
  if (sl.keys?.length && (!sl.forall || new Set([sl.forall, ...sl.keys]).size !== sl.keys.length + 1))
2273
2312
  throw new Error(`step law ${sl.name}: further keys come with a first, each a different name`);
2274
2313
  unquantified(`step law ${sl.name}`, sl.then);
2275
- inScope(`step law ${sl.name}`, [sl.then], [...taken, ...state.map(n => `${n}'`), ...later, ...(sl.forall ? [sl.forall] : []), ...(sl.keys ?? [])], [...maps, ...carried, ...maps.map(n => `${n}'`), ...laterMaps], flagNames);
2314
+ inScope(`step law ${sl.name}`, [sl.then], [...taken, ...state.map(n => `${n}'`), ...later, ...(sl.forall ? [sl.forall] : []), ...(sl.keys ?? [])], [...maps, ...carried, ...maps.map(n => `${n}'`), ...laterMaps, ...Object.keys(m.fns ?? {})], flagNames);
2276
2315
  for (const w of whens) {
2277
2316
  unquantified(`step law ${sl.name}'s when`, w);
2278
- inScope(`step law ${sl.name}'s when`, [w], taken, [...maps, ...carried], flagNames);
2317
+ inScope(`step law ${sl.name}'s when`, [w], taken, [...maps, ...carried, ...Object.keys(m.fns ?? {})], flagNames);
2279
2318
  }
2280
2319
  if (!naturalC(sl.then) || !whens.every(naturalC))
2281
2320
  throw new Error(`step law ${sl.name}: a negative constant or factor is outside the kernel`);
@@ -1,4 +1,5 @@
1
1
  import { retainFamily, retainFrom } from "../core/proof-output.js";
2
+ import { wordDivisionCuts } from "./word-division-cuts.js";
2
3
  import { checkWatchdog } from "../core/search-watchdog.js";
3
4
  // An untrusted prover for the kernel: grows a split tree until every leaf's constraints are refuted by solve(), splitting
4
5
  // on whatever atom the hypotheses leave open (an if's condition, a min's or ∸'s comparison, a disjunction's atoms, two
@@ -926,6 +927,18 @@ const tupledScope = () => !!eprScope.patterns && Object.values(eprScope.patterns
926
927
  // (a part of a wide goal by the EPR path first, its core widened to the part, else the usual search)
927
928
  const eprPart = (gp, until) => eprFirst(gp, { nodes: 0, until }) ?? grow(gp, new Map(), { nodes: 0, until });
928
929
  function growRoot(goal, path, budget) {
930
+ // Finite-model preflight can spend its whole share enumerating 16-bit digit
931
+ // ranges before noticing an immediate linear contradiction. Try the existing
932
+ // bounded plain search first for compact word goals. Only accept a proof tree
933
+ // (never a relaxed model); the same kernel checks it below as every other tree.
934
+ if (!path.size && !budget.nodes && goal.wordDivision) {
935
+ const local = wordDivisionCuts(goal, (g, p) => { const r = grow(g, p, budget); return 'tree' in r ? r.tree : undefined; }, widen);
936
+ if (local)
937
+ return { tree: local, nodes: budget.nodes };
938
+ const quick = growPlain(goal, path, { nodes: 0, until: budget.until, cap: 64 });
939
+ if ('tree' in quick)
940
+ return quick;
941
+ }
929
942
  const wide = !path.size && !budget.nodes && wideFor(goal), epr = !!eprScope.patterns && !eprScope.busy;
930
943
  // (a wide goal's parts by the EPR path too, where the goal is EPR-shaped)
931
944
  if (wide) {
@@ -0,0 +1,6 @@
1
+ import { type E } from '../core/machine.js';
2
+ import { type Goal, type Path, type Tree } from './kernel.js';
3
+ type Prove = (goal: Goal, path: Path) => Tree | undefined;
4
+ type Widen = (part: Goal, whole: Goal, tree: Tree, opaque: Record<string, E>, pp: Path, wp: Path) => Tree | undefined;
5
+ export declare function wordDivisionCuts(goal: Goal, prove: Prove, widen: Widen): Tree | undefined;
6
+ export {};
@@ -0,0 +1,69 @@
1
+ // Untrusted local lemmas: every branch and the final tree use the ordinary checker.
2
+ // Avoid combining four radix columns into an unsafe 2^64 intermediate by proving
3
+ // c_i = multiplicationCarry_i + additionCarry_i one column at a time.
4
+ import { walkOnce } from "../core/machine.js";
5
+ import { add, scale } from "../core/solver.js";
6
+ import { canon, check, linear } from "./kernel.js";
7
+ import { parseWordDivisionName, wordDivisionArgs, wordDivisionName } from "./word-division.js";
8
+ export function wordDivisionCuts(goal, prove, widen) {
9
+ let found, modular = false;
10
+ walkOnce(goal.hyps.at(-1), o => {
11
+ const e = o;
12
+ if (e.op !== 'get')
13
+ return;
14
+ if (e.map === 'mod$65536')
15
+ modular = true;
16
+ if (parseWordDivisionName(e.map)?.width === 64)
17
+ found ??= e;
18
+ });
19
+ if (!found || !modular)
20
+ return;
21
+ const key = found.key, args = wordDivisionArgs(key, 64);
22
+ if (!args)
23
+ return;
24
+ const zero = { op: 'const', value: 0 };
25
+ const sum = (xs) => xs.reduce((a, b) => ({ op: 'add', a, b }), zero);
26
+ const get = (part, i) => ({ op: 'get', map: wordDivisionName(64, part, i), key });
27
+ const call = (map, key) => ({ op: 'get', map, key });
28
+ let mp = zero, ap = zero;
29
+ const cuts = [];
30
+ for (let i = 0; i < 4; i++) {
31
+ const col = sum([mp, ...Array.from({ length: i + 1 }, (_, j) => ({ op: 'prod', a: get('q', j), b: args[4 + i - j] }))]);
32
+ const digit = call('mod$65536', col);
33
+ mp = call('div$65536', col);
34
+ ap = call('div$65536', sum([digit, get('r', i), ap]));
35
+ const a = get('c', i + 1), b = sum([mp, ap]), la = linear(a, new Map()), lb = linear(b, new Map());
36
+ if (!la || !lb)
37
+ return;
38
+ cuts.push({ a, b, lin: add(la, scale(lb, -1)) });
39
+ }
40
+ const branch = (p, lin, holds) => new Map(p).set(canon(lin), { lin, holds });
41
+ const ordinary = (g, p) => {
42
+ const tree = prove(g, p);
43
+ return tree && check(g, tree, p) ? tree : undefined;
44
+ };
45
+ const walk = (i, p) => {
46
+ if (i === cuts.length)
47
+ return ordinary(goal, p);
48
+ const cut = cuts[i], l = cut.lin, neg = scale(l, -1);
49
+ if (p.has(canon(l)) || p.has(canon(neg)) || Object.keys(l).every(k => k === '1'))
50
+ return;
51
+ const part = { name: `word carry ${i + 1}`, hyps: [...goal.hyps.slice(0, -1), { op: 'not', x: { op: '=', a: cut.a, b: cut.b } }] };
52
+ const noP = branch(p, l, false), yesP = branch(p, l, true), lowP = branch(yesP, neg, false), eqP = branch(yesP, neg, true);
53
+ const no = ordinary(part, noP), low = ordinary(part, lowP);
54
+ if (!no || !low)
55
+ return;
56
+ const noWide = widen(part, goal, no, {}, noP, noP), lowWide = widen(part, goal, low, {}, lowP, lowP);
57
+ if (!noWide || !lowWide)
58
+ return;
59
+ const rest = walk(i + 1, eqP);
60
+ return rest ? { split: l, yes: { split: neg, yes: rest, no: lowWide }, no: noWide } : undefined;
61
+ };
62
+ const d = linear(sum(args.slice(4)), new Map());
63
+ if (!d)
64
+ return;
65
+ const nonzero = add({ '1': 1 }, scale(d, -1)), yesP = branch(new Map(), nonzero, true), noP = branch(new Map(), nonzero, false);
66
+ const yes = walk(0, yesP), no = ordinary(goal, noP);
67
+ const tree = yes && no ? { split: nonzero, yes, no } : undefined;
68
+ return tree && check(goal, tree) ? tree : undefined;
69
+ }
@@ -0,0 +1,12 @@
1
+ import type { C, E } from '../core/machine.js';
2
+ export type WordDivisionSpec = {
3
+ width: 8 | 16 | 32 | 64;
4
+ part: 'q' | 'r' | 'c';
5
+ index: number;
6
+ };
7
+ export declare function wordDivisionName(width: WordDivisionSpec['width'], part: WordDivisionSpec['part'], index: number): string;
8
+ export declare function parseWordDivisionName(name: string): WordDivisionSpec | undefined;
9
+ export declare function wordDivisionKey(args: E[]): E;
10
+ export declare function wordDivisionArgs(key: E, width: WordDivisionSpec['width']): E[] | undefined;
11
+ export declare function wordDivisionValue(width: 8 | 16 | 32 | 64, part: 'q' | 'r' | 'c', index: number, values: number[]): number;
12
+ export declare function wordDivisionFacts(terms: unknown[]): C[];