@fraczak/k 8.4.0 → 8.5.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 (113) hide show
  1. package/CHANGELOG.md +59 -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 +156 -123
  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 -371
  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/cli.mjs +0 -31
  27. package/backends/wasm/README.md +88 -66
  28. package/backends/wasm/src/cli.mjs +0 -31
  29. package/canonical-pattern.mjs +69 -35
  30. package/codecs/README.md +23 -261
  31. package/codecs/WIRE_FORMAT.md +132 -0
  32. package/core.k +5 -15
  33. package/index.mjs +5 -1
  34. package/named-patterns.mjs +55 -7
  35. package/object.mjs +28 -6
  36. package/objects/README.md +24 -109
  37. package/package.json +8 -3
  38. package/paper/Makefile +17 -0
  39. package/paper/k-paper.pdf +0 -0
  40. package/paper/k-paper.tex +435 -0
  41. package/parser.jison +0 -10
  42. package/parser.mjs +32 -43
  43. package/repl.mjs +79 -101
  44. package/scripts/benchmark-idempotency.mjs +3 -3
  45. package/scripts/run-tests.mjs +1 -1
  46. package/scripts/test-package.mjs +64 -0
  47. package/tests/README.md +66 -46
  48. package/tests/code-derivation/core.mjs +61 -0
  49. package/tests/helpers/cli.mjs +45 -0
  50. package/tests/integration.sh +2 -3
  51. package/tests/test-arithmetics.mjs +47 -237
  52. package/tests/test-djson-methods.mjs +71 -275
  53. package/tests/test-hash-normalization.mjs +22 -1
  54. package/tests/test-karatsuba.mjs +18 -126
  55. package/tests/test-named-patterns.mjs +174 -606
  56. package/tests/test-paper-examples.mjs +90 -0
  57. package/tests/test-poly.mjs +2 -2
  58. package/tests/test-repl-html.mjs +2 -2
  59. package/tests/test-repl.mjs +89 -38
  60. package/tests/test.mjs +27 -68
  61. package/AGENTS.md +0 -35
  62. package/CLAUDE.md +0 -64
  63. package/DOCS/BIG_PICTURE.md +0 -439
  64. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  65. package/DOCS/CANONICAL_PATTERNS.md +0 -349
  66. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  67. package/DOCS/CONVERGENCE.md +0 -123
  68. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  69. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  70. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  71. package/DOCS/Makefile +0 -99
  72. package/DOCS/NAMED_PATTERNS.md +0 -340
  73. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  74. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  75. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -136
  76. package/DOCS/book/01-introduction.md +0 -48
  77. package/DOCS/book/02-syntax-and-values.md +0 -110
  78. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  79. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  80. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  81. package/DOCS/book/06-values-in-memory.md +0 -1085
  82. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  83. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  84. package/DOCS/book/09-compiler-architecture.md +0 -160
  85. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  86. package/DOCS/book/14-canonical-serialization.md +0 -176
  87. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  88. package/DOCS/book/overview.txt +0 -68
  89. package/DOCS/book.md +0 -50
  90. package/Examples/bnat.k +0 -308
  91. package/Examples/buda.k +0 -66
  92. package/Examples/byte.k +0 -35
  93. package/Examples/code.k +0 -43
  94. package/Examples/vhdl_to_k.k +0 -67
  95. package/JOURNAL.md +0 -288
  96. package/TODO.md +0 -107
  97. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  98. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  99. package/backends/wasm/demo_ieee.mjs +0 -318
  100. package/browser/vfs-data.mjs +0 -21
  101. package/codecs/BINARY_FORMAT.md +0 -53
  102. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  103. package/codecs/pandoc.css +0 -71
  104. package/tests/code-derivation/blowup.mjs +0 -25
  105. package/tests/code-derivation/bnat.mjs +0 -11
  106. package/tests/code-derivation/dot.mjs +0 -37
  107. package/tests/code-derivation/index.mjs +0 -20
  108. package/tests/code-derivation/loop.mjs +0 -17
  109. package/tests/code-derivation/nat.mjs +0 -10
  110. package/tests/code-derivation/not-not.mjs +0 -14
  111. package/tests/code-derivation/product.mjs +0 -22
  112. package/tests/code-derivation/rlz.mjs +0 -13
  113. 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.
@@ -27,38 +27,7 @@ export function loadLibraryFromPath(libPath) {
27
27
  return loadLibrary(decodeObject(fs.readFileSync(libPath)));
28
28
  }
