@fraczak/k 8.4.1 → 8.5.1

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 (116) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/DOCS/ARCHITECTURE.md +83 -0
  3. package/DOCS/CODECS.md +93 -204
  4. package/DOCS/DICTIONARY.md +42 -1241
  5. package/DOCS/FILE_FORMATS.md +170 -625
  6. package/DOCS/GETTING_STARTED.md +164 -0
  7. package/DOCS/KIR_V1.md +22 -33
  8. package/DOCS/KVM_EXECUTION_MODEL.md +88 -481
  9. package/DOCS/PATTERNS.md +155 -138
  10. package/DOCS/POLYMORPHIC_IR.md +83 -101
  11. package/DOCS/PROFILING_AND_TRACING.md +52 -166
  12. package/DOCS/README.md +35 -0
  13. package/DOCS/REPL.md +100 -377
  14. package/DOCS/TEXTUAL_VALUES.md +53 -81
  15. package/DOCS/TYPE_DERIVATION.md +95 -234
  16. package/DOCS/book-combined.md +3786 -0
  17. package/Examples/arithmetics.k +45 -59
  18. package/Examples/djson.k +102 -112
  19. package/Examples/karatsuba-mult.k +2 -3
  20. package/Examples/list.k +6 -7
  21. package/Examples/nat.k +6 -6
  22. package/Examples/poly.k +45 -45
  23. package/LICENSE +15 -0
  24. package/README.md +72 -410
  25. package/backends/llvm/README.md +75 -97
  26. package/backends/llvm/src/kvm2llvm.mjs +5 -4
  27. package/backends/llvm/src/llvm.mjs +2 -1
  28. package/backends/llvm/tests/integration.sh +7 -0
  29. package/backends/llvm/tests/test-llvm.mjs +20 -0
  30. package/backends/wasm/README.md +88 -66
  31. package/backends/wasm/src/kvm2wasm.mjs +64 -18
  32. package/backends/wasm/tests/integration.sh +5 -0
  33. package/backends/wasm/tests/test-wasm.mjs +86 -2
  34. package/canonical-pattern.mjs +7 -3
  35. package/codecs/README.md +23 -261
  36. package/codecs/WIRE_FORMAT.md +132 -0
  37. package/core.k +5 -15
  38. package/named-patterns.mjs +19 -7
  39. package/objects/README.md +24 -109
  40. package/package.json +8 -3
  41. package/paper/Makefile +17 -0
  42. package/paper/k-paper.pdf +0 -0
  43. package/paper/k-paper.tex +435 -0
  44. package/parser.jison +0 -10
  45. package/parser.mjs +32 -43
  46. package/repl.mjs +74 -29
  47. package/scripts/benchmark-idempotency.mjs +3 -3
  48. package/scripts/run-tests.mjs +1 -1
  49. package/scripts/test-package.mjs +64 -0
  50. package/tests/README.md +66 -46
  51. package/tests/code-derivation/core.mjs +61 -0
  52. package/tests/helpers/cli.mjs +45 -0
  53. package/tests/integration.sh +2 -3
  54. package/tests/test-arithmetics.mjs +47 -237
  55. package/tests/test-djson-methods.mjs +71 -275
  56. package/tests/test-hash-normalization.mjs +22 -1
  57. package/tests/test-karatsuba.mjs +18 -126
  58. package/tests/test-named-patterns.mjs +174 -621
  59. package/tests/test-paper-examples.mjs +90 -0
  60. package/tests/test-poly.mjs +2 -2
  61. package/tests/test-repl-html.mjs +22 -10
  62. package/tests/test-repl.mjs +49 -41
  63. package/tests/test.mjs +27 -68
  64. package/AGENTS.md +0 -35
  65. package/CLAUDE.md +0 -64
  66. package/DOCS/BIG_PICTURE.md +0 -439
  67. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  68. package/DOCS/CANONICAL_PATTERNS.md +0 -362
  69. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  70. package/DOCS/CONVERGENCE.md +0 -123
  71. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  72. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  73. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  74. package/DOCS/Makefile +0 -99
  75. package/DOCS/NAMED_PATTERNS.md +0 -361
  76. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  77. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  78. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -134
  79. package/DOCS/book/01-introduction.md +0 -48
  80. package/DOCS/book/02-syntax-and-values.md +0 -110
  81. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  82. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  83. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  84. package/DOCS/book/06-values-in-memory.md +0 -1085
  85. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  86. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  87. package/DOCS/book/09-compiler-architecture.md +0 -160
  88. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  89. package/DOCS/book/14-canonical-serialization.md +0 -176
  90. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  91. package/DOCS/book/overview.txt +0 -68
  92. package/DOCS/book.md +0 -50
  93. package/Examples/bnat.k +0 -308
  94. package/Examples/buda.k +0 -66
  95. package/Examples/byte.k +0 -35
  96. package/Examples/code.k +0 -43
  97. package/Examples/vhdl_to_k.k +0 -67
  98. package/JOURNAL.md +0 -288
  99. package/TODO.md +0 -107
  100. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  101. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  102. package/backends/wasm/demo_ieee.mjs +0 -318
  103. package/browser/vfs-data.mjs +0 -21
  104. package/codecs/BINARY_FORMAT.md +0 -53
  105. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  106. package/codecs/pandoc.css +0 -71
  107. package/tests/code-derivation/blowup.mjs +0 -25
  108. package/tests/code-derivation/bnat.mjs +0 -11
  109. package/tests/code-derivation/dot.mjs +0 -37
  110. package/tests/code-derivation/index.mjs +0 -20
  111. package/tests/code-derivation/loop.mjs +0 -17
  112. package/tests/code-derivation/nat.mjs +0 -10
  113. package/tests/code-derivation/not-not.mjs +0 -14
  114. package/tests/code-derivation/product.mjs +0 -22
  115. package/tests/code-derivation/rlz.mjs +0 -13
  116. package/tests/test-fingerprint.mjs +0 -38
