@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/ast.mjs
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* kTVM AST definitions, canonical JSON artifact conversion, and error types.
|
|
3
|
+
*
|
|
4
|
+
* Implements the dual canonical representation specified in DOCS/KTVM_SPEC.md §9:
|
|
5
|
+
* - Shared AST manipulated by parser, printer, validator, specializer, and VM
|
|
6
|
+
* - 1-to-1 JSON artifact (`format: "k-tvm"`, `version: 1`)
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const KTVM_FORMAT = "k-tvm";
|
|
10
|
+
export const KTVM_VERSION = 1;
|
|
11
|
+
|
|
12
|
+
export class KTVMSyntaxError extends SyntaxError {
|
|
13
|
+
constructor(message, { line = 1, col = 1 } = {}) {
|
|
14
|
+
super(`${message} (at ${line}:${col})`);
|
|
15
|
+
this.name = "KTVMSyntaxError";
|
|
16
|
+
this.line = line;
|
|
17
|
+
this.col = col;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export class KTVMValidationError extends Error {
|
|
22
|
+
constructor(errors) {
|
|
23
|
+
const list = Array.isArray(errors) ? errors : [errors];
|
|
24
|
+
super(`kTVM validation failed:\n - ${list.join("\n - ")}`);
|
|
25
|
+
this.name = "KTVMValidationError";
|
|
26
|
+
this.errors = list;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export class KTVMSchemaError extends TypeError {
|
|
31
|
+
constructor(message) {
|
|
32
|
+
super(`SchemaError: ${message}`);
|
|
33
|
+
this.name = "KTVMSchemaError";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export class KTVMQuotaError extends RangeError {
|
|
38
|
+
constructor(kind, limit, observed) {
|
|
39
|
+
super(`QuotaError: ${kind} limit exceeded (${observed} > ${limit})`);
|
|
40
|
+
this.name = "KTVMQuotaError";
|
|
41
|
+
this.quotaKind = kind;
|
|
42
|
+
this.limit = limit;
|
|
43
|
+
this.observed = observed;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// --- Schema AST Constructors ---
|
|
48
|
+
|
|
49
|
+
export const S = {
|
|
50
|
+
unit: () => ({ kind: "unit" }),
|
|
51
|
+
any: () => ({ kind: "any" }),
|
|
52
|
+
product: (fields = []) => ({ kind: "product", fields }),
|
|
53
|
+
openProduct: (fields = []) => ({ kind: "open_product", fields }),
|
|
54
|
+
union: (fields = []) => ({ kind: "union", fields }),
|
|
55
|
+
openUnion: (fields = []) => ({ kind: "open_union", fields }),
|
|
56
|
+
ref: (name, args = []) => ({ kind: "ref", name, args })
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export function createModule({
|
|
60
|
+
version = "0.1",
|
|
61
|
+
layer = "mono",
|
|
62
|
+
entry = null,
|
|
63
|
+
schemas = [],
|
|
64
|
+
procs = [],
|
|
65
|
+
kernels = [],
|
|
66
|
+
tables = []
|
|
67
|
+
} = {}) {
|
|
68
|
+
return {
|
|
69
|
+
format: KTVM_FORMAT,
|
|
70
|
+
formatVersion: KTVM_VERSION,
|
|
71
|
+
version,
|
|
72
|
+
layer,
|
|
73
|
+
entry,
|
|
74
|
+
schemas,
|
|
75
|
+
procs,
|
|
76
|
+
kernels,
|
|
77
|
+
tables
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function cloneAst(node) {
|
|
82
|
+
return structuredClone(node);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Export a kTVM module AST to its canonical JSON artifact (`format: "k-tvm"`).
|
|
87
|
+
*/
|
|
88
|
+
export function moduleToJSON(mod) {
|
|
89
|
+
return {
|
|
90
|
+
format: KTVM_FORMAT,
|
|
91
|
+
formatVersion: KTVM_VERSION,
|
|
92
|
+
version: mod.version || "0.1",
|
|
93
|
+
layer: mod.layer,
|
|
94
|
+
entry: mod.entry ?? null,
|
|
95
|
+
schemas: cloneAst(mod.schemas || []),
|
|
96
|
+
procs: cloneAst(mod.procs || []),
|
|
97
|
+
kernels: cloneAst(mod.kernels || []),
|
|
98
|
+
tables: cloneAst(mod.tables || [])
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Hydrate a canonical `format: "k-tvm"` JSON artifact back into a kTVM module AST.
|
|
104
|
+
*/
|
|
105
|
+
export function moduleFromJSON(obj) {
|
|
106
|
+
if (!obj || typeof obj !== "object") {
|
|
107
|
+
throw new Error("Invalid k-tvm JSON artifact: expected object");
|
|
108
|
+
}
|
|
109
|
+
if (obj.format !== KTVM_FORMAT) {
|
|
110
|
+
throw new Error(`Invalid k-tvm JSON artifact format: ${obj.format}`);
|
|
111
|
+
}
|
|
112
|
+
if (obj.formatVersion !== KTVM_VERSION) {
|
|
113
|
+
throw new Error(`Unsupported k-tvm formatVersion: ${obj.formatVersion}`);
|
|
114
|
+
}
|
|
115
|
+
if (obj.layer !== "poly" && obj.layer !== "mono") {
|
|
116
|
+
throw new Error(`Invalid k-tvm layer: ${obj.layer}`);
|
|
117
|
+
}
|
|
118
|
+
return createModule({
|
|
119
|
+
version: obj.version || "0.1",
|
|
120
|
+
layer: obj.layer,
|
|
121
|
+
entry: obj.entry ?? null,
|
|
122
|
+
schemas: cloneAst(obj.schemas || []),
|
|
123
|
+
procs: cloneAst(obj.procs || []),
|
|
124
|
+
kernels: cloneAst(obj.kernels || []),
|
|
125
|
+
tables: cloneAst(obj.tables || [])
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Encode/decode dense integer arrays for `packed_base64` table blocks (little-endian Int32).
|
|
131
|
+
*/
|
|
132
|
+
export function packInt32Base64(int32Array) {
|
|
133
|
+
const arr = int32Array instanceof Int32Array ? int32Array : Int32Array.from(int32Array);
|
|
134
|
+
const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
135
|
+
return Buffer.from(bytes).toString("base64");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function unpackInt32Base64(base64Str) {
|
|
139
|
+
const buf = Buffer.from(base64Str, "base64");
|
|
140
|
+
if ((buf.byteLength & 3) !== 0) {
|
|
141
|
+
throw new Error(`Invalid packed_base64 Int32 byte length: ${buf.byteLength}`);
|
|
142
|
+
}
|
|
143
|
+
const out = new Int32Array(buf.byteLength / 4);
|
|
144
|
+
for (let i = 0; i < out.length; i++) {
|
|
145
|
+
out[i] = buf.readInt32LE(i * 4);
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Compute the exact sets of outer channels (`cons`, `prod`) consumed and produced
|
|
152
|
+
* by a network statement block (such as an arm of `switch`), excluding local
|
|
153
|
+
* `chan` declarations inside the block.
|
|
154
|
+
*/
|
|
155
|
+
export function collectSwitchOuterIO(stmts, outerChanMap) {
|
|
156
|
+
const locals = new Set();
|
|
157
|
+
const cons = new Set();
|
|
158
|
+
const prod = new Set();
|
|
159
|
+
|
|
160
|
+
const addCons = (v) => {
|
|
161
|
+
if (v && !locals.has(v) && outerChanMap.has(v)) cons.add(v);
|
|
162
|
+
};
|
|
163
|
+
const addProd = (v) => {
|
|
164
|
+
if (v && !locals.has(v) && outerChanMap.has(v)) prod.add(v);
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
function walk(list) {
|
|
168
|
+
for (const s of list || []) {
|
|
169
|
+
switch (s.op) {
|
|
170
|
+
case "chan":
|
|
171
|
+
locals.add(s.name);
|
|
172
|
+
break;
|
|
173
|
+
case "drain":
|
|
174
|
+
addCons(s.src);
|
|
175
|
+
break;
|
|
176
|
+
case "gate":
|
|
177
|
+
case "splice":
|
|
178
|
+
case "coerce":
|
|
179
|
+
case "wrap":
|
|
180
|
+
case "match":
|
|
181
|
+
case "project":
|
|
182
|
+
case "guard":
|
|
183
|
+
addCons(s.src);
|
|
184
|
+
addProd(s.dst);
|
|
185
|
+
break;
|
|
186
|
+
case "const_unit":
|
|
187
|
+
addProd(s.dst);
|
|
188
|
+
break;
|
|
189
|
+
case "tee":
|
|
190
|
+
addCons(s.src);
|
|
191
|
+
for (const d of s.dsts) addProd(d);
|
|
192
|
+
break;
|
|
193
|
+
case "demux":
|
|
194
|
+
addCons(s.src);
|
|
195
|
+
for (const f of s.fields) addProd(f.name);
|
|
196
|
+
break;
|
|
197
|
+
case "mux":
|
|
198
|
+
for (const f of s.fields) addCons(f.name);
|
|
199
|
+
addProd(s.dst);
|
|
200
|
+
break;
|
|
201
|
+
case "spawn":
|
|
202
|
+
case "exec":
|
|
203
|
+
case "spec":
|
|
204
|
+
for (const i of s.inputs) addCons(i);
|
|
205
|
+
for (const o of s.outputs) addProd(o);
|
|
206
|
+
break;
|
|
207
|
+
case "switch": {
|
|
208
|
+
const inner = s.arms.length > 0 ? s.arms[0].body : (s.defaultBody || []);
|
|
209
|
+
walk(inner);
|
|
210
|
+
break;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
walk(stmts);
|
|
217
|
+
return { cons, prod };
|
|
218
|
+
}
|
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* kTVM Channel ADT (`BitDeque`), Kernel-Local LIFO `BitStack`, and `QuotaTracker`.
|
|
3
|
+
*
|
|
4
|
+
* Implements DOCS/KTVM_SPEC.md §3 and the 8-tuple channel state:
|
|
5
|
+
* c = <buf, st, prodSchema, consSchema, aligned, prod, cons, scope>
|
|
6
|
+
* - buf: unread bit sequence in a power-of-2 Uint32Array ring buffer
|
|
7
|
+
* - st (`status`): strictly monotone lifecycle `OPEN -> CLOSED | FAILED`
|
|
8
|
+
* - prodSchema / prodNodeId: suffix schema owed by producer at value boundaries
|
|
9
|
+
* - consSchema / consNodeId: full schema expected by consumer at value boundaries
|
|
10
|
+
* - aligned: consumer boundary-alignment flag (`true` iff no mid-value bits shifted)
|
|
11
|
+
* - prod, cons: unique owning producer / consumer handles (SPSC linearity)
|
|
12
|
+
* - scope: enclosing speculation scope ID (`0` = root scope)
|
|
13
|
+
* - Global byte / node / step quota enforcement (`KTVMQuotaError`)
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { KTVMQuotaError } from "./ast.mjs";
|
|
17
|
+
|
|
18
|
+
const MASKS = new Uint32Array(32);
|
|
19
|
+
for (let i = 1; i <= 30; i++) MASKS[i] = ((1 << i) - 1) >>> 0;
|
|
20
|
+
MASKS[31] = 0x7fffffff;
|
|
21
|
+
|
|
22
|
+
export const CHAN_STATUS = Object.freeze({
|
|
23
|
+
OPEN: "OPEN",
|
|
24
|
+
CLOSED: "CLOSED",
|
|
25
|
+
FAILED: "FAILED"
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
export class QuotaTracker {
|
|
29
|
+
constructor({
|
|
30
|
+
maxBitDequeBytes = Infinity,
|
|
31
|
+
maxNodes = Infinity,
|
|
32
|
+
maxSteps = Infinity
|
|
33
|
+
} = {}) {
|
|
34
|
+
this.maxBitDequeBytes = maxBitDequeBytes;
|
|
35
|
+
this.maxNodes = maxNodes;
|
|
36
|
+
this.maxSteps = maxSteps;
|
|
37
|
+
|
|
38
|
+
this.liveBitDequeBytes = 0;
|
|
39
|
+
this.peakBitDequeBytes = 0;
|
|
40
|
+
this.liveNodes = 0;
|
|
41
|
+
this.peakNodes = 0;
|
|
42
|
+
this.steps = 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
addBufferBytes(delta) {
|
|
46
|
+
this.liveBitDequeBytes += delta;
|
|
47
|
+
if (this.liveBitDequeBytes > this.peakBitDequeBytes) {
|
|
48
|
+
this.peakBitDequeBytes = this.liveBitDequeBytes;
|
|
49
|
+
}
|
|
50
|
+
if (this.liveBitDequeBytes > this.maxBitDequeBytes) {
|
|
51
|
+
throw new KTVMQuotaError("maxBitDequeBytes", this.maxBitDequeBytes, this.liveBitDequeBytes);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
addNode() {
|
|
56
|
+
this.liveNodes += 1;
|
|
57
|
+
if (this.liveNodes > this.peakNodes) {
|
|
58
|
+
this.peakNodes = this.liveNodes;
|
|
59
|
+
}
|
|
60
|
+
if (this.liveNodes > this.maxNodes) {
|
|
61
|
+
throw new KTVMQuotaError("maxNodes", this.maxNodes, this.liveNodes);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
removeNode() {
|
|
66
|
+
if (this.liveNodes > 0) this.liveNodes -= 1;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
tickStep() {
|
|
70
|
+
this.steps += 1;
|
|
71
|
+
if (this.steps > this.maxSteps) {
|
|
72
|
+
throw new KTVMQuotaError("maxSteps", this.maxSteps, this.steps);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export class BitDeque {
|
|
78
|
+
constructor(
|
|
79
|
+
id,
|
|
80
|
+
{
|
|
81
|
+
name = "",
|
|
82
|
+
prodSchema = null,
|
|
83
|
+
prodNodeId = 0,
|
|
84
|
+
consSchema = null,
|
|
85
|
+
consNodeId = 0,
|
|
86
|
+
aligned = true,
|
|
87
|
+
prod = null,
|
|
88
|
+
cons = null,
|
|
89
|
+
scope = 0,
|
|
90
|
+
quota = null,
|
|
91
|
+
initialWords = 4
|
|
92
|
+
} = {}
|
|
93
|
+
) {
|
|
94
|
+
this.id = id;
|
|
95
|
+
this.name = name || `%c${id}`;
|
|
96
|
+
this.status = CHAN_STATUS.OPEN;
|
|
97
|
+
|
|
98
|
+
// Dual schemas: upstream suffix obligation (`prodSchema`) vs. downstream view (`consSchema`)
|
|
99
|
+
this.prodSchema = prodSchema;
|
|
100
|
+
this.prodNodeId = prodNodeId;
|
|
101
|
+
this.consSchema = consSchema ?? prodSchema;
|
|
102
|
+
this.consNodeId = consSchema ? consNodeId : prodNodeId;
|
|
103
|
+
this.aligned = aligned;
|
|
104
|
+
|
|
105
|
+
this.prod = prod;
|
|
106
|
+
this.cons = cons;
|
|
107
|
+
this.scope = scope;
|
|
108
|
+
this.quota = quota;
|
|
109
|
+
this.retired = false;
|
|
110
|
+
|
|
111
|
+
this.words = new Uint32Array(initialWords);
|
|
112
|
+
this.wordMask = initialWords - 1;
|
|
113
|
+
this.capBits = initialWords << 5;
|
|
114
|
+
this.bitMask = this.capBits - 1;
|
|
115
|
+
this.headBit = 0;
|
|
116
|
+
this.lenBits = 0;
|
|
117
|
+
|
|
118
|
+
if (this.quota) {
|
|
119
|
+
this.quota.addBufferBytes(this.words.byteLength);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
get length() {
|
|
124
|
+
return this.lenBits;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
get isOpen() {
|
|
128
|
+
return this.status === CHAN_STATUS.OPEN;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
get isClosed() {
|
|
132
|
+
return this.status === CHAN_STATUS.CLOSED;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
get isFailed() {
|
|
136
|
+
return this.status === CHAN_STATUS.FAILED;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Singleton residual node list `[prodNodeId]` at the producer's aligned boundary. */
|
|
140
|
+
get prodNodeList() {
|
|
141
|
+
return this.prodSchema ? [this.prodNodeId] : [];
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Singleton residual node list `[consNodeId]` at the consumer's aligned boundary. */
|
|
145
|
+
get consNodeList() {
|
|
146
|
+
return this.consSchema ? [this.consNodeId] : [];
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
hasBits(n = 1) {
|
|
150
|
+
return this.lenBits >= n;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
_grow(minNeededBits) {
|
|
154
|
+
let newWordsLen = this.words.length << 1;
|
|
155
|
+
while ((newWordsLen << 5) < minNeededBits) newWordsLen <<= 1;
|
|
156
|
+
const oldWords = this.words;
|
|
157
|
+
const oldWordMask = this.wordMask;
|
|
158
|
+
const oldBitMask = this.bitMask;
|
|
159
|
+
const oldHead = this.headBit;
|
|
160
|
+
const oldLen = this.lenBits;
|
|
161
|
+
const oldBytes = oldWords.byteLength;
|
|
162
|
+
|
|
163
|
+
const newWords = new Uint32Array(newWordsLen);
|
|
164
|
+
if (this.quota) {
|
|
165
|
+
this.quota.addBufferBytes(newWords.byteLength - oldBytes);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
let rem = oldLen;
|
|
169
|
+
let srcPos = oldHead;
|
|
170
|
+
let dstPos = 0;
|
|
171
|
+
while (rem > 0) {
|
|
172
|
+
const chunk = rem > 30 ? 30 : rem;
|
|
173
|
+
const wi = srcPos >>> 5;
|
|
174
|
+
const bo = srcPos & 31;
|
|
175
|
+
let val;
|
|
176
|
+
if (bo + chunk <= 32) {
|
|
177
|
+
val = (oldWords[wi] >>> (32 - bo - chunk)) & MASKS[chunk];
|
|
178
|
+
} else {
|
|
179
|
+
const lo = bo + chunk - 32;
|
|
180
|
+
const hiBits = 32 - bo;
|
|
181
|
+
const w1 = (wi + 1) & oldWordMask;
|
|
182
|
+
val = (((oldWords[wi] & MASKS[hiBits]) << lo) | (oldWords[w1] >>> (32 - lo))) >>> 0;
|
|
183
|
+
}
|
|
184
|
+
const dwi = dstPos >>> 5;
|
|
185
|
+
const dbo = dstPos & 31;
|
|
186
|
+
if (dbo + chunk <= 32) {
|
|
187
|
+
newWords[dwi] |= (val << (32 - dbo - chunk)) >>> 0;
|
|
188
|
+
} else {
|
|
189
|
+
const lo = dbo + chunk - 32;
|
|
190
|
+
newWords[dwi] |= (val >>> lo) >>> 0;
|
|
191
|
+
newWords[dwi + 1] |= (val << (32 - lo)) >>> 0;
|
|
192
|
+
}
|
|
193
|
+
srcPos = (srcPos + chunk) & oldBitMask;
|
|
194
|
+
dstPos += chunk;
|
|
195
|
+
rem -= chunk;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
this.words = newWords;
|
|
199
|
+
this.wordMask = newWordsLen - 1;
|
|
200
|
+
this.capBits = newWordsLen << 5;
|
|
201
|
+
this.bitMask = this.capBits - 1;
|
|
202
|
+
this.headBit = 0;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
_pushSmall(val, width) {
|
|
206
|
+
if (width <= 0) return;
|
|
207
|
+
if (this.lenBits + width > this.capBits) {
|
|
208
|
+
this._grow(this.lenBits + width);
|
|
209
|
+
}
|
|
210
|
+
const v = (val >>> 0) & MASKS[width];
|
|
211
|
+
const tailPos = (this.headBit + this.lenBits) & this.bitMask;
|
|
212
|
+
const wi = tailPos >>> 5;
|
|
213
|
+
const bo = tailPos & 31;
|
|
214
|
+
if (bo + width <= 32) {
|
|
215
|
+
const shift = 32 - bo - width;
|
|
216
|
+
const clearMask = ~((MASKS[width] << shift) >>> 0);
|
|
217
|
+
this.words[wi] = ((this.words[wi] & clearMask) | ((v << shift) >>> 0)) >>> 0;
|
|
218
|
+
} else {
|
|
219
|
+
const lo = bo + width - 32;
|
|
220
|
+
const hiBits = 32 - bo;
|
|
221
|
+
const w1 = (wi + 1) & this.wordMask;
|
|
222
|
+
const hiMask = ~MASKS[hiBits];
|
|
223
|
+
this.words[wi] = ((this.words[wi] & hiMask) | (v >>> lo)) >>> 0;
|
|
224
|
+
const loShift = 32 - lo;
|
|
225
|
+
const loMask = ~((MASKS[lo] << loShift) >>> 0);
|
|
226
|
+
this.words[w1] = ((this.words[w1] & loMask) | ((v << loShift) >>> 0)) >>> 0;
|
|
227
|
+
}
|
|
228
|
+
this.lenBits += width;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Append `width` bits (0..32, MSB-first) to the back of the buffer. */
|
|
232
|
+
pushBits(val, width) {
|
|
233
|
+
if (width <= 0) return;
|
|
234
|
+
if (width <= 30) {
|
|
235
|
+
this._pushSmall(val, width);
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
const hiWidth = width - 16;
|
|
239
|
+
this._pushSmall((val >>> 16) >>> 0, hiWidth);
|
|
240
|
+
this._pushSmall(val & 0xffff, 16);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
_unshiftSmall(val, width) {
|
|
244
|
+
if (width <= 0) return;
|
|
245
|
+
if (this.lenBits + width > this.capBits) {
|
|
246
|
+
this._grow(this.lenBits + width);
|
|
247
|
+
}
|
|
248
|
+
const v = (val >>> 0) & MASKS[width];
|
|
249
|
+
const newHead = (this.headBit - width) & this.bitMask;
|
|
250
|
+
const wi = newHead >>> 5;
|
|
251
|
+
const bo = newHead & 31;
|
|
252
|
+
if (bo + width <= 32) {
|
|
253
|
+
const shift = 32 - bo - width;
|
|
254
|
+
const clearMask = ~((MASKS[width] << shift) >>> 0);
|
|
255
|
+
this.words[wi] = ((this.words[wi] & clearMask) | ((v << shift) >>> 0)) >>> 0;
|
|
256
|
+
} else {
|
|
257
|
+
const lo = bo + width - 32;
|
|
258
|
+
const hiBits = 32 - bo;
|
|
259
|
+
const w1 = (wi + 1) & this.wordMask;
|
|
260
|
+
const hiMask = ~MASKS[hiBits];
|
|
261
|
+
this.words[wi] = ((this.words[wi] & hiMask) | (v >>> lo)) >>> 0;
|
|
262
|
+
const loShift = 32 - lo;
|
|
263
|
+
const loMask = ~((MASKS[lo] << loShift) >>> 0);
|
|
264
|
+
this.words[w1] = ((this.words[w1] & loMask) | ((v << loShift) >>> 0)) >>> 0;
|
|
265
|
+
}
|
|
266
|
+
this.headBit = newHead;
|
|
267
|
+
this.lenBits += width;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Prepend `width` bits (0..32, MSB-first) onto the front of the buffer. */
|
|
271
|
+
unshiftBits(val, width) {
|
|
272
|
+
if (width <= 0) return;
|
|
273
|
+
if (width <= 30) {
|
|
274
|
+
this._unshiftSmall(val, width);
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
// Prepend low 16 bits first, then high bits in front of them
|
|
278
|
+
const hiWidth = width - 16;
|
|
279
|
+
this._unshiftSmall(val & 0xffff, 16);
|
|
280
|
+
this._unshiftSmall((val >>> 16) >>> 0, hiWidth);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
_peekSmallAt(bitOffset, width) {
|
|
284
|
+
if (width <= 0) return 0;
|
|
285
|
+
const pos = (this.headBit + bitOffset) & this.bitMask;
|
|
286
|
+
const wi = pos >>> 5;
|
|
287
|
+
const bo = pos & 31;
|
|
288
|
+
if (bo + width <= 32) {
|
|
289
|
+
return (this.words[wi] >>> (32 - bo - width)) & MASKS[width];
|
|
290
|
+
}
|
|
291
|
+
const lo = bo + width - 32;
|
|
292
|
+
const hiBits = 32 - bo;
|
|
293
|
+
const w1 = (wi + 1) & this.wordMask;
|
|
294
|
+
return (((this.words[wi] & MASKS[hiBits]) << lo) | (this.words[w1] >>> (32 - lo))) >>> 0;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Non-destructively read `width` bits (0..32) starting at `bitOffset` from front. */
|
|
298
|
+
peekBitsAt(bitOffset, width) {
|
|
299
|
+
if (width <= 0) return 0;
|
|
300
|
+
if (bitOffset < 0 || bitOffset + width > this.lenBits) {
|
|
301
|
+
throw new RangeError(
|
|
302
|
+
`BitDeque.peekBitsAt(${bitOffset}, ${width}) out of bounds (lenBits=${this.lenBits})`
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
if (width <= 30) return this._peekSmallAt(bitOffset, width);
|
|
306
|
+
const hiWidth = width - 16;
|
|
307
|
+
const hi = this._peekSmallAt(bitOffset, hiWidth);
|
|
308
|
+
const lo = this._peekSmallAt(bitOffset + hiWidth, 16);
|
|
309
|
+
return (((hi << 16) >>> 0) | lo) >>> 0;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
peekBits(width) {
|
|
313
|
+
return this.peekBitsAt(0, width);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Read and discard `width` bits (0..32) from front of buffer. */
|
|
317
|
+
shiftBits(width) {
|
|
318
|
+
if (width <= 0) return 0;
|
|
319
|
+
const val = this.peekBitsAt(0, width);
|
|
320
|
+
this.headBit = (this.headBit + width) & this.bitMask;
|
|
321
|
+
this.lenBits -= width;
|
|
322
|
+
return val;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** Prepend all bits of `src` in front of `this`, emptying `src`. Returns bits moved. */
|
|
326
|
+
unshiftFromDeque(src) {
|
|
327
|
+
const total = src.lenBits;
|
|
328
|
+
if (total === 0) return 0;
|
|
329
|
+
if (this.lenBits + total > this.capBits) {
|
|
330
|
+
this._grow(this.lenBits + total);
|
|
331
|
+
}
|
|
332
|
+
// Walk backwards from end of `src` in 30-bit chunks, unshifting onto front of `this`.
|
|
333
|
+
let rem = total;
|
|
334
|
+
while (rem > 0) {
|
|
335
|
+
const chunk = rem > 30 ? 30 : rem;
|
|
336
|
+
const offset = rem - chunk;
|
|
337
|
+
const bits = src._peekSmallAt(offset, chunk);
|
|
338
|
+
this._unshiftSmall(bits, chunk);
|
|
339
|
+
rem -= chunk;
|
|
340
|
+
}
|
|
341
|
+
src.headBit = 0;
|
|
342
|
+
src.lenBits = 0;
|
|
343
|
+
return total;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Append all bits of `src` to the back of `this`, emptying `src`. Returns bits moved. */
|
|
347
|
+
pushFromDeque(src) {
|
|
348
|
+
const total = src.lenBits;
|
|
349
|
+
if (total === 0) return 0;
|
|
350
|
+
if (this.lenBits + total > this.capBits) {
|
|
351
|
+
this._grow(this.lenBits + total);
|
|
352
|
+
}
|
|
353
|
+
let moved = 0;
|
|
354
|
+
while (src.lenBits > 0) {
|
|
355
|
+
const chunk = src.lenBits > 30 ? 30 : src.lenBits;
|
|
356
|
+
const bits = src.shiftBits(chunk);
|
|
357
|
+
this._pushSmall(bits, chunk);
|
|
358
|
+
moved += chunk;
|
|
359
|
+
}
|
|
360
|
+
return moved;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Steal the backing buffer of `src` in O(1) (`0` bits copied), emptying `src`. */
|
|
364
|
+
adoptBufferFrom(src) {
|
|
365
|
+
if (this.quota) {
|
|
366
|
+
this.quota.addBufferBytes(-this.words.byteLength);
|
|
367
|
+
}
|
|
368
|
+
this.words = src.words;
|
|
369
|
+
this.wordMask = src.wordMask;
|
|
370
|
+
this.capBits = src.capBits;
|
|
371
|
+
this.bitMask = src.bitMask;
|
|
372
|
+
this.headBit = src.headBit;
|
|
373
|
+
this.lenBits = src.lenBits;
|
|
374
|
+
|
|
375
|
+
// Leave `src` with an empty minimal backing buffer (released cleanly on release())
|
|
376
|
+
src.words = new Uint32Array(0);
|
|
377
|
+
src.wordMask = 0;
|
|
378
|
+
src.capBits = 0;
|
|
379
|
+
src.bitMask = 0;
|
|
380
|
+
src.headBit = 0;
|
|
381
|
+
src.lenBits = 0;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
close() {
|
|
385
|
+
if (this.status === CHAN_STATUS.OPEN) {
|
|
386
|
+
this.status = CHAN_STATUS.CLOSED;
|
|
387
|
+
this.prod = null;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
fail() {
|
|
392
|
+
if (this.status === CHAN_STATUS.OPEN) {
|
|
393
|
+
this.status = CHAN_STATUS.FAILED;
|
|
394
|
+
this.prod = null;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
release() {
|
|
399
|
+
if (this.retired) return;
|
|
400
|
+
this.retired = true;
|
|
401
|
+
if (this.quota && this.words.byteLength > 0) {
|
|
402
|
+
this.quota.addBufferBytes(-this.words.byteLength);
|
|
403
|
+
}
|
|
404
|
+
this.words = new Uint32Array(0);
|
|
405
|
+
this.lenBits = 0;
|
|
406
|
+
this.capBits = 0;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Debug helper: return unread bits as a '0'/'1' string. */
|
|
410
|
+
toBitString() {
|
|
411
|
+
let out = "";
|
|
412
|
+
for (let i = 0; i < this.lenBits; i++) {
|
|
413
|
+
out += this._peekSmallAt(i, 1) ? "1" : "0";
|
|
414
|
+
}
|
|
415
|
+
return out;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Kernel-local LIFO bit-stack (`stack s : bits`).
|
|
421
|
+
*
|
|
422
|
+
* Bits are stored sequentially in a growable Uint32Array; `push(word, k)` pushes
|
|
423
|
+
* LSB..MSB so `pop(k)` / `peekTop(k)` reads the top `k` bits MSB-first (so
|
|
424
|
+
* `push(0b10, 2); pop(2) === 0b10` and `push(0, 1); push(1, 1); pop(1) === 1`).
|
|
425
|
+
*/
|
|
426
|
+
export class BitStack {
|
|
427
|
+
constructor(quota = null, initialWords = 4) {
|
|
428
|
+
this.quota = quota;
|
|
429
|
+
this.words = new Uint32Array(initialWords);
|
|
430
|
+
this.lenBits = 0;
|
|
431
|
+
if (this.quota) {
|
|
432
|
+
this.quota.addBufferBytes(this.words.byteLength);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
get length() {
|
|
437
|
+
return this.lenBits;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
_ensure(neededBits) {
|
|
441
|
+
if (neededBits <= (this.words.length << 5)) return;
|
|
442
|
+
let newLen = this.words.length << 1;
|
|
443
|
+
while ((newLen << 5) < neededBits) newLen <<= 1;
|
|
444
|
+
const oldBytes = this.words.byteLength;
|
|
445
|
+
const next = new Uint32Array(newLen);
|
|
446
|
+
next.set(this.words);
|
|
447
|
+
this.words = next;
|
|
448
|
+
if (this.quota) {
|
|
449
|
+
this.quota.addBufferBytes(next.byteLength - oldBytes);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
push(word, k) {
|
|
454
|
+
if (k <= 0) return;
|
|
455
|
+
this._ensure(this.lenBits + k);
|
|
456
|
+
for (let i = 0; i < k; i++) {
|
|
457
|
+
const bit = (word >>> i) & 1;
|
|
458
|
+
const pos = this.lenBits++;
|
|
459
|
+
const wi = pos >>> 5;
|
|
460
|
+
const bo = pos & 31;
|
|
461
|
+
if (bit) this.words[wi] = (this.words[wi] | (1 << bo)) >>> 0;
|
|
462
|
+
else this.words[wi] = (this.words[wi] & ~(1 << bo)) >>> 0;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
peekTop(k) {
|
|
467
|
+
if (k <= 0) return 0;
|
|
468
|
+
if (k > this.lenBits) {
|
|
469
|
+
throw new RangeError(`BitStack.peekTop(${k}) underflow (lenBits=${this.lenBits})`);
|
|
470
|
+
}
|
|
471
|
+
let val = 0;
|
|
472
|
+
for (let i = 0; i < k; i++) {
|
|
473
|
+
const pos = this.lenBits - 1 - i;
|
|
474
|
+
const bit = (this.words[pos >>> 5] >>> (pos & 31)) & 1;
|
|
475
|
+
val = ((val << 1) | bit) >>> 0;
|
|
476
|
+
}
|
|
477
|
+
return val;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
pop(k) {
|
|
481
|
+
const val = this.peekTop(k);
|
|
482
|
+
this.lenBits -= k;
|
|
483
|
+
return val;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
clear() {
|
|
487
|
+
this.lenBits = 0;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
release() {
|
|
491
|
+
if (this.quota && this.words.byteLength > 0) {
|
|
492
|
+
this.quota.addBufferBytes(-this.words.byteLength);
|
|
493
|
+
}
|
|
494
|
+
this.words = new Uint32Array(0);
|
|
495
|
+
this.lenBits = 0;
|
|
496
|
+
}
|
|
497
|
+
}
|