29
29
  if (ext === ".k") {
30
- let depLibs = [];
31
- const baseName = path.basename(libPath);
32
- if (baseName === "poly.k") {
33
- const dir = path.dirname(libPath);
34
- const arithPath = path.join(dir, "arithmetics.k");
35
- if (fs.existsSync(arithPath)) {
36
- const arithLib = loadLibrary(
37
- compileLibrary(fs.readFileSync(arithPath, "utf8"), {
38
- source: arithPath
39
- })
40
- );
41
- depLibs.push(arithLib);
42
- }
43
- }
44
30
  const rawSource = fs.readFileSync(libPath, "utf8");
45
- if (depLibs.length > 0) {
46
- const neededExports = [
47
- "0", "int", "inc", "dec", "nat", "zero_int?", "neg?", "GT"
48
- ];
49
- const preamble = buildExportPreamble(neededExports, depLibs);
50
- const compiled = compileLibrary(preamble + rawSource, {
51
- source: libPath,
52
- libraries: depLibs
53
- });
54
- const mergedLib = loadLibrary(compiled);
55
- for (const dep of depLibs) {
56
- for (const [k, v] of Object.entries(dep.relAlias || {})) {
57
- if (!mergedLib.relAlias[k]) mergedLib.relAlias[k] = v;
58
- }
59
- }
60
- return mergedLib;
61
- }
62
31
  return loadLibrary(compileLibrary(rawSource, { source: libPath }));
63
32
  }
64
33
  throw new Error(`Unsupported library extension: ${ext}`);
@@ -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.
@@ -35,38 +35,7 @@ export function loadLibraryFromPath(libPath) {
35
35
  return loadLibrary(decodeObject(fs.readFileSync(libPath)));
36
36
  }
37
37
  if (ext === ".k") {
38
- let depLibs = [];
39
- const baseName = path.basename(libPath);
40
- if (baseName === "poly.k") {
41
- const dir = path.dirname(libPath);
42
- const arithPath = path.join(dir, "arithmetics.k");
43
- if (fs.existsSync(arithPath)) {
44
- const arithLib = loadLibrary(
45
- compileLibrary(fs.readFileSync(arithPath, "utf8"), {
46
- source: arithPath
47
- })
48
- );
49
- depLibs.push(arithLib);
50
- }
51
- }
52
38
  const rawSource = fs.readFileSync(libPath, "utf8");
53
- if (depLibs.length > 0) {
54
- const neededExports = [
55
- "0", "int", "inc", "dec", "nat", "zero_int?", "neg?", "GT"
56
- ];
57
- const preamble = buildExportPreamble(neededExports, depLibs);
58
- const compiled = compileLibrary(preamble + rawSource, {
59
- source: libPath,
60
- libraries: depLibs
61
- });
62
- const mergedLib = loadLibrary(compiled);
63
- for (const dep of depLibs) {
64
- for (const [k, v] of Object.entries(dep.relAlias || {})) {
65
- if (!mergedLib.relAlias[k]) mergedLib.relAlias[k] = v;
66
- }
67
- }
68
- return mergedLib;
69
- }
70
39
  return loadLibrary(compileLibrary(rawSource, { source: libPath }));
71
40
  }
72
41
  throw new Error(`Unsupported library extension: ${ext}`);
@@ -58,11 +58,27 @@ function skeletonizeFilter(filter, knots) {
58
58
  if (node.type === "code") {
59
59
  return { ...node };
60
60
  }
61
- return {
62
- type: "name",
63
- name: `__LEAF_${leafIdx++}__`,
64
- open: true
65
- };
61
+ if (node.type === "pattern_apply") {
62
+ const pos =
63
+ node.start && node.end
64
+ ? ` (lines ${node.start.line}:${node.start.column}...` +
65
+ `${node.end.line}:${node.end.column})`
66
+ : node.start
67
+ ? ` (lines ${node.start.line}:${node.start.column})`
68
+ : "";
69
+ const suffix = node.pattern?.startsWith("@") ? "" : "[]";
70
+ throw new Error(
71
+ `Unknown pattern template '${node.pattern}${suffix}'${pos}`
72
+ );
73
+ }
74
+ if (node.type === "name" || node.type === null) {
75
+ return {
76
+ type: "name",
77
+ name: `__LEAF_${leafIdx++}__`,
78
+ open: true
79
+ };
80
+ }
81
+ return node;
66
82
  }
67
83
  return walk(filter);
68
84
  }
@@ -118,21 +134,29 @@ function collectCanonicalVarPaths(canonicalFilter) {
118
134
  return paths;
119
135
  }
120
136
 
