@fraczak/k 8.9.0 → 9.1.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/CHANGELOG.md +28 -0
- package/DOCS/ARCHITECTURE.md +5 -4
- package/DOCS/DICTIONARY.md +2 -2
- package/DOCS/FILE_FORMATS.md +11 -9
- package/DOCS/KIR_V1.md +5 -1
- package/DOCS/KTVM_SPEC.md +907 -0
- package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
- package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
- package/DOCS/PROFILING_AND_TRACING.md +13 -4
- package/DOCS/README.md +3 -2
- package/DOCS/REPL.md +16 -12
- package/README.md +138 -2
- package/backend-api.mjs +31 -16
- package/backends/llvm/README.md +4 -5
- package/backends/llvm/bin/k-llvm-build.mjs +7 -19
- package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
- package/backends/llvm/bin/k-llvm.mjs +11 -33
- package/backends/llvm/src/cli.mjs +2 -12
- package/backends/llvm/src/executable.mjs +7 -95
- package/backends/llvm/src/kvm2llvm.mjs +1 -7
- package/backends/llvm/src/llvm.mjs +4 -113
- package/backends/llvm/tests/k-llvm-run.mjs +1 -6
- package/backends/llvm/tests/perf-support.mjs +3 -5
- package/backends/llvm/tests/test-llvm.mjs +2 -16
- package/backends/wasm/README.md +7 -3
- package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
- package/backends/wasm/bin/k-wasm.mjs +4 -6
- package/backends/wasm/src/cli.mjs +8 -24
- package/backends/wasm/src/wasm.mjs +60 -57
- package/backends/wasm/tests/test-wasm.mjs +41 -2
- package/browser/repl-browser.mjs +9 -8
- package/browser/shims/buffer.mjs +31 -2
- package/browser/shims/child_process.mjs +26 -0
- package/browser/shims/fs.mjs +3 -1
- package/codecs/runtime/prefix-codec.mjs +67 -1
- package/conformance/run.mjs +17 -2
- package/harness/adapters/ktvm-llvm.mjs +118 -0
- package/harness/adapters/ktvm-wasm.mjs +104 -0
- package/harness/adapters/ktvm.mjs +133 -0
- package/harness/registry.mjs +9 -0
- package/ktvm/ast.mjs +218 -0
- package/ktvm/bit-deque.mjs +497 -0
- package/ktvm/fixtures/integer-streaming.k +477 -0
- package/ktvm/index.mjs +130 -0
- package/ktvm/llvm/index.mjs +202 -0
- package/ktvm/llvm/lower-c.mjs +1258 -0
- package/ktvm/llvm/runtime.h +3542 -0
- package/ktvm/llvm/test-llvm.mjs +476 -0
- package/ktvm/lower-kir.mjs +2221 -0
- package/ktvm/optimize/fuse-kernel.mjs +2111 -0
- package/ktvm/optimize/index.mjs +116 -0
- package/ktvm/optimize/mwtr.mjs +283 -0
- package/ktvm/optimize/simplify-procs.mjs +5250 -0
- package/ktvm/optimize/synthesize-tables.mjs +1105 -0
- package/ktvm/parser.mjs +1101 -0
- package/ktvm/printer.mjs +281 -0
- package/ktvm/schema.mjs +1134 -0
- package/ktvm/specialize.mjs +538 -0
- package/ktvm/test-conformance.mjs +597 -0
- package/ktvm/test-ktvm.mjs +1805 -0
- package/ktvm/test-optimize.mjs +598 -0
- package/ktvm/validator.mjs +1280 -0
- package/ktvm/vm.mjs +2225 -0
- package/ktvm/wasm/index.mjs +331 -0
- package/ktvm/wasm/lower-wasm.mjs +1272 -0
- package/ktvm/wasm/runtime.wat +4404 -0
- package/ktvm/wasm/test-wasm.mjs +429 -0
- package/ktvm/wire.mjs +679 -0
- package/package.json +1 -9
- package/paper/Makefile +8 -5
- package/paper/k-transducer-compiler.pdf +0 -0
- package/paper/k-transducer-compiler.tex +658 -0
- package/paper/replay-diagnostic.mjs +63 -0
- package/repl.mjs +101 -20
- package/scripts/build-repl-html.mjs +40 -18
- package/scripts/perf-bigint-compare.mjs +12 -16
- package/scripts/perf-ieee.mjs +14 -232
- package/scripts/perf-int.mjs +16 -274
- package/scripts/perf-multiplication.mjs +116 -121
- package/scripts/perf-poly.mjs +9 -263
- package/scripts/run-tests.mjs +5 -2
- package/scripts/test-package.mjs +15 -3
- package/tests/README.md +3 -3
- package/tests/test-repl-html.mjs +72 -15
- package/tests/test-repl.mjs +24 -17
- package/DOCS/POLYMORPHIC_IR.md +0 -86
- package/access-table.mjs +0 -343
- package/pkir.mjs +0 -772
- package/tests/test-access-table.mjs +0 -213
- package/tests/test-pkir.mjs +0 -530
package/ktvm/wire.mjs
ADDED
|
@@ -0,0 +1,679 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strictly iterative k-wire boundary codecs and resumable 1-state DPDA steppers.
|
|
3
|
+
*
|
|
4
|
+
* Guarantees zero host call-stack recursion (handles arbitrarily deep 4,096+ bit
|
|
5
|
+
* values cleanly) and 100% bit-exact conformance with codecs/WIRE_FORMAT.md and
|
|
6
|
+
* codecs/runtime/prefix-codec.mjs.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { Value, isProduct, isVariant } from "../Value.mjs";
|
|
10
|
+
import {
|
|
11
|
+
encodeToWire,
|
|
12
|
+
decodeWire,
|
|
13
|
+
choiceWidth,
|
|
14
|
+
propertyListToPattern,
|
|
15
|
+
patternToPropertyList,
|
|
16
|
+
CORE_PATTERN_PROPERTY_LIST
|
|
17
|
+
} from "../codecs/runtime/prefix-codec.mjs";
|
|
18
|
+
import {
|
|
19
|
+
textToStringValue,
|
|
20
|
+
stringValueToText
|
|
21
|
+
} from "../codecs/runtime/unicode-string.mjs";
|
|
22
|
+
import { BitDeque } from "./bit-deque.mjs";
|
|
23
|
+
import {
|
|
24
|
+
compareLabels,
|
|
25
|
+
normalizeNodeList,
|
|
26
|
+
nodeListComplete,
|
|
27
|
+
stepNodeListTag
|
|
28
|
+
} from "./schema.mjs";
|
|
29
|
+
|
|
30
|
+
export const DPDA_RESULT = Object.freeze({
|
|
31
|
+
DONE: "DONE",
|
|
32
|
+
NEED_BITS: "NEED_BITS",
|
|
33
|
+
FAILED: "FAILED"
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Strictly iterative Value -> BitDeque encoder under closed property-list `plist`.
|
|
38
|
+
*/
|
|
39
|
+
export function encodePayloadToDeque(value, plist, deque, rootId = 0) {
|
|
40
|
+
const stack = [{ val: value, nodeId: rootId }];
|
|
41
|
+
while (stack.length > 0) {
|
|
42
|
+
const { val, nodeId } = stack.pop();
|
|
43
|
+
const [kind, edges] = plist[nodeId];
|
|
44
|
+
if (kind === "closed-product") {
|
|
45
|
+
if (!isProduct(val)) {
|
|
46
|
+
throw new Error(`Expected product value at schema node ${nodeId}`);
|
|
47
|
+
}
|
|
48
|
+
// Push children in reverse canonical order so LIFO emits them in canonical order.
|
|
49
|
+
for (let i = edges.length - 1; i >= 0; i--) {
|
|
50
|
+
const [label, targetId] = edges[i];
|
|
51
|
+
if (!(label in val.product)) {
|
|
52
|
+
throw new Error(`Product value missing field '${label}' at schema node ${nodeId}`);
|
|
53
|
+
}
|
|
54
|
+
stack.push({ val: val.product[label], nodeId: targetId });
|
|
55
|
+
}
|
|
56
|
+
} else if (kind === "closed-union") {
|
|
57
|
+
if (!isVariant(val)) {
|
|
58
|
+
throw new Error(`Expected variant value at schema node ${nodeId}`);
|
|
59
|
+
}
|
|
60
|
+
const ord = edges.findIndex(([l]) => l === val.tag);
|
|
61
|
+
if (ord < 0) {
|
|
62
|
+
throw new Error(`Variant tag '${val.tag}' not in closed union at node ${nodeId}`);
|
|
63
|
+
}
|
|
64
|
+
const w = choiceWidth(edges.length);
|
|
65
|
+
if (w > 0) deque.pushBits(ord, w);
|
|
66
|
+
stack.push({ val: val.value, nodeId: edges[ord][1] });
|
|
67
|
+
} else {
|
|
68
|
+
throw new Error(`Cannot encode payload under non-closed schema kind '${kind}'`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Strictly iterative BitDeque -> Value decoder under closed property-list `plist`.
|
|
75
|
+
* Rejects truncation, invalid union ordinals, and leftover unconsumed bits.
|
|
76
|
+
*/
|
|
77
|
+
export function decodeDequeToValue(deque, plist, rootId = 0, { exact = true } = {}) {
|
|
78
|
+
const results = [];
|
|
79
|
+
// Frames: { kind: "decode", nodeId } | { kind: "build_product", labels } | { kind: "build_variant", tag }
|
|
80
|
+
const frames = [{ kind: "decode", nodeId: rootId }];
|
|
81
|
+
|
|
82
|
+
while (frames.length > 0) {
|
|
83
|
+
const frame = frames.pop();
|
|
84
|
+
if (frame.kind === "build_product") {
|
|
85
|
+
const n = frame.labels.length;
|
|
86
|
+
const vals = new Array(n);
|
|
87
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
88
|
+
vals[i] = results.pop();
|
|
89
|
+
}
|
|
90
|
+
const fields = {};
|
|
91
|
+
for (let i = 0; i < n; i++) {
|
|
92
|
+
fields[frame.labels[i]] = vals[i];
|
|
93
|
+
}
|
|
94
|
+
results.push(Value.product(fields));
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (frame.kind === "build_variant") {
|
|
98
|
+
const payload = results.pop();
|
|
99
|
+
results.push(Value.variant(frame.tag, payload));
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const [kind, edges] = plist[frame.nodeId];
|
|
104
|
+
if (kind === "closed-product") {
|
|
105
|
+
if (edges.length === 0) {
|
|
106
|
+
results.push(Value.product({}));
|
|
107
|
+
} else {
|
|
108
|
+
frames.push({ kind: "build_product", labels: edges.map(([l]) => l) });
|
|
109
|
+
for (let i = edges.length - 1; i >= 0; i--) {
|
|
110
|
+
frames.push({ kind: "decode", nodeId: edges[i][1] });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
} else if (kind === "closed-union") {
|
|
114
|
+
if (edges.length === 0) {
|
|
115
|
+
throw new Error("Cannot decode empty union");
|
|
116
|
+
}
|
|
117
|
+
const w = choiceWidth(edges.length);
|
|
118
|
+
let ord = 0;
|
|
119
|
+
if (w > 0) {
|
|
120
|
+
if (!deque.hasBits(w)) {
|
|
121
|
+
throw new Error(`Truncated k-wire stream: needed ${w} bits at union node ${frame.nodeId}`);
|
|
122
|
+
}
|
|
123
|
+
ord = deque.shiftBits(w);
|
|
124
|
+
}
|
|
125
|
+
if (ord >= edges.length) {
|
|
126
|
+
throw new Error(`Invalid union ordinal ${ord} (expected < ${edges.length}) at node ${frame.nodeId}`);
|
|
127
|
+
}
|
|
128
|
+
const [tag, targetId] = edges[ord];
|
|
129
|
+
frames.push({ kind: "build_variant", tag });
|
|
130
|
+
frames.push({ kind: "decode", nodeId: targetId });
|
|
131
|
+
} else {
|
|
132
|
+
throw new Error(`Cannot decode payload under non-closed schema kind '${kind}'`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (exact && deque.length !== 0) {
|
|
137
|
+
throw new Error(`Trailing unconsumed bits in BitDeque (${deque.length} bits remaining)`);
|
|
138
|
+
}
|
|
139
|
+
return results[0];
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Push a byte buffer into a BitDeque (MSB-first per byte), stripping trailing
|
|
144
|
+
* zero-padding beyond `totalBits` if specified.
|
|
145
|
+
*/
|
|
146
|
+
export function writeBytesToDeque(bytes, deque, totalBits = bytes.length * 8) {
|
|
147
|
+
let rem = totalBits;
|
|
148
|
+
for (let i = 0; i < bytes.length && rem > 0; i++) {
|
|
149
|
+
if (rem >= 8) {
|
|
150
|
+
deque.pushBits(bytes[i], 8);
|
|
151
|
+
rem -= 8;
|
|
152
|
+
} else {
|
|
153
|
+
deque.pushBits(bytes[i] >>> (8 - rem), rem);
|
|
154
|
+
rem = 0;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Drain a BitDeque into a zero-padded Uint8Array (exact k-wire byte framing).
|
|
161
|
+
*/
|
|
162
|
+
export function dequeToPaddedBytes(deque) {
|
|
163
|
+
const totalBits = deque.length;
|
|
164
|
+
const byteLen = Math.ceil(totalBits / 8);
|
|
165
|
+
const out = Buffer.alloc(byteLen);
|
|
166
|
+
let byteIdx = 0;
|
|
167
|
+
let rem = totalBits;
|
|
168
|
+
while (rem >= 8) {
|
|
169
|
+
out[byteIdx++] = deque.shiftBits(8);
|
|
170
|
+
rem -= 8;
|
|
171
|
+
}
|
|
172
|
+
if (rem > 0) {
|
|
173
|
+
out[byteIdx++] = (deque.shiftBits(rem) << (8 - rem)) & 0xff;
|
|
174
|
+
}
|
|
175
|
+
return out;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Decode ONLY the k-wire envelope header prefix (`encode(pattern_value)`) without
|
|
180
|
+
* running a JS DPDA over the payload bits. Returns `{ plist, headerBitLen, canonicalOrder }`
|
|
181
|
+
* so Wasm/native runners can validate and stream the remaining payload bits directly.
|
|
182
|
+
*/
|
|
183
|
+
export function splitWireHeaderOnly(buffer, { quota = null } = {}) {
|
|
184
|
+
const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
|
|
185
|
+
const full = new BitDeque(-1, { quota });
|
|
186
|
+
const totalBits = bytes.length * 8;
|
|
187
|
+
writeBytesToDeque(bytes, full, totalBits);
|
|
188
|
+
|
|
189
|
+
const patternValue = decodeDequeToValue(full, CORE_PATTERN_PROPERTY_LIST, 0, { exact: false });
|
|
190
|
+
const headerBitLen = totalBits - full.length;
|
|
191
|
+
full.release();
|
|
192
|
+
|
|
193
|
+
const rawPlist = patternValueToPropertyList(patternValue);
|
|
194
|
+
let canonicalOrder = true;
|
|
195
|
+
const plist = rawPlist.map(([kind, edges]) => {
|
|
196
|
+
for (let i = 1; i < edges.length; i++) {
|
|
197
|
+
if (compareLabels(edges[i - 1][0], edges[i][0]) >= 0) {
|
|
198
|
+
canonicalOrder = false;
|
|
199
|
+
break;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (kind === "open-union") return ["closed-union", edges];
|
|
203
|
+
if (kind === "open-product") return ["closed-product", edges];
|
|
204
|
+
return [kind, edges];
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
return { plist, headerBitLen, canonicalOrder };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Decode an enveloped k-wire byte buffer (`encode(pattern_value) encode(payload)`)
|
|
212
|
+
* strictly iteratively into `{ plist, payloadDeque }`.
|
|
213
|
+
*
|
|
214
|
+
* Rejects malformed headers, truncated streams, invalid ordinals, and nonzero
|
|
215
|
+
* trailing padding bits (matching WIRE_FORMAT.md).
|
|
216
|
+
*/
|
|
217
|
+
export function splitEnvelopedWire(buffer, { quota = null } = {}) {
|
|
218
|
+
const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
|
|
219
|
+
const full = new BitDeque(-1, { quota });
|
|
220
|
+
writeBytesToDeque(bytes, full, bytes.length * 8);
|
|
221
|
+
|
|
222
|
+
// Decode the pattern header using K's CORE_PATTERN_PROPERTY_LIST
|
|
223
|
+
const patternValue = decodeDequeToValue(full, CORE_PATTERN_PROPERTY_LIST, 0, { exact: false });
|
|
224
|
+
const rawPlist = patternValueToPropertyList(patternValue);
|
|
225
|
+
// Concrete k-wire headers may tag value-derived variants/products as `open-union` /
|
|
226
|
+
// `open-product` (see prefix-codec.mjs `deriveClosedPatternFromValue`), whose wire
|
|
227
|
+
// encoding is identical to `closed-union` / `closed-product` over their listed edges.
|
|
228
|
+
const plist = rawPlist.map(([kind, edges]) => {
|
|
229
|
+
if (kind === "open-union") return ["closed-union", edges];
|
|
230
|
+
if (kind === "open-product") return ["closed-product", edges];
|
|
231
|
+
return [kind, edges];
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
// Validate and extract exact payload bits by running DPDA copy into payloadDeque,
|
|
235
|
+
// then verify all remaining bits (< 8) are zero trailing byte padding.
|
|
236
|
+
const payloadDeque = new BitDeque(-2, { prodSchema: plist, consSchema: plist, quota });
|
|
237
|
+
const copyState = createDpdaCopy(plist, 0);
|
|
238
|
+
const res = stepDpdaCopy(full, payloadDeque, copyState);
|
|
239
|
+
if (res !== DPDA_RESULT.DONE) {
|
|
240
|
+
full.release();
|
|
241
|
+
payloadDeque.release();
|
|
242
|
+
throw new Error("Malformed k-wire envelope payload (truncated or invalid union ordinal)");
|
|
243
|
+
}
|
|
244
|
+
if (full.length >= 8) {
|
|
245
|
+
const extra = full.length;
|
|
246
|
+
full.release();
|
|
247
|
+
payloadDeque.release();
|
|
248
|
+
throw new Error(`Malformed k-wire envelope: ${extra} trailing bits after payload`);
|
|
249
|
+
}
|
|
250
|
+
if (full.length > 0) {
|
|
251
|
+
const pad = full.shiftBits(full.length);
|
|
252
|
+
if (pad !== 0) {
|
|
253
|
+
full.release();
|
|
254
|
+
payloadDeque.release();
|
|
255
|
+
throw new Error(`Malformed k-wire envelope: nonzero trailing padding bits (0b${pad.toString(2)})`);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
full.release();
|
|
259
|
+
payloadDeque.close();
|
|
260
|
+
return { plist, payloadDeque };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Frame a closed `plist` + payload `BitDeque` into a complete enveloped k-wire
|
|
265
|
+
* `Uint8Array`, 100% bit-exact with `encodeToWire` in `codecs/runtime/prefix-codec.mjs`.
|
|
266
|
+
*/
|
|
267
|
+
export function frameEnvelopedWire(plist, payloadDeque) {
|
|
268
|
+
const headerVal = propertyListToPatternValue(plist);
|
|
269
|
+
const out = new BitDeque(-3);
|
|
270
|
+
encodePayloadToDeque(headerVal, CORE_PATTERN_PROPERTY_LIST, out, 0);
|
|
271
|
+
out.pushFromDeque(payloadDeque);
|
|
272
|
+
const bytes = dequeToPaddedBytes(out);
|
|
273
|
+
out.release();
|
|
274
|
+
return bytes;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Convenience bridge: encode a K `Value` under closed `plist` to enveloped k-wire bytes
|
|
279
|
+
* using K's canonical `encodeToWire`.
|
|
280
|
+
*/
|
|
281
|
+
export function encodeValueToEnvelopedWire(value, plist) {
|
|
282
|
+
return encodeToWire(value, plist);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export function decodeEnvelopedWireToValue(bytes) {
|
|
286
|
+
return decodeWire(Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes));
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// --- Pattern Value <-> Property List helpers (using K's canonical pattern codec) ---
|
|
290
|
+
|
|
291
|
+
function patternValueToPropertyList(patternValue) {
|
|
292
|
+
// Reuse K's canonical decoder by encoding only header? Better: convert directly!
|
|
293
|
+
// Pattern value matches CORE_PATTERN_PROPERTY_LIST (list of node variants).
|
|
294
|
+
const nodes = [];
|
|
295
|
+
let cur = patternValue;
|
|
296
|
+
while (isVariant(cur) && cur.tag === "cons") {
|
|
297
|
+
const nodeVal = cur.value.product.car;
|
|
298
|
+
const kind = nodeVal.tag;
|
|
299
|
+
const edges = [];
|
|
300
|
+
if (kind !== "any") {
|
|
301
|
+
let ecur = nodeVal.value;
|
|
302
|
+
while (isVariant(ecur) && ecur.tag === "cons") {
|
|
303
|
+
const edgeProd = ecur.value.product.car.product;
|
|
304
|
+
const label = decodeKStringValue(edgeProd.label);
|
|
305
|
+
const target = decodeKBitsUint(edgeProd.target);
|
|
306
|
+
edges.push([label, target]);
|
|
307
|
+
ecur = ecur.value.product.cdr;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
nodes.push([kind, edges]);
|
|
311
|
+
cur = cur.value.product.cdr;
|
|
312
|
+
}
|
|
313
|
+
return nodes;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function propertyListToPatternValue(plist) {
|
|
317
|
+
// Use K's own `encodeToWire` header or direct conversion via `patternToPropertyList`.
|
|
318
|
+
// Build canonical pattern[] Value directly matching CORE_PATTERN_PROPERTY_LIST!
|
|
319
|
+
let listVal = Value.variant("nil", Value.product({}));
|
|
320
|
+
for (let i = plist.length - 1; i >= 0; i--) {
|
|
321
|
+
const [kind, edges] = plist[i];
|
|
322
|
+
let nodeVal;
|
|
323
|
+
if (kind === "any") {
|
|
324
|
+
nodeVal = Value.variant("any", Value.product({}));
|
|
325
|
+
} else {
|
|
326
|
+
let edgeList = Value.variant("nil", Value.product({}));
|
|
327
|
+
for (let j = edges.length - 1; j >= 0; j--) {
|
|
328
|
+
const [label, target] = edges[j];
|
|
329
|
+
const edgeProd = Value.product({
|
|
330
|
+
label: encodeKStringValue(label),
|
|
331
|
+
target: encodeKBitsUint(target)
|
|
332
|
+
});
|
|
333
|
+
edgeList = Value.variant("cons", Value.product({ car: edgeProd, cdr: edgeList }));
|
|
334
|
+
}
|
|
335
|
+
nodeVal = Value.variant(kind, edgeList);
|
|
336
|
+
}
|
|
337
|
+
listVal = Value.variant("cons", Value.product({ car: nodeVal, cdr: listVal }));
|
|
338
|
+
}
|
|
339
|
+
return listVal;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function decodeKBitsUint(bitsVal) {
|
|
343
|
+
// `bits[]` target indices in WIRE_FORMAT.md / prefix-codec.mjs are LSB-first (`01_` = 2)
|
|
344
|
+
let acc = 0;
|
|
345
|
+
let place = 1;
|
|
346
|
+
let cur = bitsVal;
|
|
347
|
+
while (isVariant(cur) && cur.tag !== "_") {
|
|
348
|
+
if (cur.tag === "1") acc += place;
|
|
349
|
+
place *= 2;
|
|
350
|
+
cur = cur.value;
|
|
351
|
+
}
|
|
352
|
+
return acc;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function encodeKBitsUint(n) {
|
|
356
|
+
const unit = Value.product({});
|
|
357
|
+
if (n === 0) return Value.variant("_", unit);
|
|
358
|
+
const bits = [];
|
|
359
|
+
let v = n;
|
|
360
|
+
while (v > 0) {
|
|
361
|
+
bits.push(v & 1 ? "1" : "0");
|
|
362
|
+
v = Math.floor(v / 2);
|
|
363
|
+
}
|
|
364
|
+
let cur = Value.variant("_", unit);
|
|
365
|
+
for (let i = bits.length - 1; i >= 0; i--) {
|
|
366
|
+
cur = Value.variant(bits[i], cur);
|
|
367
|
+
}
|
|
368
|
+
return cur;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function decodeKStringValue(strVal) {
|
|
372
|
+
return stringValueToText(strVal);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function encodeKStringValue(str) {
|
|
376
|
+
return textToStringValue(str);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// --- Strictly Iterative, Resumable 1-State Pushdown Steppers & Schema Cursor ---
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Create a resumable 1-state schema DPDA cursor initialized with a single node
|
|
383
|
+
* ID or a front-to-back residual node list `[v_1, ..., v_k]`.
|
|
384
|
+
*
|
|
385
|
+
* Internally stores `stack` in LIFO order (head `v_1` at `stack[stack.length - 1]`).
|
|
386
|
+
*/
|
|
387
|
+
export function createSchemaCursor(plist, nodes = [0]) {
|
|
388
|
+
const list = typeof nodes === "number" ? [nodes] : [...nodes];
|
|
389
|
+
const stack = new Array(list.length);
|
|
390
|
+
for (let i = 0; i < list.length; i++) {
|
|
391
|
+
stack[i] = list[list.length - 1 - i];
|
|
392
|
+
}
|
|
393
|
+
return { plist, stack };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Return the cursor's current residual node list in front-to-back order `[v_1, ..., v_k]`.
|
|
398
|
+
*/
|
|
399
|
+
export function cursorNodeList(cursor) {
|
|
400
|
+
const { stack } = cursor;
|
|
401
|
+
const out = new Array(stack.length);
|
|
402
|
+
for (let i = 0; i < stack.length; i++) {
|
|
403
|
+
out[i] = stack[stack.length - 1 - i];
|
|
404
|
+
}
|
|
405
|
+
return out;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Unified strictly iterative 1-state schema DPDA stepper.
|
|
410
|
+
*
|
|
411
|
+
* Advances `cursor` across `srcDeque` according to the node-list prefix
|
|
412
|
+
* derivative rules; if `dstDeque` is provided, mirrors every shifted tag code
|
|
413
|
+
* into `dstDeque` (providing both `dpda_skip` and `dpda_copy` from one core loop).
|
|
414
|
+
*/
|
|
415
|
+
export function stepSchemaCursor(srcDeque, cursor, dstDeque = null) {
|
|
416
|
+
const { plist, stack } = cursor;
|
|
417
|
+
while (stack.length > 0) {
|
|
418
|
+
const nodeId = stack[stack.length - 1];
|
|
419
|
+
const node = plist[nodeId];
|
|
420
|
+
if (!node) return DPDA_RESULT.FAILED;
|
|
421
|
+
const [kind, edges] = node;
|
|
422
|
+
if (kind === "closed-product") {
|
|
423
|
+
stack.pop();
|
|
424
|
+
for (let i = edges.length - 1; i >= 0; i--) {
|
|
425
|
+
stack.push(edges[i][1]);
|
|
426
|
+
}
|
|
427
|
+
} else if (kind === "closed-union") {
|
|
428
|
+
if (edges.length === 0) return DPDA_RESULT.FAILED;
|
|
429
|
+
const w = choiceWidth(edges.length);
|
|
430
|
+
let ord = 0;
|
|
431
|
+
if (w > 0) {
|
|
432
|
+
if (!srcDeque.hasBits(w)) {
|
|
433
|
+
return srcDeque.isOpen ? DPDA_RESULT.NEED_BITS : DPDA_RESULT.FAILED;
|
|
434
|
+
}
|
|
435
|
+
ord = srcDeque.shiftBits(w);
|
|
436
|
+
srcDeque.aligned = false;
|
|
437
|
+
}
|
|
438
|
+
if (ord >= edges.length) return DPDA_RESULT.FAILED;
|
|
439
|
+
if (dstDeque && w > 0) dstDeque.pushBits(ord, w);
|
|
440
|
+
stack.pop();
|
|
441
|
+
stack.push(edges[ord][1]);
|
|
442
|
+
} else {
|
|
443
|
+
return DPDA_RESULT.FAILED;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
return DPDA_RESULT.DONE;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
export function createDpdaSkip(plist, rootId = 0) {
|
|
450
|
+
return createSchemaCursor(plist, rootId);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
export function stepDpdaSkip(srcDeque, state) {
|
|
454
|
+
return stepSchemaCursor(srcDeque, state, null);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
export function createDpdaCopy(plist, rootId = 0) {
|
|
458
|
+
return createSchemaCursor(plist, rootId);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
export function stepDpdaCopy(srcDeque, dstDeque, state) {
|
|
462
|
+
return stepSchemaCursor(srcDeque, state, dstDeque);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function readBitsFromBuffer(bytes, bitOffset, width, limitBits) {
|
|
466
|
+
if (width <= 0) return 0;
|
|
467
|
+
if (bitOffset < 0 || bitOffset + width > limitBits) return -1;
|
|
468
|
+
let val = 0;
|
|
469
|
+
for (let i = 0; i < width; i++) {
|
|
470
|
+
const pos = bitOffset + i;
|
|
471
|
+
const bit = (bytes[pos >>> 3] >>> (7 - (pos & 7))) & 1;
|
|
472
|
+
val = ((val << 1) | bit) >>> 0;
|
|
473
|
+
}
|
|
474
|
+
return val;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Scan an immutable packed `k-wire` byte buffer starting at any aligned bit
|
|
479
|
+
* offset `(startBitOffset, nodes)` represented as a residual node list
|
|
480
|
+
* `[v_1, ..., v_k]` of `plist` (Definition 2.3).
|
|
481
|
+
*
|
|
482
|
+
* Modes:
|
|
483
|
+
* - `mode: "tag"` — normalizes leading products, reads the head union tag at
|
|
484
|
+
* `startBitOffset`, and returns the updated aligned offset
|
|
485
|
+
* and normalized residual node list.
|
|
486
|
+
* - `mode: "value"` — skips the complete sub-value conforming to `nodes[0]`
|
|
487
|
+
* via the 1-state schema DPDA without copying into a
|
|
488
|
+
* `BitDeque`, returning the new aligned offset and remaining
|
|
489
|
+
* continuation `nodes.slice(1)` (normalized if `normalize: true`).
|
|
490
|
+
*/
|
|
491
|
+
export function scanBufferAlignedOffset(
|
|
492
|
+
bytes,
|
|
493
|
+
startBitOffset,
|
|
494
|
+
plist,
|
|
495
|
+
nodes = [0],
|
|
496
|
+
{ mode = "value", totalBits = null, normalize = false } = {}
|
|
497
|
+
) {
|
|
498
|
+
const buf = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
499
|
+
const limitBits = totalBits === null ? buf.length * 8 : totalBits;
|
|
500
|
+
if (!Number.isInteger(startBitOffset) || startBitOffset < 0 || startBitOffset > limitBits) {
|
|
501
|
+
return {
|
|
502
|
+
ok: false,
|
|
503
|
+
reason: `startBitOffset ${startBitOffset} out of bounds [0..${limitBits}]`
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
const list = typeof nodes === "number" ? [nodes] : [...nodes];
|
|
507
|
+
|
|
508
|
+
if (mode === "tag") {
|
|
509
|
+
let norm;
|
|
510
|
+
try {
|
|
511
|
+
norm = normalizeNodeList(plist, list);
|
|
512
|
+
} catch (err) {
|
|
513
|
+
return { ok: false, reason: err.message };
|
|
514
|
+
}
|
|
515
|
+
if (norm.length === 0) {
|
|
516
|
+
return { ok: false, reason: "aligned offset is already at end of value" };
|
|
517
|
+
}
|
|
518
|
+
const headId = norm[0];
|
|
519
|
+
const headNode = plist[headId];
|
|
520
|
+
if (!headNode || headNode[0] !== "closed-union") {
|
|
521
|
+
return {
|
|
522
|
+
ok: false,
|
|
523
|
+
reason: `expected closed-union at node ${headId}, got '${headNode ? headNode[0] : "missing"}'`
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
const edges = headNode[1];
|
|
527
|
+
if (edges.length === 0) {
|
|
528
|
+
return { ok: false, reason: `empty closed-union at node ${headId}` };
|
|
529
|
+
}
|
|
530
|
+
const w = choiceWidth(edges.length);
|
|
531
|
+
const ord = w > 0 ? readBitsFromBuffer(buf, startBitOffset, w, limitBits) : 0;
|
|
532
|
+
if (ord < 0) {
|
|
533
|
+
return {
|
|
534
|
+
ok: false,
|
|
535
|
+
reason: `truncated k-wire buffer: needed ${w} bits at bit offset ${startBitOffset}`
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
const step = stepNodeListTag(plist, norm, ord);
|
|
539
|
+
if (!step.ok) return step;
|
|
540
|
+
return {
|
|
541
|
+
ok: true,
|
|
542
|
+
bitOffset: startBitOffset + w,
|
|
543
|
+
headNodeId: step.headNodeId,
|
|
544
|
+
label: step.label,
|
|
545
|
+
ordinal: step.ordinal,
|
|
546
|
+
width: step.width,
|
|
547
|
+
targetId: step.targetId,
|
|
548
|
+
nodes: step.nextNodes,
|
|
549
|
+
complete: step.nextNodes.length === 0
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
if (mode === "value") {
|
|
554
|
+
if (list.length === 0) {
|
|
555
|
+
return { ok: true, bitOffset: startBitOffset, headNodeId: null, nodes: [], complete: true };
|
|
556
|
+
}
|
|
557
|
+
const headNodeId = list[0];
|
|
558
|
+
const rest = list.slice(1);
|
|
559
|
+
const stack = [headNodeId];
|
|
560
|
+
let bitOffset = startBitOffset;
|
|
561
|
+
const zeroBitUnionSeen = new Set();
|
|
562
|
+
|
|
563
|
+
while (stack.length > 0) {
|
|
564
|
+
const nodeId = stack[stack.length - 1];
|
|
565
|
+
const node = plist[nodeId];
|
|
566
|
+
if (!node) {
|
|
567
|
+
return { ok: false, reason: `invalid schema node ${nodeId}` };
|
|
568
|
+
}
|
|
569
|
+
const [kind, edges] = node;
|
|
570
|
+
if (kind === "closed-product") {
|
|
571
|
+
// Normalize leading products with cycle protection
|
|
572
|
+
let normHead;
|
|
573
|
+
try {
|
|
574
|
+
normHead = normalizeNodeList(plist, [nodeId]);
|
|
575
|
+
} catch (err) {
|
|
576
|
+
return { ok: false, reason: err.message };
|
|
577
|
+
}
|
|
578
|
+
stack.pop();
|
|
579
|
+
for (let i = normHead.length - 1; i >= 0; i--) {
|
|
580
|
+
stack.push(normHead[i]);
|
|
581
|
+
}
|
|
582
|
+
} else if (kind === "closed-union") {
|
|
583
|
+
if (edges.length === 0) {
|
|
584
|
+
return { ok: false, reason: `empty closed-union at node ${nodeId}` };
|
|
585
|
+
}
|
|
586
|
+
const w = choiceWidth(edges.length);
|
|
587
|
+
let ord = 0;
|
|
588
|
+
if (w > 0) {
|
|
589
|
+
ord = readBitsFromBuffer(buf, bitOffset, w, limitBits);
|
|
590
|
+
if (ord < 0) {
|
|
591
|
+
return {
|
|
592
|
+
ok: false,
|
|
593
|
+
reason: `truncated k-wire buffer: needed ${w} bits at bit offset ${bitOffset}`
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
bitOffset += w;
|
|
597
|
+
zeroBitUnionSeen.clear();
|
|
598
|
+
} else {
|
|
599
|
+
if (zeroBitUnionSeen.has(nodeId)) {
|
|
600
|
+
return { ok: false, reason: `unguarded 0-bit union cycle at node ${nodeId}` };
|
|
601
|
+
}
|
|
602
|
+
zeroBitUnionSeen.add(nodeId);
|
|
603
|
+
}
|
|
604
|
+
if (ord >= edges.length) {
|
|
605
|
+
return {
|
|
606
|
+
ok: false,
|
|
607
|
+
reason: `invalid union ordinal ${ord} (expected < ${edges.length}) at node ${nodeId}`
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
stack.pop();
|
|
611
|
+
stack.push(edges[ord][1]);
|
|
612
|
+
} else {
|
|
613
|
+
return { ok: false, reason: `cannot scan non-closed schema kind '${kind}'` };
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
let outNodes;
|
|
618
|
+
let complete;
|
|
619
|
+
try {
|
|
620
|
+
outNodes = normalize ? normalizeNodeList(plist, rest) : rest;
|
|
621
|
+
complete = nodeListComplete(plist, outNodes);
|
|
622
|
+
} catch (err) {
|
|
623
|
+
return { ok: false, reason: err.message };
|
|
624
|
+
}
|
|
625
|
+
return {
|
|
626
|
+
ok: true,
|
|
627
|
+
bitOffset,
|
|
628
|
+
headNodeId,
|
|
629
|
+
nodes: outNodes,
|
|
630
|
+
complete
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
return { ok: false, reason: `unknown scan mode '${mode}'` };
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
export function createDpdaCoerce(srcPlist, srcRoot, dstPlist, dstRoot) {
|
|
638
|
+
return { srcPlist, dstPlist, stack: [{ s: srcRoot, d: dstRoot }] };
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
export function stepDpdaCoerce(srcDeque, dstDeque, state) {
|
|
642
|
+
const { srcPlist, dstPlist, stack } = state;
|
|
643
|
+
while (stack.length > 0) {
|
|
644
|
+
const { s, d } = stack[stack.length - 1];
|
|
645
|
+
const [sKind, sEdges] = srcPlist[s];
|
|
646
|
+
const [dKind, dEdges] = dstPlist[d];
|
|
647
|
+
|
|
648
|
+
if (sKind === "closed-product" && dKind === "closed-product") {
|
|
649
|
+
if (sEdges.length !== dEdges.length) return DPDA_RESULT.FAILED;
|
|
650
|
+
stack.pop();
|
|
651
|
+
for (let i = sEdges.length - 1; i >= 0; i--) {
|
|
652
|
+
if (sEdges[i][0] !== dEdges[i][0]) return DPDA_RESULT.FAILED;
|
|
653
|
+
stack.push({ s: sEdges[i][1], d: dEdges[i][1] });
|
|
654
|
+
}
|
|
655
|
+
} else if (sKind === "closed-union" && dKind === "closed-union") {
|
|
656
|
+
if (sEdges.length === 0 || dEdges.length === 0) return DPDA_RESULT.FAILED;
|
|
657
|
+
const sw = choiceWidth(sEdges.length);
|
|
658
|
+
let sOrd = 0;
|
|
659
|
+
if (sw > 0) {
|
|
660
|
+
if (!srcDeque.hasBits(sw)) {
|
|
661
|
+
return srcDeque.isOpen ? DPDA_RESULT.NEED_BITS : DPDA_RESULT.FAILED;
|
|
662
|
+
}
|
|
663
|
+
sOrd = srcDeque.shiftBits(sw);
|
|
664
|
+
srcDeque.aligned = false;
|
|
665
|
+
}
|
|
666
|
+
if (sOrd >= sEdges.length) return DPDA_RESULT.FAILED;
|
|
667
|
+
const [label, sNext] = sEdges[sOrd];
|
|
668
|
+
const dOrd = dEdges.findIndex(([l]) => l === label);
|
|
669
|
+
if (dOrd < 0) return DPDA_RESULT.FAILED;
|
|
670
|
+
const dw = choiceWidth(dEdges.length);
|
|
671
|
+
if (dw > 0) dstDeque.pushBits(dOrd, dw);
|
|
672
|
+
stack.pop();
|
|
673
|
+
stack.push({ s: sNext, d: dEdges[dOrd][1] });
|
|
674
|
+
} else {
|
|
675
|
+
return DPDA_RESULT.FAILED;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
return DPDA_RESULT.DONE;
|
|
679
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fraczak/k",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "9.1.0",
|
|
4
4
|
"description": "k — a language for content-addressable schemas and data transformations over algebraic data types (products and tagged unions); includes runtime, contract derivation, REPL, and codec toolchain",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -21,17 +21,9 @@
|
|
|
21
21
|
"benchmark:html": "node scripts/render-benchmark.mjs",
|
|
22
22
|
"perf:ieee": "node scripts/perf-ieee.mjs",
|
|
23
23
|
"perf:ieee:full": "node scripts/perf-ieee.mjs --full",
|
|
24
|
-
"perf:ieee:pkir": "BACKENDS=pkir node scripts/perf-ieee.mjs",
|
|
25
|
-
"perf:ieee:llvm-pkir": "BACKENDS=llvm-pkir node scripts/perf-ieee.mjs",
|
|
26
24
|
"perf:int": "node scripts/perf-int.mjs",
|
|
27
|
-
"perf:int:pkir": "BACKENDS=pkir node scripts/perf-int.mjs",
|
|
28
|
-
"perf:int:llvm-pkir": "BACKENDS=llvm-pkir node scripts/perf-int.mjs",
|
|
29
25
|
"perf:mult": "node scripts/perf-multiplication.mjs",
|
|
30
|
-
"perf:mult:pkir": "node scripts/perf-multiplication.mjs --backends pkir",
|
|
31
|
-
"perf:mult:llvm-pkir": "node scripts/perf-multiplication.mjs --backends llvm-pkir",
|
|
32
26
|
"perf:poly": "node scripts/perf-poly.mjs",
|
|
33
|
-
"perf:poly:pkir": "BACKENDS=pkir node scripts/perf-poly.mjs",
|
|
34
|
-
"perf:poly:llvm-pkir": "BACKENDS=llvm-pkir node scripts/perf-poly.mjs",
|
|
35
27
|
"perf:poly:trace": "node scripts/perf-poly.mjs --trace",
|
|
36
28
|
"perf:idempotency": "node scripts/benchmark-idempotency.mjs",
|
|
37
29
|
"deps:graph": "node scripts/generate-dependency-graph.mjs",
|