@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
@@ -15,7 +15,7 @@ import { runWasmArtifact } from "../src/wasm.mjs";
15
15
  function helpText() {
16
16
  const prog = argv[1] || "k-wasm.mjs";
17
17
  return [
18
- "Compile k source, .ko, .kvm, or .pkir to WebAssembly in memory",
18
+ "Compile k source, .ko, or .kvm to WebAssembly in memory",
19
19
  "and run it over a binary pattern+value wire stream.",
20
20
  "",
21
21
  `Usage: ${prog} [options]`,
@@ -23,14 +23,13 @@ function helpText() {
23
23
  "",
24
24
  "Arguments:",
25
25
  " source-snippet Inline k source snippet (in the style of k.mjs).",
26
- " input-file Source .k, .ko, .kvm, or .pkir file.",
26
+ " input-file Source .k, .ko, or .kvm file.",
27
27
  " input-wire-file Optional binary wire input (default: stdin).",
28
28
  "",
29
29
  "Options:",
30
30
  " --lib file Load one .klib or .k library before compiling.",
31
31
  " --use spec Use library alias in scope (repeatable).",
32
32
  " spec is 'name' or 'libname:localname'.",
33
- " --pkir Lower via Polymorphic K IR (PKIR).",
34
33
  " -h, --help Show this help.",
35
34
  "",
36
35
  "Environment Variables:",
@@ -55,7 +54,7 @@ async function main() {
55
54
  return;
56
55
  }
57
56
 
58
- const { libraries, useSpecs, usePKIR } = parseCompileOptions(args);
57
+ const { libraries, useSpecs } = parseCompileOptions(args);
59
58
  const programInput = resolveProgramInput(args);
60
59
  const inputPath = args.shift();
61
60
  if (args.length > 0) throw new Error("Too many arguments");
@@ -71,8 +70,7 @@ async function main() {
71
70
  const artifact = await compileProgramInput(programInput, {
72
71
  libraries,
73
72
  useSpecs,
74
- inputEnvelopePattern,
75
- usePKIR
73
+ inputEnvelopePattern
76
74
  });
77
75
  stdout.write(await runWasmArtifact(artifact, inputBuffer));
78
76
  }
@@ -10,8 +10,7 @@ import {
10
10
  import {
11
11
  compileWasmArtifact,
12
12
  compileWasmArtifactFromKVM,
13
- compileWasmArtifactFromObject,
14
- compileWasmArtifactFromPKIR
13
+ compileWasmArtifactFromObject
15
14
  } from "./wasm.mjs";
16
15
 
17
16
  function readAll(stream) {
@@ -45,7 +44,6 @@ function parseCompileOptions(args) {
45
44
  const libraries = [];
46
45
  const useSpecs = [];
47
46
  let loadedLibrary = false;
48
- let usePKIR = false;
49
47
 
50
48
  while (args.length > 0) {
51
49
  if (args[0] === "--") {
@@ -70,9 +68,6 @@ function parseCompileOptions(args) {
70
68
  );
71
69
  }
72
70
  useSpecs.push(spec);
73
- } else if (args[0] === "--pkir") {
74
- args.shift();
75
- usePKIR = true;
76
71
  } else if (args[0].startsWith("--")) {
77
72
  break;
78
73
  } else {
@@ -80,7 +75,7 @@ function parseCompileOptions(args) {
80
75
  }
81
76
  }
82
77
 
83
- return { libraries, useSpecs, usePKIR };
78
+ return { libraries, useSpecs };
84
79
  }
85
80
 
86
81
  function fileInputType(filePath) {
@@ -88,7 +83,6 @@ function fileInputType(filePath) {
88
83
  if (ext === ".ko") return "ko";
89
84
  if (ext === ".kvm") return "kvm";
90
85
  if (ext === ".klib") return "klib";
91
- if (ext === ".pkir") return "pkir";
92
86
  return "source-file";
93
87
  }
94
88
 
@@ -111,7 +105,7 @@ function resolveProgramInput(args, { allowStdinSource = false } = {}) {
111
105
  return { kind, path: inputArg, sourceName: inputArg };
112
106
  }
113
107
 
114
- if ([".k", ".ko", ".kvm", ".klib", ".wasm", ".pkir"].includes(ext)) {
108
+ if ([".k", ".ko", ".kvm", ".klib", ".wasm"].includes(ext)) {
115
109
  throw new Error(`Input file not found: ${inputArg}`);
116
110
  }
117
111
 
@@ -129,8 +123,7 @@ async function compileProgramInput(
129
123
  useSpecs = [],
130
124
  exportSpecs = [],
131
125
  stdin = null,
132
- inputEnvelopePattern = null,
133
- usePKIR = false
126
+ inputEnvelopePattern = null
134
127
  } = {}
135
128
  ) {
136
129
  const specs = useSpecs.length > 0 ? useSpecs : exportSpecs;
@@ -139,8 +132,7 @@ async function compileProgramInput(
139
132
  libraries,
140
133
  use: specs,
141
134
  source: input.sourceName,
142
- inputEnvelopePattern,
143
- usePKIR
135
+ inputEnvelopePattern
144
136
  });
145
137
  }
146
138
 
@@ -152,8 +144,7 @@ async function compileProgramInput(
152
144
  libraries,
153
145
  use: specs,
154
146
  source: input.sourceName,
155
- inputEnvelopePattern,
156
- usePKIR
147
+ inputEnvelopePattern
157
148
  });
158
149
  }
159
150
 
@@ -162,24 +153,17 @@ async function compileProgramInput(
162
153
  libraries,
163
154
  use: specs,
164
155
  source: input.sourceName,
165
- inputEnvelopePattern,
166
- usePKIR
156
+ inputEnvelopePattern
167
157
  });
168
158
  }
169
159
 
170
160
  if (input.kind === "ko") {
171
161
  const obj = decodeObject(fs.readFileSync(input.path));
172
162
  return compileWasmArtifactFromObject(obj, {
173
- inputEnvelopePattern,
174
- usePKIR
163
+ inputEnvelopePattern
175
164
  });
176
165
  }
177
166
 
178
- if (input.kind === "pkir") {
179
- const pkir = JSON.parse(fs.readFileSync(input.path, "utf8"));
180
- return compileWasmArtifactFromPKIR(pkir);
181
- }
182
-
183
167
  if (input.kind === "kvm") {
184
168
  const kvm = JSON.parse(fs.readFileSync(input.path, "utf8"));
185
169
  return compileWasmArtifactFromKVM(kvm);
@@ -14,9 +14,7 @@ import {
14
14
  propertyListToPattern,
15
15
  Value,
16
16
  specializeKVM,
17
- specializeObjectRelations,
18
- compileRelationToPKIR,
19
- lowerPKIRToKVM
17
+ specializeObjectRelations
20
18
  } from "@fraczak/k/backend-api.mjs";
21
19
  import { intersectPropertyListPatterns } from "@fraczak/k/codecs/runtime/codec.mjs";
22
20
  import { propertyListToFilter } from "@fraczak/k/codecs/runtime/show-value.mjs";
@@ -285,7 +283,7 @@ function cloneKVMFunction(kvmFunc) {
285
283
  };
286
284
  }
287
285
 
288
- function compileModule(mainRelName, defs, { usePKIR = false } = {}) {
286
+ function compileModule(mainRelName, defs) {
289
287
  const compiled = new Set();
290
288
  const queue = [mainRelName];
291
289
  const wats = [];
@@ -301,14 +299,8 @@ function compileModule(mainRelName, defs, { usePKIR = false } = {}) {
301
299
  throw new Error(`Relation ${name} not found`);
302
300
  }
303
301
 
304
- let kvmFunc;
305
- if (usePKIR) {
306
- const pkir = compileRelationToPKIR(relDef, name);
307
- kvmFunc = lowerPKIRToKVM(pkir);
308
- } else {
309
- kvmFunc = lowerToKVM(relDef, name);
310
- kvmFunc.typePatternGraph = relDef.typePatternGraph;
311
- }
302
+ const kvmFunc = lowerToKVM(relDef, name);
303
+ kvmFunc.typePatternGraph = relDef.typePatternGraph;
312
304
  scanCalls(kvmFunc.body, compiled, queue);
313
305
 
314
306
  kvmFunc.name = nameMap.get(name) || cleanName(name);
@@ -481,7 +473,7 @@ function validateInputEnvelope(inputPattern, valuePattern) {
481
473
  async function compileWasmArtifactFromDefs(
482
474
  defs,
483
475
  mainRelName = "__main__",
484
- { typingMode = "generic", usePKIR = false } = {}
476
+ { typingMode = "generic" } = {}
485
477
  ) {
486
478
  resetTagIds();
487
479
  const mainRel = defs.rels[mainRelName];
@@ -491,8 +483,7 @@ async function compileWasmArtifactFromDefs(
491
483
 
492
484
  const { wat: moduleWatBody, relationNames, entryName } = compileModule(
493
485
  mainRelName,
494
- defs,
495
- { usePKIR }
486
+ defs
496
487
  );
497
488
  assertRelationsConverged(defs, relationNames);
498
489
  const fullWat = runtimeWat.trim().slice(0, -1) + "\n" + moduleWatBody + "\n)";
@@ -588,7 +579,7 @@ async function compileWasmArtifactFromKVM(kvmInput, options = {}) {
588
579
 
589
580
  async function compileWasmArtifactFromObject(
590
581
  object,
591
- { entry = null, inputEnvelopePattern = null, usePKIR = false } = {}
582
+ { entry = null, inputEnvelopePattern = null } = {}
592
583
  ) {
593
584
  if (!object?.rels) {
594
585
  throw new Error("Expected .ko input to contain k object relations");
@@ -632,8 +623,7 @@ async function compileWasmArtifactFromObject(
632
623
  }
633
624
 
634
625
  return compileWasmArtifactFromDefs(defs, mainRelName, {
635
- typingMode,
636
- usePKIR
626
+ typingMode
637
627
  });
638
628
  }
639
629
 
@@ -644,8 +634,7 @@ async function compileWasmArtifact(
644
634
  use = [],
645
635
  exports = [],
646
636
  source: sourceName = null,
647
- inputEnvelopePattern = null,
648
- usePKIR = false
637
+ inputEnvelopePattern = null
649
638
  } = {}
650
639
  ) {
651
640
  const specs = use.length > 0 ? use : exports;
@@ -690,43 +679,10 @@ async function compileWasmArtifact(
690
679
  }
691
680
 
692
681
  return compileWasmArtifactFromDefs(defs, "__main__", {
693
- typingMode,
694
- usePKIR
682
+ typingMode
695
683
  });
696
684
  }
697
685
 
698
- async function compileWasmArtifactFromPKIR(pkirInput, options = {}) {
699
- let kvmProgram;
700
- let entry = options.entry || "__main__";
701
- if (pkirInput && typeof pkirInput === "object") {
702
- if (pkirInput.format === "pk-ir" && pkirInput.functions) {
703
- entry = pkirInput.entry || entry;
704
- kvmProgram = {};
705
- for (const [name, f] of Object.entries(pkirInput.functions)) {
706
- kvmProgram[name] = lowerPKIRToKVM(f);
707
- }
708
- } else if (pkirInput.instructions) {
709
- const kvm = lowerPKIRToKVM(pkirInput);
710
- entry = kvm.name || entry;
711
- kvmProgram = { [entry]: kvm };
712
- } else if (pkirInput.functions) {
713
- entry = pkirInput.entry || entry;
714
- kvmProgram = {};
715
- for (const [name, f] of Object.entries(pkirInput.functions)) {
716
- kvmProgram[name] = lowerPKIRToKVM(f);
717
- }
718
- } else {
719
- throw new Error("Invalid PKIR input for WebAssembly compilation");
720
- }
721
- } else {
722
- throw new Error("Expected PKIR input object");
723
- }
724
- return compileWasmArtifactFromKVM(
725
- { format: "k-vm", layer: "KVM", entry, functions: kvmProgram },
726
- options
727
- );
728
- }
729
-
730
686
  function createTagRegistry(entries) {
731
687
  const tagToId = new Map();
732
688
  const idToTag = new Map();
@@ -1127,7 +1083,6 @@ export {
1127
1083
  appendCustomSection,
1128
1084
  compileWasmArtifactFromKVM,
1129
1085
  compileWasmArtifactFromObject,
1130
- compileWasmArtifactFromPKIR,
1131
1086
  compileWasmArtifact,
1132
1087
  instantiateWasmArtifact,
1133
1088
  metadataFromModule,
@@ -1145,7 +1100,6 @@ export default {
1145
1100
  appendCustomSection,
1146
1101
  compileWasmArtifactFromKVM,
1147
1102
  compileWasmArtifactFromObject,
1148
- compileWasmArtifactFromPKIR,
1149
1103
  compileWasmArtifact,
1150
1104
  metadataFromModule,
1151
1105
  readArenaValue,
@@ -311,17 +311,18 @@ export async function executeCommand(input) {
311
311
  function updateEngineUI() {
312
312
  const badge = document.getElementById("engine-badge");
313
313
  if (!badge) return;
314
- badge.classList.remove("js-mode", "pkir-mode");
314
+ badge.classList.remove("js-mode", "ktvm-mode");
315
315
  if (state.engine === "js") {
316
316
  badge.textContent = "js-in-process";
317
317
  badge.classList.add("js-mode");
318
- } else if (state.engine === "pkir") {
319
- badge.textContent = "pkir-wasm";
320
- badge.classList.add("pkir-mode");
318
+ } else if (state.engine === "ktvm") {
319
+ badge.textContent = "ktvm-wasm";
320
+ badge.classList.add("ktvm-mode");
321
321
  } else {
322
322
  badge.textContent = "wasm-in-process";
323
323
  }
324
- badge.title = `Engine: ${state.engine} (click to toggle wasm/pkir/js)`;
324
+ badge.title = `Engine: ${state.engine} (click to switch wasm/ktvm/js)`;
325
+ badge.setAttribute("aria-label", `${badge.textContent} — switch evaluation engine`);
325
326
  }
326
327
 
327
328
  function adjustInputHeight() {
@@ -985,14 +986,14 @@ export function initRepl() {
985
986
  }
986
987
  });
987
988
 
988
- // Engine Badge toggle (wasm -> pkir -> js -> wasm)
989
+ // Engine Badge toggle (wasm -> ktvm -> js -> wasm)
989
990
  const engineBadge = document.getElementById("engine-badge");
990
991
  if (engineBadge) {
991
992
  engineBadge.onclick = () => {
992
993
  let nextEngine;
993
994
  if (state.engine === "wasm") {
994
- nextEngine = "pkir";
995
- } else if (state.engine === "pkir") {
995
+ nextEngine = "ktvm";
996
+ } else if (state.engine === "ktvm") {
996
997
  nextEngine = "js";
997
998
  } else {
998
999
  nextEngine = "wasm";
@@ -1,9 +1,30 @@
1
1
  export class Buffer extends Uint8Array {
2
- static from(data, encoding) {
2
+ static from(data, encodingOrOffset, length) {
3
3
  if (typeof data === "string") {
4
+ if (encodingOrOffset === "base64") {
5
+ const bin = atob(data.replace(/\s+/g, ""));
6
+ const out = new Buffer(bin.length);
7
+ for (let i = 0; i < bin.length; i++) {
8
+ out[i] = bin.charCodeAt(i);
9
+ }
10
+ return out;
11
+ }
12
+ if (encodingOrOffset === "hex") {
13
+ const clean = data.replace(/\s+/g, "");
14
+ const out = new Buffer(Math.floor(clean.length / 2));
15
+ for (let i = 0; i < out.length; i++) {
16
+ out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
17
+ }
18
+ return out;
19
+ }
4
20
  return new Buffer(new TextEncoder().encode(data));
5
21
  }
6
- if (data instanceof Uint8Array || Array.isArray(data) || data instanceof ArrayBuffer) {
22
+ if (data instanceof ArrayBuffer || (typeof SharedArrayBuffer !== "undefined" && data instanceof SharedArrayBuffer)) {
23
+ const offset = typeof encodingOrOffset === "number" ? encodingOrOffset : 0;
24
+ const len = typeof length === "number" ? length : (data.byteLength - offset);
25
+ return new Buffer(data, offset, len);
26
+ }
27
+ if (data instanceof Uint8Array || Array.isArray(data)) {
7
28
  return new Buffer(data);
8
29
  }
9
30
  if (data?.buffer instanceof ArrayBuffer) {
@@ -46,6 +67,14 @@ export class Buffer extends Uint8Array {
46
67
  if (encoding === "hex") {
47
68
  return Array.from(this).map(b => b.toString(16).padStart(2, "0")).join("");
48
69
  }
70
+ if (encoding === "base64") {
71
+ let bin = "";
72
+ const chunk = 0x8000;
73
+ for (let i = 0; i < this.length; i += chunk) {
74
+ bin += String.fromCharCode(...this.subarray(i, Math.min(i + chunk, this.length)));
75
+ }
76
+ return btoa(bin);
77
+ }
49
78
  return new TextDecoder("utf-8").decode(this);
50
79
  }
51
80
 
@@ -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
  }
@@ -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
+ }