121
- function toAstFilter(node) {
137
+ function toAstFilter(node, canonicalParams = []) {
122
138
  if (!node || typeof node !== "object") return node;
123
139
  const res = { ...node };
124
- if (
125
- res.name &&
126
- /^X\d+$/.test(res.name) &&
127
- (!res.fields || Object.keys(res.fields).length === 0)
128
- ) {
129
- res.type = "name";
130
- res.open = true;
140
+ if (res.type === null) {
141
+ return {
142
+ type: "name",
143
+ name: res.name,
144
+ open: true
145
+ };
146
+ }
147
+ if (res.type === "name") {
148
+ return {
149
+ type: "name",
150
+ name: res.name,
151
+ ...(canonicalParams.includes(res.name)
152
+ ? { open: true }
153
+ : {})
154
+ };
131
155
  }
132
156
  if (res.fields) {
133
157
  res.fields = {};
134
158
  for (const [k, v] of Object.entries(node.fields)) {
135
- res.fields[k] = toAstFilter(v);
159
+ res.fields[k] = toAstFilter(v, canonicalParams);
136
160
  }
137
161
  }
138
162
  return res;
@@ -155,12 +179,24 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
155
179
  canonicalFilterAst: pat._canonicalFilterAst || null
156
180
  };
157
181
  }
158
- if (typeof name === "string" && name.startsWith("@")) {
182
+ const isDirectCanonical =
183
+ typeof name === "string" && name.startsWith("@");
184
+ if (isDirectCanonical) {
159
185
  pat._canonical = name;
160
186
  }
161
187
  const formalParams = pat.params || [];
162
188
  const formalCount = formalParams.length;
163
189
  const allPatterns = { ...(options.patterns || {}) };
190
+ if (options.libraries) {
191
+ for (const lib of options.libraries) {
192
+ const lp =
193
+ lib.patterns ||
194
+ lib.defs?.patterns ||
195
+ lib.sourceDefs?.patterns ||
196
+ {};
197
+ Object.assign(allPatterns, lp);
198
+ }
199
+ }
164
200
  if (name && pat) allPatterns[name] = pat;
165
201
 
166
202
  let pathMap = {};
@@ -180,13 +216,6 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
180
216
  }
181
217
  }
182
218
 
183
- let expandedFilter = null;
184
- try {
185
- expandedFilter = expandFilter(pat.filter, allPatterns);
186
- } catch {
187
- expandedFilter = pat.filter;
188
- }
189
-
190
219
  if (!pat.filter) {
191
220
  return {
192
221
  hash: pat._canonical || null,
@@ -195,8 +224,12 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
195
224
  };
196
225
  }
197
226
 
227
+ const expandedFilter = expandFilter(pat.filter, allPatterns);
228
+
198
229
  const knots = collectFilterKnots(expandedFilter);
199
- const skeletonFilter = skeletonizeFilter(expandedFilter, knots);
230
+ const skeletonFilter = isDirectCanonical
231
+ ? expandedFilter
232
+ : skeletonizeFilter(expandedFilter, knots);
200
233
  const source = `? ${prettyFilter(skeletonFilter)}`;
201
234
  try {
202
235
  const annotated = annotate(source, {
@@ -266,7 +299,10 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
266
299
  formalCount > 0 ? selectedParams : [];
267
300
  pat._graphParams = graphParams || [];
268
301
  pat._aliasArgs = aliasArgs;
269
- pat._canonicalFilterAst = toAstFilter(canonicalFilter);
302
+ pat._canonicalFilterAst = toAstFilter(
303
+ canonicalFilter,
304
+ graphParams || []
305
+ );
270
306
 
271
307
  return {
272
308
  hash: pat._canonical,
@@ -276,18 +312,16 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
276
312
  canonicalParams: pat._graphParams,
277
313
  canonicalFilterAst: pat._canonicalFilterAst
278
314
  };
279
- } catch {
280
- return {
281
- hash: pat._canonical || null,
282
- def: pat._canonicalDef || null,
283
- params: pat._canonicalParams || null
284
- };
315
+ } catch (err) {
316
+ if (isDirectCanonical) {
317
+ return {
318
+ hash: pat._canonical || null,
319
+ def: pat._canonicalDef || null,
320
+ params: pat._canonicalParams || null
321
+ };
322
+ }
323
+ throw err;
285
324
  }
286
- return {
287
- hash: pat._canonical || null,
288
- def: pat._canonicalDef || null,
289
- params: pat._canonicalParams || null
290
- };
291
325
  }
292
326
 
293
327
  export function canonicalPatternHash(name, pat, options = {}) {