@fraczak/k 8.8.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 (94) 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 +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/codecs/djson.mjs +2 -3
  35. package/codecs/int.mjs +66 -14
  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 +482 -0
  43. package/ktvm/fixtures/integer-streaming.k +477 -0
  44. package/ktvm/index.mjs +119 -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 +543 -0
  58. package/ktvm/specialize.mjs +538 -0
  59. package/ktvm/test-conformance.mjs +597 -0
  60. package/ktvm/test-ktvm.mjs +1376 -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 +4413 -0
  67. package/ktvm/wasm/test-wasm.mjs +426 -0
  68. package/ktvm/wire.mjs +489 -0
  69. package/lib/djson.k +175 -173
  70. package/lib/generic.k +82 -97
  71. package/lib/ieee.k +110 -115
  72. package/lib/integer.k +25 -31
  73. package/package.json +1 -9
  74. package/repl.mjs +101 -20
  75. package/scripts/build-repl-html.mjs +40 -18
  76. package/scripts/perf-bigint-compare.mjs +275 -0
  77. package/scripts/perf-ieee.mjs +9 -229
  78. package/scripts/perf-int.mjs +14 -272
  79. package/scripts/perf-multiplication.mjs +8 -54
  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-djson-methods.mjs +0 -1
  85. package/tests/test-djson.mjs +0 -1
  86. package/tests/test-generic.mjs +5 -7
  87. package/tests/test-repl-html.mjs +72 -15
  88. package/tests/test-repl.mjs +27 -20
  89. package/tests/test-structural-values.mjs +1 -1
  90. package/DOCS/POLYMORPHIC_IR.md +0 -86
  91. package/access-table.mjs +0 -343
  92. package/pkir.mjs +0 -772
  93. package/tests/test-access-table.mjs +0 -213
  94. package/tests/test-pkir.mjs +0 -530
package/repl.mjs CHANGED
@@ -10,6 +10,9 @@ import { argv, exit, stdin, stdout } from "node:process";
10
10
  import { annotate, parse } from "./index.mjs";
11
11
  import run, { constrainWithPattern, run_rel } from "./run.mjs";
12
12
  import { compileWasmArtifactFromObject, instantiateWasmArtifact } from "./backends/wasm/src/wasm.mjs";
13
+ import { compileObjectToKTVMWasm, instantiateKTVMWasm } from "./ktvm/wasm/index.mjs";
14
+ import { compareLabels, isClosedPlist } from "./ktvm/schema.mjs";
15
+ import { encodeValueToEnvelopedWire } from "./ktvm/wire.mjs";
13
16
  import { exportPatternGraph } from "./codecs/runtime/codec.mjs";
14
17
  import { patternToPropertyList } from "./codecs/runtime/pattern-json.mjs";
15
18
  import codes from "./codes.mjs";
@@ -61,11 +64,13 @@ import {
61
64
  } from "./repl-codecs.mjs";
62
65
 
63
66
  const NAME_RE = /^[a-zA-Z0-9_+-][a-zA-Z0-9_?!+-]*$/;
67
+ const VALID_ENGINES = ["wasm", "ktvm", "js"];
68
+ const VALID_ENGINES_TEXT = VALID_ENGINES.join(", ");
64
69
  const COMMAND_NAMES = [
65
70
  "help", "rel", "pattern", "pat", "patterns", "pats",
66
71
  "all-patterns", "all-pat",
67
72
  "codecs", "rels", "codec", "input", "reset", "klib", "ko", "load",
68
- "engine", "wasm", "pkir", "js", "limit",
73
+ "engine", "wasm", "ktvm", "js", "limit",
69
74
  "max-pat-length", "maxPatLength",
70
75
  "quit", "exit"
71
76
  ];
