@fraczak/k 8.9.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +28 -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 +907 -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 +13 -4
  10. package/DOCS/README.md +3 -2
  11. package/DOCS/REPL.md +16 -12
  12. package/README.md +138 -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 -7
  21. package/backends/llvm/src/llvm.mjs +4 -113
  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 +2 -16
  25. package/backends/wasm/README.md +7 -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 +60 -57
  30. package/backends/wasm/tests/test-wasm.mjs +41 -2
  31. package/browser/repl-browser.mjs +9 -8
  32. package/browser/shims/buffer.mjs +31 -2
  33. package/browser/shims/child_process.mjs +26 -0
  34. package/browser/shims/fs.mjs +3 -1
  35. package/codecs/runtime/prefix-codec.mjs +67 -1
  36. package/conformance/run.mjs +17 -2
  37. package/harness/adapters/ktvm-llvm.mjs +118 -0
  38. package/harness/adapters/ktvm-wasm.mjs +104 -0
  39. package/harness/adapters/ktvm.mjs +133 -0
  40. package/harness/registry.mjs +9 -0
  41. package/ktvm/ast.mjs +218 -0
  42. package/ktvm/bit-deque.mjs +497 -0
  43. package/ktvm/fixtures/integer-streaming.k +477 -0
  44. package/ktvm/index.mjs +130 -0
  45. package/ktvm/llvm/index.mjs +202 -0
  46. package/ktvm/llvm/lower-c.mjs +1258 -0
  47. package/ktvm/llvm/runtime.h +3542 -0
  48. package/ktvm/llvm/test-llvm.mjs +476 -0
  49. package/ktvm/lower-kir.mjs +2221 -0
  50. package/ktvm/optimize/fuse-kernel.mjs +2111 -0
  51. package/ktvm/optimize/index.mjs +116 -0
  52. package/ktvm/optimize/mwtr.mjs +283 -0
  53. package/ktvm/optimize/simplify-procs.mjs +5250 -0
  54. package/ktvm/optimize/synthesize-tables.mjs +1105 -0
  55. package/ktvm/parser.mjs +1101 -0
  56. package/ktvm/printer.mjs +281 -0
  57. package/ktvm/schema.mjs +1134 -0
  58. package/ktvm/specialize.mjs +538 -0
  59. package/ktvm/test-conformance.mjs +597 -0
  60. package/ktvm/test-ktvm.mjs +1805 -0
  61. package/ktvm/test-optimize.mjs +598 -0
  62. package/ktvm/validator.mjs +1280 -0
  63. package/ktvm/vm.mjs +2225 -0
  64. package/ktvm/wasm/index.mjs +331 -0
  65. package/ktvm/wasm/lower-wasm.mjs +1272 -0
  66. package/ktvm/wasm/runtime.wat +4404 -0
  67. package/ktvm/wasm/test-wasm.mjs +429 -0
  68. package/ktvm/wire.mjs +679 -0
  69. package/package.json +1 -9
  70. package/paper/Makefile +8 -5
  71. package/paper/k-transducer-compiler.pdf +0 -0
  72. package/paper/k-transducer-compiler.tex +658 -0
  73. package/paper/replay-diagnostic.mjs +63 -0
  74. package/repl.mjs +101 -20
  75. package/scripts/build-repl-html.mjs +40 -18
  76. package/scripts/perf-bigint-compare.mjs +12 -16
  77. package/scripts/perf-ieee.mjs +14 -232
  78. package/scripts/perf-int.mjs +16 -274
  79. package/scripts/perf-multiplication.mjs +116 -121
  80. package/scripts/perf-poly.mjs +9 -263
  81. package/scripts/run-tests.mjs +5 -2
  82. package/scripts/test-package.mjs +15 -3
  83. package/tests/README.md +3 -3
  84. package/tests/test-repl-html.mjs +72 -15
  85. package/tests/test-repl.mjs +24 -17
  86. package/DOCS/POLYMORPHIC_IR.md +0 -86
  87. package/access-table.mjs +0 -343
  88. package/pkir.mjs +0 -772
  89. package/tests/test-access-table.mjs +0 -213
  90. package/tests/test-pkir.mjs +0 -530
