@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
@@ -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
  }
package/codecs/djson.mjs CHANGED
@@ -16,7 +16,7 @@
16
16
  * >
17
17
  *
18
18
  * - In `list`, element at index i >= 0 is stored at the canonical binary
19
- * bit-path of i (0 -> [0], 1 -> [1], 2 -> [1,0], 3 -> [1,1], ...).
19
+ * bit-path of i (0 -> [], 1 -> [1], 2 -> [1,0], 3 -> [1,1], ...).
20
20
  * - In `object`, entry with key k is stored at the prefix-free Unicode
21
21
  * character bit-path of k.
22
22
  */
@@ -167,7 +167,7 @@ function readBitsMSB(bits, offset, width) {
167
167
  }
168
168
 
169
169
  export function indexToBitPath(index) {
170
- if (index === 0) return [0];
170
+ if (index === 0) return [];
171
171
  const bits = [];
172
172
  let n = index;
173
173
  while (n > 0) {
@@ -179,7 +179,6 @@ export function indexToBitPath(index) {
179
179
  }
180
180
 
181
181
  export function bitPathToIndex(bits) {
182
- if (bits.length === 1 && bits[0] === 0) return 0;
183
182
  let n = 0;
184
183
  for (const b of bits) {
185
184
  n = n * 2 + b;
package/codecs/int.mjs CHANGED
@@ -32,12 +32,42 @@ const INT_LIST_PATTERN = patternFromFilter(`
32
32
  > = list
33
33
  `);
34
34
 
35
- // Build bits Value (MSB outermost) from a non-negative BigInt.
36
- function buildBits(n) {
37
- const bitChars = n === 0n ? ["0"] : n.toString(2).split("");
35
+ const DEC_BASE = 1_000_000_000;
36
+ const DEC_CHUNK = 9;
37
+ const BIT_CHUNK = 20;
38
+ const BIT_BASE = 1 << BIT_CHUNK; // 2^20 * 10^9 < Number.MAX_SAFE_INTEGER
39
+
40
+ // Build bits Value (MSB outermost) directly from a validated non-negative decimal string.
41
+ function decimalToBits(str) {
38
42
  let v = Value.variant("_", Value.product({}));
39
- for (let i = bitChars.length - 1; i >= 0; i--) {
40
- v = Value.variant(bitChars[i], v);
43
+ if (str === "0") return v;
44
+ const limbs = [];
45
+ const firstLen = str.length % DEC_CHUNK || DEC_CHUNK;
46
+ limbs.push(Number(str.slice(0, firstLen)));
47
+ for (let i = firstLen; i < str.length; i += DEC_CHUNK) {
48
+ limbs.push(Number(str.slice(i, i + DEC_CHUNK)));
49
+ }
50
+ let start = 0;
51
+ while (start < limbs.length) {
52
+ let rem = 0;
53
+ for (let i = start; i < limbs.length; i++) {
54
+ const cur = rem * DEC_BASE + limbs[i];
55
+ const q = Math.floor(cur / BIT_BASE);
56
+ limbs[i] = q;
57
+ rem = cur - q * BIT_BASE;
58
+ }
59
+ while (start < limbs.length && limbs[start] === 0) start++;
60
+ if (start < limbs.length) {
61
+ for (let b = 0; b < BIT_CHUNK; b++) {
62
+ v = Value.variant((rem & 1) === 1 ? "1" : "0", v);
63
+ rem >>>= 1;
64
+ }
65
+ } else {
66
+ while (rem > 0) {
67
+ v = Value.variant((rem & 1) === 1 ? "1" : "0", v);
68
+ rem >>>= 1;
69
+ }
70
+ }
41
71
  }
42
72
  return v;
43
73
  }
@@ -51,9 +81,8 @@ function parseIntStr(str) {
51
81
  if (!/^(0|[1-9][0-9]*)$/.test(str)) {
52
82
  throw new Error(`Invalid integer syntax: ${JSON.stringify(str)}`);
53
83
  }
54
- const n = BigInt(str);
55
- if (n === 0n) sign = "+";
56
- return Value.variant(sign, buildBits(n));
84
+ if (str === "0") sign = "+";
85
+ return Value.variant(sign, decimalToBits(str));
57
86
  }
58
87
 
59
88
  // Parse a list of decimal integers, e.g. "[0,1,2]" or "[]"
@@ -94,15 +123,38 @@ function printSingleInt(value) {
94
123
  throw new Error("Not a valid k int value");
95
124
  }
96
125
  const sign = value.tag;
97
- let bits = "";
126
+ const limbs = []; // base-10^9, least-significant limb at index 0
98
127
  let node = value.value;
99
128
  while (isVariant(node) && node.tag !== "_") {
100
- bits += node.tag;
101
- node = node.value;
129
+ let chunkVal = 0;
130
+ let chunkBits = 0;
131
+ while (chunkBits < BIT_CHUNK && isVariant(node) && node.tag !== "_") {
132
+ if (node.tag !== "0" && node.tag !== "1") {
133
+ throw new Error("Not a valid k int value");
134
+ }
135
+ chunkVal = (chunkVal << 1) | (node.tag === "1" ? 1 : 0);
136
+ chunkBits++;
137
+ node = node.value;
138
+ }
139
+ const mult = 1 << chunkBits;
140
+ let carry = chunkVal;
141
+ for (let i = 0; i < limbs.length; i++) {
142
+ const cur = limbs[i] * mult + carry;
143
+ carry = Math.floor(cur / DEC_BASE);
144
+ limbs[i] = cur - carry * DEC_BASE;
145
+ }
146
+ if (carry > 0) {
147
+ limbs.push(carry);
148
+ }
149
+ }
150
+ if (!isVariant(node) || node.tag !== "_" || !isProduct(node.value) || Object.keys(node.value.product).length !== 0) {
151
+ throw new Error("Not a valid k int value");
152
+ }
153
+ if (limbs.length === 0) return "0";
154
+ let digits = String(limbs[limbs.length - 1]);
155
+ for (let i = limbs.length - 2; i >= 0; i--) {
156
+ digits += String(limbs[i]).padStart(DEC_CHUNK, "0");
102
157
  }
103
- const n = bits === "" ? 0n : BigInt("0b" + bits);
104
- const digits = n.toString(10);
105
- if (n === 0n) return "0";
106
158
  return (sign === "-" ? "-" : "") + digits;
107
159
  }
108
160
 
@@ -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++;