@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.
Files changed (84) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/DOCS/ARCHITECTURE.md +5 -4
  3. package/DOCS/DICTIONARY.md +2 -2
  4. package/DOCS/FILE_FORMATS.md +11 -9
  5. package/DOCS/KIR_V1.md +5 -1
  6. package/DOCS/KTVM_SPEC.md +902 -0
  7. package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
  8. package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
  9. package/DOCS/PROFILING_AND_TRACING.md +6 -4
  10. package/DOCS/README.md +3 -2
  11. package/DOCS/REPL.md +16 -12
  12. package/README.md +132 -2
  13. package/backend-api.mjs +31 -16
  14. package/backends/llvm/README.md +4 -5
  15. package/backends/llvm/bin/k-llvm-build.mjs +7 -19
  16. package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
  17. package/backends/llvm/bin/k-llvm.mjs +11 -33
  18. package/backends/llvm/src/cli.mjs +2 -12
  19. package/backends/llvm/src/executable.mjs +7 -95
  20. package/backends/llvm/src/kvm2llvm.mjs +1 -5
  21. package/backends/llvm/src/llvm.mjs +4 -111
  22. package/backends/llvm/tests/k-llvm-run.mjs +1 -6
  23. package/backends/llvm/tests/perf-support.mjs +3 -5
  24. package/backends/llvm/tests/test-llvm.mjs +0 -16
  25. package/backends/wasm/README.md +2 -3
  26. package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
  27. package/backends/wasm/bin/k-wasm.mjs +4 -6
  28. package/backends/wasm/src/cli.mjs +8 -24
  29. package/backends/wasm/src/wasm.mjs +10 -56
  30. package/browser/repl-browser.mjs +9 -8
  31. package/browser/shims/buffer.mjs +31 -2
  32. package/browser/shims/child_process.mjs +26 -0
  33. package/browser/shims/fs.mjs +3 -1
  34. package/conformance/run.mjs +17 -2
  35. package/harness/adapters/ktvm-llvm.mjs +118 -0
  36. package/harness/adapters/ktvm-wasm.mjs +104 -0
  37. package/harness/adapters/ktvm.mjs +133 -0
  38. package/harness/registry.mjs +9 -0
  39. package/ktvm/ast.mjs +218 -0
  40. package/ktvm/bit-deque.mjs +482 -0
  41. package/ktvm/fixtures/integer-streaming.k +477 -0
  42. package/ktvm/index.mjs +119 -0
  43. package/ktvm/llvm/index.mjs +202 -0
  44. package/ktvm/llvm/lower-c.mjs +1258 -0
  45. package/ktvm/llvm/runtime.h +3542 -0
  46. package/ktvm/llvm/test-llvm.mjs +476 -0
  47. package/ktvm/lower-kir.mjs +2221 -0
  48. package/ktvm/optimize/fuse-kernel.mjs +2111 -0
  49. package/ktvm/optimize/index.mjs +116 -0
  50. package/ktvm/optimize/mwtr.mjs +283 -0
  51. package/ktvm/optimize/simplify-procs.mjs +5250 -0
  52. package/ktvm/optimize/synthesize-tables.mjs +1105 -0
  53. package/ktvm/parser.mjs +1101 -0
  54. package/ktvm/printer.mjs +281 -0
  55. package/ktvm/schema.mjs +543 -0
  56. package/ktvm/specialize.mjs +538 -0
  57. package/ktvm/test-conformance.mjs +597 -0
  58. package/ktvm/test-ktvm.mjs +1376 -0
  59. package/ktvm/test-optimize.mjs +598 -0
  60. package/ktvm/validator.mjs +1280 -0
  61. package/ktvm/vm.mjs +2225 -0
  62. package/ktvm/wasm/index.mjs +331 -0
  63. package/ktvm/wasm/lower-wasm.mjs +1272 -0
  64. package/ktvm/wasm/runtime.wat +4413 -0
  65. package/ktvm/wasm/test-wasm.mjs +426 -0
  66. package/ktvm/wire.mjs +489 -0
  67. package/package.json +1 -9
  68. package/repl.mjs +101 -20
  69. package/scripts/build-repl-html.mjs +40 -18
  70. package/scripts/perf-bigint-compare.mjs +12 -16
  71. package/scripts/perf-ieee.mjs +9 -229
  72. package/scripts/perf-int.mjs +14 -272
  73. package/scripts/perf-multiplication.mjs +8 -54
  74. package/scripts/perf-poly.mjs +9 -263
  75. package/scripts/run-tests.mjs +5 -2
  76. package/scripts/test-package.mjs +15 -3
  77. package/tests/README.md +3 -3
  78. package/tests/test-repl-html.mjs +72 -15
  79. package/tests/test-repl.mjs +24 -17
  80. package/DOCS/POLYMORPHIC_IR.md +0 -86
  81. package/access-table.mjs +0 -343
  82. package/pkir.mjs +0 -772
  83. package/tests/test-access-table.mjs +0 -213
  84. package/tests/test-pkir.mjs +0 -530