@@ -1,127 +1,87 @@
1
- # k-llvm
1
+ # LLVM backend
2
2
 
3
- Experimental LLVM backend prototype for `k`.
3
+ The experimental LLVM backend lowers k programs to LLVM IR and links them with
4
+ the C runtime. It supports source/object execution, compiled native executables,
5
+ kVM input, and the experimental PKIR path.
4
6
 
5
- This package lives under the `k` monorepo as `backends/llvm`. It consumes the
6
- backend bridge from the root `@fraczak/k` package and starts from compiled
7
- `.ko` objects:
8
-
9
- ```text
10
- .k source -> .ko -> envelope-specialized KIR-P -> LLVM IR prototype
11
- ```
12
-
13
- The first milestone is not performance. It is a stable backend pipeline that
14
- can load an object, specialize it through KIR-P, and produce an inspectable
15
- LLVM module.
16
-
17
- ## Quick Start
18
-
19
- From the monorepo root, install the workspace dependencies, then run the
20
- backend from `backends/llvm`:
7
+ Commands belong to the root package. Install dependencies from the repository
8
+ root and ensure Clang is available:
21
9
 
22
10
  ```sh
23
11
  npm install
24
- cd backends/llvm
25
- node ../../objects/compile.mjs '()' /tmp/id.ko
26
- node ./bin/k-llvm-compile.mjs /tmp/id.ko /tmp/id.ll
12
+ clang --version
27
13
  ```
28
14
 
29
- The generated `.ll` embeds the envelope-specialized KIR-P contract as module
30
- data and exposes the first runtime ABI slice:
15
+ `CLANG` or `CC` can select the compiler binary. `npm link` at the root exposes
16
+ `k-llvm`, `k-llvm-compile`, and `k-llvm-build`.
31
17
 
32
- ```llvm
33
- %k_result = type { i32, ptr }
18
+ ## Compile and run
34
19
 
35
- define %k_result @k_main(ptr %rt, ptr %input)
36
- ```
20
+ Build a program with a closed unit input and a constant result:
37
21
 
38
- `%rt` is an opaque runtime handle and `%input` is an opaque boxed `k_value*`.
39
- The first executable lowerings support identity, typed filters and singleton
40
- code filters, product field projection, product construction, variant
41
- construction, and variant projection. Unsupported operations return a nonzero
42
- status in `k_result`. These operations can compose through KIR `comp`.
22
+ ```sh
23
+ node backends/llvm/bin/k-llvm-build.mjs '?{} {} |ok' /tmp/k-ok.exe
24
+ node codecs/unit.mjs --parse | /tmp/k-ok.exe | node codecs/k-print.mjs
25
+ ```
43
26
 
44
- ## CLI
27
+ This prints `"ok"`. To compile and run directly over an input envelope:
45
28
 
46
29
  ```sh
47
- k-llvm-build [options] [source-snippet | input-file [output-exe]]
48
- k-llvm-compile [options] [source-snippet | input-file [output.ll]]
49
- k-llvm [options] ( source-snippet | input-file ) [ input-wire-file ]
30
+ node codecs/unit.mjs --parse |
31
+ node backends/llvm/bin/k-llvm.mjs '|ok' |
32
+ node codecs/k-print.mjs
50
33
  ```
51
34
 
