@fraczak/k 8.9.0 → 9.0.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 +17 -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 +902 -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 +6 -4
- package/DOCS/README.md +3 -2
- package/DOCS/REPL.md +16 -12
- package/README.md +132 -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 -5
- package/backends/llvm/src/llvm.mjs +4 -111
- 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 +0 -16
- package/backends/wasm/README.md +2 -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 +10 -56
- 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/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 +482 -0
- package/ktvm/fixtures/integer-streaming.k +477 -0
- package/ktvm/index.mjs +119 -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 +543 -0
- package/ktvm/specialize.mjs +538 -0
- package/ktvm/test-conformance.mjs +597 -0
- package/ktvm/test-ktvm.mjs +1376 -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 +4413 -0
- package/ktvm/wasm/test-wasm.mjs +426 -0
- package/ktvm/wire.mjs +489 -0
- package/package.json +1 -9
- 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 +9 -229
- package/scripts/perf-int.mjs +14 -272
- package/scripts/perf-multiplication.mjs +8 -54
- 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
|
@@ -0,0 +1,1272 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Concrete `mono` kTVM -> WebAssembly Text (`WAT`) Compiler (Milestone 4).
|
|
3
|
+
*
|
|
4
|
+
* Lowers a validated concrete `mono` kTVM module (including unoptimized procs,
|
|
5
|
+
* fused kernels, virtual stacks, SWAR-compressed `chunk_table`s, `stack_table`s,
|
|
6
|
+
* and `fsm_table`s) into a standalone, zero-JS-callback WAT module backed by
|
|
7
|
+
* `k/ktvm/wasm/runtime.wat`.
|
|
8
|
+
*
|
|
9
|
+
* Key properties:
|
|
10
|
+
* - Global Moore-minimized schema DFA deduplication (`schemasEquivalent` = `i32.eq`).
|
|
11
|
+
* - Static linear-memory data segments for schema tables, chunk/stack/FSM tables,
|
|
12
|
+
* switch/spec descriptors, and pre-encoded output `k-wire` headers.
|
|
13
|
+
* - Straight-line Wasm instantiation functions for all `proc`s, `switch` arms,
|
|
14
|
+
* and `spec` branches (no bytecode interpreter).
|
|
15
|
+
* - Native Wasm `br_table` state machines for all compiled `kernel`s with
|
|
16
|
+
* suspend-point splitting and zero-overhead hot table bursts.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import fs from "node:fs";
|
|
20
|
+
import path from "node:path";
|
|
21
|
+
import { fileURLToPath } from "node:url";
|
|
22
|
+
|
|
23
|
+
import { collectSwitchOuterIO } from "../ast.mjs";
|
|
24
|
+
import { BitDeque } from "../bit-deque.mjs";
|
|
25
|
+
import {
|
|
26
|
+
compileSchemaExprToPlist,
|
|
27
|
+
mooreMinimize,
|
|
28
|
+
productFields
|
|
29
|
+
} from "../schema.mjs";
|
|
30
|
+
import { encodePayloadToDeque } from "../wire.mjs";
|
|
31
|
+
import { choiceWidth, CORE_PATTERN_PROPERTY_LIST } from "../../codecs/runtime/prefix-codec.mjs";
|
|
32
|
+
import { textToStringValue } from "../../codecs/runtime/unicode-string.mjs";
|
|
33
|
+
import { Value } from "../../Value.mjs";
|
|
34
|
+
|
|
35
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
36
|
+
let _runtimeWat = null;
|
|
37
|
+
function getRuntimeWat() {
|
|
38
|
+
if (_runtimeWat !== null) return _runtimeWat;
|
|
39
|
+
const localPath = path.join(__dirname, "runtime.wat");
|
|
40
|
+
if (fs.existsSync(localPath)) {
|
|
41
|
+
const text = fs.readFileSync(localPath, "utf8");
|
|
42
|
+
if (text.includes("ktvm_run_wire")) {
|
|
43
|
+
_runtimeWat = text;
|
|
44
|
+
return _runtimeWat;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
_runtimeWat = fs.readFileSync("ktvm/wasm/runtime.wat", "utf8");
|
|
48
|
+
return _runtimeWat;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function encodeBytesToWatString(bytes) {
|
|
52
|
+
let out = "";
|
|
53
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
54
|
+
const b = bytes[i];
|
|
55
|
+
out += "\\" + b.toString(16).padStart(2, "0");
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
class DataBuilder {
|
|
61
|
+
constructor(startOffset = 256) {
|
|
62
|
+
this.offset = startOffset;
|
|
63
|
+
this.chunks = []; // { offset, bytes: Uint8Array }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
align(a = 4) {
|
|
67
|
+
this.offset = (this.offset + (a - 1)) & ~(a - 1);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
emitBytes(bytes, alignment = 4) {
|
|
71
|
+
this.align(alignment);
|
|
72
|
+
const addr = this.offset;
|
|
73
|
+
const copy = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
74
|
+
if (copy.length > 0) {
|
|
75
|
+
this.chunks.push({ offset: addr, bytes: copy });
|
|
76
|
+
this.offset += copy.length;
|
|
77
|
+
}
|
|
78
|
+
return addr;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
emitI32Array(ints) {
|
|
82
|
+
const buf = new ArrayBuffer(ints.length * 4);
|
|
83
|
+
const dv = new DataView(buf);
|
|
84
|
+
for (let i = 0; i < ints.length; i++) {
|
|
85
|
+
dv.setInt32(i * 4, ints[i] | 0, true);
|
|
86
|
+
}
|
|
87
|
+
return this.emitBytes(new Uint8Array(buf), 4);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
toWatDataSegments() {
|
|
91
|
+
if (this.chunks.length === 0) return "";
|
|
92
|
+
// Merge contiguous/nearby chunks into a single compact static image!
|
|
93
|
+
const start = this.chunks[0].offset;
|
|
94
|
+
const end = this.offset;
|
|
95
|
+
const merged = new Uint8Array(end - start);
|
|
96
|
+
for (const c of this.chunks) {
|
|
97
|
+
merged.set(c.bytes, c.offset - start);
|
|
98
|
+
}
|
|
99
|
+
// Emit in 4096-byte WAT data segments for fast wabt parsing
|
|
100
|
+
const lines = [];
|
|
101
|
+
const CHUNK = 4096;
|
|
102
|
+
for (let off = 0; off < merged.length; off += CHUNK) {
|
|
103
|
+
const slice = merged.subarray(off, Math.min(off + CHUNK, merged.length));
|
|
104
|
+
lines.push(` (data (i32.const ${start + off}) "${encodeBytesToWatString(slice)}")`);
|
|
105
|
+
}
|
|
106
|
+
return lines.join("\n");
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function propertyListToPatternVal(plist) {
|
|
111
|
+
const UNIT = Value.product({});
|
|
112
|
+
const encodeKBitsUint = (n) => {
|
|
113
|
+
if (n === 0) return Value.variant("_", UNIT);
|
|
114
|
+
const bits = [];
|
|
115
|
+
let v = n;
|
|
116
|
+
while (v > 0) { bits.push(v & 1 ? "1" : "0"); v = Math.floor(v / 2); }
|
|
117
|
+
let cur = Value.variant("_", UNIT);
|
|
118
|
+
for (let i = bits.length - 1; i >= 0; i--) cur = Value.variant(bits[i], cur);
|
|
119
|
+
return cur;
|
|
120
|
+
};
|
|
121
|
+
let listVal = Value.variant("nil", UNIT);
|
|
122
|
+
for (let i = plist.length - 1; i >= 0; i--) {
|
|
123
|
+
const [kind, edges] = plist[i];
|
|
124
|
+
let nodeVal;
|
|
125
|
+
if (kind === "any") {
|
|
126
|
+
nodeVal = Value.variant("any", UNIT);
|
|
127
|
+
} else {
|
|
128
|
+
let edgeList = Value.variant("nil", UNIT);
|
|
129
|
+
for (let j = edges.length - 1; j >= 0; j--) {
|
|
130
|
+
const [label, target] = edges[j];
|
|
131
|
+
const edgeProd = Value.product({
|
|
132
|
+
label: textToStringValue(label),
|
|
133
|
+
target: encodeKBitsUint(target)
|
|
134
|
+
});
|
|
135
|
+
edgeList = Value.variant("cons", Value.product({ car: edgeProd, cdr: edgeList }));
|
|
136
|
+
}
|
|
137
|
+
nodeVal = Value.variant(kind, edgeList);
|
|
138
|
+
}
|
|
139
|
+
listVal = Value.variant("cons", Value.product({ car: nodeVal, cdr: listVal }));
|
|
140
|
+
}
|
|
141
|
+
return listVal;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function encodeHeaderBitsForPlist(plist) {
|
|
145
|
+
const dq = new BitDeque(-98);
|
|
146
|
+
encodePayloadToDeque(propertyListToPatternVal(plist), CORE_PATTERN_PROPERTY_LIST, dq, 0);
|
|
147
|
+
const bitLen = dq.length;
|
|
148
|
+
const nBytes = (bitLen + 7) >> 3;
|
|
149
|
+
const bytes = new Uint8Array(nBytes);
|
|
150
|
+
for (let i = 0; i < nBytes; i++) {
|
|
151
|
+
const rem = dq.length;
|
|
152
|
+
if (rem >= 8) bytes[i] = dq.shiftBits(8);
|
|
153
|
+
else bytes[i] = dq.shiftBits(rem) << (8 - rem);
|
|
154
|
+
}
|
|
155
|
+
dq.release();
|
|
156
|
+
return { bytes, bitLen };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Compile a validated concrete `mono` kTVM module into standalone WAT source +
|
|
161
|
+
* metadata (`inPlist`, `outPlist`, `inHeader`, `outHeader`, `tableBytes`).
|
|
162
|
+
*/
|
|
163
|
+
export function compileKTVMToWat(mod, { entry = null } = {}) {
|
|
164
|
+
if (mod.layer !== "mono") {
|
|
165
|
+
throw new Error("compileKTVMToWat requires a concrete 'mono' kTVM module");
|
|
166
|
+
}
|
|
167
|
+
const entryName = entry || mod.entry;
|
|
168
|
+
const procMap = new Map((mod.procs || []).map((p) => [p.name, p]));
|
|
169
|
+
const kernelMap = new Map((mod.kernels || []).map((k) => [k.name, k]));
|
|
170
|
+
const tableMap = new Map((mod.tables || []).map((t) => [t.name, t]));
|
|
171
|
+
const schemaDecls = new Map((mod.schemas || []).map((s) => [s.name, s]));
|
|
172
|
+
|
|
173
|
+
const entryProc = procMap.get(entryName);
|
|
174
|
+
const entryKernel = kernelMap.get(entryName);
|
|
175
|
+
const entryTarget = entryProc || entryKernel;
|
|
176
|
+
if (!entryTarget) throw new Error(`Unknown entry '${entryName}'`);
|
|
177
|
+
if (entryTarget.inputs.length !== 1 || entryTarget.outputs.length !== 1) {
|
|
178
|
+
throw new Error(`kTVM Wasm entry '${entryName}' must have 1 input and 1 output (got ${entryTarget.inputs.length} -> ${entryTarget.outputs.length})`);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// --- 1. Global Moore-Minimized Schema DFA Registry & Tag Interner ---
|
|
182
|
+
const tagToId = new Map();
|
|
183
|
+
const internTag = (tag) => {
|
|
184
|
+
const s = String(tag);
|
|
185
|
+
let id = tagToId.get(s);
|
|
186
|
+
if (id === undefined) {
|
|
187
|
+
id = tagToId.size;
|
|
188
|
+
tagToId.set(s, id);
|
|
189
|
+
}
|
|
190
|
+
return id;
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
const plistCache = new Map();
|
|
194
|
+
const resolvePlist = (expr) => {
|
|
195
|
+
const key = JSON.stringify(expr);
|
|
196
|
+
if (!plistCache.has(key)) {
|
|
197
|
+
const raw = compileSchemaExprToPlist(expr, schemaDecls, { allowOpen: false });
|
|
198
|
+
plistCache.set(key, mooreMinimize(raw, 0).plist);
|
|
199
|
+
}
|
|
200
|
+
return plistCache.get(key);
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
// Global deduplicated schema states: mooreKey -> { id, kind, edges: [[tagId, targetKey]] }
|
|
204
|
+
const schemaByMoore = new Map();
|
|
205
|
+
const schemaNodes = []; // indexed by global id (`0` is always `unit`!)
|
|
206
|
+
|
|
207
|
+
const internPlistState = (plist, nodeId = 0) => {
|
|
208
|
+
const min = mooreMinimize(plist, nodeId);
|
|
209
|
+
if (schemaByMoore.has(min.key)) return schemaByMoore.get(min.key).id;
|
|
210
|
+
|
|
211
|
+
// Register all reachable states of `min.plist` in two passes (handles cycles cleanly!)
|
|
212
|
+
const localToGlobal = new Array(min.plist.length);
|
|
213
|
+
const localMins = new Array(min.plist.length);
|
|
214
|
+
const newlyAdded = [];
|
|
215
|
+
|
|
216
|
+
for (let i = 0; i < min.plist.length; i++) {
|
|
217
|
+
const sm = i === 0 ? min : mooreMinimize(min.plist, i);
|
|
218
|
+
localMins[i] = sm;
|
|
219
|
+
if (schemaByMoore.has(sm.key)) {
|
|
220
|
+
localToGlobal[i] = schemaByMoore.get(sm.key).id;
|
|
221
|
+
} else {
|
|
222
|
+
const id = schemaNodes.length;
|
|
223
|
+
const entry = { id, key: sm.key, kind: min.plist[i][0], edges: null };
|
|
224
|
+
schemaNodes.push(entry);
|
|
225
|
+
schemaByMoore.set(sm.key, entry);
|
|
226
|
+
localToGlobal[i] = id;
|
|
227
|
+
newlyAdded.push({ i, entry });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
for (const { i, entry } of newlyAdded) {
|
|
231
|
+
const [, rawEdges] = min.plist[i];
|
|
232
|
+
entry.edges = rawEdges.map(([lbl, tgt]) => [internTag(lbl), localToGlobal[tgt]]);
|
|
233
|
+
}
|
|
234
|
+
return localToGlobal[0];
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
// Always reserve global schema ID 0 for `unit`!
|
|
238
|
+
internPlistState([["closed-product", []]], 0);
|
|
239
|
+
|
|
240
|
+
const internSchemaExpr = (expr) => internPlistState(resolvePlist(expr), 0);
|
|
241
|
+
|
|
242
|
+
const inPlist = resolvePlist(entryTarget.inputs[0].schema);
|
|
243
|
+
const outPlist = resolvePlist(entryTarget.outputs[0].schema);
|
|
244
|
+
const inSchemaId = internPlistState(inPlist, 0);
|
|
245
|
+
const outSchemaId = internPlistState(outPlist, 0);
|
|
246
|
+
|
|
247
|
+
// Pre-intern all schemas referenced in procs & kernels
|
|
248
|
+
const walkBlockSchemas = (stmts) => {
|
|
249
|
+
for (const s of stmts || []) {
|
|
250
|
+
if (s.schema) internSchemaExpr(s.schema);
|
|
251
|
+
if (s.srcSchema) internSchemaExpr(s.srcSchema);
|
|
252
|
+
if (s.dstSchema) internSchemaExpr(s.dstSchema);
|
|
253
|
+
if (s.tag !== undefined) internTag(s.tag);
|
|
254
|
+
if (s.op === "switch") {
|
|
255
|
+
for (const a of s.arms) {
|
|
256
|
+
for (const p of a.patterns) if (p.kind === "tag") internTag(p.tag);
|
|
257
|
+
walkBlockSchemas(a.body);
|
|
258
|
+
}
|
|
259
|
+
if (s.defaultBody) walkBlockSchemas(s.defaultBody);
|
|
260
|
+
} else if (s.op === "spec") {
|
|
261
|
+
for (const b of s.branches) walkBlockSchemas(b.body);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
for (const p of mod.procs || []) {
|
|
266
|
+
for (const i of p.inputs) internSchemaExpr(i.schema);
|
|
267
|
+
for (const o of p.outputs) internSchemaExpr(o.schema);
|
|
268
|
+
walkBlockSchemas(p.body);
|
|
269
|
+
}
|
|
270
|
+
for (const k of mod.kernels || []) {
|
|
271
|
+
for (const i of k.inputs) internSchemaExpr(i.schema);
|
|
272
|
+
for (const o of k.outputs) internSchemaExpr(o.schema);
|
|
273
|
+
for (const b of k.blocks || []) {
|
|
274
|
+
for (const s of b.stmts) {
|
|
275
|
+
if (s.nextSchema) internSchemaExpr(s.nextSchema);
|
|
276
|
+
if (s.schema) internSchemaExpr(s.schema);
|
|
277
|
+
if (s.srcSchema) internSchemaExpr(s.srcSchema);
|
|
278
|
+
if (s.dstSchema) internSchemaExpr(s.dstSchema);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const data = new DataBuilder(256);
|
|
284
|
+
|
|
285
|
+
// --- 2. Pack Static Data Segments: Schemas, Tables, Headers ---
|
|
286
|
+
|
|
287
|
+
// 2a. Schema Edges & Schema Nodes
|
|
288
|
+
const edgePtrs = schemaNodes.map((sn) => {
|
|
289
|
+
if (sn.edges.length === 0) return 0;
|
|
290
|
+
const flat = [];
|
|
291
|
+
for (const [tid, tgt] of sn.edges) {
|
|
292
|
+
flat.push(tid, tgt);
|
|
293
|
+
}
|
|
294
|
+
return data.emitI32Array(flat);
|
|
295
|
+
});
|
|
296
|
+
const schemaNodeWords = [];
|
|
297
|
+
for (let i = 0; i < schemaNodes.length; i++) {
|
|
298
|
+
const sn = schemaNodes[i];
|
|
299
|
+
const isUnion = sn.kind === "closed-union" ? 1 : 0;
|
|
300
|
+
const width = isUnion ? choiceWidth(sn.edges.length) : 0;
|
|
301
|
+
schemaNodeWords.push(isUnion, width, sn.edges.length, edgePtrs[i]);
|
|
302
|
+
}
|
|
303
|
+
const DATA_SCHEMA_NODES = data.emitI32Array(schemaNodeWords);
|
|
304
|
+
|
|
305
|
+
// 2b. Output & Input k-wire headers
|
|
306
|
+
const inHeader = encodeHeaderBitsForPlist(inPlist);
|
|
307
|
+
const outHeader = encodeHeaderBitsForPlist(outPlist);
|
|
308
|
+
const DATA_OUT_HDR_PTR = outHeader.bytes.length > 0 ? data.emitBytes(outHeader.bytes, 4) : 0;
|
|
309
|
+
const DATA_OUT_HDR_BITS = outHeader.bitLen;
|
|
310
|
+
|
|
311
|
+
// 2c. Static Chunk / Stack / FSM Tables
|
|
312
|
+
const tableMetaPtrs = new Map();
|
|
313
|
+
let totalTableBytes = 0;
|
|
314
|
+
|
|
315
|
+
const packKind = (k) => {
|
|
316
|
+
const s = k?.ident ?? k;
|
|
317
|
+
if (s === "CONT") return 0;
|
|
318
|
+
if (s === "EXIT") return 1;
|
|
319
|
+
if (s === "NEED_MORE") return 2;
|
|
320
|
+
return 3; // FAIL
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
for (const t of mod.tables || []) {
|
|
324
|
+
const entries = t.entries || [];
|
|
325
|
+
let numEntries = 0;
|
|
326
|
+
for (const r of entries) if (r.index + 1 > numEntries) numEntries = r.index + 1;
|
|
327
|
+
// Also support packedBase64 chunk_tables!
|
|
328
|
+
let entryBuf;
|
|
329
|
+
if (t.packedBase64 && entries.length === 0) {
|
|
330
|
+
const raw = Buffer.from(t.packedBase64, "base64");
|
|
331
|
+
const states = t.props.states || 1;
|
|
332
|
+
const inSpecs = t.props.inputs || [];
|
|
333
|
+
const totalEff = inSpecs.reduce((a, inp) => a + (inp.eff_bits ?? inp.raw_bits), 0);
|
|
334
|
+
numEntries = states * (1 << totalEff);
|
|
335
|
+
entryBuf = new Uint8Array(numEntries * 16);
|
|
336
|
+
const dv = new DataView(entryBuf.buffer);
|
|
337
|
+
const dvRaw = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
|
|
338
|
+
for (let i = 0; i < numEntries; i++) {
|
|
339
|
+
if (i * 8 + 8 <= raw.byteLength) {
|
|
340
|
+
const w0 = dvRaw.getUint32(i * 8, true);
|
|
341
|
+
const w1 = dvRaw.getUint32(i * 8 + 4, true);
|
|
342
|
+
const kind = w0 & 3;
|
|
343
|
+
const nextQ = (w0 >>> 2) & 0x3f;
|
|
344
|
+
const sh0 = (w0 >>> 8) & 0xff;
|
|
345
|
+
const sh1 = (w0 >>> 16) & 0xff;
|
|
346
|
+
const elen0 = (w0 >>> 24) & 0xff;
|
|
347
|
+
dv.setUint8(i * 16 + 0, kind);
|
|
348
|
+
dv.setUint8(i * 16 + 1, nextQ);
|
|
349
|
+
dv.setUint8(i * 16 + 2, sh0);
|
|
350
|
+
dv.setUint8(i * 16 + 3, sh1);
|
|
351
|
+
dv.setUint8(i * 16 + 4, elen0);
|
|
352
|
+
dv.setUint32(i * 16 + 8, w1 >>> 0, true);
|
|
353
|
+
} else {
|
|
354
|
+
dv.setUint8(i * 16 + 0, 2); // NEED_MORE
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
} else {
|
|
358
|
+
entryBuf = new Uint8Array(numEntries * 16);
|
|
359
|
+
const dv = new DataView(entryBuf.buffer);
|
|
360
|
+
// Default missing slots to NEED_MORE (2)
|
|
361
|
+
for (let i = 0; i < numEntries; i++) dv.setUint8(i * 16 + 0, 2);
|
|
362
|
+
|
|
363
|
+
for (const row of entries) {
|
|
364
|
+
const off = row.index * 16;
|
|
365
|
+
const v = row.value;
|
|
366
|
+
const kind = packKind(v.kind);
|
|
367
|
+
dv.setUint8(off + 0, kind);
|
|
368
|
+
if (t.kind === "chunk_table") {
|
|
369
|
+
dv.setUint8(off + 1, (kind === 1 ? (v.exit ?? 0) : (v.next_q ?? 0)) & 0xff);
|
|
370
|
+
const sh = v.shift || [];
|
|
371
|
+
const el = v.emit_len || [];
|
|
372
|
+
const ew = v.emit_word || [];
|
|
373
|
+
dv.setUint8(off + 2, (sh[0] ?? 0) & 0xff);
|
|
374
|
+
dv.setUint8(off + 3, (sh[1] ?? 0) & 0xff);
|
|
375
|
+
dv.setUint8(off + 4, (el[0] ?? 0) & 0xff);
|
|
376
|
+
dv.setUint8(off + 5, (el[1] ?? 0) & 0xff);
|
|
377
|
+
dv.setUint32(off + 8, (ew[0] ?? 0) >>> 0, true);
|
|
378
|
+
dv.setUint32(off + 12, (ew[1] ?? 0) >>> 0, true);
|
|
379
|
+
} else if (t.kind === "stack_table") {
|
|
380
|
+
dv.setUint8(off + 1, (kind === 1 ? (v.exit ?? 0) : (v.next_q ?? 0)) & 0xff);
|
|
381
|
+
dv.setUint8(off + 2, (v.shift_stream ?? 0) & 0xff);
|
|
382
|
+
dv.setUint8(off + 3, (v.pop_stack ?? 0) & 0xff);
|
|
383
|
+
dv.setUint8(off + 4, (v.push_stack_len ?? 0) & 0xff);
|
|
384
|
+
dv.setUint8(off + 5, (v.emit_len ?? 0) & 0xff);
|
|
385
|
+
dv.setUint32(off + 8, (v.push_stack_word ?? 0) >>> 0, true);
|
|
386
|
+
dv.setUint32(off + 12, (v.emit_word ?? 0) >>> 0, true);
|
|
387
|
+
} else if (t.kind === "fsm_table") {
|
|
388
|
+
dv.setUint8(off + 1, (v.exit ?? 0) & 0xff);
|
|
389
|
+
const sh = v.shift || [];
|
|
390
|
+
const el = v.emit_len || [];
|
|
391
|
+
const ew = v.emit_word || [];
|
|
392
|
+
dv.setUint8(off + 2, (sh[0] ?? 0) & 0xff);
|
|
393
|
+
dv.setUint8(off + 4, (el[0] ?? 0) & 0xff);
|
|
394
|
+
dv.setUint8(off + 5, (el[1] ?? 0) & 0xff);
|
|
395
|
+
dv.setUint32(off + 8, (ew[0] ?? 0) >>> 0, true);
|
|
396
|
+
dv.setUint32(off + 12, (ew[1] ?? 0) >>> 0, true);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
const entriesPtr = entryBuf.length > 0 ? data.emitBytes(entryBuf, 4) : 0;
|
|
402
|
+
totalTableBytes += entryBuf.length;
|
|
403
|
+
|
|
404
|
+
if (t.kind === "chunk_table") {
|
|
405
|
+
const ins = t.props.inputs || [];
|
|
406
|
+
const outs = t.props.outputs || [];
|
|
407
|
+
const maskOf = (inp) => {
|
|
408
|
+
if (!inp || !inp.compress || inp.compress.ident === "none") return -1;
|
|
409
|
+
if (typeof inp.compress.mask === "number") return inp.compress.mask | 0;
|
|
410
|
+
return -1;
|
|
411
|
+
};
|
|
412
|
+
const modeOf = (o) => ((o?.mode?.ident ?? o?.mode ?? "push") === "unshift" ? 1 : 0);
|
|
413
|
+
const metaPtr = data.emitI32Array([
|
|
414
|
+
entriesPtr,
|
|
415
|
+
numEntries,
|
|
416
|
+
ins.length,
|
|
417
|
+
outs.length,
|
|
418
|
+
ins[0]?.raw_bits ?? 0,
|
|
419
|
+
ins[0]?.eff_bits ?? ins[0]?.raw_bits ?? 0,
|
|
420
|
+
maskOf(ins[0]),
|
|
421
|
+
ins[1]?.raw_bits ?? 0,
|
|
422
|
+
ins[1]?.eff_bits ?? ins[1]?.raw_bits ?? 0,
|
|
423
|
+
maskOf(ins[1]),
|
|
424
|
+
modeOf(outs[0]),
|
|
425
|
+
modeOf(outs[1])
|
|
426
|
+
]);
|
|
427
|
+
tableMetaPtrs.set(t.name, metaPtr);
|
|
428
|
+
} else if (t.kind === "stack_table") {
|
|
429
|
+
const wStream = t.props.stream_bits ?? 0;
|
|
430
|
+
const wStack = t.props.stack_bits ?? 0;
|
|
431
|
+
const encStr = t.props.stack_encoding?.ident ?? t.props.stack_encoding ?? "bits";
|
|
432
|
+
const stEnc = encStr === "depth_only" ? 1 : 0;
|
|
433
|
+
const stStride = stEnc === 1 ? (wStack + 1) : ((1 << (wStack + 1)) - 1);
|
|
434
|
+
const outMode = (t.props.output_mode?.ident ?? t.props.output_mode ?? "push") === "unshift" ? 1 : 0;
|
|
435
|
+
const metaPtr = data.emitI32Array([
|
|
436
|
+
entriesPtr,
|
|
437
|
+
numEntries,
|
|
438
|
+
wStream,
|
|
439
|
+
wStack,
|
|
440
|
+
stEnc,
|
|
441
|
+
stStride,
|
|
442
|
+
outMode,
|
|
443
|
+
0
|
|
444
|
+
]);
|
|
445
|
+
tableMetaPtrs.set(t.name, metaPtr);
|
|
446
|
+
} else if (t.kind === "fsm_table") {
|
|
447
|
+
const wRaw = t.props.input_bits ?? 0;
|
|
448
|
+
const oms = t.props.output_modes || [];
|
|
449
|
+
const modeOf = (m) => ((m?.ident ?? m ?? "push") === "unshift" ? 1 : 0);
|
|
450
|
+
const metaPtr = data.emitI32Array([
|
|
451
|
+
entriesPtr,
|
|
452
|
+
numEntries,
|
|
453
|
+
wRaw,
|
|
454
|
+
oms.length || 1,
|
|
455
|
+
modeOf(oms[0]),
|
|
456
|
+
modeOf(oms[1]),
|
|
457
|
+
0
|
|
458
|
+
]);
|
|
459
|
+
tableMetaPtrs.set(t.name, metaPtr);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// --- 3. Assign Function Table Indices for Procs, Kernels, Switch Arms, Spec Branches ---
|
|
464
|
+
const fnTableNames = [];
|
|
465
|
+
const registerFn = (watName) => {
|
|
466
|
+
const idx = fnTableNames.length;
|
|
467
|
+
fnTableNames.push(watName);
|
|
468
|
+
return idx;
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
const procFnIdx = new Map();
|
|
472
|
+
const procWatName = new Map();
|
|
473
|
+
let fnSeq = 0;
|
|
474
|
+
for (const p of mod.procs || []) {
|
|
475
|
+
const wn = `$p_${fnSeq++}`;
|
|
476
|
+
procWatName.set(p.name, wn);
|
|
477
|
+
procFnIdx.set(p.name, registerFn(wn));
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const kernelFnIdx = new Map();
|
|
481
|
+
const kernelWatName = new Map();
|
|
482
|
+
const kernelMeta = new Map();
|
|
483
|
+
for (const k of mod.kernels || []) {
|
|
484
|
+
const wn = `$k_${fnSeq++}`;
|
|
485
|
+
kernelWatName.set(k.name, wn);
|
|
486
|
+
kernelFnIdx.set(k.name, registerFn(wn));
|
|
487
|
+
const regInits = (k.regs || []).map((r) => r.init ?? 0);
|
|
488
|
+
const regInitPtr = regInits.length > 0 ? data.emitI32Array(regInits) : 0;
|
|
489
|
+
// Count distinct temp names used in kernel
|
|
490
|
+
const tempNames = new Set();
|
|
491
|
+
for (const b of k.blocks || []) {
|
|
492
|
+
for (const s of b.stmts) {
|
|
493
|
+
if (s.dst && (s.op === "peek_bits" || s.op === "stack_pop")) tempNames.add(s.dst);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
kernelMeta.set(k.name, {
|
|
497
|
+
funcIdx: kernelFnIdx.get(k.name),
|
|
498
|
+
inCount: k.inputs.length,
|
|
499
|
+
outCount: k.outputs.length,
|
|
500
|
+
numRegs: (k.regs || []).length,
|
|
501
|
+
numStacks: (k.stacks || []).length,
|
|
502
|
+
numTemps: tempNames.size,
|
|
503
|
+
regInitPtr,
|
|
504
|
+
tempToIdx: new Map([...tempNames].map((n, i) => [n, i])),
|
|
505
|
+
regToIdx: new Map((k.regs || []).map((r, i) => [r.name, i])),
|
|
506
|
+
stackToIdx: new Map((k.stacks || []).map((s, i) => [s.name, i])),
|
|
507
|
+
inToIdx: new Map(k.inputs.map((p, i) => [p.name, i])),
|
|
508
|
+
outToIdx: new Map(k.outputs.map((p, i) => [p.name, i]))
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
const emittedFuncs = [];
|
|
513
|
+
|
|
514
|
+
// --- 4. Compile `proc` / `switch` arm / `spec` branch blocks to straight-line Wasm ---
|
|
515
|
+
|
|
516
|
+
function compileBlockFn(watFnName, stmts, envSlots) {
|
|
517
|
+
// envSlots: array of `{ kind: "chan"|"barrier"|"token", name }`
|
|
518
|
+
const chanLocal = new Map();
|
|
519
|
+
const barLocal = new Map();
|
|
520
|
+
const tokLocal = new Map();
|
|
521
|
+
let localSeq = 0;
|
|
522
|
+
const localDecls = [];
|
|
523
|
+
const freshLocal = (prefix = "v") => {
|
|
524
|
+
const nm = `$${prefix}_${localSeq++}`;
|
|
525
|
+
localDecls.push(`(local ${nm} i32)`);
|
|
526
|
+
return nm;
|
|
527
|
+
};
|
|
528
|
+
|
|
529
|
+
const lines = [];
|
|
530
|
+
const tmpNode = freshLocal("n");
|
|
531
|
+
const tmpArr = freshLocal("arr");
|
|
532
|
+
|
|
533
|
+
// Load env slots into locals
|
|
534
|
+
for (let i = 0; i < envSlots.length; i++) {
|
|
535
|
+
const sl = envSlots[i];
|
|
536
|
+
const loc = freshLocal("e");
|
|
537
|
+
if (sl.kind === "chan") chanLocal.set(sl.name, loc);
|
|
538
|
+
else if (sl.kind === "barrier") barLocal.set(sl.name, loc);
|
|
539
|
+
else if (sl.kind === "token") tokLocal.set(sl.name, loc);
|
|
540
|
+
lines.push(` (local.set ${loc} (i32.load (i32.add (local.get $env) (i32.const ${i * 4}))))`);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
for (const s of stmts || []) {
|
|
544
|
+
switch (s.op) {
|
|
545
|
+
case "chan": {
|
|
546
|
+
const loc = freshLocal("c");
|
|
547
|
+
chanLocal.set(s.name, loc);
|
|
548
|
+
const sid = internSchemaExpr(s.schema);
|
|
549
|
+
lines.push(` (local.set ${loc} (call $chan_alloc (local.get $sc) (i32.const ${sid})))`);
|
|
550
|
+
break;
|
|
551
|
+
}
|
|
552
|
+
case "barrier": {
|
|
553
|
+
const loc = freshLocal("b");
|
|
554
|
+
barLocal.set(s.name, loc);
|
|
555
|
+
lines.push(` (local.set ${loc} (call $barrier_alloc))`);
|
|
556
|
+
break;
|
|
557
|
+
}
|
|
558
|
+
case "const_unit": {
|
|
559
|
+
lines.push(` (call $emit_const_unit (local.get $sc) (local.get ${chanLocal.get(s.dst)}))`);
|
|
560
|
+
break;
|
|
561
|
+
}
|
|
562
|
+
case "splice": {
|
|
563
|
+
lines.push(` (call $emit_splice (local.get $sc) (local.get ${chanLocal.get(s.src)}) (local.get ${chanLocal.get(s.dst)}))`);
|
|
564
|
+
break;
|
|
565
|
+
}
|
|
566
|
+
case "coerce": {
|
|
567
|
+
const sSid = internSchemaExpr(s.srcSchema);
|
|
568
|
+
const dSid = internSchemaExpr(s.dstSchema);
|
|
569
|
+
lines.push(` (call $emit_coerce (local.get $sc) (local.get ${chanLocal.get(s.src)}) (local.get ${chanLocal.get(s.dst)}) (i32.const ${sSid}) (i32.const ${dSid}))`);
|
|
570
|
+
break;
|
|
571
|
+
}
|
|
572
|
+
case "wrap": {
|
|
573
|
+
const tid = internTag(s.tag);
|
|
574
|
+
lines.push(` (call $emit_wrap (local.get $sc) (local.get ${chanLocal.get(s.src)}) (local.get ${chanLocal.get(s.dst)}) (i32.const ${tid}))`);
|
|
575
|
+
break;
|
|
576
|
+
}
|
|
577
|
+
case "match": {
|
|
578
|
+
const tid = internTag(s.tag);
|
|
579
|
+
lines.push(` (call $emit_match (local.get $sc) (local.get ${chanLocal.get(s.src)}) (local.get ${chanLocal.get(s.dst)}) (i32.const ${tid}))`);
|
|
580
|
+
break;
|
|
581
|
+
}
|
|
582
|
+
case "drain": {
|
|
583
|
+
const sid = internSchemaExpr(s.schema);
|
|
584
|
+
const barExpr = s.barrier ? `(local.get ${barLocal.get(s.barrier)})` : `(i32.const 0)`;
|
|
585
|
+
lines.push(` (call $emit_drain (local.get $sc) (local.get ${chanLocal.get(s.src)}) (i32.const ${sid}) ${barExpr})`);
|
|
586
|
+
break;
|
|
587
|
+
}
|
|
588
|
+
case "gate": {
|
|
589
|
+
lines.push(` (call $emit_gate (local.get $sc) (local.get ${barLocal.get(s.barrier)}) (local.get ${chanLocal.get(s.src)}) (local.get ${chanLocal.get(s.dst)}))`);
|
|
590
|
+
break;
|
|
591
|
+
}
|
|
592
|
+
case "demux": {
|
|
593
|
+
const pl = resolvePlist(s.schema);
|
|
594
|
+
const sid = internPlistState(pl, 0);
|
|
595
|
+
const pf = productFields(pl, 0);
|
|
596
|
+
const byLbl = new Map(s.fields.map((f) => [f.label, f.name]));
|
|
597
|
+
const orderedOuts = pf.map((f) => byLbl.get(f.label));
|
|
598
|
+
lines.push(` (local.set ${tmpNode} (call $node_alloc (local.get $sc) (i32.const 6) (i32.const 1) (i32.const ${orderedOuts.length})))`);
|
|
599
|
+
lines.push(` (if (i32.ne (local.get ${tmpNode}) (i32.const 0)) (then`);
|
|
600
|
+
lines.push(` (call $node_set_in (local.get ${tmpNode}) (i32.const 0) (local.get ${chanLocal.get(s.src)}))`);
|
|
601
|
+
for (let i = 0; i < orderedOuts.length; i++) {
|
|
602
|
+
lines.push(` (call $node_set_out (local.get ${tmpNode}) (i32.const ${i}) (local.get ${chanLocal.get(orderedOuts[i])}))`);
|
|
603
|
+
}
|
|
604
|
+
lines.push(` (i32.store (i32.add (local.get ${tmpNode}) (i32.const 32)) (i32.const ${sid}))`);
|
|
605
|
+
lines.push(` ))`);
|
|
606
|
+
break;
|
|
607
|
+
}
|
|
608
|
+
case "mux": {
|
|
609
|
+
const pl = resolvePlist(s.schema);
|
|
610
|
+
const sid = internPlistState(pl, 0);
|
|
611
|
+
const pf = productFields(pl, 0);
|
|
612
|
+
const byLbl = new Map(s.fields.map((f) => [f.label, f.name]));
|
|
613
|
+
const orderedIns = pf.map((f) => byLbl.get(f.label));
|
|
614
|
+
lines.push(` (local.set ${tmpNode} (call $node_alloc (local.get $sc) (i32.const 7) (i32.const ${orderedIns.length}) (i32.const 1)))`);
|
|
615
|
+
lines.push(` (if (i32.ne (local.get ${tmpNode}) (i32.const 0)) (then`);
|
|
616
|
+
for (let i = 0; i < orderedIns.length; i++) {
|
|
617
|
+
lines.push(` (call $node_set_in (local.get ${tmpNode}) (i32.const ${i}) (local.get ${chanLocal.get(orderedIns[i])}))`);
|
|
618
|
+
}
|
|
619
|
+
lines.push(` (call $node_set_out (local.get ${tmpNode}) (i32.const 0) (local.get ${chanLocal.get(s.dst)}))`);
|
|
620
|
+
lines.push(` (i32.store (i32.add (local.get ${tmpNode}) (i32.const 32)) (i32.const ${sid}))`);
|
|
621
|
+
lines.push(` ))`);
|
|
622
|
+
break;
|
|
623
|
+
}
|
|
624
|
+
case "tee": {
|
|
625
|
+
lines.push(` (local.set ${tmpNode} (call $node_alloc (local.get $sc) (i32.const 8) (i32.const 1) (i32.const ${s.dsts.length})))`);
|
|
626
|
+
lines.push(` (if (i32.ne (local.get ${tmpNode}) (i32.const 0)) (then`);
|
|
627
|
+
lines.push(` (call $node_set_in (local.get ${tmpNode}) (i32.const 0) (local.get ${chanLocal.get(s.src)}))`);
|
|
628
|
+
for (let i = 0; i < s.dsts.length; i++) {
|
|
629
|
+
lines.push(` (call $node_set_out (local.get ${tmpNode}) (i32.const ${i}) (local.get ${chanLocal.get(s.dsts[i])}))`);
|
|
630
|
+
}
|
|
631
|
+
lines.push(` ))`);
|
|
632
|
+
break;
|
|
633
|
+
}
|
|
634
|
+
case "spawn": {
|
|
635
|
+
const targetIdx = procFnIdx.get(s.target);
|
|
636
|
+
if (targetIdx === undefined) throw new Error(`Unknown spawn target proc '${s.target}'`);
|
|
637
|
+
lines.push(` (local.set ${tmpNode} (call $node_alloc (local.get $sc) (i32.const 14) (i32.const ${s.inputs.length}) (i32.const ${s.outputs.length})))`);
|
|
638
|
+
lines.push(` (if (i32.ne (local.get ${tmpNode}) (i32.const 0)) (then`);
|
|
639
|
+
for (let i = 0; i < s.inputs.length; i++) {
|
|
640
|
+
lines.push(` (call $node_set_in (local.get ${tmpNode}) (i32.const ${i}) (local.get ${chanLocal.get(s.inputs[i])}))`);
|
|
641
|
+
}
|
|
642
|
+
for (let i = 0; i < s.outputs.length; i++) {
|
|
643
|
+
lines.push(` (call $node_set_out (local.get ${tmpNode}) (i32.const ${i}) (local.get ${chanLocal.get(s.outputs[i])}))`);
|
|
644
|
+
}
|
|
645
|
+
lines.push(` (i32.store (i32.add (local.get ${tmpNode}) (i32.const 32)) (i32.const ${targetIdx}))`);
|
|
646
|
+
if (s.after) {
|
|
647
|
+
lines.push(` (i32.store (i32.add (local.get ${tmpNode}) (i32.const 36)) (local.get ${tokLocal.get(s.after)}))`);
|
|
648
|
+
}
|
|
649
|
+
if (s.token) {
|
|
650
|
+
const tLoc = freshLocal("tok");
|
|
651
|
+
tokLocal.set(s.token, tLoc);
|
|
652
|
+
lines.push(` (local.set ${tLoc} (call $token_alloc (i32.load (i32.add (local.get ${tmpNode}) (i32.const 24))) (i32.const ${s.outputs.length})))`);
|
|
653
|
+
}
|
|
654
|
+
lines.push(` ))`);
|
|
655
|
+
break;
|
|
656
|
+
}
|
|
657
|
+
case "exec": {
|
|
658
|
+
const km = kernelMeta.get(s.target);
|
|
659
|
+
if (!km) throw new Error(`Unknown exec target kernel '${s.target}'`);
|
|
660
|
+
lines.push(` (local.set ${tmpNode} (call $emit_kernel (local.get $sc) (i32.const ${km.funcIdx}) (i32.const ${km.inCount}) (i32.const ${km.outCount}) (i32.const ${km.numRegs}) (i32.const ${km.numStacks}) (i32.const ${km.numTemps}) (i32.const ${km.regInitPtr})))`);
|
|
661
|
+
lines.push(` (if (i32.ne (local.get ${tmpNode}) (i32.const 0)) (then`);
|
|
662
|
+
for (let i = 0; i < s.inputs.length; i++) {
|
|
663
|
+
lines.push(` (call $node_set_in (local.get ${tmpNode}) (i32.const ${i}) (local.get ${chanLocal.get(s.inputs[i])}))`);
|
|
664
|
+
}
|
|
665
|
+
for (let i = 0; i < s.outputs.length; i++) {
|
|
666
|
+
lines.push(` (call $node_set_out (local.get ${tmpNode}) (i32.const ${i}) (local.get ${chanLocal.get(s.outputs[i])}))`);
|
|
667
|
+
}
|
|
668
|
+
lines.push(` ))`);
|
|
669
|
+
break;
|
|
670
|
+
}
|
|
671
|
+
case "switch": {
|
|
672
|
+
const firstBody = s.arms.length > 0 ? s.arms[0].body : (s.defaultBody || []);
|
|
673
|
+
const { cons: swCons, prod: swProd } = collectSwitchOuterIO(firstBody, chanLocal);
|
|
674
|
+
const remIns = [...swCons];
|
|
675
|
+
const remOuts = [...swProd];
|
|
676
|
+
|
|
677
|
+
// Capture ALL currently live channels, barriers, and tokens in scope for switch arms
|
|
678
|
+
const capSlots = [];
|
|
679
|
+
for (const [nm] of chanLocal.entries()) capSlots.push({ kind: "chan", name: nm });
|
|
680
|
+
for (const [nm] of barLocal.entries()) capSlots.push({ kind: "barrier", name: nm });
|
|
681
|
+
for (const [nm] of tokLocal.entries()) capSlots.push({ kind: "token", name: nm });
|
|
682
|
+
|
|
683
|
+
let testedMask = 0;
|
|
684
|
+
for (const arm of s.arms) {
|
|
685
|
+
for (let j = 0; j < arm.patterns.length; j++) {
|
|
686
|
+
if (arm.patterns[j].kind === "tag") testedMask |= (1 << j);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
const armEntries = [];
|
|
691
|
+
for (const arm of s.arms) {
|
|
692
|
+
const armFnName = `$sw_${fnSeq++}`;
|
|
693
|
+
const armFnIdx = registerFn(armFnName);
|
|
694
|
+
compileBlockFn(armFnName, arm.body, capSlots);
|
|
695
|
+
armEntries.push(armFnIdx);
|
|
696
|
+
for (const p of arm.patterns) {
|
|
697
|
+
armEntries.push(p.kind === "tag" ? internTag(p.tag) : -1);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
let defFnIdx = -1;
|
|
701
|
+
if (s.defaultBody) {
|
|
702
|
+
const defFnName = `$swd_${fnSeq++}`;
|
|
703
|
+
defFnIdx = registerFn(defFnName);
|
|
704
|
+
compileBlockFn(defFnName, s.defaultBody, capSlots);
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
const switchDescPtr = data.emitI32Array([
|
|
708
|
+
s.inputs.length,
|
|
709
|
+
s.arms.length,
|
|
710
|
+
defFnIdx,
|
|
711
|
+
testedMask,
|
|
712
|
+
...armEntries
|
|
713
|
+
]);
|
|
714
|
+
|
|
715
|
+
lines.push(` (local.set ${tmpNode} (call $node_alloc (local.get $sc) (i32.const 11) (i32.const ${remIns.length}) (i32.const ${remOuts.length})))`);
|
|
716
|
+
lines.push(` (if (i32.ne (local.get ${tmpNode}) (i32.const 0)) (then`);
|
|
717
|
+
for (let i = 0; i < remIns.length; i++) {
|
|
718
|
+
lines.push(` (call $node_set_in (local.get ${tmpNode}) (i32.const ${i}) (local.get ${chanLocal.get(remIns[i])}))`);
|
|
719
|
+
}
|
|
720
|
+
for (let i = 0; i < remOuts.length; i++) {
|
|
721
|
+
lines.push(` (call $node_set_out (local.get ${tmpNode}) (i32.const ${i}) (local.get ${chanLocal.get(remOuts[i])}))`);
|
|
722
|
+
}
|
|
723
|
+
lines.push(` (i32.store (i32.add (local.get ${tmpNode}) (i32.const 32)) (i32.const ${switchDescPtr}))`);
|
|
724
|
+
// Pack captured env
|
|
725
|
+
if (capSlots.length > 0) {
|
|
726
|
+
lines.push(` (local.set ${tmpArr} (call $alloc (i32.const ${capSlots.length * 4})))`);
|
|
727
|
+
for (let i = 0; i < capSlots.length; i++) {
|
|
728
|
+
const sl = capSlots[i];
|
|
729
|
+
const loc = sl.kind === "chan" ? chanLocal.get(sl.name) : (sl.kind === "barrier" ? barLocal.get(sl.name) : tokLocal.get(sl.name));
|
|
730
|
+
lines.push(` (i32.store (i32.add (local.get ${tmpArr}) (i32.const ${i * 4})) (local.get ${loc}))`);
|
|
731
|
+
}
|
|
732
|
+
lines.push(` (i32.store (i32.add (local.get ${tmpNode}) (i32.const 36)) (local.get ${tmpArr}))`);
|
|
733
|
+
lines.push(` (i32.store (i32.add (local.get ${tmpNode}) (i32.const 40)) (i32.const ${capSlots.length}))`);
|
|
734
|
+
}
|
|
735
|
+
// Pack inspectChans
|
|
736
|
+
if (s.inputs.length > 0) {
|
|
737
|
+
lines.push(` (local.set ${tmpArr} (call $alloc (i32.const ${s.inputs.length * 4})))`);
|
|
738
|
+
for (let i = 0; i < s.inputs.length; i++) {
|
|
739
|
+
lines.push(` (i32.store (i32.add (local.get ${tmpArr}) (i32.const ${i * 4})) (local.get ${chanLocal.get(s.inputs[i])}))`);
|
|
740
|
+
}
|
|
741
|
+
lines.push(` (i32.store (i32.add (local.get ${tmpNode}) (i32.const 44)) (local.get ${tmpArr}))`);
|
|
742
|
+
lines.push(` (i32.store (i32.add (local.get ${tmpNode}) (i32.const 48)) (i32.const ${s.inputs.length}))`);
|
|
743
|
+
}
|
|
744
|
+
lines.push(` ))`);
|
|
745
|
+
break;
|
|
746
|
+
}
|
|
747
|
+
case "spec": {
|
|
748
|
+
const brSlots = [
|
|
749
|
+
...s.inputs.map((nm) => ({ kind: "chan", name: nm })),
|
|
750
|
+
...s.outputs.map((nm) => ({ kind: "chan", name: nm }))
|
|
751
|
+
];
|
|
752
|
+
const brFnIndices = [];
|
|
753
|
+
for (const br of s.branches) {
|
|
754
|
+
const brName = `$sp_${fnSeq++}`;
|
|
755
|
+
const brIdx = registerFn(brName);
|
|
756
|
+
compileBlockFn(brName, br.body, brSlots);
|
|
757
|
+
brFnIndices.push(brIdx);
|
|
758
|
+
}
|
|
759
|
+
const specDescPtr = data.emitI32Array([s.branches.length, ...brFnIndices]);
|
|
760
|
+
|
|
761
|
+
lines.push(` (local.set ${tmpNode} (call $node_alloc (local.get $sc) (i32.const 12) (i32.const ${s.inputs.length}) (i32.const ${s.outputs.length})))`);
|
|
762
|
+
lines.push(` (if (i32.ne (local.get ${tmpNode}) (i32.const 0)) (then`);
|
|
763
|
+
for (let i = 0; i < s.inputs.length; i++) {
|
|
764
|
+
lines.push(` (call $node_set_in (local.get ${tmpNode}) (i32.const ${i}) (local.get ${chanLocal.get(s.inputs[i])}))`);
|
|
765
|
+
}
|
|
766
|
+
for (let i = 0; i < s.outputs.length; i++) {
|
|
767
|
+
lines.push(` (call $node_set_out (local.get ${tmpNode}) (i32.const ${i}) (local.get ${chanLocal.get(s.outputs[i])}))`);
|
|
768
|
+
}
|
|
769
|
+
lines.push(` (i32.store (i32.add (local.get ${tmpNode}) (i32.const 32)) (i32.const ${specDescPtr}))`);
|
|
770
|
+
lines.push(` ))`);
|
|
771
|
+
break;
|
|
772
|
+
}
|
|
773
|
+
default:
|
|
774
|
+
throw new Error(`Unsupported proc instruction '${s.op}' in Wasm compiler`);
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
emittedFuncs.push([
|
|
779
|
+
` (func ${watFnName} (type $block_fn) (param $sc i32) (param $env i32)`,
|
|
780
|
+
...localDecls.map((d) => ` ${d}`),
|
|
781
|
+
...lines,
|
|
782
|
+
` )`
|
|
783
|
+
].join("\n"));
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
for (const p of mod.procs || []) {
|
|
787
|
+
const envSlots = [
|
|
788
|
+
...p.inputs.map((i) => ({ kind: "chan", name: i.name })),
|
|
789
|
+
...p.outputs.map((o) => ({ kind: "chan", name: o.name }))
|
|
790
|
+
];
|
|
791
|
+
compileBlockFn(procWatName.get(p.name), p.body, envSlots);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// --- 5. Compile `kernel`s to Native Wasm `br_table` State Machines ---
|
|
795
|
+
|
|
796
|
+
const SUSPEND_OPS = new Set([
|
|
797
|
+
"peek_bits",
|
|
798
|
+
"shift_bits",
|
|
799
|
+
"shift_tag",
|
|
800
|
+
"drain_guard",
|
|
801
|
+
"dpda_copy",
|
|
802
|
+
"dpda_coerce",
|
|
803
|
+
"yield"
|
|
804
|
+
]);
|
|
805
|
+
|
|
806
|
+
function compileKernelFn(k) {
|
|
807
|
+
const km = kernelMeta.get(k.name);
|
|
808
|
+
const watName = kernelWatName.get(k.name);
|
|
809
|
+
|
|
810
|
+
// Order blocks so `entry` is ALWAYS pc = 0!
|
|
811
|
+
const orderedBlocks = [];
|
|
812
|
+
const entryBlk = k.blocks.find((b) => b.label === "entry");
|
|
813
|
+
orderedBlocks.push(entryBlk);
|
|
814
|
+
for (const b of k.blocks) if (b.label !== "entry") orderedBlocks.push(b);
|
|
815
|
+
|
|
816
|
+
// Split each block at suspending statements so every PC resumes cleanly at stmt 0!
|
|
817
|
+
const states = []; // { pc, stmts, term, fallthroughPc }
|
|
818
|
+
const labelToPc = new Map();
|
|
819
|
+
|
|
820
|
+
for (const b of orderedBlocks) {
|
|
821
|
+
const startPc = states.length;
|
|
822
|
+
labelToPc.set(b.label, startPc);
|
|
823
|
+
|
|
824
|
+
const segs = [];
|
|
825
|
+
let cur = [];
|
|
826
|
+
for (const s of b.stmts) {
|
|
827
|
+
if (SUSPEND_OPS.has(s.op) && cur.length > 0) {
|
|
828
|
+
segs.push(cur);
|
|
829
|
+
cur = [s];
|
|
830
|
+
} else {
|
|
831
|
+
cur.push(s);
|
|
832
|
+
// After `drain_guard`/`dpda_copy`/`dpda_coerce`/`yield`, also split so the next
|
|
833
|
+
// statement has its own PC when resuming after completion or yield!
|
|
834
|
+
if (s.op === "drain_guard" || s.op === "dpda_copy" || s.op === "dpda_coerce" || s.op === "yield") {
|
|
835
|
+
segs.push(cur);
|
|
836
|
+
cur = [];
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
if (cur.length > 0 || segs.length === 0) segs.push(cur);
|
|
841
|
+
|
|
842
|
+
for (let i = 0; i < segs.length; i++) {
|
|
843
|
+
const pc = states.length;
|
|
844
|
+
const isLast = i === segs.length - 1;
|
|
845
|
+
states.push({
|
|
846
|
+
pc,
|
|
847
|
+
stmts: segs[i],
|
|
848
|
+
term: isLast ? b.term : null,
|
|
849
|
+
fallthroughPc: isLast ? -1 : pc + 1
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
const M = states.length;
|
|
855
|
+
const lines = [];
|
|
856
|
+
lines.push(` (func ${watName} (type $kernel_fn) (param $n i32) (result i32)`);
|
|
857
|
+
lines.push(` (local $ks i32)`);
|
|
858
|
+
lines.push(` (local $pc i32)`);
|
|
859
|
+
lines.push(` (local $ch i32)`);
|
|
860
|
+
lines.push(` (local $val i32)`);
|
|
861
|
+
lines.push(` (local $st i32)`);
|
|
862
|
+
lines.push(` (local $res i32)`);
|
|
863
|
+
lines.push(` (local $burst i32)`);
|
|
864
|
+
lines.push(` (local $nn i32)`);
|
|
865
|
+
lines.push(` (local.set $ks (i32.load (i32.add (local.get $n) (i32.const 40))))`);
|
|
866
|
+
lines.push(` (local.set $pc (i32.load (i32.add (local.get $n) (i32.const 36))))`);
|
|
867
|
+
lines.push(` (local.set $burst (i32.const 0))`);
|
|
868
|
+
lines.push(` (loop $dispatch`);
|
|
869
|
+
lines.push(` (if (i32.ge_s (local.get $burst) (i32.const 64)) (then`);
|
|
870
|
+
lines.push(` (i32.store (i32.add (local.get $n) (i32.const 36)) (local.get $pc))`);
|
|
871
|
+
lines.push(` (return (i32.const 0))))`);
|
|
872
|
+
lines.push(` (local.set $burst (i32.add (local.get $burst) (i32.const 1)))`);
|
|
873
|
+
|
|
874
|
+
const emitGoto = (targetPc) => [
|
|
875
|
+
` (if (call $quota_tick_step) (then (i32.store (i32.add (local.get $n) (i32.const 36)) (i32.const ${targetPc})) (return (i32.const 0))))`,
|
|
876
|
+
` (local.set $pc (i32.const ${targetPc}))`,
|
|
877
|
+
` (br $dispatch)`
|
|
878
|
+
];
|
|
879
|
+
|
|
880
|
+
// Pre-generate body lines for each state `0 .. M-1`
|
|
881
|
+
const stateBodies = new Array(M);
|
|
882
|
+
for (let i = 0; i < M; i++) {
|
|
883
|
+
const st = states[i];
|
|
884
|
+
const bl = [];
|
|
885
|
+
|
|
886
|
+
for (const s of st.stmts) {
|
|
887
|
+
switch (s.op) {
|
|
888
|
+
case "peek_bits": {
|
|
889
|
+
const inIdx = km.inToIdx.get(s.src);
|
|
890
|
+
const tIdx = km.tempToIdx.get(s.dst);
|
|
891
|
+
const needed = s.offset + s.width;
|
|
892
|
+
const eofPc = labelToPc.get(s.onEof);
|
|
893
|
+
bl.push(` (local.set $ch (call $node_get_in (local.get $n) (i32.const ${inIdx})))`);
|
|
894
|
+
bl.push(` (if (i32.lt_s (i32.load (i32.add (local.get $ch) (i32.const 44))) (i32.const ${needed})) (then`);
|
|
895
|
+
bl.push(` (if (i32.eq (i32.load (local.get $ch)) (i32.const 0)) (then`);
|
|
896
|
+
bl.push(` (i32.store (i32.add (local.get $n) (i32.const 36)) (local.get $pc))`);
|
|
897
|
+
bl.push(` (global.set $g_need_pull (local.get $ch))`);
|
|
898
|
+
bl.push(` (return (i32.const 1))))`);
|
|
899
|
+
bl.push(` (if (i32.eq (i32.load (local.get $ch)) (i32.const 2)) (then (return (call $k_fail (local.get $n)))))`);
|
|
900
|
+
bl.push(` (local.set $pc (i32.const ${eofPc}))`);
|
|
901
|
+
bl.push(` (br $dispatch)))`);
|
|
902
|
+
bl.push(` (i32.store (i32.add (i32.load (i32.add (local.get $ks) (i32.const 20))) (i32.const ${tIdx * 4})) (call $bd_peek_bits_at (local.get $ch) (i32.const ${s.offset}) (i32.const ${s.width})))`);
|
|
903
|
+
break;
|
|
904
|
+
}
|
|
905
|
+
case "shift_bits": {
|
|
906
|
+
const inIdx = km.inToIdx.get(s.src);
|
|
907
|
+
bl.push(` (local.set $ch (call $node_get_in (local.get $n) (i32.const ${inIdx})))`);
|
|
908
|
+
if (s.width > 0) {
|
|
909
|
+
bl.push(` (if (i32.lt_s (i32.load (i32.add (local.get $ch) (i32.const 44))) (i32.const ${s.width})) (then`);
|
|
910
|
+
bl.push(` (if (i32.eq (i32.load (local.get $ch)) (i32.const 0)) (then`);
|
|
911
|
+
bl.push(` (i32.store (i32.add (local.get $n) (i32.const 36)) (local.get $pc))`);
|
|
912
|
+
bl.push(` (global.set $g_need_pull (local.get $ch))`);
|
|
913
|
+
bl.push(` (return (i32.const 1))))`);
|
|
914
|
+
bl.push(` (return (call $k_fail (local.get $n)))))`);
|
|
915
|
+
bl.push(` (drop (call $bd_shift_bits (local.get $ch) (i32.const ${s.width})))`);
|
|
916
|
+
}
|
|
917
|
+
bl.push(` (i32.store (i32.add (local.get $ch) (i32.const 12)) (i32.const 0))`);
|
|
918
|
+
break;
|
|
919
|
+
}
|
|
920
|
+
case "shift_tag": {
|
|
921
|
+
const inIdx = km.inToIdx.get(s.src);
|
|
922
|
+
const nextSid = internSchemaExpr(s.nextSchema);
|
|
923
|
+
bl.push(` (local.set $ch (call $node_get_in (local.get $n) (i32.const ${inIdx})))`);
|
|
924
|
+
if (s.width > 0) {
|
|
925
|
+
bl.push(` (if (i32.lt_s (i32.load (i32.add (local.get $ch) (i32.const 44))) (i32.const ${s.width})) (then`);
|
|
926
|
+
bl.push(` (if (i32.eq (i32.load (local.get $ch)) (i32.const 0)) (then`);
|
|
927
|
+
bl.push(` (i32.store (i32.add (local.get $n) (i32.const 36)) (local.get $pc))`);
|
|
928
|
+
bl.push(` (global.set $g_need_pull (local.get $ch))`);
|
|
929
|
+
bl.push(` (return (i32.const 1))))`);
|
|
930
|
+
bl.push(` (return (call $k_fail (local.get $n)))))`);
|
|
931
|
+
bl.push(` (drop (call $bd_shift_bits (local.get $ch) (i32.const ${s.width})))`);
|
|
932
|
+
}
|
|
933
|
+
bl.push(` (i32.store (i32.add (local.get $ch) (i32.const 8)) (i32.const ${nextSid}))`);
|
|
934
|
+
bl.push(` (i32.store (i32.add (local.get $ch) (i32.const 12)) (i32.const 1))`);
|
|
935
|
+
break;
|
|
936
|
+
}
|
|
937
|
+
case "push_bits": {
|
|
938
|
+
const outIdx = km.outToIdx.get(s.dst);
|
|
939
|
+
const bitsVal = parseInt(s.bits, 2) | 0;
|
|
940
|
+
bl.push(` (call $bd_push_bits (call $node_get_out (local.get $n) (i32.const ${outIdx})) (i32.const ${bitsVal}) (i32.const ${s.width}))`);
|
|
941
|
+
break;
|
|
942
|
+
}
|
|
943
|
+
case "unshift_bits": {
|
|
944
|
+
const outIdx = km.outToIdx.get(s.dst);
|
|
945
|
+
const bitsVal = parseInt(s.bits, 2) | 0;
|
|
946
|
+
bl.push(` (call $bd_unshift_bits (call $k_get_unshift_buf (local.get $n) (i32.const ${outIdx})) (i32.const ${bitsVal}) (i32.const ${s.width}))`);
|
|
947
|
+
break;
|
|
948
|
+
}
|
|
949
|
+
case "set_reg": {
|
|
950
|
+
const rIdx = km.regToIdx.get(s.reg);
|
|
951
|
+
bl.push(` (i32.store (i32.add (i32.load (local.get $ks)) (i32.const ${rIdx * 4})) (i32.const ${s.value | 0}))`);
|
|
952
|
+
break;
|
|
953
|
+
}
|
|
954
|
+
case "stack_push": {
|
|
955
|
+
const sIdx = km.stackToIdx.get(s.stack);
|
|
956
|
+
const bitsVal = parseInt(s.bits, 2) | 0;
|
|
957
|
+
bl.push(` (call $bs_push (i32.load (i32.add (i32.load (i32.add (local.get $ks) (i32.const 4))) (i32.const ${sIdx * 4}))) (i32.const ${bitsVal}) (i32.const ${s.width}))`);
|
|
958
|
+
break;
|
|
959
|
+
}
|
|
960
|
+
case "stack_pop": {
|
|
961
|
+
const sIdx = km.stackToIdx.get(s.stack);
|
|
962
|
+
const tIdx = km.tempToIdx.get(s.dst);
|
|
963
|
+
const emptyPc = labelToPc.get(s.onEmpty);
|
|
964
|
+
bl.push(` (local.set $st (i32.load (i32.add (i32.load (i32.add (local.get $ks) (i32.const 4))) (i32.const ${sIdx * 4}))))`);
|
|
965
|
+
bl.push(` (if (i32.lt_s (i32.load (i32.add (local.get $st) (i32.const 8))) (i32.const ${s.width})) (then`);
|
|
966
|
+
bl.push(` (local.set $pc (i32.const ${emptyPc}))`);
|
|
967
|
+
bl.push(` (br $dispatch)))`);
|
|
968
|
+
bl.push(` (i32.store (i32.add (i32.load (i32.add (local.get $ks) (i32.const 20))) (i32.const ${tIdx * 4})) (call $bs_pop (local.get $st) (i32.const ${s.width})))`);
|
|
969
|
+
break;
|
|
970
|
+
}
|
|
971
|
+
case "stack_clear": {
|
|
972
|
+
const sIdx = km.stackToIdx.get(s.stack);
|
|
973
|
+
bl.push(` (call $bs_clear (i32.load (i32.add (i32.load (i32.add (local.get $ks) (i32.const 4))) (i32.const ${sIdx * 4}))))`);
|
|
974
|
+
break;
|
|
975
|
+
}
|
|
976
|
+
case "drain_guard": {
|
|
977
|
+
const inIdx = km.inToIdx.get(s.src);
|
|
978
|
+
const sid = internSchemaExpr(s.schema);
|
|
979
|
+
bl.push(` (local.set $res (call $k_drain_guard (local.get $n) (i32.const ${inIdx}) (i32.const ${sid})))`);
|
|
980
|
+
bl.push(` (if (i32.eq (local.get $res) (i32.const 1)) (then (i32.store (i32.add (local.get $n) (i32.const 36)) (local.get $pc)) (return (i32.const 1))))`);
|
|
981
|
+
bl.push(` (if (i32.eq (local.get $res) (i32.const 2)) (then (return (call $k_fail (local.get $n)))))`);
|
|
982
|
+
break;
|
|
983
|
+
}
|
|
984
|
+
case "dpda_copy": {
|
|
985
|
+
const inIdx = km.inToIdx.get(s.src);
|
|
986
|
+
const outIdx = km.outToIdx.get(s.dst);
|
|
987
|
+
const sid = internSchemaExpr(s.schema);
|
|
988
|
+
bl.push(` (local.set $res (call $k_dpda_copy (local.get $n) (i32.const ${inIdx}) (i32.const ${outIdx}) (i32.const ${sid})))`);
|
|
989
|
+
bl.push(` (if (i32.eq (local.get $res) (i32.const 1)) (then (i32.store (i32.add (local.get $n) (i32.const 36)) (local.get $pc)) (return (i32.const 1))))`);
|
|
990
|
+
bl.push(` (if (i32.eq (local.get $res) (i32.const 2)) (then (return (call $k_fail (local.get $n)))))`);
|
|
991
|
+
break;
|
|
992
|
+
}
|
|
993
|
+
case "dpda_coerce": {
|
|
994
|
+
const inIdx = km.inToIdx.get(s.src);
|
|
995
|
+
const outIdx = km.outToIdx.get(s.dst);
|
|
996
|
+
const sSid = internSchemaExpr(s.srcSchema);
|
|
997
|
+
const dSid = internSchemaExpr(s.dstSchema);
|
|
998
|
+
bl.push(` (local.set $res (call $k_dpda_coerce (local.get $n) (i32.const ${inIdx}) (i32.const ${outIdx}) (i32.const ${sSid}) (i32.const ${dSid})))`);
|
|
999
|
+
bl.push(` (if (i32.eq (local.get $res) (i32.const 1)) (then (i32.store (i32.add (local.get $n) (i32.const 36)) (local.get $pc)) (return (i32.const 1))))`);
|
|
1000
|
+
bl.push(` (if (i32.eq (local.get $res) (i32.const 2)) (then (return (call $k_fail (local.get $n)))))`);
|
|
1001
|
+
break;
|
|
1002
|
+
}
|
|
1003
|
+
case "splice": {
|
|
1004
|
+
const inIdx = km.inToIdx.get(s.src);
|
|
1005
|
+
const outIdx = km.outToIdx.get(s.dst);
|
|
1006
|
+
bl.push(` (call $k_splice (local.get $n) (i32.const ${inIdx}) (i32.const ${outIdx}))`);
|
|
1007
|
+
break;
|
|
1008
|
+
}
|
|
1009
|
+
case "close": {
|
|
1010
|
+
const outIdx = km.outToIdx.get(s.dst);
|
|
1011
|
+
bl.push(` (call $k_close (local.get $n) (i32.const ${outIdx}))`);
|
|
1012
|
+
break;
|
|
1013
|
+
}
|
|
1014
|
+
case "yield": {
|
|
1015
|
+
const outIdx = km.outToIdx.get(s.dst);
|
|
1016
|
+
bl.push(` (i32.store (i32.add (local.get $ks) (i32.const 28)) (i32.const ${s.threshold | 0}))`);
|
|
1017
|
+
bl.push(` (local.set $ch (call $node_get_out (local.get $n) (i32.const ${outIdx})))`);
|
|
1018
|
+
if (st.fallthroughPc >= 0) {
|
|
1019
|
+
bl.push(` (if (i32.and (i32.ne (i32.load (i32.add (local.get $ch) (i32.const 20))) (i32.const 0)) (i32.ge_s (i32.load (i32.add (local.get $ch) (i32.const 44))) (i32.const ${s.threshold | 0}))) (then`);
|
|
1020
|
+
bl.push(` (i32.store (i32.add (local.get $n) (i32.const 36)) (i32.const ${st.fallthroughPc}))`);
|
|
1021
|
+
bl.push(` (return (i32.const 2))))`);
|
|
1022
|
+
}
|
|
1023
|
+
break;
|
|
1024
|
+
}
|
|
1025
|
+
default:
|
|
1026
|
+
throw new Error(`Unsupported kernel stmt '${s.op}' in Wasm compiler`);
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
if (st.fallthroughPc >= 0) {
|
|
1031
|
+
bl.push(` (local.set $pc (i32.const ${st.fallthroughPc}))`);
|
|
1032
|
+
bl.push(` (br $dispatch)`);
|
|
1033
|
+
stateBodies[i] = bl;
|
|
1034
|
+
continue;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
const t = st.term;
|
|
1038
|
+
switch (t.op) {
|
|
1039
|
+
case "goto": {
|
|
1040
|
+
bl.push(...emitGoto(labelToPc.get(t.target)));
|
|
1041
|
+
break;
|
|
1042
|
+
}
|
|
1043
|
+
case "retire": {
|
|
1044
|
+
bl.push(` (call $k_retire (local.get $n))`);
|
|
1045
|
+
bl.push(` (return (i32.const 0))`);
|
|
1046
|
+
break;
|
|
1047
|
+
}
|
|
1048
|
+
case "fail": {
|
|
1049
|
+
bl.push(` (return (call $k_fail (local.get $n)))`);
|
|
1050
|
+
break;
|
|
1051
|
+
}
|
|
1052
|
+
case "handoff": {
|
|
1053
|
+
bl.push(` (local.set $st (i32.load (i32.add (local.get $n) (i32.const 8))))`);
|
|
1054
|
+
const inIndices = t.inputs.map((v) => km.inToIdx.get(v));
|
|
1055
|
+
const outIndices = t.outputs.map((v) => km.outToIdx.get(v));
|
|
1056
|
+
bl.push(` (call $retire_node (local.get $n))`);
|
|
1057
|
+
if (kernelMeta.has(t.target)) {
|
|
1058
|
+
const tm = kernelMeta.get(t.target);
|
|
1059
|
+
bl.push(` (local.set $nn (call $emit_kernel (local.get $st) (i32.const ${tm.funcIdx}) (i32.const ${tm.inCount}) (i32.const ${tm.outCount}) (i32.const ${tm.numRegs}) (i32.const ${tm.numStacks}) (i32.const ${tm.numTemps}) (i32.const ${tm.regInitPtr})))`);
|
|
1060
|
+
} else {
|
|
1061
|
+
const pIdx = procFnIdx.get(t.target);
|
|
1062
|
+
if (pIdx === undefined) throw new Error(`Unknown handoff target '${t.target}'`);
|
|
1063
|
+
bl.push(` (local.set $nn (call $node_alloc (local.get $st) (i32.const 14) (i32.const ${inIndices.length}) (i32.const ${outIndices.length})))`);
|
|
1064
|
+
bl.push(` (if (i32.ne (local.get $nn) (i32.const 0)) (then (i32.store (i32.add (local.get $nn) (i32.const 32)) (i32.const ${pIdx}))))`);
|
|
1065
|
+
}
|
|
1066
|
+
bl.push(` (if (i32.ne (local.get $nn) (i32.const 0)) (then`);
|
|
1067
|
+
for (let j = 0; j < inIndices.length; j++) {
|
|
1068
|
+
bl.push(` (call $node_set_in (local.get $nn) (i32.const ${j}) (call $node_get_in (local.get $n) (i32.const ${inIndices[j]})))`);
|
|
1069
|
+
}
|
|
1070
|
+
for (let j = 0; j < outIndices.length; j++) {
|
|
1071
|
+
bl.push(` (call $node_set_out (local.get $nn) (i32.const ${j}) (call $node_get_out (local.get $n) (i32.const ${outIndices[j]})))`);
|
|
1072
|
+
}
|
|
1073
|
+
bl.push(` ))`);
|
|
1074
|
+
bl.push(` (return (i32.const 0))`);
|
|
1075
|
+
break;
|
|
1076
|
+
}
|
|
1077
|
+
case "switch_bits": {
|
|
1078
|
+
const tIdx = km.tempToIdx.get(t.src);
|
|
1079
|
+
bl.push(` (local.set $val (i32.load (i32.add (i32.load (i32.add (local.get $ks) (i32.const 20))) (i32.const ${tIdx * 4}))))`);
|
|
1080
|
+
for (const c of t.cases) {
|
|
1081
|
+
const cVal = parseInt(c.bits, 2) | 0;
|
|
1082
|
+
const tPc = labelToPc.get(c.target);
|
|
1083
|
+
bl.push(` (if (i32.eq (local.get $val) (i32.const ${cVal})) (then (local.set $pc (i32.const ${tPc})) (br $dispatch)))`);
|
|
1084
|
+
}
|
|
1085
|
+
if (t.defaultTarget) {
|
|
1086
|
+
bl.push(` (local.set $pc (i32.const ${labelToPc.get(t.defaultTarget)}))`);
|
|
1087
|
+
bl.push(` (br $dispatch)`);
|
|
1088
|
+
} else {
|
|
1089
|
+
bl.push(` (return (call $k_fail (local.get $n)))`);
|
|
1090
|
+
}
|
|
1091
|
+
break;
|
|
1092
|
+
}
|
|
1093
|
+
case "switch_reg": {
|
|
1094
|
+
const rIdx = km.regToIdx.get(t.reg);
|
|
1095
|
+
bl.push(` (local.set $val (i32.load (i32.add (i32.load (local.get $ks)) (i32.const ${rIdx * 4}))))`);
|
|
1096
|
+
for (const c of t.cases) {
|
|
1097
|
+
const tPc = labelToPc.get(c.target);
|
|
1098
|
+
bl.push(` (if (i32.eq (local.get $val) (i32.const ${c.value | 0})) (then (local.set $pc (i32.const ${tPc})) (br $dispatch)))`);
|
|
1099
|
+
}
|
|
1100
|
+
bl.push(` (return (call $k_fail (local.get $n)))`);
|
|
1101
|
+
break;
|
|
1102
|
+
}
|
|
1103
|
+
case "table_step": {
|
|
1104
|
+
const metaPtr = tableMetaPtrs.get(t.table);
|
|
1105
|
+
const rIdx = km.regToIdx.get(t.reg);
|
|
1106
|
+
const in0 = km.inToIdx.get(t.inputs[0]);
|
|
1107
|
+
const in1 = t.inputs.length > 1 ? km.inToIdx.get(t.inputs[1]) : 0;
|
|
1108
|
+
const out0 = km.outToIdx.get(t.outputs[0]);
|
|
1109
|
+
const out1 = t.outputs.length > 1 ? km.outToIdx.get(t.outputs[1]) : 0;
|
|
1110
|
+
bl.push(` (local.set $res (call $exec_chunk_table_step (local.get $n) (i32.const ${metaPtr}) (i32.const ${rIdx}) (i32.const ${in0}) (i32.const ${in1}) (i32.const ${out0}) (i32.const ${out1})))`);
|
|
1111
|
+
emitTableDispatch(bl, t.exits, labelToPc);
|
|
1112
|
+
break;
|
|
1113
|
+
}
|
|
1114
|
+
case "stack_table_step": {
|
|
1115
|
+
const metaPtr = tableMetaPtrs.get(t.table);
|
|
1116
|
+
const rIdx = km.regToIdx.get(t.reg);
|
|
1117
|
+
const inIdx = km.inToIdx.get(t.input);
|
|
1118
|
+
const sIdx = km.stackToIdx.get(t.stack);
|
|
1119
|
+
const outIdx = km.outToIdx.get(t.output);
|
|
1120
|
+
bl.push(` (local.set $res (call $exec_stack_table_step (local.get $n) (i32.const ${metaPtr}) (i32.const ${rIdx}) (i32.const ${inIdx}) (i32.const ${sIdx}) (i32.const ${outIdx})))`);
|
|
1121
|
+
emitTableDispatch(bl, t.exits, labelToPc);
|
|
1122
|
+
break;
|
|
1123
|
+
}
|
|
1124
|
+
case "fsm_table_step": {
|
|
1125
|
+
const metaPtr = tableMetaPtrs.get(t.table);
|
|
1126
|
+
const inIdx = km.inToIdx.get(t.input);
|
|
1127
|
+
const out0 = km.outToIdx.get(t.outputs[0]);
|
|
1128
|
+
const out1 = t.outputs.length > 1 ? km.outToIdx.get(t.outputs[1]) : 0;
|
|
1129
|
+
bl.push(` (local.set $res (call $exec_fsm_table_step (local.get $n) (i32.const ${metaPtr}) (i32.const ${inIdx}) (i32.const ${out0}) (i32.const ${out1})))`);
|
|
1130
|
+
emitTableDispatch(bl, t.exits, labelToPc);
|
|
1131
|
+
break;
|
|
1132
|
+
}
|
|
1133
|
+
default:
|
|
1134
|
+
throw new Error(`Unsupported kernel terminator '${t.op}' in Wasm compiler`);
|
|
1135
|
+
}
|
|
1136
|
+
stateBodies[i] = bl;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
// Emit balanced binary-split + bounded-depth `br_table` dispatch (max nesting <= 20 even
|
|
1140
|
+
// for 1,000+ states, preventing wabt recursive-descent stack overflow!)
|
|
1141
|
+
const emitRange = (lo, hi) => {
|
|
1142
|
+
const count = hi - lo;
|
|
1143
|
+
if (count <= 16) {
|
|
1144
|
+
for (let i = hi - 1; i >= lo; i--) {
|
|
1145
|
+
lines.push(` (block $s_${i}`);
|
|
1146
|
+
}
|
|
1147
|
+
const targets = [];
|
|
1148
|
+
for (let i = lo; i < hi; i++) targets.push(`$s_${i}`);
|
|
1149
|
+
const idxExpr = lo === 0 ? `(local.get $pc)` : `(i32.sub (local.get $pc) (i32.const ${lo}))`;
|
|
1150
|
+
lines.push(` (br_table ${targets.join(" ")} ${idxExpr})`);
|
|
1151
|
+
for (let i = lo; i < hi; i++) {
|
|
1152
|
+
lines.push(` )`);
|
|
1153
|
+
lines.push(...stateBodies[i]);
|
|
1154
|
+
}
|
|
1155
|
+
return;
|
|
1156
|
+
}
|
|
1157
|
+
const mid = (lo + hi) >> 1;
|
|
1158
|
+
lines.push(` (if (i32.lt_s (local.get $pc) (i32.const ${mid})) (then`);
|
|
1159
|
+
emitRange(lo, mid);
|
|
1160
|
+
lines.push(` ) (else`);
|
|
1161
|
+
emitRange(mid, hi);
|
|
1162
|
+
lines.push(` ))`);
|
|
1163
|
+
};
|
|
1164
|
+
|
|
1165
|
+
emitRange(0, M);
|
|
1166
|
+
|
|
1167
|
+
lines.push(` ) ;; end $dispatch`);
|
|
1168
|
+
lines.push(` (i32.const 0)`);
|
|
1169
|
+
lines.push(` )`);
|
|
1170
|
+
emittedFuncs.push(lines.join("\n"));
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
function emitTableDispatch(lines, exits, labelToPc) {
|
|
1174
|
+
const shortPc = labelToPc.get(exits.short || exits.fail);
|
|
1175
|
+
const failPc = labelToPc.get(exits.fail);
|
|
1176
|
+
lines.push(` (if (i32.eq (local.get $res) (i32.const 0)) (then (i32.store (i32.add (local.get $n) (i32.const 36)) (local.get $pc)) (return (i32.const 0))))`);
|
|
1177
|
+
lines.push(` (if (i32.eq (local.get $res) (i32.const 1)) (then (i32.store (i32.add (local.get $n) (i32.const 36)) (local.get $pc)) (return (i32.const 1))))`);
|
|
1178
|
+
lines.push(` (if (i32.eq (local.get $res) (i32.const 2)) (then (i32.store (i32.add (local.get $n) (i32.const 36)) (local.get $pc)) (return (i32.const 2))))`);
|
|
1179
|
+
lines.push(` (if (i32.eq (local.get $res) (i32.const 3)) (then (local.set $pc (i32.const ${shortPc})) (br $dispatch)))`);
|
|
1180
|
+
lines.push(` (if (i32.eq (local.get $res) (i32.const 4)) (then (local.set $pc (i32.const ${failPc})) (br $dispatch)))`);
|
|
1181
|
+
const numericExits = Object.entries(exits)
|
|
1182
|
+
.filter(([k]) => k !== "short" && k !== "fail")
|
|
1183
|
+
.map(([k, lbl]) => [Number(k), labelToPc.get(lbl)])
|
|
1184
|
+
.sort((a, b) => a[0] - b[0]);
|
|
1185
|
+
for (const [eid, epc] of numericExits) {
|
|
1186
|
+
lines.push(` (if (i32.eq (local.get $res) (i32.const ${100 + eid})) (then (local.set $pc (i32.const ${epc})) (br $dispatch)))`);
|
|
1187
|
+
}
|
|
1188
|
+
lines.push(` (local.set $pc (i32.const ${failPc}))`);
|
|
1189
|
+
lines.push(` (br $dispatch)`);
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
for (const k of mod.kernels || []) {
|
|
1193
|
+
compileKernelFn(k);
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
// --- 6. Emit `$start_entry` & Static Globals / Function Table / Data Segments ---
|
|
1197
|
+
const startEntryLines = [
|
|
1198
|
+
` (func $start_entry (param $sc i32) (param $rootIn i32) (param $rootOut i32)`,
|
|
1199
|
+
` (local $n i32)`
|
|
1200
|
+
];
|
|
1201
|
+
if (entryProc) {
|
|
1202
|
+
const pIdx = procFnIdx.get(entryName);
|
|
1203
|
+
startEntryLines.push(
|
|
1204
|
+
` (local.set $n (call $node_alloc (local.get $sc) (i32.const 14) (i32.const 1) (i32.const 1)))`,
|
|
1205
|
+
` (if (i32.eqz (local.get $n)) (then (return)))`,
|
|
1206
|
+
` (call $node_set_in (local.get $n) (i32.const 0) (local.get $rootIn))`,
|
|
1207
|
+
` (call $node_set_out (local.get $n) (i32.const 0) (local.get $rootOut))`,
|
|
1208
|
+
` (i32.store (i32.add (local.get $n) (i32.const 32)) (i32.const ${pIdx}))`
|
|
1209
|
+
);
|
|
1210
|
+
} else {
|
|
1211
|
+
const km = kernelMeta.get(entryName);
|
|
1212
|
+
startEntryLines.push(
|
|
1213
|
+
` (local.set $n (call $emit_kernel (local.get $sc) (i32.const ${km.funcIdx}) (i32.const 1) (i32.const 1) (i32.const ${km.numRegs}) (i32.const ${km.numStacks}) (i32.const ${km.numTemps}) (i32.const ${km.regInitPtr})))`,
|
|
1214
|
+
` (if (i32.eqz (local.get $n)) (then (return)))`,
|
|
1215
|
+
` (call $node_set_in (local.get $n) (i32.const 0) (local.get $rootIn))`,
|
|
1216
|
+
` (call $node_set_out (local.get $n) (i32.const 0) (local.get $rootOut))`
|
|
1217
|
+
);
|
|
1218
|
+
}
|
|
1219
|
+
startEntryLines.push(` )`);
|
|
1220
|
+
|
|
1221
|
+
data.align(16);
|
|
1222
|
+
const DATA_IO_BASE = data.offset;
|
|
1223
|
+
// Default 1 MiB reserved for I/O buffer (expandable dynamically via `ktvm_reserve_io`)
|
|
1224
|
+
const DATA_HEAP_BASE = DATA_IO_BASE + 1048576;
|
|
1225
|
+
|
|
1226
|
+
const fnTableCount = Math.max(1, fnTableNames.length);
|
|
1227
|
+
const elemLine = fnTableNames.length > 0
|
|
1228
|
+
? ` (elem (i32.const 0) func ${fnTableNames.join(" ")})`
|
|
1229
|
+
: "";
|
|
1230
|
+
|
|
1231
|
+
const wat = [
|
|
1232
|
+
`(module`,
|
|
1233
|
+
getRuntimeWat(),
|
|
1234
|
+
``,
|
|
1235
|
+
` ;; --- Generated Module Static Constants & Function Table ---`,
|
|
1236
|
+
` (global $DATA_SCHEMA_NODES i32 (i32.const ${DATA_SCHEMA_NODES}))`,
|
|
1237
|
+
` (global $DATA_IN_SCHEMA_ID i32 (i32.const ${inSchemaId}))`,
|
|
1238
|
+
` (global $DATA_OUT_SCHEMA_ID i32 (i32.const ${outSchemaId}))`,
|
|
1239
|
+
` (global $DATA_OUT_HDR_PTR i32 (i32.const ${DATA_OUT_HDR_PTR}))`,
|
|
1240
|
+
` (global $DATA_OUT_HDR_BITS i32 (i32.const ${DATA_OUT_HDR_BITS}))`,
|
|
1241
|
+
` (global $DATA_IO_BASE i32 (i32.const ${DATA_IO_BASE}))`,
|
|
1242
|
+
` (global $DATA_HEAP_BASE i32 (i32.const ${DATA_HEAP_BASE}))`,
|
|
1243
|
+
``,
|
|
1244
|
+
` (table ${fnTableCount} funcref)`,
|
|
1245
|
+
elemLine,
|
|
1246
|
+
``,
|
|
1247
|
+
data.toWatDataSegments(),
|
|
1248
|
+
``,
|
|
1249
|
+
startEntryLines.join("\n"),
|
|
1250
|
+
``,
|
|
1251
|
+
emittedFuncs.join("\n\n"),
|
|
1252
|
+
`)`
|
|
1253
|
+
].join("\n");
|
|
1254
|
+
|
|
1255
|
+
return {
|
|
1256
|
+
wat,
|
|
1257
|
+
entry: entryName,
|
|
1258
|
+
inPlist,
|
|
1259
|
+
outPlist,
|
|
1260
|
+
inHeader,
|
|
1261
|
+
outHeader,
|
|
1262
|
+
stats: {
|
|
1263
|
+
schemaNodes: schemaNodes.length,
|
|
1264
|
+
procs: (mod.procs || []).length,
|
|
1265
|
+
kernels: (mod.kernels || []).length,
|
|
1266
|
+
tables: (mod.tables || []).length,
|
|
1267
|
+
totalTableBytes,
|
|
1268
|
+
staticDataBytes: DATA_IO_BASE - 256,
|
|
1269
|
+
functions: fnTableNames.length
|
|
1270
|
+
}
|
|
1271
|
+
};
|
|
1272
|
+
}
|