@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
@@ -3,12 +3,10 @@ import { compileObjectBuffer, decodeObject } from "@fraczak/k/object.mjs";
3
3
  import {
4
4
  compileObjectToLLVM,
5
5
  compileLLVMArtifactFromKVM,
6
- compileLLVMArtifactFromPKIR,
7
6
  emitLLVMModule,
8
7
  llvmIdentifier
9
8
  } from "../src/llvm.mjs";
10
9
  import { objectToKVMArtifact } from "@fraczak/k/kvm.mjs";
11
- import { compileRelationToPKIR } from "@fraczak/k/backend-api.mjs";
12
10
 
13
11
  function kirP(body, { patternGraph = null } = {}) {
14
12
  return {
@@ -230,6 +228,8 @@ assert.match(unionLLVM, /call %k_result @k_union_arm_1\(ptr %rt, ptr %input\)/);
230
228
  assert.match(unionLLVM, /load ptr, ptr %mark_block_slot\d+/);
231
229
  assert.match(unionLLVM, /%rewind_fast_ok\d+ = and i1 %rewind_has_mark\d+, %rewind_same_block\d+/);
232
230
  assert.match(unionLLVM, /call void @k_rt_rewind\(ptr %rt, %k_rt_mark %mark\d+\)/);
231
+ // A fast rewind keeps older free blocks available for subsequent allocations.
232
+ assert.doesNotMatch(unionLLVM, /getelementptr i8, ptr %rt, i64 32/);
233
233
 
234
234
  const nestedUnionObject = decodeObject(compileObjectBuffer("{ < /x |left, /y |right > z }", { source: "llvm-nested-union.k" }));
235
235
  const { llvm: nestedUnionLLVM } = compileObjectToLLVM(nestedUnionObject, {
@@ -297,18 +297,4 @@ assert.match(kvmLLVM, /source_filename = "k-llvm:__main__"/);
297
297
  assert.match(kvmLLVM, /define %k_result @k_main/);
298
298
  assert.match(kvmLLVM, /store ptr %product_fields\d+, ptr %ptr_slot\d+/);
299
299
 
300
- // Test PKIR lowering via compileObjectToLLVM with usePKIR: true
301
- const pkirObjectLLVM = compileObjectToLLVM(productObject, {
302
- usePKIR: true
303
- });
304
- assert.match(pkirObjectLLVM.llvm, /source_filename = "k-llvm:__main__"/);
305
- assert.match(pkirObjectLLVM.llvm, /define %k_result @k_main/);
306
-
307
- // Test compileLLVMArtifactFromPKIR directly
308
- const mainRel = productObject.rels[productObject.main || "__main__"];
309
- const pkirFromRel = compileRelationToPKIR(mainRel, "__main__");
310
- const pkirLLVM = compileLLVMArtifactFromPKIR(pkirFromRel);
311
- assert.match(pkirLLVM, /source_filename = "k-llvm:__main__"/);
312
- assert.match(pkirLLVM, /define %k_result @k_main/);
313
-
314
300
  console.log("OK");
@@ -34,7 +34,7 @@ node codecs/unit.mjs --parse |
34
34
 
35
35
  | Command | Purpose |
36
36
  | --- | --- |
37
- | `k-wasm` | Compile and execute a source expression/file, `.ko`, `.kvm`, or `.pkir` |
37
+ | `k-wasm` | Compile and execute a source expression/file, `.ko`, or `.kvm` |
38
38
  | `k-wasm-compile` | Produce a `.wasm` artifact from those program forms |
39
39
  | `k-wasm-run` | Execute a previously compiled `.wasm` artifact |
40
40
 
@@ -45,8 +45,7 @@ input.
45
45
 
46
46
  Compile commands accept one `--lib file` and repeated `--use alias` or
47
47
  `--use libraryAlias:localAlias` options before the program. Libraries can
48
- be `.k` source or `.klib` objects. `--pkir` chooses the experimental PKIR
49
- lowering path; `-o` / `--output` selects an output path.
48
+ be `.k` source or `.klib` objects. `-o` / `--output` selects an output path.
50
49
 
51
50
  Existing paths are read as files. Recognized missing filenames are errors;
52
51
  other program arguments are treated as inline source.
@@ -75,6 +74,7 @@ A module contains the reachable functions, the arena runtime from
75
74
  | `abi` | `"arena-v1"` |
76
75
  | `entry` | Exported function called by the runner |
77
76
  | `inputPattern` / `outputPattern` | Patterns used by the arena adapters |
77
+ | `wireIdentity` | Optional compiler proof that the entry returns its input under one closed contract |
78
78
  | `tags` | Statically known variant tags and their IDs |
79
79
 
80
80
  The entry ABI is `(input_pointer i32) -> (output_pointer i32, ok i32)`.
@@ -92,6 +92,10 @@ contract is needed.
92
92
 
93
93
  ## Limits and implementation
94
94
 
95
+ The wire runner can forward the bytes for a proven identity after validating
96
+ the complete payload and matching the canonical header. This path skips arena
97
+ conversion. Frames with other headers go through the normal adapter.
98
+
95
99
  A `.wasm` file still needs a host that understands the arena ABI and metadata.
96
100
  The CLI host is Node.js; the browser REPL bundles its own in-process adapter.
97
101
 
@@ -12,7 +12,7 @@ import {
12
12
  function helpText() {
13
13
  const prog = argv[1] || "k-wasm-compile.mjs";
14
14
  return [
15
- "Compile k source, .ko, .kvm, or .pkir into a WebAssembly (.wasm)",
15
+ "Compile k source, .ko, or .kvm into a WebAssembly (.wasm)",
16
16
  "artifact.",
17
17
  "",
18
18
  `Usage: ${prog} [options]`,
@@ -20,13 +20,12 @@ function helpText() {
20
20
  "",
21
21
  "Arguments:",
22
22
  " source-snippet Inline k source snippet (in the style of k.mjs).",
23
- " input-file Source .k, .ko, .kvm, or .pkir file.",
23
+ " input-file Source .k, .ko, or .kvm file.",
24
24
  " Reads UTF-8 source from stdin when omitted.",
25
25
  " output-wasm Output .wasm path. Writes to stdout if omitted.",
26
26
  "",
27
27
  "Options:",
28
28
  " -o, --output path Specify output file path explicitly.",
29
- " --pkir Lower via Polymorphic K IR (PKIR).",
30
29
  " --lib file Load one .klib or .k library before compiling.",
31
30
  " --use spec Use library alias in scope (repeatable).",
32
31
  " spec is 'name' or 'libname:localname'.",
@@ -35,7 +34,6 @@ function helpText() {
35
34
  "Examples:",
36
35
  ` ${prog} 'x = |x; x x' program.wasm`,
37
36
  ` ${prog} program.k -o program.wasm`,
38
- ` ${prog} --pkir program.k -o program.wasm`,
39
37
  ` ${prog} --lib core.klib --use add program.k program.wasm`
40
38
  ].join("\n");
41
39
  }
@@ -66,7 +64,7 @@ try {
66
64
  }
67
65
  }
68
66
 
69
- const { libraries, useSpecs, usePKIR } =
67
+ const { libraries, useSpecs } =
70
68
  parseCompileOptions(remainingArgs);
71
69
  const input = resolveProgramInput(remainingArgs, {
72
70
  allowStdinSource: true
@@ -77,8 +75,7 @@ try {
77
75
  const artifact = await compileProgramInput(input, {
78
76
  libraries,
79
77
  useSpecs,
80
- stdin,
81
- usePKIR
78
+ stdin
82
79
  });
83
80
  if (outputPath == null) {
84
81
  stdout.write(artifact);
@@ -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,10 +14,9 @@ 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";
19
+ import { makeWireValidator } from "@fraczak/k/codecs/runtime/prefix-codec.mjs";
21
20
  import { intersectPropertyListPatterns } from "@fraczak/k/codecs/runtime/codec.mjs";
22
21
  import { propertyListToFilter } from "@fraczak/k/codecs/runtime/show-value.mjs";
23
22
  import { parse } from "@fraczak/k/index.mjs";
@@ -285,11 +284,12 @@ function cloneKVMFunction(kvmFunc) {
285
284
  };
286
285
  }
287
286
 
288
- function compileModule(mainRelName, defs, { usePKIR = false } = {}) {
287
+ function compileModule(mainRelName, defs) {
289
288
  const compiled = new Set();
290
289
  const queue = [mainRelName];
291
290
  const wats = [];
292
291
  const nameMap = cleanFunctionNameMap(Object.keys(defs.rels));
292
+ let entryBody;
293
293
 
294
294
  while (queue.length > 0) {
295
295
  const name = queue.shift();
@@ -301,14 +301,9 @@ function compileModule(mainRelName, defs, { usePKIR = false } = {}) {
301
301
  throw new Error(`Relation ${name} not found`);
302
302
  }
303
303
 
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
- }
304
+ const kvmFunc = lowerToKVM(relDef, name);
305
+ if (name === mainRelName) entryBody = kvmFunc.body;
306
+ kvmFunc.typePatternGraph = relDef.typePatternGraph;
312
307
  scanCalls(kvmFunc.body, compiled, queue);
313
308
 
314
309
  kvmFunc.name = nameMap.get(name) || cleanName(name);
@@ -320,6 +315,7 @@ function compileModule(mainRelName, defs, { usePKIR = false } = {}) {
320
315
  return {
321
316
  wat: wats.join("\n\n"),
322
317
  relationNames: [...compiled],
318
+ entryBody,
323
319
  entryName: nameMap.get(mainRelName) || cleanName(mainRelName)
324
320
  };
325
321
  }
@@ -421,6 +417,27 @@ function isMonomorphicPattern(pattern) {
421
417
  pattern.every(([kind]) => kind === "closed-product" || kind === "closed-union");
422
418
  }
423
419
 
420
+ function sameClosedPattern(inputPattern, outputPattern) {
421
+ return isMonomorphicPattern(inputPattern) &&
422
+ JSON.stringify(inputPattern) === JSON.stringify(outputPattern);
423
+ }
424
+
425
+ // Prove a straight-line return of the original input. Every guard must be
426
+ // implied by the contract that will be checked at the wire boundary.
427
+ function isWireIdentity(body, inputPattern, outputPattern) {
428
+ if (!sameClosedPattern(inputPattern, outputPattern) || !body?.length) return false;
429
+ const contract = JSON.stringify(inputPattern);
430
+ let input = "%in";
431
+ for (const inst of body.slice(0, -1)) {
432
+ if (inst.src !== input || !inst.dest) return false;
433
+ if (inst.op !== "id" &&
434
+ !(inst.op === "guard_pattern" && JSON.stringify(inst.pattern) === contract)) return false;
435
+ input = inst.dest;
436
+ }
437
+ const last = body[body.length - 1];
438
+ return last.op === "return" && last.src === input;
439
+ }
440
+
424
441
  function classifyTyping(inputPattern, outputPattern, status = "unknown", mode = "generic") {
425
442
  const input = isMonomorphicPattern(inputPattern) ? "monomorphic" : "polymorphic";
426
443
  const output = isMonomorphicPattern(outputPattern) ? "monomorphic" : "polymorphic";
@@ -481,7 +498,7 @@ function validateInputEnvelope(inputPattern, valuePattern) {
481
498
  async function compileWasmArtifactFromDefs(
482
499
  defs,
483
500
  mainRelName = "__main__",
484
- { typingMode = "generic", usePKIR = false } = {}
501
+ { typingMode = "generic" } = {}
485
502
  ) {
486
503
  resetTagIds();
487
504
  const mainRel = defs.rels[mainRelName];
@@ -489,10 +506,9 @@ async function compileWasmArtifactFromDefs(
489
506
  throw new Error(`No main relation (${mainRelName}) defined in script`);
490
507
  }
491
508
 
492
- const { wat: moduleWatBody, relationNames, entryName } = compileModule(
509
+ const { wat: moduleWatBody, relationNames, entryName, entryBody } = compileModule(
493
510
  mainRelName,
494
- defs,
495
- { usePKIR }
511
+ defs
496
512
  );
497
513
  assertRelationsConverged(defs, relationNames);
498
514
  const fullWat = runtimeWat.trim().slice(0, -1) + "\n" + moduleWatBody + "\n)";
@@ -506,6 +522,7 @@ async function compileWasmArtifactFromDefs(
506
522
  entry: entryName || cleanName(mainRelName),
507
523
  inputPattern,
508
524
  outputPattern,
525
+ ...(isWireIdentity(entryBody, inputPattern, outputPattern) && { wireIdentity: true }),
509
526
  typing: classifyTyping(
510
527
  inputPattern,
511
528
  outputPattern,
@@ -575,6 +592,7 @@ async function compileWasmArtifactFromKVM(kvmInput, options = {}) {
575
592
  relation,
576
593
  inputPattern: mainFunc.inputPattern,
577
594
  outputPattern: mainFunc.outputPattern,
595
+ ...(isWireIdentity(mainFunc.body, mainFunc.inputPattern, mainFunc.outputPattern) && { wireIdentity: true }),
578
596
  typing: classifyTyping(
579
597
  mainFunc.inputPattern,
580
598
  mainFunc.outputPattern,
@@ -588,7 +606,7 @@ async function compileWasmArtifactFromKVM(kvmInput, options = {}) {
588
606
 
589
607
  async function compileWasmArtifactFromObject(
590
608
  object,
591
- { entry = null, inputEnvelopePattern = null, usePKIR = false } = {}
609
+ { entry = null, inputEnvelopePattern = null } = {}
592
610
  ) {
593
611
  if (!object?.rels) {
594
612
  throw new Error("Expected .ko input to contain k object relations");
@@ -632,8 +650,7 @@ async function compileWasmArtifactFromObject(
632
650
  }
633
651
 
634
652
  return compileWasmArtifactFromDefs(defs, mainRelName, {
635
- typingMode,
636
- usePKIR
653
+ typingMode
637
654
  });
638
655
  }
639
656
 
@@ -644,8 +661,7 @@ async function compileWasmArtifact(
644
661
  use = [],
645
662
  exports = [],
646
663
  source: sourceName = null,
647
- inputEnvelopePattern = null,
648
- usePKIR = false
664
+ inputEnvelopePattern = null
649
665
  } = {}
650
666
  ) {
651
667
  const specs = use.length > 0 ? use : exports;
@@ -690,43 +706,10 @@ async function compileWasmArtifact(
690
706
  }
691
707
 
692
708
  return compileWasmArtifactFromDefs(defs, "__main__", {
693
- typingMode,
694
- usePKIR
709
+ typingMode
695
710
  });
696
711
  }
697
712
 
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
713
  function createTagRegistry(entries) {
731
714
  const tagToId = new Map();
732
715
  const idToTag = new Map();
@@ -1001,9 +984,31 @@ async function instantiateWasmArtifact(wasmBuffer) {
1001
984
  const tags = createTagRegistry(metadata.tags);
1002
985
  const inputPattern = propertyListToPattern(metadata.inputPattern);
1003
986
  const outputPattern = propertyListToPattern(metadata.outputPattern);
987
+ const validateIdentityWire = metadata.wireIdentity === true &&
988
+ sameClosedPattern(metadata.inputPattern, metadata.outputPattern)
989
+ ? makeWireValidator(metadata.outputPattern)
990
+ : null;
1004
991
 
1005
992
  function execute(inputBuffer, options = {}) {
1006
993
  const t0 = process.hrtime.bigint();
994
+ if (validateIdentityWire?.(inputBuffer)) {
995
+ const validated = process.hrtime.bigint();
996
+ const outputWire = Buffer.from(inputBuffer);
997
+ if (!options.trace) return outputWire;
998
+ const done = process.hrtime.bigint();
999
+ return {
1000
+ outputWire,
1001
+ trace: {
1002
+ decodeNs: Number(validated - t0),
1003
+ flatInNs: 0,
1004
+ evalNs: 0,
1005
+ flatOutNs: 0,
1006
+ encodeNs: Number(done - validated),
1007
+ totalNs: Number(done - t0)
1008
+ }
1009
+ };
1010
+ }
1011
+
1007
1012
  const { pattern: valuePattern, value } = decodeWire(inputBuffer);
1008
1013
  if (!isMonomorphicPattern(metadata.inputPattern)) {
1009
1014
  validateInputEnvelope(metadata.inputPattern, valuePattern);
@@ -1127,7 +1132,6 @@ export {
1127
1132
  appendCustomSection,
1128
1133
  compileWasmArtifactFromKVM,
1129
1134
  compileWasmArtifactFromObject,
1130
- compileWasmArtifactFromPKIR,
1131
1135
  compileWasmArtifact,
1132
1136
  instantiateWasmArtifact,
1133
1137
  metadataFromModule,
@@ -1145,7 +1149,6 @@ export default {
1145
1149
  appendCustomSection,
1146
1150
  compileWasmArtifactFromKVM,
1147
1151
  compileWasmArtifactFromObject,
1148
- compileWasmArtifactFromPKIR,
1149
1152
  compileWasmArtifact,
1150
1153
  metadataFromModule,
1151
1154
  readArenaValue,
@@ -141,9 +141,14 @@ console.log("==> Running Compiler Scaffolding Tests (id, fail, return)");
141
141
  console.log("Compiler Scaffolding tests passed successfully!");
142
142
  }
143
143
 
144
- import { annotate, objectToKVMArtifact } from "@fraczak/k/backend-api.mjs";
144
+ import { annotate, encodeToWire, objectToKVMArtifact } from "@fraczak/k/backend-api.mjs";
145
145
  import { compileObjectBuffer, decodeObject } from "@fraczak/k/object.mjs";
146
- import { compileWasmArtifactFromKVM, metadataFromModule } from "../src/wasm.mjs";
146
+ import {
147
+ compileWasmArtifact,
148
+ compileWasmArtifactFromKVM,
149
+ instantiateWasmArtifact,
150
+ metadataFromModule
151
+ } from "../src/wasm.mjs";
147
152
  import { getTagId } from "../src/kvm2wasm.mjs";
148
153
 
149
154
  console.log("==> Running Wrapped kVM Artifact Test");
@@ -160,6 +165,40 @@ console.log("==> Running Wrapped kVM Artifact Test");
160
165
  assert(!("instanceKey" in metadata));
161
166
  assert.deepEqual(metadata.inputPattern, artifact.inputPattern);
162
167
  assert.deepEqual(metadata.outputPattern, artifact.outputPattern);
168
+ assert.equal(metadata.wireIdentity, true);
169
+ }
170
+
171
+ console.log("==> Running Validated Wire Identity Tests");
172
+ {
173
+ const source = "?<{} a, {} b, {} c> ()";
174
+ const runner = await instantiateWasmArtifact(await compileWasmArtifact(source));
175
+ assert.equal(runner.metadata.wireIdentity, true);
176
+ const value = Value.variant("b", Value.product({}));
177
+ const frame = encodeToWire(value, runner.metadata.inputPattern);
178
+ const mark = runner.exports.arena_mark();
179
+ const { outputWire, trace } = runner.execute(frame, { trace: true });
180
+ assert.deepEqual(outputWire, frame);
181
+ assert.equal(trace.flatInNs, 0);
182
+ assert.equal(trace.evalNs, 0);
183
+ assert.equal(trace.flatOutNs, 0);
184
+ assert.equal(runner.exports.arena_mark(), mark);
185
+ assert.equal(runner.executeValue(value).tag, "b");
186
+
187
+ const differentHeader = encodeToWire(value);
188
+ assert.notDeepEqual(differentHeader, frame);
189
+ assert.deepEqual(runner.execute(differentHeader), frame);
190
+ assert.throws(() => runner.execute(Buffer.concat([frame, Buffer.alloc(1)])), /trailing bytes/);
191
+
192
+ const invalidChoice = Buffer.from(frame);
193
+ const otherTag = encodeToWire(Value.variant("c", Value.product({})), runner.metadata.inputPattern);
194
+ for (let i = 0; i < frame.length; i++) invalidChoice[i] |= otherTag[i];
195
+ assert.throws(() => runner.execute(invalidChoice), /Invalid choice/);
196
+
197
+ const changesValue = await instantiateWasmArtifact(
198
+ await compileWasmArtifact("?<{} a, {} b, {} c> < /a |b, /b |c, /c |a >")
199
+ );
200
+ assert.equal(changesValue.metadata.wireIdentity, undefined);
201
+ assert.notDeepEqual(changesValue.execute(frame), frame);
163
202
  }
164
203
 
165
204
  console.log("==> Running Product Operations Integration Tests");
@@ -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