52
- Options:
53
-
54
- - `-o, --output path`: specify output file path explicitly.
55
- - `--lib file`: load one `.klib` or `.k` dependency before compiling.
56
- - `--export spec`: export a library alias into scope. Repeatable.
57
- - `--pkir`: lower via Polymorphic K IR (PKIR).
58
- - `--retype rel`: relation to specialize (defaults to object main).
59
- - `--opt flag`: Clang optimization flag (-O0, -O1, -O2, -O3).
60
- - `-h, --help`: show usage.
61
-
62
- The compile commands follow the unified k CLI input convention: pass
63
- inline source, an existing `.k` source file, or a `.ko`/`.klib` object.
64
- Reads UTF-8 source from stdin when input is omitted. Output paths can be
65
- specified as a positional argument or explicitly with `-o, --output`.
66
- `k-llvm-build` emits a native executable that reads and writes the binary
67
- k pattern+value envelope used by `codecs/k-parse.mjs` and
68
- `codecs/k-print.mjs`. The executable checks the stdin envelope pattern
69
- against the compiled input pattern and encodes stdout with the compiled
70
- output pattern.
71
- `k-llvm` reads the binary wire envelope, specializes the relation to
72
- that input pattern, caches the compiled native executable, and writes
73
- the compiled output envelope to stdout.
74
- The native envelope codec supports the k Unicode string encoding used
75
- for labels and tags.
76
-
77
- ## Tests
35
+ To inspect generated LLVM IR:
78
36
 
79
37
  ```sh
80
- npm test
81
- node ./scripts/conformance.mjs
82
- npm run perf:int
83
- npm run perf:ieee
38
+ node backends/llvm/bin/k-llvm-compile.mjs '?{} {} |ok' /tmp/k-ok.ll
84
39
  ```
85
40
 
86
- The conformance runner reuses supported fixtures from `../../conformance`,
87
- emits LLVM IR for each fixture, generates a small C driver for the fixture
88
- input and expected value, links it with `runtime/krt.c`, and runs the binary.
41
+ ## Commands and options
42
+
43
+ | Command | Result |
44
+ | --- | --- |
45
+ | `k-llvm` | Compile, cache, and execute a native program for an input envelope |
46
+ | `k-llvm-compile` | Emit textual LLVM IR |
47
+ | `k-llvm-build` | Link a standalone executable that reads/writes k wire values |
89
48
 
90
- The performance runners mirror the `k-wasm` integer and IEEE harnesses. They
91
- load the real example programs from `@fraczak/k`, generate the same operation
92
- matrices, compare backend output to native `k` results, and time the native JS,
93
- kVM, and LLVM executable lanes. Set `LLVM_ONLY=1` to skip native timing,
94
- `ITERATIONS=N` to change samples, and `LLVM_STRICT=1` to make unsupported LLVM
95
- cases fail the process. The LLVM lane uses persistent executables by default;
96
- set `LLVM_PIPELINE=1` to measure parallel request pipelining or
97
- `LLVM_SPAWN_PER_CALL=1` to reproduce the older spawn-per-operation timing.
49
+ Compile/build commands accept inline source or a source, `.ko`, `.kvm`, or
50
+ `.pkir` input. A `.klib` needs a selected relation, supplied through the
51
+ tool's `--retype` option or linked into source with a terminal expression.
52
+ Source is read from stdin when omitted. The execution command instead requires
53
+ a program argument and reads binary input from stdin or an optional filename.
98
54
 
99
- ## Scope
55
+ Common compile options:
100
56
 
101
- Current output:
57
+ - `-o` / `--output path`: output path instead of a positional output.
58
+ - `--lib file`: one `.k` or `.klib` dependency.
59
+ - `--export name` or `--export libraryName:localName`: repeatable alias imports.
60
+ - `--pkir`: compile source through PKIR.
61
+ - `--retype relation`: select the relation for envelope specialization.
62
+ - `--opt flag`: Clang optimization flag.
102
63
 
103
- - KIR-P envelope specialization through `@fraczak/k/backend-api.mjs`;
104
- - textual LLVM IR with embedded envelope-specialized KIR-P metadata;
105
- - boxed runtime ABI declarations;
106
- - identity, filter/code erasure, product projection/construction, and variant
107
- construction/projection lowerings as `@k_main(k_rt*, k_value*) -> k_result`;
108
- - KIR `comp` lowering for sequencing supported operations;
109
- - KIR `empty` failure and ordered `union` branch selection;
110
- - KIR `ref` lowering to internal `%k_result` relation functions;
111
- - a tiny C runtime under `runtime/`.
64
+ Build/compile tools accept `--input-pattern` as JSON or a pattern file when
65
+ an explicit specialization input is needed. `k-llvm` derives the envelope
66
+ from its wire input; `--no-cache` disables reuse, and `--cache-dir` selects
67
+ the executable cache. Each command's `--help` lists its supported options
68
+ and defaults.
112
69
 
113
- Next backend steps:
70
+ Existing program paths are read as files; recognized missing filenames are
71
+ errors. See [file formats](../../DOCS/FILE_FORMATS.md) for shared linking rules.
114
72
 
115
- - add an executable conformance mode once the runtime ABI exists.
73
+ ## Runtime contract
116
74
 
