gdp-wired 0.50.6 → 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.
- package/dist/core/dsl.d.ts +4 -1
- package/dist/core/dsl.js +47 -3
- package/dist/core/fixed-division.d.ts +9 -0
- package/dist/core/fixed-division.js +87 -0
- package/dist/core/fixed-integers.d.ts +33 -0
- package/dist/core/fixed-integers.js +279 -0
- package/dist/core/machine.d.ts +1 -0
- package/dist/core/machine.js +33 -3
- package/dist/kernel/integer-primitives.d.ts +38 -0
- package/dist/kernel/integer-primitives.js +179 -0
- package/dist/kernel/kernel.d.ts +1 -0
- package/dist/kernel/kernel.js +44 -5
- package/dist/kernel/prove.js +13 -0
- package/dist/kernel/word-division-cuts.d.ts +6 -0
- package/dist/kernel/word-division-cuts.js +69 -0
- package/dist/kernel/word-division.d.ts +12 -0
- package/dist/kernel/word-division.js +167 -0
- package/dist/lean-kernel/emit.d.ts +4 -1
- package/dist/lean-kernel/emit.js +36 -11
- package/dist/lean-kernel/integer-primitives.d.ts +17 -0
- package/dist/lean-kernel/integer-primitives.js +81 -0
- package/dist/lean-kernel/library.js +13 -0
- package/dist/lean-kernel/word-division-export.d.ts +26 -0
- package/dist/lean-kernel/word-division-export.js +172 -0
- package/dist/lean-kernel/word-division-lower.d.ts +10 -0
- package/dist/lean-kernel/word-division-lower.js +103 -0
- package/package.json +1 -1
package/dist/core/dsl.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { FixedWord } from './fixed-integers.js';
|
|
2
|
+
export { fixedInt, FixedWord, fixedFailure, fixedSelect } from './fixed-integers.js';
|
|
1
3
|
import { type TranslationFields } from './source-check.js';
|
|
2
4
|
import { type C, type E, type Fn, type Law, type Recurrence, type Machine, type Rand, type Request, type State, type Sum } from './machine.js';
|
|
3
5
|
import { type Fold, type Ghosted, type Goal, type Liveness, type Loop, type Recur, type StepLaw, type Tree } from '../kernel/kernel.js';
|
|
@@ -56,6 +58,7 @@ export declare function when<K extends string>(c: Cond, then: Choice<K>, otherwi
|
|
|
56
58
|
export declare function when(c: Cond, then: Str, otherwise: Str | string): Str;
|
|
57
59
|
export declare function when(c: Cond, then: string, otherwise: Str): Str;
|
|
58
60
|
export declare function when<V>(c: Cond, then: Maybe<V>, otherwise: Maybe<V>): Maybe<V>;
|
|
61
|
+
export declare function when(c: Cond, then: FixedWord, otherwise: FixedWord): FixedWord;
|
|
59
62
|
export declare function when(c: Cond, then: Cond, otherwise: Cond): Cond;
|
|
60
63
|
export declare function when<C extends Cases, T extends string>(c: Cond, then: Variant<C, T>, otherwise: Variant<C, T>): Variant<C, T>;
|
|
61
64
|
export declare function when<T extends Record<string, unknown>>(c: Cond, then: T, otherwise: T): T;
|
|
@@ -549,7 +552,7 @@ type ValuesOf<K extends Kinds> = {
|
|
|
549
552
|
[n in keyof K]: K[n] extends Kind<infer V> ? V : never;
|
|
550
553
|
};
|
|
551
554
|
type Obj = object;
|
|
552
|
-
type Writes<V> = V extends Decimal ? DecimalLike | string : V extends Int ? IntLike : V extends Cond ? Cond | boolean : V extends Choice<infer K> ? Choice<K> | K : V extends Maybe<infer W> ? Maybe<W> | Writes<W> | null : V extends Str ? Str | string : V extends Variant<infer C, infer T> ? Variant<C, T> | VariantWrite<C, T> : V extends Term ? TermLike : V extends Record<string, unknown> ? {
|
|
555
|
+
type Writes<V> = V extends FixedWord ? FixedWord : V extends Decimal ? DecimalLike | string : V extends Int ? IntLike : V extends Cond ? Cond | boolean : V extends Choice<infer K> ? Choice<K> | K : V extends Maybe<infer W> ? Maybe<W> | Writes<W> | null : V extends Str ? Str | string : V extends Variant<infer C, infer T> ? Variant<C, T> | VariantWrite<C, T> : V extends Term ? TermLike : V extends Record<string, unknown> ? {
|
|
553
556
|
[k in keyof V]: Writes<V[k]>;
|
|
554
557
|
} : TermLike;
|
|
555
558
|
type Update<S extends Obj, M extends Obj> = Partial<{
|
package/dist/core/dsl.js
CHANGED
|
@@ -17,6 +17,9 @@ import { searchNow as countedSearchNow } from "./wall.js";
|
|
|
17
17
|
//
|
|
18
18
|
// A step returns its updates as one object: every right-hand side reads the state before the step, as the kernel and
|
|
19
19
|
// both runtimes do.
|
|
20
|
+
import { FixedWord, fixedFailure, fixedSelect } from "./fixed-integers.js";
|
|
21
|
+
import { captureFixed } from "./fixed-division.js";
|
|
22
|
+
export { fixedInt, FixedWord, fixedFailure, fixedSelect } from "./fixed-integers.js";
|
|
20
23
|
import { binder, copyVariable, encodeBinders, generatedVariable, guardReserved, internalName, plainDeclaration, variable } from "./dsl-binders.js";
|
|
21
24
|
import { candidates, cone, searchCounted } from "./counts.js";
|
|
22
25
|
import { proveCandidateSeeds } from "./candidate-seeds.js";
|
|
@@ -129,6 +132,8 @@ export const not = (c) => c.not();
|
|
|
129
132
|
export const min = (a, b) => new Term({ op: 'min', a: termOf(a), b: termOf(b) }, both(valOf(a), valOf(b), Math.min));
|
|
130
133
|
export const max = (a, b) => new Term({ op: 'max', a: termOf(a), b: termOf(b) }, both(valOf(a), valOf(b), Math.max));
|
|
131
134
|
export function when(c, then, otherwise) {
|
|
135
|
+
if (then instanceof FixedWord && otherwise instanceof FixedWord)
|
|
136
|
+
return fixedSelect(c, then, otherwise);
|
|
132
137
|
if (then instanceof Cond && otherwise instanceof Cond)
|
|
133
138
|
return choose(c, then, otherwise);
|
|
134
139
|
if (then instanceof Variant && otherwise instanceof Variant) {
|
|
@@ -178,6 +183,8 @@ const isRecord = (x) => typeof x === 'object' && x !== null && Object.getPrototy
|
|
|
178
183
|
// missing in both or present in both and the same, a variant in the same case with the same fields, a record field by
|
|
179
184
|
// field.
|
|
180
185
|
export function same(a, b) {
|
|
186
|
+
if (a instanceof FixedWord && b instanceof FixedWord)
|
|
187
|
+
return a.eq(b);
|
|
181
188
|
if (a instanceof Cond && b instanceof Cond)
|
|
182
189
|
return a.iff(b);
|
|
183
190
|
if (a instanceof Choice && b instanceof Choice)
|
|
@@ -1954,7 +1961,8 @@ export class Rule {
|
|
|
1954
1961
|
const { kind, init: start } = x;
|
|
1955
1962
|
kinded.push([n, kind]);
|
|
1956
1963
|
if (typeof start === 'function') {
|
|
1957
|
-
const parts = (p) => kind.store(n,
|
|
1964
|
+
const parts = (p) => { const value = start(p); const stored = kind.store(n, value); if (Object.values(stored).some(t => { const f = fixedFailure(t); return f && f.ok !== false; }))
|
|
1965
|
+
throw new Error(`primitive traps in initializer ${n} are not supported`); return stored; };
|
|
1958
1966
|
for (const part of kind.vars(n))
|
|
1959
1967
|
entries.push([part, p => parts(p)[part]]);
|
|
1960
1968
|
}
|
|
@@ -2457,7 +2465,31 @@ export class Rule {
|
|
|
2457
2465
|
if (!(n in flags))
|
|
2458
2466
|
flags[n] = out;
|
|
2459
2467
|
}
|
|
2460
|
-
const
|
|
2468
|
+
const capturedFixed = captureFixed(() => s.step?.(env));
|
|
2469
|
+
for (const [name, condition] of Object.entries(capturedFixed.flags)) {
|
|
2470
|
+
if (name in env || Object.hasOwn(flags, name))
|
|
2471
|
+
throw new Error(`${s.name}: fixed division flag collision ${name}`);
|
|
2472
|
+
flags[name] = condition;
|
|
2473
|
+
}
|
|
2474
|
+
const updates = { ...capturedFixed.value };
|
|
2475
|
+
// Preserve primitive effects before a kind flattens its value into natural limbs.
|
|
2476
|
+
const primitiveFailures = [], seenPrimitive = new Set(), seenFailure = new Set();
|
|
2477
|
+
const inspectPrimitive = (value) => {
|
|
2478
|
+
if (!value || typeof value !== 'object' || seenPrimitive.has(value))
|
|
2479
|
+
return;
|
|
2480
|
+
seenPrimitive.add(value);
|
|
2481
|
+
const failure = fixedFailure(value);
|
|
2482
|
+
if (failure && !seenFailure.has(failure.c)) {
|
|
2483
|
+
seenFailure.add(failure.c);
|
|
2484
|
+
primitiveFailures.push(failure.c);
|
|
2485
|
+
}
|
|
2486
|
+
if (Object.getPrototypeOf(value) === Object.prototype || Array.isArray(value))
|
|
2487
|
+
Object.values(value).forEach(inspectPrimitive);
|
|
2488
|
+
};
|
|
2489
|
+
Object.values(updates).forEach(inspectPrimitive);
|
|
2490
|
+
const primitiveFailure = primitiveFailures.length ? { op: 'or', xs: primitiveFailures } : undefined;
|
|
2491
|
+
if (primitiveFailure && (s.record || s.counts?.length || s.sums.length || s.ghost))
|
|
2492
|
+
throw new Error(`${s.name}: primitive traps with history, counts, sums or ghosts are not yet supported`);
|
|
2461
2493
|
// A kinded variable's update, as its variables' terms.
|
|
2462
2494
|
for (const [n, k] of s.kinded ?? []) {
|
|
2463
2495
|
const u = updates[n];
|
|
@@ -2479,6 +2511,17 @@ export class Rule {
|
|
|
2479
2511
|
else
|
|
2480
2512
|
state[n] = hoist.term(termOf(u));
|
|
2481
2513
|
}
|
|
2514
|
+
// A failure is retained as a stuttering branch for kernel obligations, not
|
|
2515
|
+
// assumed away. Runtime evaluation throws before any scalar/map/history write.
|
|
2516
|
+
if (primitiveFailure) {
|
|
2517
|
+
for (const [name, value] of Object.entries(state))
|
|
2518
|
+
state[name] = { op: 'if', c: primitiveFailure, then: variable(name), else: value };
|
|
2519
|
+
for (const [name, write] of Object.entries(maps)) {
|
|
2520
|
+
if ('each' in write)
|
|
2521
|
+
throw new Error(`${s.name}: primitive traps in per-key writes are not yet supported`);
|
|
2522
|
+
maps[name] = { ...write, value: { op: 'if', c: primitiveFailure, then: { op: 'get', map: name, key: write.key }, else: write.value } };
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2482
2525
|
// An existential in a precondition or the assumption: a value the params or the request bring (a param or an input
|
|
2483
2526
|
// the runtimes find, encodeParams and encodeInput), fresh for each existential and, for a request, each step.
|
|
2484
2527
|
const pre0 = pulledOut(s.pre.map(f => f(pEnv)), `${s.name}: a precondition`, 'some$p'), as0 = pulledOut(s.assume.map(f => f(env)), `${s.name}: the assumption`, 'some$a');
|
|
@@ -2516,6 +2559,7 @@ export class Rule {
|
|
|
2516
2559
|
];
|
|
2517
2560
|
const m = {
|
|
2518
2561
|
name: s.name, params, inputs,
|
|
2562
|
+
...(primitiveFailure ? { primitiveFailure } : {}),
|
|
2519
2563
|
state: Object.fromEntries(s.state.map(([n, init]) => [n, typeof init === 'number' ? termOf(init) : termOf(init(pEnv))])),
|
|
2520
2564
|
...(s.maps.length ? { maps: Object.fromEntries(s.maps) } : {}),
|
|
2521
2565
|
...(s.carried?.length ? { inputMaps: s.carried } : {}),
|
|
@@ -3346,7 +3390,7 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
|
|
|
3346
3390
|
return undefined;
|
|
3347
3391
|
}
|
|
3348
3392
|
// The kernel's report as a verdict: its first goal left unproven, with its counterexample and why.
|
|
3349
|
-
export const verdictOf = (out) => retainFrom(({ proven: out.proven, checked: out.checked, ...(out.failed ? { goal: out.failed.goal, stuck: out.failed.stuck, ...(out.failed.witness ? { witness: out.failed.witness } : {}), ...(out.failed.why ? { why: out.failed.why } : {}) } : {}) }), [out]);
|
|
3393
|
+
export const verdictOf = (out) => retainFrom(({ proven: out.proven && out.checked, checked: out.checked, ...(out.failed ? { goal: out.failed.goal, stuck: out.failed.stuck, ...(out.failed.witness ? { witness: out.failed.witness } : {}), ...(out.failed.why ? { why: out.failed.why } : {}) } : {}), ...(out.proven && !out.checked ? { stuck: 'unknown', why: 'kernel rejected the candidate proof' } : {}) }), [out]);
|
|
3350
3394
|
const refutedVerdict = (out) => ({ proven: false, checked: false, goal: out.goal, stuck: 'sat', witness: out.witness, ...(out.run ? { run: out.run } : {}) });
|
|
3351
3395
|
// The divisors some laws read (modBy, divBy), noted on the rule so its machine declares them: a law may come from
|
|
3352
3396
|
// another instance of the same rule (a factory called twice).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { FixedWord, type DivisionRounding, type Overflow } from './fixed-integers.js';
|
|
2
|
+
import { Cond } from './dsl.js';
|
|
3
|
+
export { wordDivisionKey, wordDivisionName } from '../kernel/word-division.js';
|
|
4
|
+
type C = Cond['c'];
|
|
5
|
+
export declare function captureFixed<T>(f: () => T): {
|
|
6
|
+
value: T;
|
|
7
|
+
flags: Record<string, C>;
|
|
8
|
+
};
|
|
9
|
+
export declare function divideFixed(a: FixedWord, b: FixedWord, rounding: DivisionRounding, mode: Overflow, remainder: boolean): FixedWord;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { FixedWord, fixedSelect } from "./fixed-integers.js";
|
|
2
|
+
import { Term, all, any, lit } from "./dsl.js";
|
|
3
|
+
import { wordDivisionKey, wordDivisionName } from "../kernel/word-division.js";
|
|
4
|
+
export { wordDivisionKey, wordDivisionName } from "../kernel/word-division.js";
|
|
5
|
+
// Preserve the capture API for DSL assembly; intrinsic getters need no flags.
|
|
6
|
+
let active;
|
|
7
|
+
export function captureFixed(f) {
|
|
8
|
+
const previous = active, flags = Object.create(null);
|
|
9
|
+
active = flags;
|
|
10
|
+
try {
|
|
11
|
+
return { value: f(), flags };
|
|
12
|
+
}
|
|
13
|
+
finally {
|
|
14
|
+
active = previous;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
const zero = () => lit(0);
|
|
18
|
+
const no = () => zero().eq(1);
|
|
19
|
+
const radixOf = (a) => a.width === 8 ? 256 : 65536;
|
|
20
|
+
const pure = (w, signed = w.signed) => new FixedWord(w.width, signed, w.limbs);
|
|
21
|
+
const same = (a, b) => all(...a.map((x, i) => x.eq(b[i])));
|
|
22
|
+
const nonzero = (a) => any(...a.map(x => x.ne(0)));
|
|
23
|
+
const neg = (a) => pure(a).negate('WRAP');
|
|
24
|
+
const sign = (a) => a.limbs[a.limbs.length - 1].atLeast(radixOf(a) / 2);
|
|
25
|
+
// Intrinsic quotients and residues are keyed by both unsigned magnitudes.
|
|
26
|
+
// Known inputs use BigInt for metadata; symbolic limbs leave val undefined.
|
|
27
|
+
const magnitude = (limbs, radix) => {
|
|
28
|
+
let value = 0n;
|
|
29
|
+
for (let i = limbs.length - 1; i >= 0; i--) {
|
|
30
|
+
const digit = limbs[i].val;
|
|
31
|
+
if (digit === undefined)
|
|
32
|
+
return undefined;
|
|
33
|
+
value = value * radix + BigInt(digit);
|
|
34
|
+
}
|
|
35
|
+
return value;
|
|
36
|
+
};
|
|
37
|
+
const select = (c, a, b) => fixedSelect(c, a, b);
|
|
38
|
+
export function divideFixed(a, b, rounding, mode, remainder) {
|
|
39
|
+
if (!(a instanceof FixedWord) || !(b instanceof FixedWord) || a.width !== b.width || a.signed !== b.signed)
|
|
40
|
+
throw new TypeError('fixed integers must have identical width and signedness');
|
|
41
|
+
if (!['WRAP', 'SATURATE', 'TRAP'].includes(mode))
|
|
42
|
+
throw new RangeError('an explicit overflow mode is required');
|
|
43
|
+
if (!['FLOOR', 'TRUNCATING', 'EUCLIDEAN'].includes(rounding))
|
|
44
|
+
throw new RangeError('unknown division rounding');
|
|
45
|
+
if (!active)
|
|
46
|
+
throw new Error('symbolic fixed integer division requires captureFixed');
|
|
47
|
+
const radix = radixOf(a), n = a.limbs.length;
|
|
48
|
+
const aa = pure(a), bb = pure(b);
|
|
49
|
+
const aNeg = a.signed ? sign(aa) : no(), bNeg = b.signed ? sign(bb) : no();
|
|
50
|
+
const am = pure(a.signed ? select(aNeg, neg(aa), aa) : aa, false);
|
|
51
|
+
const bm = pure(b.signed ? select(bNeg, neg(bb), bb) : bb, false);
|
|
52
|
+
const key = wordDivisionKey([...am.limbs, ...bm.limbs].map(x => x.e));
|
|
53
|
+
const av = magnitude(am.limbs, BigInt(radix)), bv = magnitude(bm.limbs, BigInt(radix));
|
|
54
|
+
if (bv === 0n)
|
|
55
|
+
return new FixedWord(a.width, a.signed, Array.from({ length: n }, zero), zero().eq(0));
|
|
56
|
+
const qv = av === undefined || bv === undefined ? undefined : av / bv;
|
|
57
|
+
const rv = av === undefined || bv === undefined ? undefined : av % bv;
|
|
58
|
+
const digits = (kind, value) => Array.from({ length: n }, (_, i) => new Term({ op: 'get', map: wordDivisionName(a.width, kind, i), key }, value === undefined ? undefined : Number(value / (BigInt(radix) ** BigInt(i)) % BigInt(radix))));
|
|
59
|
+
const uq = new FixedWord(a.width, false, digits('q', qv));
|
|
60
|
+
const ur = new FixedWord(a.width, false, digits('r', rv));
|
|
61
|
+
const qNegative = a.signed ? aNeg.iff(bNeg).not() : no();
|
|
62
|
+
let q = a.signed ? select(qNegative, neg(pure(uq, true)), pure(uq, true)) : uq;
|
|
63
|
+
let r = a.signed ? select(aNeg, neg(pure(ur, true)), pure(ur, true)) : ur;
|
|
64
|
+
const rNotZero = nonzero(ur.limbs);
|
|
65
|
+
if (a.signed && rounding === 'FLOOR') {
|
|
66
|
+
const adjust = all(rNotZero, qNegative);
|
|
67
|
+
q = select(adjust, q.minus(new FixedWord(a.width, true, [lit(1), ...Array.from({ length: n - 1 }, zero)]), 'WRAP'), q);
|
|
68
|
+
r = select(adjust, r.plus(bb, 'WRAP'), r);
|
|
69
|
+
}
|
|
70
|
+
else if (a.signed && rounding === 'EUCLIDEAN') {
|
|
71
|
+
const adjust = all(rNotZero, aNeg);
|
|
72
|
+
const one = new FixedWord(a.width, true, [lit(1), ...Array.from({ length: n - 1 }, zero)]);
|
|
73
|
+
q = select(adjust, select(bNeg, q.plus(one, 'WRAP'), q.minus(one, 'WRAP')), q);
|
|
74
|
+
r = select(adjust, r.plus(pure(bm, true), 'WRAP'), r);
|
|
75
|
+
}
|
|
76
|
+
const minimum = Array.from({ length: n }, (_, i) => lit(i === n - 1 ? radix / 2 : 0));
|
|
77
|
+
const maximum = Array.from({ length: n }, (_, i) => lit(i === n - 1 ? radix / 2 - 1 : radix - 1));
|
|
78
|
+
const overflow = a.signed ? all(aNeg, same(a.limbs, minimum), same(b.limbs, Array.from({ length: n }, () => lit(radix - 1)))) : no();
|
|
79
|
+
if (a.signed) {
|
|
80
|
+
const min = new FixedWord(a.width, true, minimum);
|
|
81
|
+
const max = new FixedWord(a.width, true, maximum);
|
|
82
|
+
q = select(overflow, mode === 'SATURATE' ? max : min, q);
|
|
83
|
+
r = select(overflow, new FixedWord(a.width, true, Array.from({ length: n }, zero)), r);
|
|
84
|
+
}
|
|
85
|
+
const failure = any(...[a.failure, b.failure, nonzero(b.limbs).not(), mode === 'TRAP' ? overflow : undefined].filter((x) => !!x));
|
|
86
|
+
return new FixedWord(a.width, a.signed, (remainder ? r : q).limbs, failure);
|
|
87
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { Kind, Term, Cond, type Raw } from './dsl.js';
|
|
2
|
+
export type FixedWidth = 8 | 16 | 32 | 64;
|
|
3
|
+
export type Overflow = 'WRAP' | 'SATURATE' | 'TRAP';
|
|
4
|
+
export type DivisionRounding = 'FLOOR' | 'TRUNCATING' | 'EUCLIDEAN';
|
|
5
|
+
export declare class FixedWord {
|
|
6
|
+
readonly width: FixedWidth;
|
|
7
|
+
readonly signed: boolean;
|
|
8
|
+
readonly limbs: readonly Term[];
|
|
9
|
+
readonly failure?: Cond | undefined;
|
|
10
|
+
constructor(width: FixedWidth, signed: boolean, limbs: readonly Term[], failure?: Cond | undefined);
|
|
11
|
+
private check;
|
|
12
|
+
private finish;
|
|
13
|
+
private checkComparison;
|
|
14
|
+
eq(b: FixedWord): Cond;
|
|
15
|
+
ne(b: FixedWord): Cond;
|
|
16
|
+
lt(b: FixedWord): Cond;
|
|
17
|
+
atMost(b: FixedWord): Cond;
|
|
18
|
+
gt(b: FixedWord): Cond;
|
|
19
|
+
atLeast(b: FixedWord): Cond;
|
|
20
|
+
plus(b: FixedWord, mode: Overflow): FixedWord;
|
|
21
|
+
minus(b: FixedWord, mode: Overflow): FixedWord;
|
|
22
|
+
negate(mode: Overflow): FixedWord;
|
|
23
|
+
mul(b: FixedWord, mode: Overflow): FixedWord;
|
|
24
|
+
cast(width: FixedWidth, signed: boolean, mode: Overflow): FixedWord;
|
|
25
|
+
div(b: FixedWord, rounding: DivisionRounding, mode: Overflow): FixedWord;
|
|
26
|
+
rem(b: FixedWord, rounding: DivisionRounding, mode: Overflow): FixedWord;
|
|
27
|
+
private divide;
|
|
28
|
+
}
|
|
29
|
+
export declare const fixedFailure: (value: unknown) => Cond | undefined;
|
|
30
|
+
export declare const fixedSelect: (condition: Cond, a: FixedWord, b: FixedWord) => FixedWord;
|
|
31
|
+
export declare const fixedInt: (width: FixedWidth, signed: boolean) => Kind<FixedWord> & {
|
|
32
|
+
lift(value: Raw | bigint): FixedWord;
|
|
33
|
+
};
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { Kind, Term, lit, when, all, any } from "./dsl.js";
|
|
2
|
+
import { divideFixed } from "./fixed-division.js";
|
|
3
|
+
const validKind = (width, signed) => {
|
|
4
|
+
if (![8, 16, 32, 64].includes(width))
|
|
5
|
+
throw new RangeError('fixed width must be 8, 16, 32, or 64');
|
|
6
|
+
if (typeof signed !== 'boolean')
|
|
7
|
+
throw new TypeError('fixed signedness must be boolean');
|
|
8
|
+
};
|
|
9
|
+
const base = (w) => w === 8 ? 256 : 65536;
|
|
10
|
+
const digits = (w) => w === 8 ? 1 : w / 16;
|
|
11
|
+
const falseCond = () => lit(0).eq(1);
|
|
12
|
+
// Store lowers a word to plain Terms. Keep its failure on fresh wrappers rather
|
|
13
|
+
// than mutating the shared limbs, which may also belong to an untrapped word.
|
|
14
|
+
const storedTermFailures = new WeakMap();
|
|
15
|
+
const validMode = (mode) => {
|
|
16
|
+
if (mode !== 'WRAP' && mode !== 'SATURATE' && mode !== 'TRAP')
|
|
17
|
+
throw new RangeError('an explicit overflow mode is required');
|
|
18
|
+
};
|
|
19
|
+
const failures = (...cs) => {
|
|
20
|
+
const present = cs.filter((c) => c !== undefined);
|
|
21
|
+
return present.length ? any(...present) : undefined;
|
|
22
|
+
};
|
|
23
|
+
const select = (c, a, b) => a.map((x, i) => when(c, x, b[i]));
|
|
24
|
+
const constant = (w, signed, value) => {
|
|
25
|
+
const mod = 1n << BigInt(w);
|
|
26
|
+
let x = ((value % mod) + mod) % mod;
|
|
27
|
+
const radix = BigInt(base(w));
|
|
28
|
+
return Array.from({ length: digits(w) }, () => { const d = Number(x % radix); x /= radix; return lit(d); });
|
|
29
|
+
};
|
|
30
|
+
const equal = (a, b) => all(...a.map((x, i) => x.eq(b[i])));
|
|
31
|
+
const less = (a, b) => {
|
|
32
|
+
let result = falseCond();
|
|
33
|
+
for (let i = 0; i < a.length; i++)
|
|
34
|
+
result = any(a[i].lt(b[i]), all(a[i].eq(b[i]), result));
|
|
35
|
+
return result;
|
|
36
|
+
};
|
|
37
|
+
const addRaw = (a, b, radix) => {
|
|
38
|
+
let carry = lit(0);
|
|
39
|
+
const low = [];
|
|
40
|
+
for (let i = 0; i < a.length; i++) {
|
|
41
|
+
const sum = a[i].plus(b[i]).plus(carry); // at most 2*65535+1
|
|
42
|
+
low.push(sum.modBy(radix));
|
|
43
|
+
carry = sum.divBy(radix);
|
|
44
|
+
}
|
|
45
|
+
return { low, carry };
|
|
46
|
+
};
|
|
47
|
+
const invert = (xs, radix) => xs.map(x => lit(radix - 1).minus(x));
|
|
48
|
+
const negateRaw = (xs, radix) => addRaw(invert(xs, radix), [lit(1), ...Array.from({ length: xs.length - 1 }, () => lit(0))], radix).low;
|
|
49
|
+
const signOf = (xs, radix) => xs[xs.length - 1].atLeast(radix / 2);
|
|
50
|
+
const magnitude = (xs, radix, negative) => select(negative, negateRaw(xs, radix), xs);
|
|
51
|
+
const maxWord = (w, signed) => constant(w, signed, (1n << BigInt(w - (signed ? 1 : 0))) - 1n);
|
|
52
|
+
const minWord = (w, signed) => constant(w, signed, signed ? -(1n << BigInt(w - 1)) : 0n);
|
|
53
|
+
const rawBigInt = (w, signed, xs) => {
|
|
54
|
+
if (xs.some(x => x.val === undefined))
|
|
55
|
+
return undefined;
|
|
56
|
+
let n = 0n;
|
|
57
|
+
for (let i = xs.length - 1; i >= 0; i--)
|
|
58
|
+
n = n * BigInt(base(w)) + BigInt(xs[i].val);
|
|
59
|
+
return signed && n >= (1n << BigInt(w - 1)) ? n - (1n << BigInt(w)) : n;
|
|
60
|
+
};
|
|
61
|
+
const parse = (w, signed, raw) => {
|
|
62
|
+
if (typeof raw === 'number') {
|
|
63
|
+
if (w === 64 || !Number.isSafeInteger(raw))
|
|
64
|
+
throw new RangeError('unsafe or 64-bit number: use a decimal string or bigint');
|
|
65
|
+
}
|
|
66
|
+
else if (typeof raw !== 'string' && typeof raw !== 'bigint')
|
|
67
|
+
throw new TypeError('fixed integer requires an integer or decimal string');
|
|
68
|
+
if (typeof raw === 'string' && !/^-?(0|[1-9][0-9]*)$/.test(raw))
|
|
69
|
+
throw new RangeError('fixed integer requires a decimal integer string');
|
|
70
|
+
const n = BigInt(raw);
|
|
71
|
+
const lo = signed ? -(1n << BigInt(w - 1)) : 0n;
|
|
72
|
+
const hi = (1n << BigInt(w - (signed ? 1 : 0))) - 1n;
|
|
73
|
+
if (n < lo || n > hi)
|
|
74
|
+
throw new RangeError(`${n} outside ${signed ? 'signed' : 'unsigned'} ${w}-bit range`);
|
|
75
|
+
return n;
|
|
76
|
+
};
|
|
77
|
+
export class FixedWord {
|
|
78
|
+
width;
|
|
79
|
+
signed;
|
|
80
|
+
limbs;
|
|
81
|
+
failure;
|
|
82
|
+
constructor(width, signed, limbs, failure) {
|
|
83
|
+
this.width = width;
|
|
84
|
+
this.signed = signed;
|
|
85
|
+
this.limbs = limbs;
|
|
86
|
+
this.failure = failure;
|
|
87
|
+
validKind(width, signed);
|
|
88
|
+
if (limbs.length !== digits(width))
|
|
89
|
+
throw new RangeError('incorrect fixed integer limb count');
|
|
90
|
+
}
|
|
91
|
+
check(other) {
|
|
92
|
+
if (!(other instanceof FixedWord))
|
|
93
|
+
throw new TypeError('fixed integer operand required');
|
|
94
|
+
if (this.width !== other.width || this.signed !== other.signed)
|
|
95
|
+
throw new TypeError('fixed integers must have identical width and signedness; cast explicitly');
|
|
96
|
+
}
|
|
97
|
+
finish(low, overflow, mode, negative, inherited) {
|
|
98
|
+
validMode(mode);
|
|
99
|
+
const result = mode === 'SATURATE' ? select(overflow, select(negative, minWord(this.width, this.signed), maxWord(this.width, this.signed)), low) : low;
|
|
100
|
+
return new FixedWord(this.width, this.signed, result, failures(inherited, mode === 'TRAP' ? overflow : undefined));
|
|
101
|
+
}
|
|
102
|
+
checkComparison(b) {
|
|
103
|
+
this.check(b);
|
|
104
|
+
// A Cond has no failure channel. A comparison of a possibly trapped result
|
|
105
|
+
// must not erase its failure and accidentally establish a law about that result.
|
|
106
|
+
if ((this.failure && this.failure.ok !== false) || (b.failure && b.failure.ok !== false))
|
|
107
|
+
throw new Error('fixed integer comparison may discard a failure; handle the failure first');
|
|
108
|
+
}
|
|
109
|
+
eq(b) { this.checkComparison(b); return equal(this.limbs, b.limbs); }
|
|
110
|
+
ne(b) { return this.eq(b).not(); }
|
|
111
|
+
lt(b) {
|
|
112
|
+
this.checkComparison(b);
|
|
113
|
+
const aNeg = this.signed ? signOf(this.limbs, base(this.width)) : falseCond();
|
|
114
|
+
const bNeg = this.signed ? signOf(b.limbs, base(this.width)) : falseCond();
|
|
115
|
+
return this.signed ? any(all(aNeg, bNeg.not()), all(aNeg.iff(bNeg), less(this.limbs, b.limbs))) : less(this.limbs, b.limbs);
|
|
116
|
+
}
|
|
117
|
+
atMost(b) { return any(this.lt(b), this.eq(b)); }
|
|
118
|
+
gt(b) { return b.lt(this); }
|
|
119
|
+
atLeast(b) { return b.atMost(this); }
|
|
120
|
+
plus(b, mode) {
|
|
121
|
+
validMode(mode);
|
|
122
|
+
this.check(b);
|
|
123
|
+
const { low, carry } = addRaw(this.limbs, b.limbs, base(this.width));
|
|
124
|
+
const na = signOf(this.limbs, base(this.width)), nb = signOf(b.limbs, base(this.width)), nr = signOf(low, base(this.width));
|
|
125
|
+
const over = this.signed ? all(na.iff(nb), na.iff(nr).not()) : carry.eq(1);
|
|
126
|
+
return this.finish(low, over, mode, this.signed ? na : falseCond(), failures(this.failure, b.failure));
|
|
127
|
+
}
|
|
128
|
+
minus(b, mode) {
|
|
129
|
+
validMode(mode);
|
|
130
|
+
this.check(b);
|
|
131
|
+
// Add the complement and one; carry=0 iff unsigned subtraction borrowed.
|
|
132
|
+
const radix = base(this.width);
|
|
133
|
+
const complement = invert(b.limbs, radix);
|
|
134
|
+
const { low, carry } = addRaw(this.limbs, complement, radix);
|
|
135
|
+
const incremented = addRaw(low, [lit(1), ...Array.from({ length: low.length - 1 }, () => lit(0))], radix);
|
|
136
|
+
const noBorrow = any(carry.eq(1), incremented.carry.eq(1));
|
|
137
|
+
const na = signOf(this.limbs, radix), nb = signOf(b.limbs, radix), nr = signOf(incremented.low, radix);
|
|
138
|
+
const over = this.signed ? all(na.iff(nb).not(), nr.iff(na).not()) : noBorrow.not();
|
|
139
|
+
return this.finish(incremented.low, over, mode, this.signed ? na : lit(0).eq(0), failures(this.failure, b.failure));
|
|
140
|
+
}
|
|
141
|
+
negate(mode) { return new FixedWord(this.width, this.signed, constant(this.width, this.signed, 0n)).minus(this, mode); }
|
|
142
|
+
mul(b, mode) {
|
|
143
|
+
validMode(mode);
|
|
144
|
+
this.check(b);
|
|
145
|
+
const radix = base(this.width), n = this.limbs.length;
|
|
146
|
+
const an = this.signed ? signOf(this.limbs, radix) : falseCond();
|
|
147
|
+
const bn = this.signed ? signOf(b.limbs, radix) : falseCond();
|
|
148
|
+
const a = this.signed ? magnitude(this.limbs, radix, an) : this.limbs;
|
|
149
|
+
const bb = this.signed ? magnitude(b.limbs, radix, bn) : b.limbs;
|
|
150
|
+
const out = [];
|
|
151
|
+
let carry = lit(0);
|
|
152
|
+
for (let k = 0; k < 2 * n; k++) {
|
|
153
|
+
let col = carry;
|
|
154
|
+
for (let i = Math.max(0, k - n + 1); i <= Math.min(k, n - 1); i++)
|
|
155
|
+
col = col.plus(a[i].mul(bb[k - i]));
|
|
156
|
+
// At most 4*65535²+4*65535 < 2^35; no intermediate exceeds 2^53.
|
|
157
|
+
out.push(col.modBy(radix));
|
|
158
|
+
carry = col.divBy(radix);
|
|
159
|
+
}
|
|
160
|
+
const productNegative = an.iff(bn).not();
|
|
161
|
+
const upper = out.slice(n);
|
|
162
|
+
const limit = constant(this.width, this.signed, 1n << BigInt(this.width - 1));
|
|
163
|
+
const positiveLimit = maxWord(this.width, this.signed);
|
|
164
|
+
const magnitudeLow = out.slice(0, n);
|
|
165
|
+
const high = any(...upper.map(x => x.ne(0)));
|
|
166
|
+
const overflow = this.signed
|
|
167
|
+
? any(high, all(productNegative, less(limit, magnitudeLow)), all(productNegative.not(), less(positiveLimit, magnitudeLow)))
|
|
168
|
+
: high;
|
|
169
|
+
const low = this.signed ? select(productNegative, negateRaw(magnitudeLow, radix), magnitudeLow) : magnitudeLow;
|
|
170
|
+
return this.finish(low, overflow, mode, productNegative, failures(this.failure, b.failure));
|
|
171
|
+
}
|
|
172
|
+
cast(width, signed, mode) {
|
|
173
|
+
validMode(mode);
|
|
174
|
+
validKind(width, signed);
|
|
175
|
+
const radix = base(this.width), negative = this.signed ? signOf(this.limbs, radix) : falseCond();
|
|
176
|
+
const mag = this.signed ? magnitude(this.limbs, radix, negative) : this.limbs;
|
|
177
|
+
// Conversion of limbs uses only <=65535*256 and division by the constant radix.
|
|
178
|
+
let source = mag;
|
|
179
|
+
if (radix !== base(width))
|
|
180
|
+
source = width === 8 ? [mag[0].modBy(256)] : [mag[0]];
|
|
181
|
+
const low = Array.from({ length: digits(width) }, (_, i) => source[i] ?? lit(0));
|
|
182
|
+
const sourceHigh = mag.slice(digits(width));
|
|
183
|
+
const high = any(...sourceHigh.map(x => x.ne(0)), ...(radix !== base(width) && width === 8 ? [mag[0].divBy(256).ne(0)] : []));
|
|
184
|
+
const limit = signed ? constant(width, true, 1n << BigInt(width - 1)) : maxWord(width, false);
|
|
185
|
+
const overflow = any(high, all(negative, signed ? less(limit, low) : lit(0).eq(0)), all(negative.not(), less(signed ? maxWord(width, true) : maxWord(width, false), low)));
|
|
186
|
+
const twos = negative.ok === false ? low : select(negative, negateRaw(low, base(width)), low);
|
|
187
|
+
const result = mode === 'SATURATE' ? select(overflow, select(negative, minWord(width, signed), maxWord(width, signed)), twos) : twos;
|
|
188
|
+
return new FixedWord(width, signed, result, failures(this.failure, mode === 'TRAP' ? overflow : undefined));
|
|
189
|
+
}
|
|
190
|
+
div(b, rounding, mode) { return this.divide(b, rounding, mode, false); }
|
|
191
|
+
rem(b, rounding, mode) { return this.divide(b, rounding, mode, true); }
|
|
192
|
+
divide(b, rounding, mode, remainder) {
|
|
193
|
+
this.check(b);
|
|
194
|
+
validMode(mode);
|
|
195
|
+
if (!['FLOOR', 'TRUNCATING', 'EUCLIDEAN'].includes(rounding))
|
|
196
|
+
throw new RangeError('unknown division rounding');
|
|
197
|
+
const aVal = rawBigInt(this.width, this.signed, this.limbs);
|
|
198
|
+
const bVal = rawBigInt(b.width, b.signed, b.limbs);
|
|
199
|
+
if (aVal === undefined || bVal === undefined)
|
|
200
|
+
return divideFixed(this, b, rounding, mode, remainder);
|
|
201
|
+
const min = this.signed ? -(1n << BigInt(this.width - 1)) : 0n;
|
|
202
|
+
const zero = bVal === 0n;
|
|
203
|
+
const overflow = this.signed && aVal === min && bVal === -1n;
|
|
204
|
+
let q = zero ? 0n : aVal / bVal;
|
|
205
|
+
let r = zero ? 0n : aVal % bVal;
|
|
206
|
+
if (!zero && r !== 0n) {
|
|
207
|
+
if (rounding === 'FLOOR' && ((r < 0n) !== (bVal < 0n))) {
|
|
208
|
+
q--;
|
|
209
|
+
r += bVal;
|
|
210
|
+
}
|
|
211
|
+
if (rounding === 'EUCLIDEAN' && r < 0n) {
|
|
212
|
+
q -= bVal < 0n ? -1n : 1n;
|
|
213
|
+
r += bVal < 0n ? -bVal : bVal;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (overflow) {
|
|
217
|
+
q = mode === 'SATURATE' ? -min - 1n : min;
|
|
218
|
+
r = 0n;
|
|
219
|
+
}
|
|
220
|
+
const divZero = zero ? lit(0).eq(0) : falseCond();
|
|
221
|
+
const trapOverflow = overflow && mode === 'TRAP' ? lit(0).eq(0) : undefined;
|
|
222
|
+
return new FixedWord(this.width, this.signed, constant(this.width, this.signed, remainder ? r : q), failures(this.failure, b.failure, divZero, trapOverflow));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
export const fixedFailure = (value) => value instanceof FixedWord ? value.failure : value instanceof Term ? storedTermFailures.get(value) : undefined;
|
|
226
|
+
export const fixedSelect = (condition, a, b) => {
|
|
227
|
+
if (a.width !== b.width || a.signed !== b.signed)
|
|
228
|
+
throw new TypeError('selected fixed integers need identical kinds');
|
|
229
|
+
const failure = a.failure || b.failure ? any(all(condition, a.failure ?? falseCond()), all(condition.not(), b.failure ?? falseCond())) : undefined;
|
|
230
|
+
return new FixedWord(a.width, a.signed, select(condition, a.limbs, b.limbs), failure);
|
|
231
|
+
};
|
|
232
|
+
export const fixedInt = (width, signed) => {
|
|
233
|
+
validKind(width, signed);
|
|
234
|
+
class FixedKind extends Kind {
|
|
235
|
+
vars(name) { return Array.from({ length: digits(width) }, (_, i) => `${name}$${i}`); }
|
|
236
|
+
assume(name) { return this.value(name).limbs.map(x => x.lt(base(width))); }
|
|
237
|
+
build(name, get) { return new FixedWord(width, signed, this.vars(name).map(get)); }
|
|
238
|
+
invariant(v) { return v.limbs.map(x => x.lt(base(width))); }
|
|
239
|
+
lift(value) { return new FixedWord(width, signed, constant(width, signed, parse(width, signed, value))); }
|
|
240
|
+
encode(name, raw) {
|
|
241
|
+
const limbs = constant(width, signed, parse(width, signed, raw));
|
|
242
|
+
return Object.fromEntries(this.vars(name).map((v, i) => [v, limbs[i].val]));
|
|
243
|
+
}
|
|
244
|
+
random(name, rand, _bound) {
|
|
245
|
+
return Object.fromEntries(this.vars(name).map(v => [v, rand(base(width))]));
|
|
246
|
+
}
|
|
247
|
+
sample(rand, bound) {
|
|
248
|
+
const n = BigInt(rand(Math.min(1 + Math.max(0, bound), signed ? base(width) / 2 : base(width))));
|
|
249
|
+
return width === 64 ? n.toString() : Number(n);
|
|
250
|
+
}
|
|
251
|
+
store(name, value) {
|
|
252
|
+
const word = value instanceof FixedWord ? value : this.lift(value);
|
|
253
|
+
if (word.width !== width || word.signed !== signed)
|
|
254
|
+
throw new TypeError('stored fixed integer has wrong kind');
|
|
255
|
+
return Object.fromEntries(this.vars(name).map((v, i) => {
|
|
256
|
+
const limb = word.limbs[i];
|
|
257
|
+
if (!word.failure)
|
|
258
|
+
return [v, limb];
|
|
259
|
+
const stored = new Term(limb.e, limb.val);
|
|
260
|
+
storedTermFailures.set(stored, word.failure);
|
|
261
|
+
return [v, stored];
|
|
262
|
+
}));
|
|
263
|
+
}
|
|
264
|
+
decode(name, vars) {
|
|
265
|
+
let n = 0n;
|
|
266
|
+
for (const v of this.vars(name).reverse()) {
|
|
267
|
+
const limb = vars[v];
|
|
268
|
+
if (limb === undefined || !Number.isInteger(limb) || limb < 0 || limb >= base(width))
|
|
269
|
+
throw new RangeError(`invalid fixed limb ${v}`);
|
|
270
|
+
n = n * BigInt(base(width)) + BigInt(limb);
|
|
271
|
+
}
|
|
272
|
+
if (signed && n >= 1n << BigInt(width - 1))
|
|
273
|
+
n -= 1n << BigInt(width);
|
|
274
|
+
return width === 64 ? n.toString() : Number(n);
|
|
275
|
+
}
|
|
276
|
+
empty() { return width === 64 ? '0' : 0; }
|
|
277
|
+
}
|
|
278
|
+
return new FixedKind();
|
|
279
|
+
};
|
package/dist/core/machine.d.ts
CHANGED
package/dist/core/machine.js
CHANGED
|
@@ -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)}$
|
|
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
|