@@ -0,0 +1,1101 @@
1
+ /**
2
+ * Recursive-descent lexer & parser for the kTVM textual DSL (.ktvmp / .ktvm).
3
+ *
4
+ * Implements the exact EBNF grammar from DOCS/KTVM_SPEC.md §9.
5
+ */
6
+
7
+ import { KTVMSyntaxError, S, createModule } from "./ast.mjs";
8
+
9
+ const IDENT_START = /[A-Za-z_]/;
10
+ const IDENT_CONT = /[A-Za-z0-9_?'-]/;
11
+ const DIGIT = /[0-9]/;
12
+
13
+ export function tokenize(source) {
14
+ const tokens = [];
15
+ let i = 0;
16
+ let line = 1;
17
+ let col = 1;
18
+ const n = source.length;
19
+
20
+ const advance = () => {
21
+ const ch = source[i++];
22
+ if (ch === "\n") {
23
+ line += 1;
24
+ col = 1;
25
+ } else {
26
+ col += 1;
27
+ }
28
+ return ch;
29
+ };
30
+
31
+ while (i < n) {
32
+ const ch = source[i];
33
+ // Whitespace
34
+ if (ch === " " || ch === "\t" || ch === "\r" || ch === "\n") {
35
+ advance();
36
+ continue;
37
+ }
38
+ // Line comments: -- ... or // ...
39
+ if ((ch === "-" && source[i + 1] === "-") || (ch === "/" && source[i + 1] === "/")) {
40
+ while (i < n && source[i] !== "\n") advance();
41
+ continue;
42
+ }
43
+ // Block comments: /* ... */
44
+ if (ch === "/" && source[i + 1] === "*") {
45
+ const startLine = line;
46
+ const startCol = col;
47
+ advance();
48
+ advance();
49
+ let closed = false;
50
+ while (i < n) {
51
+ if (source[i] === "*" && source[i + 1] === "/") {
52
+ advance();
53
+ advance();
54
+ closed = true;
55
+ break;
56
+ }
57
+ advance();
58
+ }
59
+ if (!closed) {
60
+ throw new KTVMSyntaxError("Unterminated block comment", { line: startLine, col: startCol });
61
+ }
62
+ continue;
63
+ }
64
+
65
+ const startLine = line;
66
+ const startCol = col;
67
+
68
+ // Multi-char punctuation
69
+ if (ch === "-" && source[i + 1] === ">") {
70
+ advance(); advance();
71
+ tokens.push({ type: "ARROW", value: "->", line: startLine, col: startCol });
72
+ continue;
73
+ }
74
+ if (ch === "=" && source[i + 1] === ">") {
75
+ advance(); advance();
76
+ tokens.push({ type: "FAT_ARROW", value: "=>", line: startLine, col: startCol });
77
+ continue;
78
+ }
79
+ if (ch === "." && source[i + 1] === "." && source[i + 2] === ".") {
80
+ advance(); advance(); advance();
81
+ tokens.push({ type: "ELLIPSIS", value: "...", line: startLine, col: startCol });
82
+ continue;
83
+ }
84
+
85
+ // Sigil identifiers: $SCHEMA, @PROC, &TABLE, %VAR
86
+ if (ch === "$" || ch === "@" || ch === "&" || ch === "%") {
87
+ if (ch === "@" && i + 1 < n && DIGIT.test(source[i + 1])) {
88
+ // @INT offset token (used in peek_bits %in, @0, 2)
89
+ advance();
90
+ let num = "";
91
+ while (i < n && DIGIT.test(source[i])) num += advance();
92
+ tokens.push({ type: "AT_INT", value: Number(num), line: startLine, col: startCol });
93
+ continue;
94
+ }
95
+ if (i + 1 < n && IDENT_START.test(source[i + 1])) {
96
+ const sigil = advance();
97
+ let id = "";
98
+ while (i < n && IDENT_CONT.test(source[i])) id += advance();
99
+ const typeMap = { "$": "SCHEMA_ID", "@": "PROC_ID", "&": "TABLE_ID", "%": "VAR_ID" };
100
+ tokens.push({ type: typeMap[sigil], value: sigil + id, line: startLine, col: startCol });
101
+ continue;
102
+ }
103
+ throw new KTVMSyntaxError(`Unexpected sigil '${ch}' without identifier`, { line: startLine, col: startCol });
104
+ }
105
+
106
+ // String literal
107
+ if (ch === "\"") {
108
+ advance();
109
+ let str = "";
110
+ let closed = false;
111
+ while (i < n) {
112
+ const c = advance();
113
+ if (c === "\"") {
114
+ closed = true;
115
+ break;
116
+ }
117
+ if (c === "\\") {
118
+ if (i >= n) break;
119
+ const esc = advance();
120
+ switch (esc) {
121
+ case "n": str += "\n"; break;
122
+ case "r": str += "\r"; break;
123
+ case "t": str += "\t"; break;
124
+ case "b": str += "\b"; break;
125
+ case "f": str += "\f"; break;
126
+ case "\\": str += "\\"; break;
127
+ case "\"": str += "\""; break;
128
+ case "u": {
129
+ let hex = "";
130
+ for (let k = 0; k < 4 && i < n; k++) hex += advance();
131
+ if (hex.length !== 4 || !/^[0-9a-fA-F]{4}$/.test(hex)) {
132
+ throw new KTVMSyntaxError(`Invalid \\u escape '\\u${hex}'`, { line: startLine, col: startCol });
133
+ }
134
+ str += String.fromCharCode(parseInt(hex, 16));
135
+ break;
136
+ }
137
+ default: str += esc; break;
138
+ }
139
+ } else {
140
+ str += c;
141
+ }
142
+ }
143
+ if (!closed) {
144
+ throw new KTVMSyntaxError("Unterminated string literal", { line: startLine, col: startCol });
145
+ }
146
+ tokens.push({ type: "STRING", value: str, line: startLine, col: startCol });
147
+ continue;
148
+ }
149
+
150
+ // Bits literal 0b... or Number (INT / FLOAT)
151
+ if (DIGIT.test(ch)) {
152
+ if (ch === "0" && (source[i + 1] === "b" || source[i + 1] === "B")) {
153
+ advance(); advance();
154
+ let bits = "";
155
+ while (i < n && (source[i] === "0" || source[i] === "1")) bits += advance();
156
+ if (bits.length === 0) {
157
+ throw new KTVMSyntaxError("Empty binary literal 0b", { line: startLine, col: startCol });
158
+ }
159
+ tokens.push({ type: "BITS_LIT", value: bits, line: startLine, col: startCol });
160
+ continue;
161
+ }
162
+ let num = "";
163
+ while (i < n && DIGIT.test(source[i])) num += advance();
164
+ if (source[i] === "." && i + 1 < n && DIGIT.test(source[i + 1])) {
165
+ num += advance();
166
+ while (i < n && DIGIT.test(source[i])) num += advance();
167
+ tokens.push({ type: "FLOAT", value: num, line: startLine, col: startCol });
168
+ } else {
169
+ tokens.push({ type: "INT", value: num, line: startLine, col: startCol });
170
+ }
171
+ continue;
172
+ }
173
+
174
+ // Identifier / keyword
175
+ if (IDENT_START.test(ch)) {
176
+ let id = "";
177
+ while (i < n && IDENT_CONT.test(source[i])) {
178
+ // Avoid swallowing '->' as part of identifier
179
+ if (source[i] === "-" && source[i + 1] === ">") break;
180
+ id += advance();
181
+ }
182
+ tokens.push({ type: "IDENT", value: id, line: startLine, col: startCol });
183
+ continue;
184
+ }
185
+
186
+ // Single-char punctuation
187
+ const single = "(){}[]:;,=.|/?+-";
188
+ if (single.includes(ch)) {
189
+ advance();
190
+ tokens.push({ type: ch, value: ch, line: startLine, col: startCol });
191
+ continue;
192
+ }
193
+
194
+ throw new KTVMSyntaxError(`Unexpected character '${ch}'`, { line: startLine, col: startCol });
195
+ }
196
+
197
+ tokens.push({ type: "EOF", value: "", line, col });
198
+ return tokens;
199
+ }
200
+
201
+ class Parser {
202
+ constructor(tokens) {
203
+ this.tokens = tokens;
204
+ this.pos = 0;
205
+ }
206
+
207
+ peek(offset = 0) {
208
+ return this.tokens[this.pos + offset] || this.tokens[this.tokens.length - 1];
209
+ }
210
+
211
+ next() {
212
+ return this.tokens[this.pos++];
213
+ }
214
+
215
+ expect(type, value = null) {
216
+ const tok = this.peek();
217
+ if (tok.type !== type || (value !== null && tok.value !== value)) {
218
+ const want = value !== null ? `'${value}'` : type;
219
+ throw new KTVMSyntaxError(`Expected ${want}, got ${tok.type} ('${tok.value}')`, tok);
220
+ }
221
+ return this.next();
222
+ }
223
+
224
+ match(type, value = null) {
225
+ const tok = this.peek();
226
+ if (tok.type === type && (value === null || tok.value === value)) {
227
+ return this.next();
228
+ }
229
+ return null;
230
+ }
231
+
232
+ parseModule() {
233
+ // header ::= "ktvm" version layer_kind ("entry" PROC_ID)? ";"
234
+ this.expect("IDENT", "ktvm");
235
+ let version;
236
+ if (this.peek().type === "FLOAT") {
237
+ version = this.next().value;
238
+ } else {
239
+ const maj = this.expect("INT").value;
240
+ this.expect(".");
241
+ const min = this.expect("INT").value;
242
+ version = `${maj}.${min}`;
243
+ }
244
+ const layerTok = this.expect("IDENT");
245
+ if (layerTok.value !== "poly" && layerTok.value !== "mono") {
246
+ throw new KTVMSyntaxError(`Expected 'poly' or 'mono', got '${layerTok.value}'`, layerTok);
247
+ }
248
+ let entry = null;
249
+ if (this.match("IDENT", "entry")) {
250
+ entry = this.expect("PROC_ID").value;
251
+ }
252
+ this.expect(";");
253
+
254
+ const schemas = [];
255
+ const procs = [];
256
+ const kernels = [];
257
+ const tables = [];
258
+
259
+ while (this.peek().type !== "EOF") {
260
+ const kw = this.peek();
261
+ if (kw.type !== "IDENT") {
262
+ throw new KTVMSyntaxError(`Expected top-level declaration, got ${kw.type} ('${kw.value}')`, kw);
263
+ }
264
+ if (kw.value === "schema") schemas.push(this.parseSchemaDecl());
265
+ else if (kw.value === "proc") procs.push(this.parseProcDecl());
266
+ else if (kw.value === "kernel") kernels.push(this.parseKernelDecl());
267
+ else if (kw.value === "table") tables.push(this.parseTableDecl());
268
+ else {
269
+ throw new KTVMSyntaxError(`Unknown top-level keyword '${kw.value}'`, kw);
270
+ }
271
+ }
272
+
273
+ return createModule({ version, layer: layerTok.value, entry, schemas, procs, kernels, tables });
274
+ }
275
+
276
+ // --- Labels & Schemas ---
277
+
278
+ parseLabel() {
279
+ const tok = this.peek();
280
+ if (tok.type === "IDENT" || tok.type === "INT" || tok.type === "STRING" || tok.type === "+" || tok.type === "-") {
281
+ return this.next().value;
282
+ }
283
+ throw new KTVMSyntaxError(`Expected label, got ${tok.type} ('${tok.value}')`, tok);
284
+ }
285
+
286
+ parseSchemaParams() {
287
+ const params = [];
288
+ if (this.match("[")) {
289
+ params.push(this.expect("SCHEMA_ID").value);
290
+ while (this.match(",")) {
291
+ params.push(this.expect("SCHEMA_ID").value);
292
+ }
293
+ this.expect("]");
294
+ }
295
+ return params;
296
+ }
297
+
298
+ parseSchemaArgs() {
299
+ const args = [];
300
+ if (this.match("[")) {
301
+ args.push(this.parseSchemaExpr());
302
+ while (this.match(",")) {
303
+ args.push(this.parseSchemaExpr());
304
+ }
305
+ this.expect("]");
306
+ }
307
+ return args;
308
+ }
309
+
310
+ parseSchemaDecl() {
311
+ this.expect("IDENT", "schema");
312
+ const name = this.expect("SCHEMA_ID").value;
313
+ const params = this.parseSchemaParams();
314
+ this.expect("=");
315
+ const expr = this.parseSchemaExpr();
316
+ this.expect(";");
317
+ return { name, params, expr };
318
+ }
319
+
320
+ parseSchemaExpr() {
321
+ const tok = this.peek();
322
+ if (tok.type === "SCHEMA_ID") {
323
+ const name = this.next().value;
324
+ const args = this.parseSchemaArgs();
325
+ return S.ref(name, args);
326
+ }
327
+ if (tok.type === "IDENT") {
328
+ if (tok.value === "unit") {
329
+ this.next();
330
+ return S.unit();
331
+ }
332
+ if (tok.value === "any") {
333
+ this.next();
334
+ return S.any();
335
+ }
336
+ if (tok.value === "product" || tok.value === "union") {
337
+ const kind = this.next().value;
338
+ this.expect("{");
339
+ const fields = this.parseFieldSpecs(false);
340
+ this.expect("}");
341
+ return kind === "product" ? S.product(fields) : S.union(fields);
342
+ }
343
+ if (tok.value === "open_product" || tok.value === "open_union") {
344
+ const kind = this.next().value;
345
+ this.expect("{");
346
+ const fields = this.parseFieldSpecs(true);
347
+ this.expect("}");
348
+ return kind === "open_product" ? S.openProduct(fields) : S.openUnion(fields);
349
+ }
350
+ }
351
+ throw new KTVMSyntaxError(`Expected schema expression, got ${tok.type} ('${tok.value}')`, tok);
352
+ }
353
+
354
+ parseFieldSpecs(requireEllipsis) {
355
+ const fields = [];
356
+ let sawEllipsis = false;
357
+ while (this.peek().type !== "}") {
358
+ if (this.match("ELLIPSIS")) {
359
+ sawEllipsis = true;
360
+ this.match(",");
361
+ break;
362
+ }
363
+ const label = this.parseLabel();
364
+ this.expect(":");
365
+ const schema = this.parseSchemaExpr();
366
+ fields.push({ label, schema });
367
+ if (!this.match(",")) {
368
+ if (this.match("ELLIPSIS")) {
369
+ sawEllipsis = true;
370
+ this.match(",");
371
+ }
372
+ break;
373
+ }
374
+ }
375
+ if (requireEllipsis && !sawEllipsis) {
376
+ throw new KTVMSyntaxError("Expected '...' in open_product / open_union", this.peek());
377
+ }
378
+ return fields;
379
+ }
380
+
381
+ // --- Procedures (Network Layer) ---
382
+
383
+ parsePortList() {
384
+ const ports = [];
385
+ if (this.peek().type === ")") return ports;
386
+ do {
387
+ const name = this.expect("VAR_ID").value;
388
+ this.expect(":");
389
+ const schema = this.parseSchemaExpr();
390
+ ports.push({ name, schema });
391
+ } while (this.match(","));
392
+ return ports;
393
+ }
394
+
395
+ parseVarList() {
396
+ const vars = [];
397
+ if (this.peek().type === ")") return vars;
398
+ do {
399
+ vars.push(this.expect("VAR_ID").value);
400
+ } while (this.match(","));
401
+ return vars;
402
+ }
403
+
404
+ parseLabeledVars() {
405
+ const fields = [];
406
+ if (this.peek().type === ")") return fields;
407
+ do {
408
+ const label = this.parseLabel();
409
+ this.expect(":");
410
+ const name = this.expect("VAR_ID").value;
411
+ fields.push({ label, name });
412
+ } while (this.match(","));
413
+ return fields;
414
+ }
415
+
416
+ parseProcDecl() {
417
+ this.expect("IDENT", "proc");
418
+ const name = this.expect("PROC_ID").value;
419
+ const params = this.parseSchemaParams();
420
+ this.expect("(");
421
+ const inputs = this.parsePortList();
422
+ this.expect(")");
423
+ this.expect("ARROW");
424
+ this.expect("(");
425
+ const outputs = this.parsePortList();
426
+ this.expect(")");
427
+
428
+ const attrs = [];
429
+ while (this.peek().type === "IDENT" && ["acyclic", "branching", "total"].includes(this.peek().value)) {
430
+ attrs.push(this.next().value);
431
+ }
432
+
433
+ this.expect("{");
434
+ const body = [];
435
+ while (this.peek().type !== "}") {
436
+ body.push(this.parseNetStmt());
437
+ }
438
+ this.expect("}");
439
+ return { name, params, inputs, outputs, attrs, body };
440
+ }
441
+
442
+ parseNetStmt() {
443
+ const tok = this.expect("IDENT");
444
+ switch (tok.value) {
445
+ case "chan": {
446
+ const name = this.expect("VAR_ID").value;
447
+ this.expect(":");
448
+ const schema = this.parseSchemaExpr();
449
+ this.expect(";");
450
+ return { op: "chan", name, schema };
451
+ }
452
+ case "barrier": {
453
+ const name = this.expect("VAR_ID").value;
454
+ this.expect(";");
455
+ return { op: "barrier", name };
456
+ }
457
+ case "drain": {
458
+ const src = this.expect("VAR_ID").value;
459
+ this.expect(":");
460
+ const schema = this.parseSchemaExpr();
461
+ let barrier = null;
462
+ if (this.match("ARROW")) {
463
+ barrier = this.expect("VAR_ID").value;
464
+ }
465
+ this.expect(";");
466
+ return { op: "drain", src, schema, barrier };
467
+ }
468
+ case "gate": {
469
+ const barrier = this.expect("VAR_ID").value;
470
+ this.expect(",");
471
+ const src = this.expect("VAR_ID").value;
472
+ this.expect("ARROW");
473
+ const dst = this.expect("VAR_ID").value;
474
+ this.expect(";");
475
+ return { op: "gate", barrier, src, dst };
476
+ }
477
+ case "splice": {
478
+ const src = this.expect("VAR_ID").value;
479
+ this.expect("ARROW");
480
+ const dst = this.expect("VAR_ID").value;
481
+ this.expect(";");
482
+ return { op: "splice", src, dst };
483
+ }
484
+ case "coerce": {
485
+ const src = this.expect("VAR_ID").value;
486
+ this.expect(":");
487
+ const srcSchema = this.parseSchemaExpr();
488
+ this.expect("ARROW");
489
+ const dst = this.expect("VAR_ID").value;
490
+ this.expect(":");
491
+ const dstSchema = this.parseSchemaExpr();
492
+ this.expect(";");
493
+ return { op: "coerce", src, srcSchema, dst, dstSchema };
494
+ }
495
+ case "const_unit": {
496
+ this.expect("ARROW");
497
+ const dst = this.expect("VAR_ID").value;
498
+ this.expect(";");
499
+ return { op: "const_unit", dst };
500
+ }
501
+ case "tee": {
502
+ const src = this.expect("VAR_ID").value;
503
+ this.expect("ARROW");
504
+ this.expect("(");
505
+ const dsts = this.parseVarList();
506
+ this.expect(")");
507
+ this.expect(";");
508
+ return { op: "tee", src, dsts };
509
+ }
510
+ case "wrap": {
511
+ this.expect("|");
512
+ const tag = this.parseLabel();
513
+ const src = this.expect("VAR_ID").value;
514
+ this.expect("ARROW");
515
+ const dst = this.expect("VAR_ID").value;
516
+ this.expect(";");
517
+ return { op: "wrap", tag, src, dst };
518
+ }
519
+ case "match": {
520
+ this.expect("/");
521
+ const tag = this.parseLabel();
522
+ const src = this.expect("VAR_ID").value;
523
+ this.expect("ARROW");
524
+ const dst = this.expect("VAR_ID").value;
525
+ this.expect(";");
526
+ return { op: "match", tag, src, dst };
527
+ }
528
+ case "demux": {
529
+ const src = this.expect("VAR_ID").value;
530
+ this.expect(":");
531
+ const schema = this.parseSchemaExpr();
532
+ this.expect("ARROW");
533
+ this.expect("(");
534
+ const fields = this.parseLabeledVars();
535
+ this.expect(")");
536
+ this.expect(";");
537
+ return { op: "demux", src, schema, fields };
538
+ }
539
+ case "mux": {
540
+ this.expect("(");
541
+ const fields = this.parseLabeledVars();
542
+ this.expect(")");
543
+ this.expect("ARROW");
544
+ const dst = this.expect("VAR_ID").value;
545
+ this.expect(":");
546
+ const schema = this.parseSchemaExpr();
547
+ this.expect(";");
548
+ return { op: "mux", fields, dst, schema };
549
+ }
550
+ case "project": {
551
+ this.expect(".");
552
+ const field = this.parseLabel();
553
+ const src = this.expect("VAR_ID").value;
554
+ this.expect(":");
555
+ const srcSchema = this.parseSchemaExpr();
556
+ this.expect("ARROW");
557
+ const dst = this.expect("VAR_ID").value;
558
+ this.expect(":");
559
+ const dstSchema = this.parseSchemaExpr();
560
+ this.expect(";");
561
+ return { op: "project", field, src, srcSchema, dst, dstSchema };
562
+ }
563
+ case "guard": {
564
+ this.expect("?");
565
+ const schema = this.parseSchemaExpr();
566
+ const src = this.expect("VAR_ID").value;
567
+ this.expect("ARROW");
568
+ const dst = this.expect("VAR_ID").value;
569
+ this.expect(";");
570
+ return { op: "guard", schema, src, dst };
571
+ }
572
+ case "spawn": {
573
+ const target = this.expect("PROC_ID").value;
574
+ const schemaArgs = this.parseSchemaArgs();
575
+ this.expect("(");
576
+ const inputs = this.parseVarList();
577
+ this.expect(")");
578
+ this.expect("ARROW");
579
+ this.expect("(");
580
+ const outputs = this.parseVarList();
581
+ this.expect(")");
582
+ let after = null;
583
+ let token = null;
584
+ if (this.match("IDENT", "after")) {
585
+ after = this.expect("VAR_ID").value;
586
+ }
587
+ if (this.match("IDENT", "as")) {
588
+ token = this.expect("VAR_ID").value;
589
+ }
590
+ this.expect(";");
591
+ return { op: "spawn", target, schemaArgs, inputs, outputs, after, token };
592
+ }
593
+ case "exec": {
594
+ const target = this.expect("PROC_ID").value;
595
+ this.expect("(");
596
+ const inputs = this.parseVarList();
597
+ this.expect(")");
598
+ this.expect("ARROW");
599
+ this.expect("(");
600
+ const outputs = this.parseVarList();
601
+ this.expect(")");
602
+ this.expect(";");
603
+ return { op: "exec", target, inputs, outputs };
604
+ }
605
+ case "switch": {
606
+ this.expect("(");
607
+ const inputs = this.parseVarList();
608
+ this.expect(")");
609
+ this.expect("{");
610
+ const arms = [];
611
+ let defaultBody = null;
612
+ while (this.peek().type !== "}") {
613
+ if (this.match("IDENT", "case")) {
614
+ this.expect("(");
615
+ const patterns = [];
616
+ do {
617
+ if (this.match("/")) {
618
+ patterns.push({ kind: "tag", tag: this.parseLabel() });
619
+ } else {
620
+ this.expect("IDENT", "_");
621
+ patterns.push({ kind: "wildcard" });
622
+ }
623
+ } while (this.match(","));
624
+ this.expect(")");
625
+ this.expect(":");
626
+ this.expect("{");
627
+ const body = [];
628
+ while (this.peek().type !== "}") body.push(this.parseNetStmt());
629
+ this.expect("}");
630
+ arms.push({ patterns, body });
631
+ } else if (this.match("IDENT", "default")) {
632
+ this.expect(":");
633
+ this.expect("{");
634
+ defaultBody = [];
635
+ while (this.peek().type !== "}") defaultBody.push(this.parseNetStmt());
636
+ this.expect("}");
637
+ } else {
638
+ throw new KTVMSyntaxError(`Expected 'case' or 'default' in switch`, this.peek());
639
+ }
640
+ }
641
+ this.expect("}");
642
+ return { op: "switch", inputs, arms, defaultBody };
643
+ }
644
+ case "spec": {
645
+ this.expect("(");
646
+ const inputs = this.parseVarList();
647
+ this.expect(")");
648
+ this.expect("ARROW");
649
+ this.expect("(");
650
+ const outputs = this.parseVarList();
651
+ this.expect(")");
652
+ this.expect("{");
653
+ const branches = [];
654
+ while (this.peek().type !== "}") {
655
+ this.expect("IDENT", "branch");
656
+ const index = Number(this.expect("INT").value);
657
+ this.expect(":");
658
+ this.expect("{");
659
+ const body = [];
660
+ while (this.peek().type !== "}") body.push(this.parseNetStmt());
661
+ this.expect("}");
662
+ branches.push({ index, body });
663
+ }
664
+ this.expect("}");
665
+ return { op: "spec", inputs, outputs, branches };
666
+ }
667
+ default:
668
+ throw new KTVMSyntaxError(`Unknown network instruction '${tok.value}'`, tok);
669
+ }
670
+ }
671
+
672
+ // --- Kernels ---
673
+
674
+ parseKernelDecl() {
675
+ this.expect("IDENT", "kernel");
676
+ const name = this.expect("PROC_ID").value;
677
+ this.expect("(");
678
+ const inputs = this.parsePortList();
679
+ this.expect(")");
680
+ this.expect("ARROW");
681
+ this.expect("(");
682
+ const outputs = this.parsePortList();
683
+ this.expect(")");
684
+
685
+ const attrs = [];
686
+ while (this.peek().type === "IDENT" && ["total", "tmc"].includes(this.peek().value)) {
687
+ attrs.push(this.next().value);
688
+ }
689
+
690
+ this.expect("{");
691
+ const regs = [];
692
+ const stacks = [];
693
+ while (this.peek().type === "IDENT" && (this.peek().value === "reg" || this.peek().value === "stack")) {
694
+ if (this.match("IDENT", "reg")) {
695
+ const rname = this.expect("IDENT").value;
696
+ this.expect(":");
697
+ this.expect("IDENT", "enum");
698
+ this.expect("(");
699
+ const states = Number(this.expect("INT").value);
700
+ this.expect(")");
701
+ let init = 0;
702
+ if (this.match("=")) {
703
+ init = Number(this.expect("INT").value);
704
+ }
705
+ this.expect(";");
706
+ regs.push({ name: rname, states, init });
707
+ } else {
708
+ this.expect("IDENT", "stack");
709
+ const sname = this.expect("IDENT").value;
710
+ this.expect(":");
711
+ this.expect("IDENT", "bits");
712
+ this.expect(";");
713
+ stacks.push({ name: sname });
714
+ }
715
+ }
716
+
717
+ const blocks = [];
718
+ while (this.peek().type !== "}") {
719
+ blocks.push(this.parseKernelBlock());
720
+ }
721
+ this.expect("}");
722
+ return { name, inputs, outputs, attrs, regs, stacks, blocks };
723
+ }
724
+
725
+ parseKernelBlock() {
726
+ const label = this.expect("IDENT").value;
727
+ this.expect(":");
728
+ const stmts = [];
729
+ let term = null;
730
+ while (true) {
731
+ const tok = this.peek();
732
+ if (tok.type === "IDENT" && this._isKernelTerm(tok.value)) {
733
+ term = this.parseKernelTerm();
734
+ break;
735
+ }
736
+ stmts.push(this.parseKernelStmt());
737
+ }
738
+ return { label, stmts, term };
739
+ }
740
+
741
+ _isKernelTerm(kw) {
742
+ return (
743
+ kw === "goto" ||
744
+ kw === "retire" ||
745
+ kw === "fail" ||
746
+ kw === "handoff" ||
747
+ kw === "switch_bits" ||
748
+ kw === "switch_reg" ||
749
+ kw === "table_step" ||
750
+ kw === "stack_table_step" ||
751
+ kw === "fsm_table_step"
752
+ );
753
+ }
754
+
755
+ parseKernelStmt() {
756
+ if (this.peek().type === "VAR_ID") {
757
+ const dst = this.next().value;
758
+ this.expect("=");
759
+ const op = this.expect("IDENT").value;
760
+ if (op === "peek_bits") {
761
+ const src = this.expect("VAR_ID").value;
762
+ this.expect(",");
763
+ const offset = this.expect("AT_INT").value;
764
+ this.expect(",");
765
+ const width = Number(this.expect("INT").value);
766
+ this.expect("IDENT", "else");
767
+ const onEof = this.expect("IDENT").value;
768
+ this.expect(";");
769
+ return { op: "peek_bits", dst, src, offset, width, onEof };
770
+ }
771
+ if (op === "stack_pop") {
772
+ const stack = this.expect("IDENT").value;
773
+ this.expect(",");
774
+ const width = Number(this.expect("INT").value);
775
+ this.expect("IDENT", "else");
776
+ const onEmpty = this.expect("IDENT").value;
777
+ this.expect(";");
778
+ return { op: "stack_pop", dst, stack, width, onEmpty };
779
+ }
780
+ throw new KTVMSyntaxError(`Expected 'peek_bits' or 'stack_pop' after '='`, this.peek());
781
+ }
782
+
783
+ const tok = this.expect("IDENT");
784
+ switch (tok.value) {
785
+ case "shift_bits": {
786
+ const src = this.expect("VAR_ID").value;
787
+ this.expect(",");
788
+ const width = Number(this.expect("INT").value);
789
+ this.expect(";");
790
+ return { op: "shift_bits", src, width };
791
+ }
792
+ case "shift_tag": {
793
+ const src = this.expect("VAR_ID").value;
794
+ this.expect(",");
795
+ const width = Number(this.expect("INT").value);
796
+ this.expect("ARROW");
797
+ const nextSchema = this.parseSchemaExpr();
798
+ this.expect(";");
799
+ return { op: "shift_tag", src, width, nextSchema };
800
+ }
801
+ case "push_bits":
802
+ case "unshift_bits": {
803
+ const dst = this.expect("VAR_ID").value;
804
+ this.expect(",");
805
+ const bits = this.expect("BITS_LIT").value;
806
+ this.expect(",");
807
+ const width = Number(this.expect("INT").value);
808
+ this.expect(";");
809
+ return { op: tok.value, dst, bits, width };
810
+ }
811
+ case "set_reg": {
812
+ const reg = this.expect("IDENT").value;
813
+ this.expect(",");
814
+ const value = Number(this.expect("INT").value);
815
+ this.expect(";");
816
+ return { op: "set_reg", reg, value };
817
+ }
818
+ case "stack_push": {
819
+ const stack = this.expect("IDENT").value;
820
+ this.expect(",");
821
+ const bits = this.expect("BITS_LIT").value;
822
+ this.expect(",");
823
+ const width = Number(this.expect("INT").value);
824
+ this.expect(";");
825
+ return { op: "stack_push", stack, bits, width };
826
+ }
827
+ case "stack_clear": {
828
+ const stack = this.expect("IDENT").value;
829
+ this.expect(";");
830
+ return { op: "stack_clear", stack };
831
+ }
832
+ case "drain_guard": {
833
+ const src = this.expect("VAR_ID").value;
834
+ this.expect(":");
835
+ const schema = this.parseSchemaExpr();
836
+ this.expect(";");
837
+ return { op: "drain_guard", src, schema };
838
+ }
839
+ case "dpda_copy": {
840
+ const src = this.expect("VAR_ID").value;
841
+ this.expect("ARROW");
842
+ const dst = this.expect("VAR_ID").value;
843
+ this.expect(":");
844
+ const schema = this.parseSchemaExpr();
845
+ this.expect(";");
846
+ return { op: "dpda_copy", src, dst, schema };
847
+ }
848
+ case "dpda_coerce": {
849
+ const src = this.expect("VAR_ID").value;
850
+ this.expect(":");
851
+ const srcSchema = this.parseSchemaExpr();
852
+ this.expect("ARROW");
853
+ const dst = this.expect("VAR_ID").value;
854
+ this.expect(":");
855
+ const dstSchema = this.parseSchemaExpr();
856
+ this.expect(";");
857
+ return { op: "dpda_coerce", src, srcSchema, dst, dstSchema };
858
+ }
859
+ case "splice": {
860
+ const src = this.expect("VAR_ID").value;
861
+ this.expect("ARROW");
862
+ const dst = this.expect("VAR_ID").value;
863
+ this.expect(";");
864
+ return { op: "splice", src, dst };
865
+ }
866
+ case "close": {
867
+ const dst = this.expect("VAR_ID").value;
868
+ this.expect(";");
869
+ return { op: "close", dst };
870
+ }
871
+ case "yield": {
872
+ const dst = this.expect("VAR_ID").value;
873
+ this.expect(",");
874
+ const threshold = Number(this.expect("INT").value);
875
+ this.expect(";");
876
+ return { op: "yield", dst, threshold };
877
+ }
878
+ default:
879
+ throw new KTVMSyntaxError(`Unknown kernel statement '${tok.value}'`, tok);
880
+ }
881
+ }
882
+
883
+ parseExitMap() {
884
+ this.expect("ARROW");
885
+ this.expect("IDENT", "exits");
886
+ this.expect("{");
887
+ const exits = {};
888
+ while (this.peek().type !== "}") {
889
+ const kTok = this.peek();
890
+ let key;
891
+ if (kTok.type === "INT") {
892
+ key = String(Number(this.next().value));
893
+ } else if (kTok.type === "IDENT" && (kTok.value === "short" || kTok.value === "fail")) {
894
+ key = this.next().value;
895
+ } else {
896
+ throw new KTVMSyntaxError(`Expected exit key (int, 'short', or 'fail')`, kTok);
897
+ }
898
+ this.expect(":");
899
+ exits[key] = this.expect("IDENT").value;
900
+ if (!this.match(",")) break;
901
+ }
902
+ this.expect("}");
903
+ return exits;
904
+ }
905
+
906
+ parseKernelTerm() {
907
+ const tok = this.expect("IDENT");
908
+ switch (tok.value) {
909
+ case "goto": {
910
+ const target = this.expect("IDENT").value;
911
+ this.expect(";");
912
+ return { op: "goto", target };
913
+ }
914
+ case "retire":
915
+ this.expect(";");
916
+ return { op: "retire" };
917
+ case "fail":
918
+ this.expect(";");
919
+ return { op: "fail" };
920
+ case "handoff": {
921
+ const target = this.expect("PROC_ID").value;
922
+ this.expect("(");
923
+ const inputs = this.parseVarList();
924
+ this.expect(")");
925
+ this.expect("ARROW");
926
+ this.expect("(");
927
+ const outputs = this.parseVarList();
928
+ this.expect(")");
929
+ this.expect(";");
930
+ return { op: "handoff", target, inputs, outputs };
931
+ }
932
+ case "switch_bits": {
933
+ const src = this.expect("VAR_ID").value;
934
+ this.expect("{");
935
+ const cases = [];
936
+ let defaultTarget = null;
937
+ while (this.peek().type !== "}") {
938
+ if (this.match("IDENT", "case")) {
939
+ const bits = this.expect("BITS_LIT").value;
940
+ this.expect(":");
941
+ this.expect("IDENT", "goto");
942
+ const target = this.expect("IDENT").value;
943
+ this.expect(";");
944
+ cases.push({ bits, target });
945
+ } else if (this.match("IDENT", "default")) {
946
+ this.expect(":");
947
+ this.expect("IDENT", "goto");
948
+ defaultTarget = this.expect("IDENT").value;
949
+ this.expect(";");
950
+ } else {
951
+ throw new KTVMSyntaxError("Expected 'case' or 'default' in switch_bits", this.peek());
952
+ }
953
+ }
954
+ this.expect("}");
955
+ return { op: "switch_bits", src, cases, defaultTarget };
956
+ }
957
+ case "switch_reg": {
958
+ const reg = this.expect("IDENT").value;
959
+ this.expect("{");
960
+ const cases = [];
961
+ while (this.peek().type !== "}") {
962
+ this.expect("IDENT", "case");
963
+ const value = Number(this.expect("INT").value);
964
+ this.expect(":");
965
+ this.expect("IDENT", "goto");
966
+ const target = this.expect("IDENT").value;
967
+ this.expect(";");
968
+ cases.push({ value, target });
969
+ }
970
+ this.expect("}");
971
+ return { op: "switch_reg", reg, cases };
972
+ }
973
+ case "table_step": {
974
+ const table = this.expect("TABLE_ID").value;
975
+ this.expect(",");
976
+ const reg = this.expect("IDENT").value;
977
+ this.expect(",");
978
+ this.expect("(");
979
+ const inputs = this.parseVarList();
980
+ this.expect(")");
981
+ this.expect(",");
982
+ this.expect("(");
983
+ const outputs = this.parseVarList();
984
+ this.expect(")");
985
+ const exits = this.parseExitMap();
986
+ this.expect(";");
987
+ return { op: "table_step", table, reg, inputs, outputs, exits };
988
+ }
989
+ case "stack_table_step": {
990
+ const table = this.expect("TABLE_ID").value;
991
+ this.expect(",");
992
+ const reg = this.expect("IDENT").value;
993
+ this.expect(",");
994
+ const input = this.expect("VAR_ID").value;
995
+ this.expect(",");
996
+ const stack = this.expect("IDENT").value;
997
+ this.expect(",");
998
+ const output = this.expect("VAR_ID").value;
999
+ const exits = this.parseExitMap();
1000
+ this.expect(";");
1001
+ return { op: "stack_table_step", table, reg, input, stack, output, exits };
1002
+ }
1003
+ case "fsm_table_step": {
1004
+ const table = this.expect("TABLE_ID").value;
1005
+ this.expect(",");
1006
+ const input = this.expect("VAR_ID").value;
1007
+ this.expect(",");
1008
+ this.expect("(");
1009
+ const outputs = this.parseVarList();
1010
+ this.expect(")");
1011
+ const exits = this.parseExitMap();
1012
+ this.expect(";");
1013
+ return { op: "fsm_table_step", table, input, outputs, exits };
1014
+ }
1015
+ default:
1016
+ throw new KTVMSyntaxError(`Unknown kernel terminator '${tok.value}'`, tok);
1017
+ }
1018
+ }
1019
+
1020
+ // --- Static Bit-Chunk Tables ---
1021
+
1022
+ parseTableDecl() {
1023
+ this.expect("IDENT", "table");
1024
+ const name = this.expect("TABLE_ID").value;
1025
+ const kindTok = this.expect("IDENT");
1026
+ if (!["chunk_table", "stack_table", "fsm_table"].includes(kindTok.value)) {
1027
+ throw new KTVMSyntaxError(`Invalid table kind '${kindTok.value}'`, kindTok);
1028
+ }
1029
+ this.expect("{");
1030
+ const props = {};
1031
+ let entries = null;
1032
+ let packedBase64 = null;
1033
+
1034
+ while (this.peek().type !== "}") {
1035
+ const kTok = this.expect("IDENT");
1036
+ if (kTok.value === "entries") {
1037
+ this.expect("{");
1038
+ entries = [];
1039
+ while (this.peek().type !== "}") {
1040
+ const idx = Number(this.expect("INT").value);
1041
+ this.expect("FAT_ARROW");
1042
+ const val = this.parseTableVal();
1043
+ this.expect(";");
1044
+ entries.push({ index: idx, value: val });
1045
+ }
1046
+ this.expect("}");
1047
+ } else if (kTok.value === "packed_base64") {
1048
+ packedBase64 = this.expect("STRING").value;
1049
+ this.expect(";");
1050
+ } else {
1051
+ this.expect(":");
1052
+ props[kTok.value] = this.parseTableVal();
1053
+ this.expect(";");
1054
+ }
1055
+ }
1056
+ this.expect("}");
1057
+ return { name, kind: kindTok.value, props, entries, packedBase64 };
1058
+ }
1059
+
1060
+ parseTableVal() {
1061
+ const tok = this.peek();
1062
+ if (tok.type === "INT") return Number(this.next().value);
1063
+ if (tok.type === "FLOAT") return Number(this.next().value);
1064
+ if (tok.type === "BITS_LIT") return { bits: this.next().value };
1065
+ if (tok.type === "STRING") return this.next().value;
1066
+ if (tok.type === "PROC_ID") return { proc: this.next().value };
1067
+ if (tok.type === "IDENT") return { ident: this.next().value };
1068
+ if (tok.type === "[") {
1069
+ this.next();
1070
+ const arr = [];
1071
+ while (this.peek().type !== "]") {
1072
+ arr.push(this.parseTableVal());
1073
+ if (!this.match(",")) break;
1074
+ }
1075
+ this.expect("]");
1076
+ return arr;
1077
+ }
1078
+ if (tok.type === "{") {
1079
+ this.next();
1080
+ const obj = {};
1081
+ while (this.peek().type !== "}") {
1082
+ const key = this.expect("IDENT").value;
1083
+ this.expect(":");
1084
+ obj[key] = this.parseTableVal();
1085
+ if (!this.match(",")) break;
1086
+ }
1087
+ this.expect("}");
1088
+ return obj;
1089
+ }
1090
+ throw new KTVMSyntaxError(`Unexpected token in table value: ${tok.type} ('${tok.value}')`, tok);
1091
+ }
1092
+ }
1093
+
1094
+ export function parseModule(source) {
1095
+ if (typeof source !== "string") {
1096
+ throw new KTVMSyntaxError("parseModule requires a string source");
1097
+ }
1098
+ const tokens = tokenize(source);
1099
+ const parser = new Parser(tokens);
1100
+ return parser.parseModule();
1101
+ }