117
- ## Runtime ABI
75
+ Compiled programs retain input/output patterns for wire boundaries. A native
76
+ runner checks incoming schemas against the compiled contract and serializes
77
+ the result with its output pattern. Partial failure is distinct from malformed
78
+ input, type errors, or compiler failures.
118
79
 
119
- The C side owns all runtime allocation:
80
+ The boxed C ABI is:
120
81
 
121
82
  ```c
122
83
  typedef struct k_rt k_rt;
123
84
  typedef struct k_value k_value;
124
-
125
85
  typedef struct {
126
86
  int32_t status;
127
87
  k_value *value;
@@ -130,7 +90,25 @@ typedef struct {
130
90
  k_result k_main(k_rt *rt, k_value *input);
131
91
  ```
132
92
 
133
- `runtime/krt.h` provides the initial boxed helpers for units, products,
134
- variants, and pointer equality. The representation is intentionally opaque so
135
- future KIR specialization can add unboxed fast paths without changing the
136
- external ABI.
93
+ [runtime/krt.h](runtime/krt.h) defines helpers and ownership through the runtime;
94
+ [runtime/krt.c](runtime/krt.c) implements values, arenas, and wire support.
95
+ [kvm2llvm.mjs](src/kvm2llvm.mjs) lowers kVM functions;
96
+ [llvm.mjs](src/llvm.mjs) coordinates object and PKIR paths.
97
+
98
+ Unsupported operations must produce diagnostics rather than silently change
99
+ semantics. Backend coverage and artifact formats remain experimental.
100
+
101
+ ## Verification and profiling
102
+
103
+ From the repository root:
104
+
105
+ ```sh
106
+ npm run test:llvm
107
+ ```
108
+
109
+ This includes native execution, the open-product field-alignment regression,
110
+ shell integration, and shared conformance fixtures.
111
+
112
+ `npm run perf:int`, `npm run perf:ieee`, and `npm run perf:poly:trace`
113
+ compare execution lanes. See the [profiling guide](../../DOCS/PROFILING_AND_TRACING.md)
114
+ for measurement boundaries and target selection.
@@ -441,10 +441,11 @@ function hasSelfTailCall(insts, funcName, isTail = true) {
441
441
  for (let i = 0; i < insts.length; i++) {
442
442
  const inst = insts[i];
443
443
  if (isTail && isSelfTailCall(insts, i, funcName)) return true;
444
- if (inst.op === "union" && inst.branches) {
444
+ if (inst.op === "union" && inst.branches && inst.branches.length > 0) {
445
445
  const unionIsTail = isTail && tailValueAfter(insts, i + 1, inst.dest);
446
- for (let bIdx = 0; bIdx < inst.branches.length; bIdx++) {
447
- if (hasSelfTailCall(inst.branches[bIdx].body, funcName, unionIsTail)) return true;
446
+ if (unionIsTail) {
447
+ const lastBranch = inst.branches[inst.branches.length - 1];
448
+ if (hasSelfTailCall(lastBranch.body, funcName, true)) return true;
448
449
  }
449
450
  }
450
451
  }
@@ -908,7 +909,7 @@ function lowerKVMFunction(kvmFunc, symbol, funcName, moduleCtx, linkage = "", op
908
909
  outputPattern: kvmFunc.outputPattern,
909
910
  body: branch.body
910
911
  };
911
- const armTailRef = tailValueAfter(insts, i + 1, inst.dest) ? tailRef : null;
912
+ const armTailRef = (isLast && tailValueAfter(insts, i + 1, inst.dest)) ? tailRef : null;
912
913
  const armBody = lowerKVMFunction(armFunc, armName, armFunc.name, moduleCtx, "internal", { ...options, tailRef: armTailRef });
913
914
  moduleCtx.syntheticFunctions.push(armBody);
914
915
 
@@ -505,7 +505,8 @@ function emitUnionFunctionBody(symbol, items, ctx, linkage = "", options = {}) {
505
505
  unsupported(ctx);
506
506
  } else {
507
507
  items.forEach((item, index) => {
508
- unionBranch(ctx, ctx.addSyntheticFunction(item, options.tail === true), "%input", index === items.length - 1);
508
+ const isLast = index === items.length - 1;
509
+ unionBranch(ctx, ctx.addSyntheticFunction(item, options.tail === true && isLast), "%input", isLast);
509
510
  });
510
511
  }
511
512
  const prefix = linkage ? `define ${linkage} %k_result` : "define %k_result";
@@ -134,6 +134,13 @@ printf '{"x":"left","y":"right"}' \
134
134
  | node ../../codecs/k-print.mjs \
135
135
  | grep -qx '"left"'
136
136
 
137
+ node ../../objects/compile.mjs 't[] = < {} a, T b > = T; f = ?t[] < /b f, /b {} |a > ?t[]; /b f' "$TMP_DIR/nonfinal-tail.ko"
138
+ printf '{"b":{"b":"a"}}\n' \
139
+ | node ../../codecs/k-parse.mjs --input-type '?< {} a, T b > = T' \
140
+ | node ./bin/k-llvm.mjs --cache-dir "$TMP_DIR/jit-cache" "$TMP_DIR/nonfinal-tail.ko" \
141
+ | node ../../codecs/k-print.mjs \
142
+ | grep -qx '"a"'
143
+
137
144
  node --input-type=module -e "import { stdout } from 'node:process'; import { encodeToWire } from '../../codecs/runtime/prefix-codec.mjs'; import { Value } from '../../Value.mjs'; const pattern = [[\"open-union\",[[\"left\",1],[\"right\",1]]],[\"closed-product\",[]]]; stdout.write(encodeToWire(Value.variant(\"left\", Value.product({}), pattern), pattern));" \
138
145
  | node ./bin/k-llvm.mjs --cache-dir "$TMP_DIR/jit-cache" "$TMP_DIR/id.ko" \
139
146
  | node --input-type=module -e "import { stdin } from 'node:process'; import { decodeWire } from '../../codecs/runtime/prefix-codec.mjs'; const chunks = []; stdin.on('data', (chunk) => chunks.push(chunk)); stdin.on('end', () => console.log(JSON.stringify(decodeWire(Buffer.concat(chunks)).pattern)));" \
@@ -264,6 +264,26 @@ const { llvm: productRecurseLLVM } = compileObjectToLLVM(productRecurseObject, {
264
264
  // Calls inside product fields must not return tail status (i32 2)
265
265
  assert.doesNotMatch(productRecurseLLVM, /insertvalue %k_result undef, i32 2, 0/);
266
266
 
267
+ const unionNonFinalRecurseObject = decodeObject(compileObjectBuffer(`
268
+ t[] = < {} a, { T x } b > = T;
269
+ f = ?t[] <
270
+ /b .x f,
271
+ /b {} |a
272
+ > ?t[];
273
+ f
274
+ `, { source: "llvm-union-nonfinal-recurse.k" }));
275
+ const { llvm: unionNonFinalRecurseLLVM } = compileObjectToLLVM(unionNonFinalRecurseObject, {
276
+ relation: "f",
277
+ inputPattern: [
278
+ ["closed-union", [["a", 1], ["b", 2]]],
279
+ ["closed-product", []],
280
+ ["closed-product", [["x", 0]]]
281
+ ]
282
+ });
283
+ // Self-calls in non-final union branches must not be lowered as tail calls (status 2 or tail_loop)
284
+ assert.doesNotMatch(unionNonFinalRecurseLLVM, /insertvalue %k_result undef, i32 2, 0/);
285
+ assert.doesNotMatch(unionNonFinalRecurseLLVM, /tail_loop:/);
286
+
267
287
  const kvmArtifact = objectToKVMArtifact(productObject, "__main__");
268
288
  assert.equal(kvmArtifact.format, "k-vm");
269
289
  const kvmLLVM = compileLLVMArtifactFromKVM(kvmArtifact, {
@@ -1,97 +1,119 @@
1
- # k WebAssembly Backend
1
+ # WebAssembly backend
2
2
 
3
- `@fraczak/k-wasm` is the experimental WebAssembly backend for
4
- [`@fraczak/k`](https://github.com/fraczak/k). It lowers typed k programs through
5
- the kVM representation, emits standard `.wasm` modules with WABT, and provides
6
- a Node.js runner for the binary `pattern + value` streams used by the k codec
7
- toolchain.
3
+ The experimental Wasm backend compiles k relations to standard WebAssembly
4
+ modules using kVM and WABT. The terminal and browser REPLs also use its
5
+ in-process execution path.
8
6
 
9
- ## Install
7
+ Commands are provided by the root package. From the repository root:
10
8
 
11
- Install dependencies from the monorepo root:
12
-
13
- ```bash
9
+ ```sh
14
10
  npm install
15
11
  ```
16
12
 
17
- Optionally expose the three backend commands on your path:
18
-
19
- ```bash
20
- npm link
21
- ```
13
+ Run the modules directly as below, or use `npm link` at the root to expose
14
+ `k-wasm`, `k-wasm-compile`, and `k-wasm-run`.
22
15
 
23
- ## Quick Start
16
+ ## Compile and run
24
17
 
25
- Compile an expression into a standalone WebAssembly artifact:
26
-
27
- ```bash
28
- node ./bin/k-wasm-compile.mjs '|ok' /tmp/ok.wasm
18
+ ```sh
19
+ node backends/wasm/bin/k-wasm-compile.mjs '?{} {} |ok' /tmp/k-ok.wasm
20
+ node codecs/unit.mjs --parse |
21
+ node backends/wasm/bin/k-wasm-run.mjs /tmp/k-ok.wasm |
22
+ node codecs/k-print.mjs
29
23
  ```
30
24
 
31
- Run it over the unit value and print the decoded result:
25
+ This prints `"ok"`. Compilation and execution in one step:
32
26
 
33
- ```bash
34
- node ../../codecs/unit.mjs --parse |
35
- node ./bin/k-wasm-run.mjs /tmp/ok.wasm |
36
- node ../../codecs/k-print.mjs
27
+ ```sh
28
+ node codecs/unit.mjs --parse |
29
+ node backends/wasm/bin/k-wasm.mjs '|ok' |
30
+ node codecs/k-print.mjs
37
31
  ```
38
32
 
39
- Expected output:
33
+ ## Inputs and libraries
40
34
 
41
- ```json
42
- "ok"
35
+ | Command | Purpose |
36
+ | --- | --- |
37
+ | `k-wasm` | Compile and execute a source expression/file, `.ko`, `.kvm`, or `.pkir` |
38
+ | `k-wasm-compile` | Produce a `.wasm` artifact from those program forms |
39
+ | `k-wasm-run` | Execute a previously compiled `.wasm` artifact |
40
+
41
+ The runners read binary schema+payload data from stdin or an optional input
42
+ filename. Compile tools read source from stdin when the program is omitted.
43
+ Source files need a terminal expression; a `.klib` alone is not an executable
44
+ input.
45
+
46
+ Compile commands accept one `--lib file` and repeated `--export alias` or
47
+ `--export 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.
50
+
51
+ Existing paths are read as files. Recognized missing filenames are errors;
52
+ other program arguments are treated as inline source.
53
+
54
+ For a library example using only a small definition:
55
+
56
+ ```sh
57
+ node objects/compile.mjs 'greet = {} |hello;' /tmp/k-demo.klib
58
+ node backends/wasm/bin/k-wasm-compile.mjs --lib /tmp/k-demo.klib --export greet '?{} greet' /tmp/k-greet.wasm
59
+ node codecs/unit.mjs --parse |
60
+ node backends/wasm/bin/k-wasm-run.mjs /tmp/k-greet.wasm |
61
+ node codecs/k-print.mjs
43
62
  ```
44
63
 
45
- With the backend and k codec commands on your path, the equivalent shorter
46
- form is:
64
+ The result is `"hello"`. The library is required at compilation time; the
65
+ module can subsequently run without the original source/library files.
47
66
 
48
- ```bash
49
- k-wasm-compile '|ok' /tmp/ok.wasm
50
- k-unit --parse | k-wasm-run /tmp/ok.wasm | k-print
51
- ```
67
+ ## Artifact and execution contract
52
68
 
53
- ## Commands
69
+ A module contains the reachable functions, the arena runtime from
70
+ [runtime.wat](runtime.wat), and one `k.metadata` custom section.
54
71
 
55
- | Command | Purpose |
72
+ | Metadata field | Meaning |
56
73
  | --- | --- |
57
- | `k-wasm` | Compile k source, `.ko`, or `.kvm` input in memory and run it immediately |
58
- | `k-wasm-compile` | Compile k source, `.ko`, or `.kvm` input into a `.wasm` artifact |
59
- | `k-wasm-run` | Run an existing `.wasm` artifact over a binary input stream |
74
+ | `format` / `version` | `"k-wasm"` / `1` |
75
+ | `abi` | `"arena-v1"` |
76
+ | `entry` | Exported function called by the runner |
77
+ | `inputPattern` / `outputPattern` | Patterns used by the arena adapters |
78
+ | `tags` | Statically known variant tags and their IDs |
60
79
 
61
- All commands accept `--help`. The compile commands follow the `k-compile`
62
- input convention: pass inline source, an existing source path, a `.ko` object,
63
- or a `.kvm` program. They also accept one `--lib` option for a `.klib`
64
- dependency and repeated `--export` options to bring library aliases into the
65
- source scope. Existing paths are treated as files; non-existing names with
66
- `.k`, `.ko`, `.kvm`, `.klib`, or `.wasm` extensions are treated as missing
67
- files; other arguments are treated as inline source. The runners read a binary
68
- input stream from standard input unless an input file is given.
80
+ The entry ABI is `(input_pointer i32) -> (output_pointer i32, ok i32)`.
81
+ `ok = 1` means a defined result; `ok = 0` means ordinary partial failure.
69
82
 
70
- ## Artifacts
83
+ The host decodes a wire value, writes it into linear memory, invokes the
84
+ entry, reads the result under its output pattern, and writes a wire value.
85
+ `instantiateWasmArtifact` also exposes `executeValue` for in-memory `Value`
86
+ input/output and optional phase tracing.
71
87
 
72
- The compiler produces a standard WebAssembly binary module containing the
73
- reachable relations, the arena runtime, and a `k.metadata` custom section. The
74
- metadata stores the entry point and the pattern information needed to encode
75
- and decode values. A compiled artifact can be run later without its original k
76
- source, object, kVM, or `.klib` files.
88
+ `k-wasm` can use the arriving input envelope while compiling. A precompiled
89
+ module runs with its stored metadata; `k-wasm-run` does not rerun derivation
90
+ on the original relation graph. Use one-step compilation when an input-specific
91
+ contract is needed.
77
92
 
78
- The current host runner targets Node.js. It is still needed to bridge between
79
- WebAssembly linear memory and k binary streams.
93
+ ## Limits and implementation
80
94
 
81
- ## Development
95
+ A `.wasm` file still needs a host that understands the arena ABI and metadata.
96
+ The CLI host is Node.js; the browser REPL bundles its own in-process adapter.
82
97
 
83
- Run the test suite:
98
+ Allocation uses a bump arena. Runners reset it between completed runs; selected
99
+ tail-loop paths also compact live state. Temporary allocation within successful
100
+ non-tail calls can still increase peak memory. The host translates exported
101
+ out-of-memory flags into diagnostics.
84
102
 
85
- ```bash
86
- npm test
87
- ```
103
+ The implementation lives in [src/wasm.mjs](src/wasm.mjs) and
104
+ [src/kvm2wasm.mjs](src/kvm2wasm.mjs). See
105
+ [compiler architecture](../../DOCS/ARCHITECTURE.md) and
106
+ [kVM](../../DOCS/KVM_EXECUTION_MODEL.md) for shared layers.
107
+
108
+ ## Verification and profiling
88
109
 
89
- Run the comparative IEEE benchmark:
110
+ From the repository root:
90
111
 
91
- ```bash
92
- npm run perf:ieee
112
+ ```sh
113
+ npm run test:wasm
114
+ npm run build:repl-html
93
115
  ```
94
116
 
95
- See [DOCS/USE-WEB-ASSEMBLY.md](DOCS/USE-WEB-ASSEMBLY.md) for the artifact
96
- format, source-file and library examples, profiling options, and current
97
- limitations.
117
+ For performance measurements, use `npm run perf:ieee` or
118
+ `npm run perf:poly:trace`. The [profiling guide](../../DOCS/PROFILING_AND_TRACING.md)
119
+ explains execution lanes and boundary costs.
@@ -197,14 +197,34 @@ export function lowerToWasm(relDef, name, options = {}) {
197
197
  return tailValueAfter(insts, index + 1, dest, inputMap, returnTarget, tailReturnTargets);
198
198
  }
199
199
 
200
- function selfTailCallAfterProduct(insts, index, productDest, inputMap, returnTarget, tailReturnTargets) {
201
- if (options.trace || inputProductFields.length === 0) return null;
202
- const callInst = insts[index + 1];
203
- if (!callInst || callInst.op !== "call" || callInst.func !== name) return null;
204
- if (mapsToReg(callInst.src, inputMap) !== productDest) return null;
205
- const callDest = cleanReg(callInst.dest);
206
- if (!tailValueAfter(insts, index + 2, callDest, inputMap, returnTarget, tailReturnTargets)) return null;
207
- return callInst;
200
+ function feedsSelfTailCall(
201
+ insts,
202
+ startIndex,
203
+ valueReg,
204
+ inputMap,
205
+ returnTarget,
206
+ tailReturnTargets,
207
+ tailCallInputTargets
208
+ ) {
209
+ if (options.trace || inputProductFields.length === 0) return false;
210
+ let current = valueReg;
211
+ for (let i = startIndex; i < insts.length; i++) {
212
+ const inst = insts[i];
213
+ if (inst.op === "guard_pattern" || inst.op === "guard_code" || inst.op === "id") {
214
+ if (mapsToReg(inst.src, inputMap) !== current) return false;
215
+ current = cleanReg(inst.dest);
216
+ continue;
217
+ }
218
+ if (inst.op === "call" && inst.func === name && mapsToReg(inst.src, inputMap) === current) {
219
+ const callDest = cleanReg(inst.dest);
220
+ return tailValueAfter(insts, i + 1, callDest, inputMap, returnTarget, tailReturnTargets);
221
+ }
222
+ if (inst.op === "return" && mapsToReg(inst.src, inputMap) === current) {
223
+ return Boolean(returnTarget && tailCallInputTargets.has(returnTarget));
224
+ }
225
+ return false;
226
+ }
227
+ return false;
208
228
  }
209
229
 
210
230
  function initInputProductLocals() {
@@ -252,7 +272,8 @@ export function lowerToWasm(relDef, name, options = {}) {
252
272
  returnTarget = null,
253
273
  failTarget = null,
254
274
  tailReturnTargets = new Set(),
255
- inputAliases = new Set(["in"])
275
+ inputAliases = new Set(["in"]),
276
+ tailCallInputTargets = new Set()
256
277
  ) {
257
278
  const lines = [];
258
279
  for (let index = 0; index < insts.length; index++) {
@@ -354,7 +375,15 @@ export function lowerToWasm(relDef, name, options = {}) {
354
375
  const dest = cleanReg(inst.dest);
355
376
  const rawSrc = cleanReg(inst.src);
356
377
  const src = inputMap[rawSrc] || rawSrc;
357
- const tailCall = selfTailCallAfterProduct(insts, index, dest, inputMap, returnTarget, tailReturnTargets);
378
+ const tailCall = feedsSelfTailCall(
379
+ insts,
380
+ index + 1,
381
+ dest,
382
+ inputMap,
383
+ returnTarget,
384
+ tailReturnTargets,
385
+ tailCallInputTargets
386
+ );
358
387
  const sortedBranches = [...inst.branches].sort((a, b) => {
359
388
  if (a.label < b.label) return -1;
360
389
  if (a.label > b.label) return 1;
@@ -382,8 +411,9 @@ export function lowerToWasm(relDef, name, options = {}) {
382
411
  { ...inputMap, "in": src },
383
412
  fieldTmp,
384
413
  failTarget,
385
- tailReturnTargets,
386
- new Set(inputAliases)
414
+ new Set(),
415
+ new Set(inputAliases),
416
+ new Set()
387
417
  );
388
418
  lines.push(branchWat);
389
419
  }
@@ -430,8 +460,9 @@ export function lowerToWasm(relDef, name, options = {}) {
430
460
  { ...inputMap, "in": src },
431
461
  fieldTmp,
432
462
  failTarget,
433
- tailReturnTargets,
434
- new Set(inputAliases)
463
+ new Set(),
464
+ new Set(inputAliases),
465
+ new Set()
435
466
  );
436
467
  lines.push(branchWat);
437
468
  }
@@ -549,9 +580,16 @@ export function lowerToWasm(relDef, name, options = {}) {
549
580
  const rawSrc = cleanReg(inst.src);
550
581
  const src = inputMap[rawSrc] || rawSrc;
551
582
  const N = inst.branches.length;
552
- const branchTailReturnTargets = tailValueAfter(insts, index + 1, dest, inputMap, returnTarget, tailReturnTargets)
553
- ? new Set([...tailReturnTargets, dest])
554
- : tailReturnTargets;
583
+ const unionIsTail = tailValueAfter(insts, index + 1, dest, inputMap, returnTarget, tailReturnTargets);
584
+ const unionFeedsSelfTailCall = feedsSelfTailCall(
585
+ insts,
586
+ index + 1,
587
+ dest,
588
+ inputMap,
589
+ returnTarget,
590
+ tailReturnTargets,
591
+ tailCallInputTargets
592
+ );
555
593
 
556
594
  const unionId = nextUnionId++;
557
595
  const arenaMark = `union_mark_${unionId}`;
@@ -566,6 +604,13 @@ export function lowerToWasm(relDef, name, options = {}) {
566
604
 
567
605
  for (let i = 0; i < N; i++) {
568
606
  const branch = inst.branches[i];
607
+ const isLast = i === N - 1;
608
+ const branchTailReturnTargets = isLast && unionIsTail
609
+ ? new Set([...tailReturnTargets, dest])
610
+ : new Set();
611
+ const branchTailCallInputTargets = unionFeedsSelfTailCall
612
+ ? new Set([...tailCallInputTargets, dest])
613
+ : (isLast && unionIsTail ? tailCallInputTargets : new Set());
569
614
  lines.push(` global.get $arena_free`);
570
615
  lines.push(` local.set $${arenaMark}`);
571
616
  const branchWat = compileInstructions(
@@ -574,7 +619,8 @@ export function lowerToWasm(relDef, name, options = {}) {
574
619
  dest,
575
620
  `$b${i}_try_${unionId}`,
576
621
  branchTailReturnTargets,
577
- new Set(inputAliases)
622
+ new Set(inputAliases),
623
+ branchTailCallInputTargets
578
624
  );
579
625
  lines.push(branchWat);
580
626
  lines.push(` br $union_done_${unionId}`);
@@ -54,6 +54,11 @@ compare_json_envelope "projected JSON number" \
54
54
  compare_json_envelope "closed product filter" \
55
55
  '{"a":[1,2,"kupa"], "b": 123}' \
56
56
  '?{X a, Y b}'
57
+ printf '{"b":{"b":"a"}}\n' |
58
+ node "$K_ROOT/codecs/k-parse.mjs" --input-type '?< {} a, T b > = T' |
59
+ node ./bin/k-wasm.mjs 't[] = < {} a, T b > = T; f = ?t[] < /b f, /b {} |a > ?t[]; /b f' |
60
+ node "$K_ROOT/codecs/k-print.mjs" |
61
+ grep -qx '"a"'
57
62
  printf '{"a":[1,2,"kupa"], "b": 123}\n' |
58
63
  node "$K_ROOT/codecs/json.mjs" --parse |
59
64
  node ./bin/k-wasm.mjs '{ .a.2 word, .b number }' |