@@ -0,0 +1,26 @@
1
+ function unsupported(name) {
2
+ throw new Error(`node:child_process.${name} is not available in the browser`);
3
+ }
4
+
5
+ export function execFileSync() {
6
+ unsupported("execFileSync");
7
+ }
8
+
9
+ export function spawnSync() {
10
+ unsupported("spawnSync");
11
+ }
12
+
13
+ export function spawn() {
14
+ unsupported("spawn");
15
+ }
16
+
17
+ export function execSync() {
18
+ unsupported("execSync");
19
+ }
20
+
21
+ export default {
22
+ execFileSync,
23
+ spawnSync,
24
+ spawn,
25
+ execSync
26
+ };
@@ -11,6 +11,8 @@ if (vfsData && typeof vfsData === "object") {
11
11
  function cleanPath(p) {
12
12
  let s = (p instanceof URL ? p.pathname : (p?.pathname || String(p))).replace(/\\/g, "/");
13
13
  if (s.startsWith("file://")) s = s.replace(/^file:\/\//, "");
14
+ const ktvmWasmIdx = s.lastIndexOf("ktvm/wasm/");
15
+ if (ktvmWasmIdx !== -1) return s.slice(ktvmWasmIdx);
14
16
  if (s.endsWith("runtime.wat")) return "backends/wasm/runtime.wat";
15
17
  const libIdx = s.lastIndexOf("lib/");
16
18
  if (libIdx !== -1) return s.slice(libIdx);
@@ -83,7 +85,7 @@ export function getAllVfsFiles() {
83
85
  }
84
86
  }
85
87
  for (const key of vfs.keys()) {
86
- if (key.endsWith("runtime.wat") || key.startsWith("backends/")) continue;
88
+ if (key.endsWith("runtime.wat") || key.startsWith("backends/") || key.startsWith("ktvm/")) continue;
87
89
  if (key.startsWith("lib/") || key.startsWith("Examples/") || key.startsWith("codecs/")) continue;
88
90
  result.add(key);
89
91
  }
@@ -550,6 +550,71 @@ function encodeToWire(value, propertyList) {
550
550
  return writer.toBuffer();
551
551
  }
552
552
 
553
+ // Match the exact canonical header and validate the packed payload without
554
+ // constructing a K value. A different header needs the ordinary codec path.
555
+ function makeWireValidator(propertyList) {
556
+ const pattern = canonicalizePattern(propertyListToPattern(propertyList));
557
+ const writer = new BitWriter();
558
+ encodeNode(writer, patternToKValue(patternToPropertyList(pattern)), CORE_PATTERN_PATTERN, 0);
559
+ const { byteLength, bitCount } = writer;
560
+ const header = writer.toBuffer();
561
+ const mask = (0xff << (8 - bitCount)) & 0xff;
562
+
563
+ return (buffer) => {
564
+ if (!Buffer.isBuffer(buffer) || buffer.length < header.length) return false;
565
+ for (let i = 0; i < byteLength; i++) {
566
+ if (buffer[i] !== header[i]) return false;
567
+ }
568
+ if (bitCount && (buffer[byteLength] & mask) !== header[byteLength]) return false;
569
+
570
+ const reader = new BitReader(buffer);
571
+ reader.byteOffset = byteLength;
572
+ reader.bitOffset = bitCount;
573
+ validatePackedPayload(reader, pattern);
574
+ return true;
575
+ };
576
+ }
577
+
578
+ function validatePackedPayload(reader, pattern) {
579
+ // An active node can recur only after the scan has consumed input.
580
+ const activeAt = new Float64Array(pattern.nodes.length).fill(-1);
581
+ const stack = [];
582
+ let id = 0;
583
+ for (;;) {
584
+ const node = pattern.nodes[id];
585
+ const position = reader.byteOffset * 8 + reader.bitOffset;
586
+ const previous = activeAt[id];
587
+ if (previous === position) throw new Error("Non-consuming recursive wire pattern");
588
+ activeAt[id] = position;
589
+ const frame = { id, previous, next: 0 };
590
+ stack.push(frame);
591
+ if (node.kind === NODE_KIND.CLOSED_UNION) {
592
+ const ordinal = reader.readBits(node.choiceBits ?? choiceWidth(node.edges.length));
593
+ if (!node.edges[ordinal]) throw new Error(`Invalid choice ${ordinal} at pattern node ${id}`);
594
+ frame.next = node.edges.length;
595
+ id = node.edges[ordinal].target;
596
+ continue;
597
+ }
598
+ if (node.kind !== NODE_KIND.CLOSED_PRODUCT) throw new Error("Expected a closed wire pattern");
599
+
600
+ while (stack.length > 0) {
601
+ const top = stack[stack.length - 1];
602
+ const edges = pattern.nodes[top.id].edges;
603
+ if (top.next < edges.length) {
604
+ id = edges[top.next++].target;
605
+ break;
606
+ }
607
+ activeAt[top.id] = top.previous;
608
+ stack.pop();
609
+ }
610
+ if (stack.length === 0) break;
611
+ }
612
+ if ((reader.buffer.length - reader.byteOffset) * 8 - reader.bitOffset >= 8) {
613
+ throw new Error("Extra trailing bytes after wire payload");
614
+ }
615
+ reader.assertZeroPadding();
616
+ }
617
+
553
618
  function readBitsAt(buffer, bitOffset, width) {
554
619
  if (width === 0) return 0;
555
620
  if ((bitOffset + width - 1) >> 3 >= buffer.length) {
@@ -1005,7 +1070,8 @@ export {
1005
1070
  propertyListToPattern,
1006
1071
  patternToPropertyList,
1007
1072
  choiceWidth,
1008
- CORE_PATTERN_PROPERTY_LIST
1073
+ CORE_PATTERN_PROPERTY_LIST,
1074
+ makeWireValidator
1009
1075
  };
1010
1076
  export default {
1011
1077
  encodeToWire,
@@ -11,10 +11,12 @@ import { objectToKIRP, retypeObjectRelation } from "../kir.mjs";
11
11
  import { validateKIRP } from "../objects/validate.mjs";
12
12
  import { exportPatternGraph } from "../codecs/runtime/codec.mjs";
13
13
  import { patternToPropertyList } from "../codecs/runtime/pattern-json.mjs";
14
+ import { encodeToWire } from "../codecs/runtime/prefix-codec.mjs";
15
+ import { executeObjectWithKTVM } from "../ktvm/index.mjs";
14
16
 
15
17
  const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
16
18
  const conformanceRoot = path.join(root, "conformance");
17
- const DEFAULT_MODES = ["source", "object", "kir", "retyped"];
19
+ const DEFAULT_MODES = ["source", "object", "kir", "retyped", "ktvm"];
18
20
 
19
21
  function helpText() {
20
22
  return [
@@ -97,11 +99,24 @@ function runRetyped(fixture) {
97
99
  if (!kir.rels[kir.main]) throw new Error(`${fixture.name}/retyped: main relation missing`);
98
100
  }
99
101
 
102
+ function runKTVM(fixture) {
103
+ const object = decodeObject(compileObjectBuffer(fixture.program, {
104
+ source: path.relative(root, fixture.dir)
105
+ }));
106
+ const inWire = encodeToWire(fixture.input);
107
+ const res = executeObjectWithKTVM(object, object.main, inWire);
108
+ if (res.status !== "OK") {
109
+ throw new Error(`${fixture.name}/ktvm: execution returned ${res.status}`);
110
+ }
111
+ assertSameValue(res.value, fixture.expected, `${fixture.name}/ktvm`);
112
+ }
113
+
100
114
  function runMode(mode, fixture) {
101
115
  if (mode === "source") return runSource(fixture);
102
116
  if (mode === "object") return runObject(fixture);
103
117
  if (mode === "kir") return runKIR(fixture);
104
118
  if (mode === "retyped") return runRetyped(fixture);
119
+ if (mode === "ktvm") return runKTVM(fixture);
105
120
  throw new Error(`Unknown conformance mode '${mode}'`);
106
121
  }
107
122
 
@@ -134,7 +149,7 @@ try {
134
149
  const fixtures = fixtureDirs(dirs).map(readFixture);
135
150
  let count = 0;
136
151
  for (const fixture of fixtures) {
137
- const fixtureModes = modes.filter((mode) => fixture.modes.includes(mode));
152
+ const fixtureModes = modes.filter((mode) => mode === "ktvm" || fixture.modes.includes(mode));
138
153
  for (const mode of fixtureModes) {
139
154
  runMode(mode, fixture);
140
155
  count++;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Benchmark harness adapter for kTVM Native C/LLVM executables (`ktvm-llvm`, `ktvm-llvm-opt`).
3
+ *
4
+ * Uses the same `PersistentExecutable` (`--server` + `K_TRACE=1`) framing protocol
5
+ * as `harness/adapters/llvm.mjs` for apples-to-apples head-to-head comparison.
6
+ */
7
+
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+
11
+ import { BackendAdapter, BackendRunner } from "../backend.mjs";
12
+ import { PersistentExecutable } from "../persistent.mjs";
13
+ import { decodeWire } from "../../backend-api.mjs";
14
+ import {
15
+ compileObjectToKTVMExecutable,
16
+ isClangAvailable
17
+ } from "../../ktvm/llvm/index.mjs";
18
+
19
+ class KTVMLLVMRunner extends BackendRunner {
20
+ constructor(backendId, servers = new Map()) {
21
+ super(backendId);
22
+ this.servers = servers;
23
+ }
24
+
25
+ getServer(exePath) {
26
+ let server = this.servers.get(exePath);
27
+ if (!server) {
28
+ server = new PersistentExecutable(exePath);
29
+ this.servers.set(exePath, server);
30
+ }
31
+ return server;
32
+ }
33
+
34
+ async runSingle(testCase, options = {}) {
35
+ const server = this.getServer(testCase.exePath);
36
+ if (options.trace) {
37
+ const res = await server.requestWithTrace(testCase.inputWire);
38
+ const decoded = decodeWire(res.payload);
39
+ return {
40
+ outputWire: res.payload,
41
+ outputVal: decoded.value,
42
+ outputPattern: decoded.pattern,
43
+ trace: res.trace
44
+ };
45
+ }
46
+ const payload = await server.request(testCase.inputWire);
47
+ const decoded = decodeWire(payload);
48
+ return {
49
+ outputWire: payload,
50
+ outputVal: decoded.value,
51
+ outputPattern: decoded.pattern
52
+ };
53
+ }
54
+
55
+ async runBatch(compiledCases) {
56
+ for (const c of compiledCases) {
57
+ const server = this.getServer(c.exePath);
58
+ await server.request(c.inputWire);
59
+ }
60
+ }
61
+
62
+ async close() {
63
+ for (const server of this.servers.values()) {
64
+ server.close();
65
+ }
66
+ this.servers.clear();
67
+ }
68
+ }
69
+
70
+ export class KTVMLLVMAdapter extends BackendAdapter {
71
+ constructor({ optimize = true, clangOpt = "-O3", ...options } = {}) {
72
+ super(
73
+ optimize ? "ktvm-llvm-opt" : "ktvm-llvm",
74
+ optimize
75
+ ? `kTVM Native C/LLVM Optimized (${clangOpt}, persistent)`
76
+ : `kTVM Native C/LLVM (${clangOpt}, persistent)`,
77
+ options
78
+ );
79
+ this.optimize = optimize;
80
+ this.clangOpt = clangOpt;
81
+ }
82
+
83
+ isAvailable() {
84
+ return isClangAvailable("clang");
85
+ }
86
+
87
+ async compile(testCase, options = {}) {
88
+ const cacheDir = options.cacheDir || path.join(process.cwd(), ".cache");
89
+ fs.mkdirSync(cacheDir, { recursive: true });
90
+ const tag = this.optimize ? "opt" : "raw";
91
+ const name = testCase.op || testCase.relName || "case";
92
+ const exePath = path.join(cacheDir, `harness_ktvm_llvm_${tag}_${name}`);
93
+
94
+ try {
95
+ const relation = testCase.relHash || testCase.relName || testCase.op || testCase.object.main;
96
+ compileObjectToKTVMExecutable(testCase.object, relation, testCase.inputPattern, exePath, {
97
+ optimize: this.optimize,
98
+ clangOpt: this.clangOpt
99
+ });
100
+ return {
101
+ status: "ok",
102
+ exePath,
103
+ inputWire: testCase.inputWire,
104
+ inputVal: testCase.inputVal,
105
+ outputPattern: testCase.outputPattern
106
+ };
107
+ } catch (error) {
108
+ return {
109
+ status: "failed",
110
+ error: error.stack || error.message || String(error)
111
+ };
112
+ }
113
+ }
114
+
115
+ async createRunner() {
116
+ return new KTVMLLVMRunner(this.id);
117
+ }
118
+ }
@@ -0,0 +1,104 @@
1
+ import {
2
+ compileObjectToKTVMWasm,
3
+ decodeWire,
4
+ instantiateKTVMWasm
5
+ } from "../../backend-api.mjs";
6
+ import { BackendAdapter, BackendRunner } from "../backend.mjs";
7
+
8
+ class KTVMWasmRunner extends BackendRunner {
9
+ constructor(backendId) {
10
+ super(backendId);
11
+ }
12
+
13
+ async runSingle(testCase) {
14
+ const t0 = process.hrtime.bigint();
15
+ const res = testCase.runner.executeWire(testCase.inputWire, { decodeValue: false });
16
+ const tEval = process.hrtime.bigint();
17
+ const evalNs = Number(tEval - t0);
18
+
19
+ let outputVal;
20
+ let outputWire = null;
21
+ if (res.status === "OK") {
22
+ outputWire = res.wire;
23
+ outputVal = decodeWire(res.wire, { eager: true }).value;
24
+ }
25
+
26
+ const trace = {
27
+ ipcReadNs: 0,
28
+ decodeNs: 0,
29
+ flatInNs: 0,
30
+ evalNs,
31
+ flatOutNs: 0,
32
+ encodeNs: 0,
33
+ ipcWriteNs: 0,
34
+ totalNs: evalNs
35
+ };
36
+
37
+ return {
38
+ outputVal,
39
+ outputWire,
40
+ trace,
41
+ profile: null
42
+ };
43
+ }
44
+
45
+ async runBatch(compiledCases) {
46
+ for (const c of compiledCases) {
47
+ c.runner.executeWire(c.inputWire, { decodeValue: false });
48
+ }
49
+ }
50
+ }
51
+
52
+ export class KTVMWasmAdapter extends BackendAdapter {
53
+ constructor(options = {}) {
54
+ const optimize = options.optimize !== false;
55
+ const id = options.id || (optimize ? "ktvm-wasm-opt" : "ktvm-wasm");
56
+ const name = options.name || (
57
+ optimize
58
+ ? "kTVM WebAssembly Optimized (fused + MWTR tables, direct k-wire)"
59
+ : "kTVM WebAssembly (direct k-wire)"
60
+ );
61
+ super(id, name, options);
62
+ this.optimize = optimize;
63
+ this.budgetBytes = options.budgetBytes;
64
+ }
65
+
66
+ isAvailable() {
67
+ return true;
68
+ }
69
+
70
+ async compile(testCase) {
71
+ try {
72
+ const inputPattern = testCase.inputPattern || (testCase.inputWire ? decodeWire(testCase.inputWire).pattern : null);
73
+ const artifact = await compileObjectToKTVMWasm(
74
+ testCase.object,
75
+ testCase.relName || testCase.op,
76
+ inputPattern,
77
+ {
78
+ optimize: this.optimize,
79
+ budgetBytes: this.budgetBytes,
80
+ validate: true,
81
+ verifyTables: true
82
+ }
83
+ );
84
+ const runner = await instantiateKTVMWasm(artifact);
85
+ return {
86
+ status: "ok",
87
+ artifact,
88
+ runner,
89
+ inputVal: testCase.inputVal,
90
+ inputWire: testCase.inputWire,
91
+ outputPattern: artifact.outPlist
92
+ };
93
+ } catch (error) {
94
+ return {
95
+ status: "failed",
96
+ error: error.stack || error.message || String(error)
97
+ };
98
+ }
99
+ }
100
+
101
+ async createRunner() {
102
+ return new KTVMWasmRunner(this.id);
103
+ }
104
+ }
@@ -0,0 +1,133 @@
1
+ import {
2
+ compileKIRToKTVM,
3
+ decodeWire,
4
+ executeKTVM,
5
+ executeKTVMWire,
6
+ optimizeKTVM
7
+ } from "../../backend-api.mjs";
8
+ import { BackendAdapter, BackendRunner } from "../backend.mjs";
9
+
10
+ class KTVMRunner extends BackendRunner {
11
+ constructor(backendId, options = {}) {
12
+ super(backendId);
13
+ this.wire = options.wire !== false;
14
+ }
15
+
16
+ async runSingle(testCase) {
17
+ const t0 = process.hrtime.bigint();
18
+ let outputVal;
19
+ let outputWire = null;
20
+ let evalNs = 0;
21
+
22
+ if (this.wire && testCase.inputWire) {
23
+ const res = executeKTVMWire(testCase.compiled.module, testCase.inputWire, {
24
+ entry: testCase.compiled.entry,
25
+ validate: false,
26
+ decodeValue: true
27
+ });
28
+ const tEnd = process.hrtime.bigint();
29
+ evalNs = Number(tEnd - t0);
30
+ outputVal = res.status === "OK" ? res.value : undefined;
31
+ outputWire = res.status === "OK" ? res.wire : null;
32
+ } else {
33
+ const res = executeKTVM(testCase.compiled.module, [testCase.inputVal], {
34
+ entry: testCase.compiled.entry,
35
+ validate: false
36
+ });
37
+ const tEnd = process.hrtime.bigint();
38
+ evalNs = Number(tEnd - t0);
39
+ outputVal = res.status === "OK" ? res.value : undefined;
40
+ }
41
+
42
+ const trace = {
43
+ ipcReadNs: 0,
44
+ decodeNs: 0,
45
+ flatInNs: 0,
46
+ evalNs,
47
+ flatOutNs: 0,
48
+ encodeNs: 0,
49
+ ipcWriteNs: 0,
50
+ totalNs: evalNs
51
+ };
52
+
53
+ return {
54
+ outputVal,
55
+ outputWire,
56
+ trace,
57
+ profile: null
58
+ };
59
+ }
60
+
61
+ async runBatch(compiledCases) {
62
+ for (const c of compiledCases) {
63
+ if (this.wire && c.inputWire) {
64
+ executeKTVMWire(c.compiled.module, c.inputWire, {
65
+ entry: c.compiled.entry,
66
+ validate: false,
67
+ decodeValue: false
68
+ });
69
+ } else {
70
+ executeKTVM(c.compiled.module, [c.inputVal], {
71
+ entry: c.compiled.entry,
72
+ validate: false,
73
+ decodeValues: false
74
+ });
75
+ }
76
+ }
77
+ }
78
+ }
79
+
80
+ export class KTVMAdapter extends BackendAdapter {
81
+ constructor(state = null, options = {}) {
82
+ const wire = options.wire !== false;
83
+ const optimize = Boolean(options.optimize);
84
+ const id = options.id || (optimize ? "ktvm-opt" : (wire ? "ktvm" : "ktvm-pure"));
85
+ const name = options.name || (
86
+ optimize
87
+ ? "kTVM Optimized (fused kernels + MWTR tables)"
88
+ : (wire ? "kTVM Reference VM (direct k-wire)" : "kTVM Reference VM (in-memory)")
89
+ );
90
+ super(id, name, options);
91
+ this.state = state;
92
+ this.wire = wire;
93
+ this.optimize = optimize;
94
+ this.budgetBytes = options.budgetBytes;
95
+ }
96
+
97
+ setState(state) {
98
+ this.state = state;
99
+ }
100
+
101
+ async compile(testCase) {
102
+ try {
103
+ const inputPattern = testCase.inputPattern || (testCase.inputWire ? decodeWire(testCase.inputWire).pattern : null);
104
+ let compiled = compileKIRToKTVM(testCase.object, testCase.relName || testCase.op, inputPattern, {
105
+ validate: true
106
+ });
107
+ if (this.optimize) {
108
+ const opt = optimizeKTVM(compiled.module, {
109
+ budgetBytes: this.budgetBytes,
110
+ validate: true,
111
+ verifyTables: true
112
+ });
113
+ compiled = { ...compiled, module: opt.module, optStats: opt.stats };
114
+ }
115
+ return {
116
+ status: "ok",
117
+ compiled,
118
+ inputVal: testCase.inputVal,
119
+ inputWire: testCase.inputWire,
120
+ outputPattern: compiled.outputPlist
121
+ };
122
+ } catch (error) {
123
+ return {
124
+ status: "failed",
125
+ error: error.stack || error.message || String(error)
126
+ };
127
+ }
128
+ }
129
+
130
+ async createRunner() {
131
+ return new KTVMRunner(this.id, { wire: this.wire });
132
+ }
133
+ }
@@ -1,5 +1,8 @@
1
1
  import { NativeAdapter } from "./adapters/native.mjs";
2
2
  import { KVMAdapter } from "./adapters/kvm.mjs";
3
+ import { KTVMAdapter } from "./adapters/ktvm.mjs";
4
+ import { KTVMWasmAdapter } from "./adapters/ktvm-wasm.mjs";
5
+ import { KTVMLLVMAdapter } from "./adapters/ktvm-llvm.mjs";
3
6
  import { WasmAdapter } from "./adapters/wasm.mjs";
4
7
  import { LLVMAdapter } from "./adapters/llvm.mjs";
5
8
 
@@ -13,6 +16,12 @@ export function createRegistry(config = {}) {
13
16
  register("native-aware", () => new NativeAdapter("aware", config.state));
14
17
  register("native-free", () => new NativeAdapter("free", config.state));
15
18
  register("kvm", () => new KVMAdapter(config.state));
19
+ register("ktvm", () => new KTVMAdapter(config.state));
20
+ register("ktvm-opt", () => new KTVMAdapter(config.state, { optimize: true }));
21
+ register("ktvm-wasm", () => new KTVMWasmAdapter({ optimize: false }));
22
+ register("ktvm-wasm-opt", () => new KTVMWasmAdapter({ optimize: true }));
23
+ register("ktvm-llvm", () => new KTVMLLVMAdapter({ optimize: false, ...(config.llvm || {}) }));
24
+ register("ktvm-llvm-opt", () => new KTVMLLVMAdapter({ optimize: true, ...(config.llvm || {}) }));
16
25
  register("wasm", () => new WasmAdapter(config.wasm || {}));
17
26
  register("wasm-in-process", () => new WasmAdapter({ id: "wasm-in-process", mode: "in-process", ...(config.wasm || {}) }));
18
27
  register("llvm", () => new LLVMAdapter(config.llvm || {}));