@@ -92,9 +97,9 @@ function emptyValue() {
92
97
  function createState(options = {}) {
93
98
  codes.load(cloneJSON(initialCodes));
94
99
  const engine = (options.engine || "wasm").toLowerCase();
95
- if (engine !== "wasm" && engine !== "pkir" && engine !== "js") {
100
+ if (!VALID_ENGINES.includes(engine)) {
96
101
  throw new Error(
97
- `Invalid engine '${options.engine}'. Valid engines: wasm, pkir, js`
102
+ `Invalid engine '${options.engine}'. Valid engines: ${VALID_ENGINES_TEXT}`
98
103
  );
99
104
  }
100
105
  return {
@@ -1256,7 +1261,7 @@ function completeCommandArgument(line, state) {
1256
1261
  }
1257
1262
 
1258
1263
  if (command === "engine") {
1259
- return completeCommandWord(line, argStart, arg, ["wasm", "pkir", "js"]);
1264
+ return completeCommandWord(line, argStart, arg, VALID_ENGINES);
1260
1265
  }
1261
1266
 
1262
1267
  if (command === "input") {
@@ -1545,8 +1550,7 @@ async function executeExpressionWithWasm(annotated, state, lineOffset = 0) {
1545
1550
 
1546
1551
  const wasmCompileStart = performance.now();
1547
1552
  const wasmBytes = await compileWasmArtifactFromObject(obj, {
1548
- inputEnvelopePattern: inputValue?.pattern,
1549
- usePKIR: state.engine === "pkir" || state.usePKIR
1553
+ inputEnvelopePattern: inputValue?.pattern
1550
1554
  });
1551
1555
  const runner = await instantiateWasmArtifact(wasmBytes);
1552
1556
  const wasmCompileMs = performance.now() - wasmCompileStart;
@@ -1558,6 +1562,81 @@ async function executeExpressionWithWasm(annotated, state, lineOffset = 0) {
1558
1562
  return { result, wasmCompileMs, executeMs };
1559
1563
  }
1560
1564
 
1565
+ function deriveClosedPlistFromValue(val) {
1566
+ const nodes = [];
1567
+ function visit(v) {
1568
+ const id = nodes.length;
1569
+ if (isVariant(v)) {
1570
+ const slot = ["closed-union", []];
1571
+ nodes.push(slot);
1572
+ const childId = visit(v.value);
1573
+ slot[1].push([v.tag, childId]);
1574
+ return id;
1575
+ }
1576
+ const slot = ["closed-product", []];
1577
+ nodes.push(slot);
1578
+ const prod = isProduct(v) ? v.product : {};
1579
+ const keys = Object.keys(prod).sort(compareLabels);
1580
+ for (const k of keys) {
1581
+ const childId = visit(prod[k]);
1582
+ slot[1].push([k, childId]);
1583
+ }
1584
+ return id;
1585
+ }
1586
+ visit(val);
1587
+ return nodes;
1588
+ }
1589
+
1590
+ async function executeExpressionWithKTVM(annotated, state, lineOffset = 0) {
1591
+ const mainRel = annotated.rels.__main__;
1592
+ if (!mainRel) return { result: undefined, wasmCompileMs: 0, executeMs: 0 };
1593
+
1594
+ let inputValue = state.value ?? emptyValue();
1595
+ if (mainRel.typePatternGraph && mainRel.def.patterns) {
1596
+ const graph = mainRel.typePatternGraph;
1597
+ const nodeId = graph.find(mainRel.def.patterns[0]);
1598
+ const inputPattern = patternToPropertyList(exportPatternGraph(graph, nodeId));
1599
+ inputValue = constrainWithPattern(inputValue, inputPattern, mainRel.def);
1600
+ }
1601
+
1602
+ const obj = {
1603
+ format: "k-object",
1604
+ codes: { ...state.codes, ...codes.dump() },
1605
+ rels: annotated.rels,
1606
+ relAlias: annotated.relAlias,
1607
+ compileStats: annotated.compileStats,
1608
+ main: "__main__"
1609
+ };
1610
+
1611
+ let inputPlist = inputValue?.pattern;
1612
+ if (!inputPlist || !isClosedPlist(inputPlist)) {
1613
+ inputPlist = deriveClosedPlistFromValue(inputValue);
1614
+ }
1615
+
1616
+ const wasmCompileStart = performance.now();
1617
+ const artifact = await compileObjectToKTVMWasm(obj, "__main__", inputPlist, {
1618
+ optimize: true,
1619
+ validate: true,
1620
+ verifyTables: true
1621
+ });
1622
+ const runner = await instantiateKTVMWasm(artifact, {
1623
+ quota: {
1624
+ maxSteps: 1_000_000_000,
1625
+ maxNodes: 2_000_000,
1626
+ maxBitDequeBytes: 256 * 1024 * 1024
1627
+ }
1628
+ });
1629
+ const wasmCompileMs = performance.now() - wasmCompileStart;
1630
+
1631
+ const inputWire = encodeValueToEnvelopedWire(inputValue, inputPlist);
1632
+ const executeStart = performance.now();
1633
+ const exec = runner.executeWire(inputWire, { decodeValue: true });
1634
+ const executeMs = performance.now() - executeStart;
1635
+
1636
+ const result = exec.status === "OK" ? exec.value : undefined;
1637
+ return { result, wasmCompileMs, executeMs };
1638
+ }
1639
+
1561
1640
  function executeExpressionWithJs(annotated, state, lineOffset = 0) {
1562
1641
  const mainRel = annotated.rels.__main__;
1563
1642
  if (!mainRel) return { result: undefined, wasmCompileMs: 0, executeMs: 0 };
@@ -1609,6 +1688,8 @@ async function runSnippet(input, state, options = {}) {
1609
1688
  try {
1610
1689
  if (state.engine === "js") {
1611
1690
  execRes = executeExpressionWithJs(annotated, state, lineOffset);
1691
+ } else if (state.engine === "ktvm") {
1692
+ execRes = await executeExpressionWithKTVM(annotated, state, lineOffset);
1612
1693
  } else {
1613
1694
  execRes = await executeExpressionWithWasm(annotated, state, lineOffset);
1614
1695
  }
@@ -1865,9 +1946,9 @@ async function evaluateCommand(line, state) {
1865
1946
  if (!mode) {
1866
1947
  return [`Current engine: ${state.engine}`];
1867
1948
  }
1868
- if (mode !== "wasm" && mode !== "pkir" && mode !== "js") {
1949
+ if (!VALID_ENGINES.includes(mode)) {
1869
1950
  throw new Error(
1870
- `Invalid engine '${arg.trim()}'. Valid engines: wasm, pkir, js`
1951
+ `Invalid engine '${arg.trim()}'. Valid engines: ${VALID_ENGINES_TEXT}`
1871
1952
  );
1872
1953
  }
1873
1954
  state.engine = mode;
@@ -1877,9 +1958,9 @@ async function evaluateCommand(line, state) {
1877
1958
  state.engine = "wasm";
1878
1959
  return ["engine set to wasm"];
1879
1960
  }
1880
- case "pkir": {
1881
- state.engine = "pkir";
1882
- return ["engine set to pkir"];
1961
+ case "ktvm": {
1962
+ state.engine = "ktvm";
1963
+ return ["engine set to ktvm"];
1883
1964
  }
1884
1965
  case "js": {
1885
1966
  state.engine = "js";
@@ -1969,7 +2050,7 @@ async function evaluateCommand(line, state) {
1969
2050
 
1970
2051
  function helpText() {
1971
2052
  return [
1972
- ":engine [wasm|pkir|js] display or switch evaluation engine",
2053
+ ":engine [wasm|ktvm|js] display or switch evaluation engine",
1973
2054
  ":rel name show relation definition",
1974
2055
  ":rels list relation aliases",
1975
2056
  ":pattern name show named pattern definition (alias :pat)",
@@ -2008,9 +2089,9 @@ function cliUsage() {
2008
2089
  console.log("Usage: k-repl [options]");
2009
2090
  console.log("");
2010
2091
  console.log("Options:");
2011
- console.log(" --engine=<wasm|pkir|js> Select engine: wasm, pkir, js");
2092
+ console.log(" --engine=<wasm|ktvm|js> Select engine: wasm, ktvm, js");
2012
2093
  console.log(" (default: wasm).");
2013
- console.log(" --pkir Shortcut for --engine=pkir.");
2094
+ console.log(" --ktvm Shortcut for --engine=ktvm.");
2014
2095
  console.log(" --wasm Shortcut for --engine=wasm.");
2015
2096
  console.log(" --js Shortcut for --engine=js.");
2016
2097
  console.log(" --limit=<num> Set maximum characters for output.");
@@ -2122,13 +2203,13 @@ if (isMainEntrypoint()) {
2122
2203
  engine = "js";
2123
2204
  } else if (arg === "--wasm") {
2124
2205
  engine = "wasm";
2125
- } else if (arg === "--pkir") {
2126
- engine = "pkir";
2206
+ } else if (arg === "--ktvm") {
2207
+ engine = "ktvm";
2127
2208
  } else if (arg.startsWith("--engine=")) {
2128
2209
  const val = arg.slice("--engine=".length).toLowerCase();
2129
- if (val !== "wasm" && val !== "pkir" && val !== "js") {
2210
+ if (!VALID_ENGINES.includes(val)) {
2130
2211
  console.error(
2131
- `Invalid engine '${val}'. Valid engines: wasm, pkir, js`
2212
+ `Invalid engine '${val}'. Valid engines: ${VALID_ENGINES_TEXT}`
2132
2213
  );
2133
2214
  exit(1);
2134
2215
  }
@@ -2136,9 +2217,9 @@ if (isMainEntrypoint()) {
2136
2217
  } else if (arg === "--engine") {
2137
2218
  i++;
2138
2219
  const val = (args[i] || "").toLowerCase();
2139
- if (val !== "wasm" && val !== "pkir" && val !== "js") {
2220
+ if (!VALID_ENGINES.includes(val)) {
2140
2221
  console.error(
2141
- `Invalid engine '${val}'. Valid engines: wasm, pkir, js`
2222
+ `Invalid engine '${val}'. Valid engines: ${VALID_ENGINES_TEXT}`
2142
2223
  );
2143
2224
  exit(1);
2144
2225
  }
@@ -52,9 +52,11 @@ const nodeShimsPlugin = {
52
52
  "node:url": path.join(projectRoot, "browser/shims/url.mjs"),
53
53
  "assert": path.join(projectRoot, "browser/shims/assert.mjs"),
54
54
  "node:assert": path.join(projectRoot, "browser/shims/assert.mjs"),
55
+ "child_process": path.join(projectRoot, "browser/shims/child_process.mjs"),
56
+ "node:child_process": path.join(projectRoot, "browser/shims/child_process.mjs"),
55
57
  };
56
58
 
57
- build.onResolve({ filter: /^(node:)?(fs|path|crypto|buffer|os|process|readline|url|assert)$/ }, (args) => {
59
+ build.onResolve({ filter: /^(node:)?(fs|path|crypto|buffer|os|process|readline|url|assert|child_process)$/ }, (args) => {
58
60
  if (shims[args.path]) {
59
61
  return { path: shims[args.path] };
60
62
  }
@@ -66,11 +68,15 @@ const nodeShimsPlugin = {
66
68
  console.log("1. Generating VFS data...");
67
69
  const vfsFiles = {};
68
70
 
69
- // Add runtime.wat
71
+ // Add runtime.wat (Wasm & kTVM Wasm)
70
72
  const runtimeWatPath = path.join(projectRoot, "backends/wasm/runtime.wat");
71
73
  if (fs.existsSync(runtimeWatPath)) {
72
74
  vfsFiles["backends/wasm/runtime.wat"] = fs.readFileSync(runtimeWatPath, "utf8");
73
75
  }
76
+ const ktvmRuntimeWatPath = path.join(projectRoot, "ktvm/wasm/runtime.wat");
77
+ if (fs.existsSync(ktvmRuntimeWatPath)) {
78
+ vfsFiles["ktvm/wasm/runtime.wat"] = fs.readFileSync(ktvmRuntimeWatPath, "utf8");
79
+ }
74
80
 
75
81
  // Add core.k
76
82
  const coreKPath = path.join(projectRoot, "core.k");
@@ -285,44 +291,60 @@ const htmlContent = `<!DOCTYPE html>
285
291
  letter-spacing: 0.5px;
286
292
  }
287
293
 
288
- .engine-badge {
294
+ .engine-badge,
295
+ button.engine-badge {
296
+ font-family: inherit;
289
297
  font-size: 11px;
290
298
  font-weight: 600;
299
+ line-height: 1.25;
291
300
  background: rgba(88, 166, 255, 0.15);
292
301
  color: var(--color-prompt);
293
302
  border: 1px solid rgba(88, 166, 255, 0.3);
294
- padding: 2px 8px;
303
+ padding: 3px 10px;
304
+ min-block-size: 24px;
295
305
  border-radius: 12px;
306
+ display: inline-flex;
307
+ align-items: center;
296
308
  cursor: pointer;
297
309
  user-select: none;
298
- transition: all 0.15s ease;
310
+ transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease;
299
311
  }
300
312
 
301
- .engine-badge:hover {
313
+ .engine-badge:hover,
314
+ button.engine-badge:hover {
302
315
  background: rgba(88, 166, 255, 0.3);
303
316
  border-color: rgba(88, 166, 255, 0.6);
304
317
  }
305
318
 
306
- .engine-badge.js-mode {
319
+ button.engine-badge:focus-visible {
320
+ outline: 2px solid var(--border-focus);
321
+ outline-offset: 2px;
322
+ }
323
+
324
+ .engine-badge.js-mode,
325
+ button.engine-badge.js-mode {
307
326
  background: rgba(240, 180, 41, 0.15);
308
327
  color: #e3b341;
309
328
  border-color: rgba(240, 180, 41, 0.4);
310
329
  }
311
330
 
312
- .engine-badge.js-mode:hover {
331
+ .engine-badge.js-mode:hover,
332
+ button.engine-badge.js-mode:hover {
313
333
  background: rgba(240, 180, 41, 0.3);
314
334
  border-color: rgba(240, 180, 41, 0.7);
315
335
  }
316
336
 
317
- .engine-badge.pkir-mode {
318
- background: rgba(187, 128, 255, 0.15);
319
- color: #d2a8ff;
320
- border-color: rgba(187, 128, 255, 0.4);
337
+ .engine-badge.ktvm-mode,
338
+ button.engine-badge.ktvm-mode {
339
+ background: rgba(57, 197, 207, 0.16);
340
+ color: #56d4dd;
341
+ border-color: rgba(57, 197, 207, 0.45);
321
342
  }
322
343
 
323
- .engine-badge.pkir-mode:hover {
324
- background: rgba(187, 128, 255, 0.3);
325
- border-color: rgba(187, 128, 255, 0.7);
344
+ .engine-badge.ktvm-mode:hover,
345
+ button.engine-badge.ktvm-mode:hover {
346
+ background: rgba(57, 197, 207, 0.3);
347
+ border-color: rgba(57, 197, 207, 0.75);
326
348
  }
327
349
 
328
350
  .status-indicator {
@@ -1691,7 +1713,7 @@ const htmlContent = `<!DOCTYPE html>
1691
1713
  <div class="nav-left">
1692
1714
  <div class="brand">
1693
1715
  <span class="brand-name">k repl</span>
1694
- <span id="engine-badge" class="engine-badge" title="Click to toggle engine (wasm/pkir/js)">wasm-in-process</span>
1716
+ <button type="button" id="engine-badge" class="engine-badge" aria-label="wasm-in-process — switch evaluation engine" title="Click to switch engine (wasm/ktvm/js)">wasm-in-process</button>
1695
1717
  </div>
1696
1718
  <div class="status-indicator">
1697
1719
  <span id="status-dot" class="status-dot ready"></span>
@@ -1726,7 +1748,7 @@ const htmlContent = `<!DOCTYPE html>
1726
1748
  <option value="expr::rels">:rels (list relations)</option>
1727
1749
  <option value="expr::engine">:engine (show engine)</option>
1728
1750
  <option value="expr::engine wasm">:engine wasm</option>
1729
- <option value="expr::engine pkir">:engine pkir</option>
1751
+ <option value="expr::engine ktvm">:engine ktvm</option>
1730
1752
  <option value="expr::engine js">:engine js</option>
1731
1753
  </optgroup>
1732
1754
  <optgroup label="Codecs &amp; Format Adapters">
@@ -1940,7 +1962,7 @@ const htmlContent = `<!DOCTYPE html>
1940
1962
  <div class="help-section">
1941
1963
  <h4>REPL Commands</h4>
1942
1964
  <table class="help-table">
1943
- <tr><td><code>:engine [wasm|pkir|js]</code></td><td>Display or switch evaluation engine (<code>wasm</code>, <code>pkir</code>, or <code>js</code>; shortcuts: <code>:wasm</code>, <code>:pkir</code>, <code>:js</code>)</td></tr>
1965
+ <tr><td><code>:engine [wasm|ktvm|js]</code></td><td>Display or switch evaluation engine (<code>wasm</code>, <code>ktvm</code>, or <code>js</code>; shortcuts: <code>:wasm</code>, <code>:ktvm</code>, <code>:js</code>)</td></tr>
1944
1966
  <tr><td><code>:load [--no-alias] &lt;file&gt;</code></td><td>Load a <code>.k</code> source or <code>.klib</code> library into current state (use <code>--no-alias</code> to import by hash only)</td></tr>
1945
1967
  <tr>
1946
1968
  <td><code>:pattern &lt;name&gt;</code></td>
@@ -0,0 +1,275 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * End-to-End Integer Squaring Benchmark: K vs JS BigInt
5
+ *
6
+ * Compares the full UTF-8 decimal string -> parse -> N squarings -> decimal print
7
+ * pipeline between JavaScript BigInt and K (lib/integer.k) across backends:
8
+ * llvm, wasm, kvm, js
9
+ *
10
+ * Usage:
11
+ * node scripts/perf-bigint-compare.mjs [options]
12
+ */
13
+
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ import { performance } from "node:perf_hooks";
17
+ import { fileURLToPath } from "node:url";
18
+
19
+ import k from "../index.mjs";
20
+ import {
21
+ codes,
22
+ createState,
23
+ decodeWire,
24
+ encodeToWire,
25
+ evaluateInput,
26
+ executeKVM
27
+ } from "../backend-api.mjs";
28
+ import { compileLibrary, loadLibrary } from "../object.mjs";
29
+ import { parse as parseIntVal, print as printIntVal } from "../codecs/int.mjs";
30
+ import { compileObjectToExecutable } from "../backends/llvm/src/executable.mjs";
31
+ import {
32
+ compileWasmArtifact,
33
+ instantiateWasmArtifact
34
+ } from "../backends/wasm/src/wasm.mjs";
35
+ import {
36
+ PersistentExecutable,
37
+ makeCacheDir,
38
+ prepareRelation
39
+ } from "../backends/llvm/tests/perf-support.mjs";
40
+
41
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
42
+ const args = process.argv.slice(2);
43
+
44
+ function getArg(flag, fallback) {
45
+ const idx = args.indexOf(flag);
46
+ return idx !== -1 && args[idx + 1] ? args[idx + 1] : fallback;
47
+ }
48
+
49
+ if (args.includes("-h") || args.includes("--help")) {
50
+ console.log(`Usage: node scripts/perf-bigint-compare.mjs [options]
51
+
52
+ End-to-end decimal parse -> N squarings -> decimal print benchmark comparing
53
+ JS BigInt against K (lib/integer.k) across execution backends.
54
+
55
+ Options:
56
+ --input <decimal> Starting decimal integer (default: 987654321)
57
+ --steps <n> Number of consecutive squarings (default: 10)
58
+ --backends <csv> K backends: llvm,wasm,kvm,js
59
+ (default: llvm,wasm)
60
+ --iters <n> Measured iterations per K backend (default: 3)
61
+ -h, --help Show this help message and exit`);
62
+ process.exit(0);
63
+ }
64
+
65
+ const INPUT = getArg("--input", "987654321");
66
+ const STEPS = Number.parseInt(getArg("--steps", "10"), 10);
67
+ const ITERS = Number.parseInt(getArg("--iters", "3"), 10);
68
+ const BACKENDS = getArg("--backends", "llvm,wasm")
69
+ .split(",")
70
+ .map((b) => b.trim().toLowerCase())
71
+ .filter(Boolean);
72
+
73
+ function fmtMs(ms) {
74
+ if (ms < 0.01) return `${(ms * 1000).toFixed(2)} µs`;
75
+ if (ms < 1) return `${(ms * 1000).toFixed(0)} µs`;
76
+ if (ms < 100) return `${ms.toFixed(2)} ms`;
77
+ if (ms < 1000) return `${ms.toFixed(1)} ms`;
78
+ return `${(ms / 1000).toFixed(2)} s`;
79
+ }
80
+
81
+ // 1. JS BigInt baseline
82
+ function benchBigInt(iters = 500) {
83
+ let expected;
84
+ for (let i = 0; i < 20; i++) {
85
+ let x = BigInt(INPUT);
86
+ for (let s = 0; s < STEPS; s++) x = x * x;
87
+ expected = x.toString(10);
88
+ }
89
+ let parseMs = 0;
90
+ let computeMs = 0;
91
+ let printMs = 0;
92
+ for (let i = 0; i < iters; i++) {
93
+ const t0 = performance.now();
94
+ let x = BigInt(INPUT);
95
+ const t1 = performance.now();
96
+ for (let s = 0; s < STEPS; s++) x = x * x;
97
+ const t2 = performance.now();
98
+ const out = x.toString(10);
99
+ const t3 = performance.now();
100
+ if (out.length !== expected.length) throw new Error("BigInt mismatch");
101
+ parseMs += t1 - t0;
102
+ computeMs += t2 - t1;
103
+ printMs += t3 - t2;
104
+ }
105
+ return {
106
+ name: "JS BigInt",
107
+ parseMs: parseMs / iters,
108
+ computeMs: computeMs / iters,
109
+ printMs: printMs / iters,
110
+ totalMs: (parseMs + computeMs + printMs) / iters,
111
+ output: expected
112
+ };
113
+ }
114
+
115
+ const bigRes = benchBigInt();
116
+ console.log(
117
+ `Input: "${INPUT}" | Squarings: ${STEPS} | Output: ${bigRes.output.length} decimal digits`
118
+ );
119
+ console.log(
120
+ `Result: ${bigRes.output.slice(0, 30)}...${bigRes.output.slice(-20)}\n`
121
+ );
122
+
123
+ // 2. Compile sqN in K (both library form for Wasm/JS and REPL state for LLVM/kVM)
124
+ const intSource = fs.readFileSync(path.join(root, "lib/integer.k"), "utf8");
125
+ const sqDefs = `\nsq = ?int[] { () x, () y } times ?int[];\nsqN = ${Array(STEPS).fill("sq").join(" ")};\n`;
126
+ const intLib = loadLibrary(
127
+ compileLibrary(intSource + sqDefs, { source: "lib/integer.k+sqN" })
128
+ );
129
+ const sqNAlias = intLib.relAlias.sqN;
130
+ const intPattern = parseIntVal("0").pattern;
131
+
132
+ const results = [bigRes];
133
+
134
+ async function benchInProcess(name, runFn, iters) {
135
+ // Warmup & conformance check
136
+ {
137
+ const val = parseIntVal(INPUT);
138
+ const outStr = printIntVal(runFn(val));
139
+ if (outStr !== bigRes.output) throw new Error(`${name}: output mismatch`);
140
+ }
141
+ let parseMs = 0;
142
+ let computeMs = 0;
143
+ let printMs = 0;
144
+ for (let i = 0; i < iters; i++) {
145
+ const t0 = performance.now();
146
+ const val = parseIntVal(INPUT);
147
+ const t1 = performance.now();
148
+ const outVal = runFn(val);
149
+ const t2 = performance.now();
150
+ const outStr = printIntVal(outVal);
151
+ const t3 = performance.now();
152
+ if (outStr !== bigRes.output) throw new Error(`${name}: output mismatch`);
153
+ parseMs += t1 - t0;
154
+ computeMs += t2 - t1;
155
+ printMs += t3 - t2;
156
+ }
157
+ return {
158
+ name,
159
+ parseMs: parseMs / iters,
160
+ computeMs: computeMs / iters,
161
+ printMs: printMs / iters,
162
+ totalMs: (parseMs + computeMs + printMs) / iters
163
+ };
164
+ }
165
+
166
+ async function benchWireServer(name, server, iters) {
167
+ // Warmup & conformance check
168
+ {
169
+ const val = parseIntVal(INPUT);
170
+ const wire = encodeToWire(val, val.pattern);
171
+ const outWire = await server.request(wire);
172
+ const outStr = printIntVal(decodeWire(outWire).value);
173
+ if (outStr !== bigRes.output) throw new Error(`${name}: output mismatch`);
174
+ }
175
+ let parseMs = 0;
176
+ let computeMs = 0;
177
+ let printMs = 0;
178
+ for (let i = 0; i < iters; i++) {
179
+ const t0 = performance.now();
180
+ const val = parseIntVal(INPUT);
181
+ const wire = encodeToWire(val, val.pattern);
182
+ const t1 = performance.now();
183
+ const outWire = await server.request(wire);
184
+ const t2 = performance.now();
185
+ const outStr = printIntVal(decodeWire(outWire).value);
186
+ const t3 = performance.now();
187
+ if (outStr !== bigRes.output) throw new Error(`${name}: output mismatch`);
188
+ parseMs += t1 - t0;
189
+ computeMs += t2 - t1;
190
+ printMs += t3 - t2;
191
+ }
192
+ return {
193
+ name,
194
+ parseMs: parseMs / iters,
195
+ computeMs: computeMs / iters,
196
+ printMs: printMs / iters,
197
+ totalMs: (parseMs + computeMs + printMs) / iters
198
+ };
199
+ }
200
+
201
+ // Prepare LLVM/kVM relation object if needed
202
+ let prepared = null;
203
+ let preparedState = null;
204
+ let cacheDir = null;
205
+ if (BACKENDS.some((b) => b === "llvm" || b === "kvm")) {
206
+ preparedState = createState();
207
+ await evaluateInput(`:load ${path.join(root, "lib/integer.k")}`, preparedState);
208
+ await evaluateInput("sq = ?int[] { () x, () y } times ?int[];", preparedState);
209
+ await evaluateInput(`sqN = ${Array(STEPS).fill("sq").join(" ")};`, preparedState);
210
+ codes.load(preparedState.codes);
211
+ prepared = prepareRelation(preparedState, "sqN", { sourceLabel: "lib/integer.k#sqN" });
212
+ cacheDir = makeCacheDir("k-bigint-cmp-");
213
+ }
214
+
215
+ for (const backend of BACKENDS) {
216
+ try {
217
+ if (backend === "llvm") {
218
+ const label = "K LLVM (-O3)";
219
+ const exe = path.join(cacheDir, `sqN_${backend}`);
220
+ compileObjectToExecutable(prepared.object, exe, {
221
+ clangOpt: "-O3",
222
+ inputPattern: intPattern
223
+ });
224
+ const srv = new PersistentExecutable(exe, {
225
+ env: { ...process.env, K_ARENA_CAPACITY_MB: "4096" }
226
+ });
227
+ try {
228
+ results.push(await benchWireServer(label, srv, ITERS));
229
+ } finally {
230
+ await srv.close();
231
+ }
232
+ } else if (backend === "wasm") {
233
+ const label = "K Wasm";
234
+ const artifact = await compileWasmArtifact(sqNAlias, {
235
+ libraries: [intLib]
236
+ });
237
+ const inst = await instantiateWasmArtifact(artifact);
238
+ results.push(
239
+ await benchInProcess(label, (val) => inst.executeValue(val), ITERS)
240
+ );
241
+ } else if (backend === "kvm") {
242
+ const kvmContext = {
243
+ rels: preparedState.rels,
244
+ findCode: codes.find,
245
+ options: { envelopeFree: true }
246
+ };
247
+ results.push(
248
+ await benchInProcess(
249
+ "K kVM",
250
+ (val) => executeKVM(prepared.kvmFunc, val, kvmContext),
251
+ Math.min(ITERS, 2)
252
+ )
253
+ );
254
+ } else if (backend === "js") {
255
+ const fn = k.compile(sqNAlias, { libraries: [intLib] });
256
+ results.push(await benchInProcess("K JS", fn, Math.min(ITERS, 2)));
257
+ } else {
258
+ console.warn(`[WARN] Unknown backend: ${backend}`);
259
+ }
260
+ } catch (err) {
261
+ console.warn(`[SKIP] ${backend}: ${err.message}`);
262
+ }
263
+ }
264
+
265
+ console.log(
266
+ `| Engine | Parse | Compute (${STEPS}x sq) | Print | Total | vs BigInt (Compute) | vs BigInt (Total) |`
267
+ );
268
+ console.log("| --- | ---: | ---: | ---: | ---: | ---: | ---: |");
269
+ for (const r of results) {
270
+ const cRatio = `${(r.computeMs / bigRes.computeMs).toFixed(1)}x`;
271
+ const tRatio = `${(r.totalMs / bigRes.totalMs).toFixed(1)}x`;
272
+ console.log(
273
+ `| ${r.name} | ${fmtMs(r.parseMs)} | ${fmtMs(r.computeMs)} | ${fmtMs(r.printMs)} | ${fmtMs(r.totalMs)} | ${cRatio} | ${tRatio} |`
274
+ );
275
+ }