@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,644 +1,189 @@
1
- # File Formats in the K Universe
2
-
3
- The `k` toolchain operates across five primary file formats: `.k`,
4
- `.ko`, `.klib`, `.kvm`, and `.pkir`. Each format occupies a distinct
5
- position in the pipeline from human-authored source to ahead-of-time
6
- (AOT) type-checked artifacts, intermediate representations, and
7
- JIT/native execution.
8
-
9
- ---
10
-
11
- ## Overview & Comparison
12
-
13
- | Extension | Role | Format / Magic | Entrypoint |
14
- |:---:|:---|:---|:---|
15
- | **`.k`** | Human source code | UTF-8 plain text | Optional |
16
- | **`.ko`** | Executable object | Binary (`KOBJ\n`) | Required |
17
- | **`.klib`** | Reusable library | UTF-8 JSON | None |
18
- | **`.kvm`** | Polymorphic kVM IR | `k-vm` (KVM-P) | Relations |
19
- | **`.pkir`** | Polymorphic IR | `pk-ir` (v1) | Relations |
20
-
21
- | Extension | Generated By | Consumed By |
22
- |:---:|:---|:---|
23
- | **`.k`** | Editor, `k-decompile` | `k.mjs`, `k-compile`, backends |
24
- | **`.ko`** | `k-compile`, REPL (`:ko`) | `k.mjs`, backends, tools |
25
- | **`.klib`** | `k-compile --lib` | REPL, linkers (`--lib`) |
26
- | **`.kvm`** | `k-compile --format kvm` | `kvm.mjs`, backends |
27
- | **`.pkir`** | `compileRelationToPKIR` | `executePKIR`, specializer |
28
-
29
- ### Format Transformation Workflow
30
-
31
- ```mermaid
32
- flowchart TD
33
- subgraph Sources ["Source & Interactive"]
34
- K[".k (Source Code)"]
35
- REPL["REPL Session"]
36
- end
37
-
38
- subgraph AOT_Artifacts ["AOT Type-Checked Artifacts"]
39
- KLIB[".klib (Library)"]
40
- KO[".ko (Executable Object)"]
41
- end
42
-
43
- subgraph IR_Artifacts ["Intermediate Representations"]
44
- KVM[".kvm (kVM Bytecode)"]
45
- PKIR[".pkir (Polymorphic IR)"]
46
- end
47
-
48
- subgraph Targets ["Execution Targets"]
49
- WASM[".wasm (WebAssembly)"]
50
- NATIVE["Native Binary"]
51
- INTERP["Interpreter / kVM / PKIR"]
52
- end
53
-
54
- %% Transformations from .k
55
- K -->|"k-compile"| KO
56
- K -->|"k-compile --lib"| KLIB
57
- K -->|"k-compile --format kvm"| KVM
58
- K -->|"compileRelationToPKIR"| PKIR
59
- K -->|":load"| REPL
60
-
61
- %% REPL exports
62
- REPL -->|":klib"| KLIB
63
- REPL -->|":ko"| KO
64
-
65
- %% Linking from .klib
66
- KLIB -->|"k-compile --lib"| KO
67
- KLIB -->|"k-compile --lib --format kvm"| KVM
68
- KLIB -->|":load"| REPL
69
-
70
- %% Lowering from .ko
71
- KO -->|"k-wasm-compile"| WASM
72
- KO -->|"k-llvm-build"| NATIVE
73
- KO -->|"k.mjs"| INTERP
74
- KO -->|"k-decompile"| K
75
- KO -->|"compileRelationToPKIR"| PKIR
76
-
77
- %% Lowering from .kvm
78
- KVM -->|"k-wasm-compile"| WASM
79
- KVM -->|"k-llvm-build"| NATIVE
80
- KVM -->|"kvm.mjs / specializeKVM"| INTERP
81
-
82
- %% Execution and Specialization from .pkir
83
- PKIR -->|"executePKIR + AccessTable"| INTERP
84
- PKIR -->|"specializePKIR"| PKIR_SPEC["Specialized PKIR"]
85
- PKIR -->|"k-wasm-compile"| WASM
86
- PKIR -->|"k-llvm-compile"| LLVM[".ll (LLVM IR)"]
87
- PKIR -->|"k-llvm-build"| NATIVE
88
- PKIR_SPEC -->|"executePKIR"| INTERP
89
- PKIR_SPEC -->|"backend lowering"| WASM
90
- PKIR_SPEC -->|"backend lowering"| NATIVE
1
+ # File formats and tools
2
+
3
+ Run the examples below from the repository root after `npm install`.
4
+ `npm link` exposes the shorter installed commands such as `k` and
5
+ `k-compile`. Every installed command supports `--help`.
6
+
7
+ ## Formats
8
+
9
+ | Format | Contents | Producer / consumer |
10
+ | --- | --- | --- |
11
+ | `.k` | Source definitions and an optional terminal expression | Editor, REPL, compiler |
12
+ | `.ko` | Compiled executable object with a main relation | `k-compile`, `k`, backend tools |
13
+ | `.klib` | Compiled definitions with no main relation | `k-compile`, `:klib`, `--lib`, `:load` |
14
+ | `.kvm` | JSON kVM artifact: polymorphic `KVM-P` template or specialized `KVM` program | `k-compile`, specialization API, backends |
15
+ | `.pkir` | JSON experimental PKIR relation (`format: "pk-ir"`, version 1) | JavaScript API, backends |
16
+ | `.wasm` | WebAssembly module with k runner metadata | `k-wasm-compile`, `k-wasm-run` |
17
+
18
+ A source file executed directly needs a terminal expression. A library can
19
+ contain definitions only. Definitions alone are also valid REPL input.
20
+
21
+ The [binary wire stream](../codecs/WIRE_FORMAT.md) carrying an input or output
22
+ value is separate from these program artifacts.
23
+
24
+ ## Run source or an object
25
+
26
+ ```sh
27
+ node codecs/unit.mjs --parse | node k.mjs '{} |ok' | node codecs/k-print.mjs
91
28
  ```
92
29
 
93
- ---
94
-
95
- ## 1. `.k` — Source Code File
96
-
97
- ### What It Is
98
- `.k` files contain the high-level, human-readable source code of the
99
- `k` language. A `.k` file defines:
100
- - **Algebraic Schemas & Named Patterns:** Products (`{ ... }`),
101
- tagged unions (`< ... >`), and reusable parameterized pattern
102
- templates (`name[...] = filter;`).
103
- - **Relations:** First-order partial functions composed via sequence,
104
- union, projection, or product construction.
105
- - **Top-level Expressions:** Computations evaluated when the file is run
106
- as a script.
107
-
108
- ### How to Generate
109
- - Written manually in any text editor.
110
- - Decompiled from an existing `.ko` or `.klib` artifact:
111
- ```bash
112
- k-decompile program.ko program.decompiled.k
113
- ```
114
-
115
- ### How to Consume
116
- - **Run directly over stream input:**
117
- ```bash
118
- ./k.mjs program.k
119
- ```
120
- - **Load into interactive REPL session:**
121
- ```k
122
- :load Examples/arithmetics.k
123
- ```
124
- - **Compile into compiled artifacts:**
125
- ```bash
126
- # Compile to executable object (.ko)
127
- k-compile program.k program.ko
128
-
129
- # Compile to reusable library (.klib)
130
- k-compile --lib program.k program.klib
131
-
132
- # Compile to polymorphic kVM template (.kvm)
133
- k-compile --format kvm program.k program.kvm
134
- ```
135
-
136
- ---
137
-
138
- ## 2. `.ko` — Executable Object File
139
-
140
- ### What It Is
141
- `.ko` is an ahead-of-time (AOT) type-checked, self-contained executable
142
- object artifact (`format: "k-object"`, `kind: "executable"`).
143
-
144
- In the `k` toolchain, "ahead-of-time" means that parsing, relation
145
- expansion, structural type derivation, and constraint convergence are
146
- completed beforehand during compilation. The resulting artifact stores
147
- the fully converged principal type graphs and interned type hashes.
148
- - **Physical Layout:** Prefixed by a 5-byte magic header `KOBJ\n`,
149
- followed by a JSON payload.
150
- - **Payload Contents:**
151
- - `codes`: Type-code dictionary (interned structural type hashes).
152
- - `rels`: Compiled relation ASTs and converged principal type graphs.
153
- - `main`: Fixed entrypoint name (usually `"__main__"`).
154
- - `meta`: Compiler origins and source position mapping.
155
- - **Key Advantage:** Skips both parsing and type derivation. Running a
156
- `.ko` executes immediately without cold-start compilation overhead.
157
-
158
- ### How to Generate
159
-
160
- #### From the CLI (`k-compile`):
161
- Compile a source file into an executable object:
162
- ```bash
163
- k-compile program.k program.ko
30
+ This prints `"ok"`. Existing paths are read as files; `k` otherwise treats its
31
+ program argument as inline source. Other compiler tools reject recognized
32
+ missing input filenames; consult their help for accepted extensions.
33
+
34
+ `k` reads a binary input stream, including when the program produces a constant.
35
+ Unit is a convenient input for a constant program; a constant relation does not
36
+ inherently require unit as its input schema.
37
+
38
+ The [textual-value guide](TEXTUAL_VALUES.md) explains `k-parse` and `k-print`.
39
+
40
+ ## Compile an executable
41
+
42
+ ```sh
43
+ node objects/compile.mjs '{} |ok' /tmp/k-ok.ko
44
+ node codecs/unit.mjs --parse | node k.mjs /tmp/k-ok.ko |
45
+ node codecs/k-print.mjs
164
46
  ```
165
47
 
166
- Compile an inline expression that links a library (`.klib` or `.k`):
167
- ```bash
168
- # Note: Library relation aliases referenced by name in the expression
169
- # must be explicitly mapped into scope via --export:
170
- k-compile --lib Examples/arithmetics.k \
171
- --export plus \
172
- --export int \
173
- --export 5 \
174
- '{() x, 5 int y} plus' \
175
- add5.ko
48
+ The output extension selects the compiler format. To select it explicitly:
49
+
50
+ ```sh
51
+ node objects/compile.mjs --format ko '{} |ok' /tmp/k-ok.ko
176
52
  ```
177
53
 
178
- #### From the REPL (`:ko`):
179
- Export the current session into an executable object with a custom
180
- entrypoint expression:
181
- ```k
182
- :load Examples/arithmetics.k
183
- :ko add5.ko {() x, 5 int y} plus
54
+ Source is read from stdin when omitted; output goes to stdout when no path is
55
+ given. `-o` / `--output` is an alternative to the positional output path.
56
+
57
+ ## Compile and link a library
58
+
59
+ ```sh
60
+ node objects/compile.mjs 'greet = {} |hello;' /tmp/k-demo.klib
61
+ node objects/compile.mjs --lib /tmp/k-demo.klib --export greet 'greet' /tmp/k-greet.ko
62
+ node codecs/unit.mjs --parse | node k.mjs /tmp/k-greet.ko |
63
+ node codecs/k-print.mjs
184
64
  ```
185
65
 
186
- ### How to Consume
187
-
188
- - **Execute using the standard interpreter (`k.mjs`):**
189
- ```bash
190
- echo "10" | ./codecs/int.mjs --parse | \
191
- ./k.mjs add5.ko | ./codecs/int.mjs --print
192
- # Output: 15
193
- ```
194
-
195
- - **Compile to a standalone WebAssembly binary (`k-wasm-compile`):**
196
- ```bash
197
- k-wasm-compile add5.ko add5.wasm
198
- echo "10" | ./codecs/int.mjs --parse | \
199
- node backends/wasm/bin/k-wasm-run.mjs add5.wasm | \
200
- ./codecs/int.mjs --print
201
- # Output: 15
202
- ```
203
-
204
- - **Compile to a native machine executable via LLVM (`k-llvm-build`):**
205
- ```bash
206
- k-llvm-build add5.ko -o add5
207
- echo "10" | ./codecs/int.mjs --parse | ./add5 | ./codecs/int.mjs --print
208
- # Output: 15
209
- ```
210
-
211
- - **Inspect, validate, or decompile:**
212
- ```bash
213
- k-inspect-object add5.ko
214
- k-validate-object add5.ko
215
- k-decompile add5.ko decompiled.k
216
- ```
217
-
218
- ---
219
-
220
- ## 3. `.klib` — Library Object File
221
-
222
- ### What It Is
223
- `.klib` is an AOT type-checked library container (`format: "k-object"`,
224
- `kind: "library"`).
225
- - **Physical Layout:** Stored as plain UTF-8 JSON (no `KOBJ\n` header).
226
- - **Payload Contents:**
227
- - `codes`: Type-code dictionary.
228
- - `rels`: Compiled and type-converged relations.
229
- - `main: null`: Unlike `.ko`, there is no single execution entrypoint.
230
- - `relAlias`: Public alias mapping of exported relations.
231
- - `typeAliases`: Public alias mapping of exported types.
232
- - **Key Advantage:** Pre-derives types across large relation suites
233
- (such as `Examples/arithmetics.k` or `poly.k`), allowing downstream
234
- programs to link them instantaneously without re-running type
235
- convergence.
236
-
237
- ### How to Generate
238
-
239
- #### From the CLI (`k-compile`):
240
- Compile a source file into a library (the format is automatically
241
- inferred from the `.klib` extension or `--lib`/`--format` flag):
242
- ```bash
243
- k-compile Examples/arithmetics.k math.klib
244
- # Or explicitly:
245
- k-compile --lib Examples/arithmetics.k math.klib
66
+ This prints `"hello"`. `--lib` loads a dependency; it does not select library
67
+ output. These are equivalent ways to generate a library from source:
68
+
69
+ ```sh
70
+ node objects/compile.mjs Examples/arithmetics.k /tmp/k-math.klib
71
+ node objects/compile.mjs --format klib Examples/arithmetics.k /tmp/k-math.klib
246
72
  ```
247
73
 
248
- #### From the REPL (`:klib`):
249
- Export all currently loaded relations and types into a reusable library:
250
- ```k
251
- :load Examples/arithmetics.k
252
- :load Examples/poly.k
253
- :klib my_lib.klib
74
+ Only one `--lib` is accepted by the current CLI. The dependency's relations are
75
+ available under canonical hashes; friendly aliases require explicit
76
+ `--export name` or `--export libraryName:localName` mappings. Repeat
77
+ `--export` for each needed alias. Source can reference hashes directly.
78
+
79
+ For example, increment a decimal input using a library relation:
80
+
81
+ ```sh
82
+ printf '42\n' | node codecs/int.mjs --parse |
83
+ node k.mjs --lib /tmp/k-math.klib --export inc 'inc' |
84
+ node codecs/int.mjs --print
254
85
  ```
255
86
 
256
- ### How to Consume
257
-
258
- - **Load into an interactive REPL session:**
259
- ```k
260
- :load math.klib
261
- ```
262
-
263
- - **Link as a dependency in downstream compilation (`--lib`):**
264
- ```bash
265
- k-compile --lib math.klib \
266
- --export plus \
267
- --export int \
268
- --export 5 \
269
- '{() x, 5 int y} plus' \
270
- add5.ko
271
- ```
272
-
273
- - **Link into standalone WebAssembly or native LLVM builds:**
274
- ```bash
275
- k-wasm-compile --lib math.klib \
276
- --export plus --export int --export 5 \
277
- '{() x, 5 int y} plus' add5.wasm
278
-
279
- k-llvm-build --lib math.klib \
280
- --export plus --export int --export 5 \
281
- '{() x, 5 int y} plus' -o add5
282
- ```
283
-
284
- - **Inspect contents or extract alias declarations:**
285
- ```bash
286
- # View object metadata summary (relation counts, type codes):
287
- k-inspect-object math.klib
288
-
289
- # Extract active alias definitions as valid k source snippet:
290
- k-extract-aliases math.klib math-aliases.k
291
-
292
- # Validate structure and KIR-P export:
293
- k-validate-object math.klib
294
- ```
295
-
296
- ---
297
-
298
- ## 4. `.kvm` — Polymorphic kVM Template File
299
-
300
- ### What It Is
301
- `.kvm` is a polymorphic register-IR template artifact
302
- (`format: "k-vm"`, `layer: "KVM-P"`, `isPolymorphic: true`).
303
-
304
- #### Why `.kvm` Exists (What You Gain):
305
-
306
- 1. **Relational AST vs. Linear Register Machine:**
307
- `.ko` and `.klib` store high-level relational combinators (compositions
308
- `(f g)`, products `{a x, b y}`, unions `<f, g>`) and structural type
309
- graphs. They contain no virtual registers, instruction sequences, or
310
- control-flow branches. `.kvm` transforms this functional tree into a
311
- linear 3-address virtual register machine IR (`alloc`, `project_field`,
312
- `make_variant`, `project_variant`, `jump_if_fail`, `call`, and loops).
313
-
314
- 2. **$1 \times N$ Backend Decoupling:**
315
- Rather than having every code generator (LLVM, WebAssembly, and the
316
- interpreter) independently lower the relational tree and
317
- re-implement type-guided control flow, relational-to-imperative
318
- lowering occurs once in `kvm.mjs`. All backends consume the exact same
319
- ~10 linear kVM instructions (`kvm2llvm.mjs`, `kvm2wasm.mjs`,
320
- `kvm.mjs`).
321
-
322
- 3. **Microsecond Polymorphic Specialization (`layer: "KVM-P"`):**
323
- In polymorphic programs, specializing `.ko` requires re-running the
324
- compiler's full structural type derivation and constraint convergence
325
- engine. A `.kvm` template stores pre-compiled register bytecode with
326
- principal pattern graphs. The runtime specializer (`specializeKVM`)
327
- prunes dead branches and folds redundant guards against concrete
328
- runtime input envelopes $(v, P_v)$ in microseconds with zero AST
329
- recompilation overhead.
330
-
331
- 4. **Inspectable & Cacheable Register IR:**
332
- `.kvm` produces a human- and machine-readable JSON or CBOR format.
333
- You can inspect virtual register assignments, verify dead-branch
334
- elimination, diff compiler output across runs, or cache the lowered IR
335
- to bypass frontend compilation when building native or WASM targets.
336
-
337
- ### How to Generate
338
-
339
- #### From the CLI (`k-compile`):
340
- Specify the `.kvm` extension or `--format kvm`:
341
- ```bash
342
- # Compile directly from an expression linking a library:
343
- k-compile --lib math.klib \
344
- --export plus --export int --export 5 \
345
- '{() x, 5 int y} plus' \
346
- add5.kvm
347
-
348
- # Or lower an existing .ko object directly into a .kvm template:
349
- k-compile add5.ko add5.kvm
87
+ This prints `43`. Numeral names such as `5` in the arithmetic library are
88
+ relations producing bit trees. `5 int` constructs a signed integer; numeral
89
+ names are not builtin literals.
90
+
91
+ ## Inspect and decompile
92
+
93
+ ```sh
94
+ node objects/inspect.mjs /tmp/k-ok.ko
95
+ node objects/validate.mjs /tmp/k-ok.ko
96
+ node objects/decompile.mjs /tmp/k-demo.klib /tmp/k-demo.k
97
+ node objects/extract-aliases.mjs /tmp/k-demo.klib
98
+ node kir.mjs /tmp/k-ok.ko > /tmp/k-ok.kir.json
99
+ node objects/validate.mjs --kir /tmp/k-ok.kir.json
350
100
  ```
351
101
 
352
- ### How to Consume
353
-
354
- - **Direct lowering from `.kvm` to Native Binaries (`k-llvm-build`):**
355
- Compile a `.kvm` template directly into a native executable:
356
- ```bash
357
- k-llvm-build add5.kvm add5-bin
358
- echo "10" | ./codecs/int.mjs --parse | \
359
- ./add5-bin | \
360
- ./codecs/int.mjs --print
361
- # Output: 15
362
- ```
363
-
364
- - **Direct lowering from `.kvm` to LLVM IR (`k-llvm-compile`):**
365
- Emit LLVM assembly directly from the register IR:
366
- ```bash
367
- k-llvm-compile add5.kvm add5.ll
368
- ```
369
-
370
- - **Direct lowering from `.kvm` to WebAssembly (`k-wasm-compile`):**
371
- Compile a `.kvm` template directly into a standalone `.wasm` module:
372
- ```bash
373
- k-wasm-compile add5.kvm add5.wasm
374
- echo "10" | ./codecs/int.mjs --parse | \
375
- node backends/wasm/bin/k-wasm-run.mjs add5.wasm | \
376
- ./codecs/int.mjs --print
377
- # Output: 15
378
- ```
379
-
380
- - **Programmatic runtime specialization (`specializeKVM`):**
381
- In JavaScript / Node.js host embeddings:
382
- ```javascript
383
- import { specializeKVM, executeKVM } from "./kvm.mjs";
384
-
385
- // Specialize polymorphic template to runtime input envelope (P, v):
386
- const specialized = specializeKVM(kvmArtifact, inputEnvelope);
387
- const result = executeKVM(specialized.func, value, context);
388
- ```
389
-
390
- ---
391
-
392
- ## 5. `.pkir` — Polymorphic K Intermediate Representation File
393
-
394
- ### What It Is
395
- `.pkir` is a state-indexed, slot-addressed intermediate representation
396
- artifact (`format: "pk-ir"`, `version: 1`).
397
-
398
- While `.kvm` models imperative register control-flow using symbolic
399
- field strings (`project_field`, `inst.label`), `.pkir` addresses the
400
- fundamental data-layout problem for polymorphic functions. It unifies
401
- streaming bitstream processing and random-access memory tables:
402
-
403
- 1. **Slot Addressing & State Indexing:**
404
- Eliminates all runtime string lookups (`val.product[label]`). Every
405
- field access is compiled to an integer slot relative to an abstract
406
- pattern state (`project_slot`, `slot`, `state`). Every variant test
407
- is compiled to a branch index (`match_variant`, `branchId`, `state`).
408
-
409
- 2. **Duality of Transducers & Witnesses:**
410
- - **Streaming Pushdown Transducers:** Navigates prefix-free serialized
411
- wire streams using static skip counts (`skipCount`). Erasing and
412
- linear operations execute in $O(\text{depth})$ stack memory with zero
413
- node materialization.
414
- - **Layout Witnesses (`AccessTable`):** Operates on random-access
415
- memory arenas. Given any concrete input schema $S$ and function
416
- access profile $P$, `buildAccessTable(S, P)` resolves physical byte
417
- offsets $\Omega(S, P)$ in a single array load.
418
-
419
- 3. **Hybrid `KVal` Fat-Pointer Representation:**
420
- Values remain compact serialized wire slices by default. When
421
- non-linear access occurs (e.g. repeated reads or field reordering),
422
- demand-driven **Spine Promotion** materializes only the outer product
423
- node into an arena record while leaving child payloads as untouched
424
- slices. Opaque payloads are never re-encoded or reconstructed.
425
-
426
- ### Payload Structure
427
-
428
- A `.pkir` artifact is structured as follows:
429
-
430
- ```json
431
- {
432
- "format": "pk-ir",
433
- "version": 1,
434
- "name": "extract_id",
435
- "inputReg": "%v0",
436
- "outputReg": "%v1",
437
- "inputPattern": 3,
438
- "outputPattern": 4,
439
- "patternGraph": { ... },
440
- "accessProfile": {
441
- "0": { "fields": ["id"], "variants": [] },
442
- "3": { "fields": [], "variants": ["click", "sensor", "ping"] }
443
- },
444
- "instructions": [
445
- {
446
- "op": "union",
447
- "dest": "%v1",
448
- "src": "%v0",
449
- "branches": [ ... ]
450
- }
451
- ]
452
- }
102
+ `k-inspect-object --kir` is another route to the
103
+ [KIR-P export](KIR_V1.md). Exported KIR-P is an inspection/backend contract;
104
+ it does not replace the stored object container.
105
+
106
+ The REPL exports current definitions with `:klib file.klib` and an executable
107
+ expression with `:ko file.ko expression`. See [REPL.md](REPL.md).
108
+
109
+ ## Object container reference
110
+
111
+ Executable objects use:
112
+
113
+ ```text
114
+ "KOBJ" 0x0a
115
+ uint32-be JSON-payload-byte-length
116
+ UTF-8 JSON payload
453
117
  ```
454
118
 
455
- #### Instruction Set Summary
456
- - `id`: Register assignment (`{ op: "id", dest, src }`).
457
- - `project_slot`: State-indexed slot projection
458
- (`{ op: "project_slot", dest, src, state, slot, label }`).
459
- - `match_variant`: State-indexed variant match
460
- (`{ op: "match_variant", dest, src, state, tag, branchId }`).
461
- - `make_variant`: Variant construction
462
- (`{ op: "make_variant", dest, src, tag }`).
463
- - `product`: Product construction with sub-instruction streams.
464
- - `union`: Multi-branch selection with failure backtracking.
465
- - `call_rel`: Relation call / recursion
466
- (`{ op: "call_rel", dest, ref, src }`).
467
- - `fail`: Unconditional branch failure (`{ op: "fail" }`).
468
- - **Specialized Instructions:**
469
- - `project_offset`: Direct memory offset projection:
470
- `{ op: "project_offset", dest, src, offset, skipCount, childState }`.
471
- - `match_tag_imm`: Immediate discriminator test
472
- (`{ op: "match_tag_imm", dest, src, tagId, branchId, childState }`).
473
-
474
- ### Why `.pkir` Exists (What You Gain)
475
-
476
- 1. **Elimination of the Envelope Tax (26x Speedup):**
477
- Previous polymorphic execution required wrapping values in dynamic
478
- envelopes $(v, P_v)$, suffering a 26x performance penalty during
479
- envelope packing/unpacking (`scripts/perf-poly.mjs`). PKIR navigates
480
- heterogeneous records directly via layout witnesses without envelopes.
481
-
482
- 2. **Sub-30µs Specialization Latency:**
483
- `specializePKIR` bakes static byte offsets into instructions and prunes
484
- dead union branches in ~27 microseconds (compared to 100–1500 ms for
485
- traditional AOT/Wasm compilation), enabling instant JIT tiering.
486
-
487
- 3. **Zero Payload Re-Encoding:**
488
- Preserves arbitrary opaque payloads (`data: payload_i`) as byte slices
489
- without traversal or re-serialization during recursive list
490
- processing (`search`, `poly_rev`).
491
-
492
- 4. **1:1 Machine Code Lowering:**
493
- Specialized PKIR instructions map directly to WebAssembly (`i64.load
494
- offset=C`, `i32.eq`) and LLVM machine instructions without dynamic
495
- runtime fallbacks (`@k_product_get_n`).
496
-
497
- ### How to Generate
498
-
499
- In JavaScript / Node.js API:
500
- ```javascript
501
- import { compileRelationToPKIR } from "@fraczak/k/backend-api.mjs";
502
-
503
- const pkir = compileRelationToPKIR(relDef, "extract_id");
119
+ Libraries are plain UTF-8 JSON with no binary header. Both payloads use
120
+ `format: "k-object"` and have no payload version field.
121
+
122
+ | Field | Role |
123
+ | --- | --- |
124
+ | `main` | `"__main__"` for compiler-generated executables, `null` for libraries |
125
+ | `codes` | Canonical closed schema definitions |
126
+ | `rels` | Relation definitions, pattern graphs, and per-relation derivation status |
127
+ | `relAlias` | Friendly relation names mapped to hashes |
128
+ | `patterns` | Deduplicated canonical pattern template ASTs |
129
+ | `patternAlias` | Friendly pattern names mapped to skeleton hashes |
130
+ | `compileStats` | Derivation statistics |
131
+ | `meta` | Origins, aliases, source ranges, and pattern routing metadata |
132
+
133
+ A relation's `typeDerivation.status` is `converged`, `not-converged`, or
134
+ `unknown`. It currently stores only status, not an iteration trace. Consumers
135
+ must check eligibility for their execution path rather than assume that every
136
+ stored relation converged.
137
+
138
+ Stored relation definitions omit source `start`/`end` ranges and generated
139
+ boundary filters. Source ranges are on `meta[hash].origins[]`. Metadata entries
140
+ have `type: "code"`, `"rel"`, or `"pattern"`; origin entries do not have a
141
+ `kind` field. Pattern origins retain `params` and `aliasArgs` so repeated
142
+ variables and parameter routing survive loading and export.
143
+
144
+ Loading hydrates pattern graphs without reparsing source. Some backend paths
145
+ then specialize those graphs for an input envelope; that can involve further
146
+ derivation. See [architecture](ARCHITECTURE.md) for the distinction.
147
+
148
+ ## kVM artifacts
149
+
150
+ ```sh
151
+ node objects/compile.mjs '?{} {} |ok' /tmp/k-ok.kvm
152
+ node backends/wasm/bin/k-wasm-compile.mjs /tmp/k-ok.kvm /tmp/k-ok-from-kvm.wasm
153
+ node codecs/unit.mjs --parse |
154
+ node backends/wasm/bin/k-wasm-run.mjs /tmp/k-ok-from-kvm.wasm |
155
+ node codecs/k-print.mjs
504
156
  ```
505
157
 
506
- ### How to Consume
507
-
508
- - **Direct Execution with AccessTable:**
509
- ```javascript
510
- import {
511
- executePKIR,
512
- buildAccessTable,
513
- valueToKVal,
514
- kvalToValue
515
- } from "@fraczak/k/backend-api.mjs";
516
-
517
- const table = buildAccessTable(schemaS, patternP);
518
- const kval = valueToKVal(inputVal, table.rootState);
519
- const resKval = executePKIR(pkir, kval, table);
520
- const result = kvalToValue(resKval);
521
- ```
522
-
523
- - **Monomorphic Specialization (`specializePKIR`):**
524
- ```javascript
525
- import {
526
- specializePKIR,
527
- executePKIR
528
- } from "@fraczak/k/backend-api.mjs";
529
-
530
- // Inlines static byte offsets and prunes dead union branches:
531
- const specialized = specializePKIR(pkir, table);
532
-
533
- // Executes with zero table overhead:
534
- const result = executePKIR(specialized, kval, null);
535
- ```
536
-
537
- - **Lowering to WebAssembly (`compileWasmArtifactFromPKIR`):**
538
- ```javascript
539
- import {
540
- compileWasmArtifactFromPKIR
541
- } from "@fraczak/k/backend-api.mjs";
542
-
543
- const wasmBytes = await compileWasmArtifactFromPKIR(pkir);
544
- ```
545
- CLI commands:
546
- ```bash
547
- # Compile .pkir directly to WebAssembly binary:
548
- node backends/wasm/bin/k-wasm-compile.mjs input.pkir -o prog.wasm
549
-
550
- # Lower .k source via PKIR to WebAssembly:
551
- node backends/wasm/bin/k-wasm-compile.mjs --pkir prog.k -o prog.wasm
552
- ```
553
-
554
- - **Lowering to LLVM IR & Native Binaries:**
555
- ```javascript
556
- import {
557
- compileLLVMArtifactFromPKIR
558
- } from "@fraczak/k/backend-api.mjs";
559
- import {
560
- compilePKIRToExecutable,
561
- compilePKIRAndRun
562
- } from "@fraczak/k/backends/llvm/src/executable.mjs";
563
-
564
- // Compile PKIR directly to LLVM IR string:
565
- const llvmIR = compileLLVMArtifactFromPKIR(pkir);
566
-
567
- // Compile PKIR directly to a native executable:
568
- compilePKIRToExecutable(pkir, "./prog.exe");
569
-
570
- // Compile and execute in one step:
571
- const res = compilePKIRAndRun(pkir, { input: inputVal });
572
- ```
573
- CLI commands:
574
- ```bash
575
- # Compile .pkir directly to LLVM IR:
576
- node backends/llvm/bin/k-llvm-compile.mjs input.pkir -o prog.ll
577
-
578
- # Lower .k source via PKIR to LLVM IR:
579
- node backends/llvm/bin/k-llvm-compile.mjs --pkir prog.k -o prog.ll
580
-
581
- # Compile .pkir directly to native executable:
582
- node backends/llvm/bin/k-llvm-build.mjs input.pkir -o prog.exe
583
-
584
- # Lower .k source via PKIR to native executable:
585
- node backends/llvm/bin/k-llvm-build.mjs --pkir prog.k -o prog.exe
586
- ```
587
-
588
- ---
589
-
590
- ## Practical Rules & Common Gotchas
591
-
592
- ### 1. Library Aliases Require Explicit `--export`
593
- In `k`, relations and types are identified canonically by their
594
- content-addressed hashes (`@hash`). There is no global symbol namespace.
595
-
596
- Human-readable identifiers (such as `plus`, `int`, or `5`) are *aliases*
597
- stored in the object metadata (`relAlias`, `typeAliases`). When linking a
598
- library via `--lib math.klib`, all compiled relations are loaded under
599
- their canonical hashes, but their human-readable aliases are not
600
- automatically imported into the consumer's local alias scope.
601
-
602
- To use friendly names in an expression, explicitly map them into scope
603
- using `--export`:
604
- ```bash
605
- # Correct: imports 'plus', 'int', and '5' aliases into local scope:
606
- k-compile --lib math.klib \
607
- --export plus --export int --export 5 \
608
- '{() x, 5 int y} plus' add5.ko
609
-
610
- # Optional renaming syntax ('libAlias:localAlias'):
611
- k-compile --lib math.klib \
612
- --export plus:+ --export int --export 5 \
613
- '{() x, 5 int y}+' add5.ko
158
+ Compiler-emitted templates use `format: "k-vm"`, `version: 1`,
159
+ `layer: "KVM-P"`, and `isPolymorphic: true`. They retain relation contracts
160
+ and instruction streams for `specializeKVM` at invocation time. Specialized
161
+ artifacts use `layer: "KVM"`.
162
+
163
+ A `.ko` can be lowered to `.kvm`. A `.klib` alone has no entry relation:
164
+ link it into source with a main expression first. The compiler can copy a
165
+ `.klib` to another `.klib` path, but does not turn a library alone into an
166
+ executable object.
167
+
168
+ See [the kVM reference](KVM_EXECUTION_MODEL.md) for execution modes and instructions.
169
+
170
+ The `k-vm` CLI currently accepts source and executable objects, rather than
171
+ loading `.kvm` JSON artifacts directly. For example:
172
+
173
+ ```sh
174
+ node codecs/unit.mjs --parse | node kvm.mjs /tmp/k-ok.ko |
175
+ node codecs/k-print.mjs
614
176
  ```
615
- You can also reference any library relation directly by its canonical
616
- hash without `--export`.
617
-
618
- ### 2. No Built-in Numbers (Relations as Values)
619
- In `k`, there are no primitive numerical types or built-in integer
620
- literals. Identifiers such as `5` or `10` are not language keywords;
621
- they are defined relations (aliases) in `Examples/arithmetics.k`:
622
- - `5` and `10` are nullary relations (constants) of type `{} -> bits`,
623
- defined as binary digit trees over:
624
- `bits? = ?< {} _, bits? 0, bits? 1 > = bits?;`.
625
- - Arithmetic operations (`plus`, `minus`, `times`, `inc`) operate on
626
- signed integers:
627
- `int? = ?< <bits 0, bits 1, {} _>=bits "+", bits "-" >`.
628
- - Passing a bit-representation like `5` to an integer relation requires
629
- applying the `int` constructor (`5 int`), producing a constant
630
- relation of type `{} -> int`.
631
-
632
- ### 3. Constant Expressions vs. Stream Transformers
633
- - **Stream Transformers:** An expression using the identity relation `()`
634
- (such as `{() x, 5 int y} plus`) depends on external input. It reads
635
- an enveloped value from `stdin` (here, a signed integer decoded via
636
- `./codecs/int.mjs --parse`).
637
- - **Closed Constant Relations:** A relation with no free inputs (such
638
- as `{10 int x, 5 int y} plus`) is a constant relation with input
639
- type of unit `{}`. When executed through `./k.mjs`, it expects
640
- an empty unit `{}` on `stdin`:
641
- ```bash
642
- echo "{}" | node codecs/k-parse.mjs | \
643
- ./k.mjs add_constants.ko | ./codecs/int.mjs --print
644
- ```
177
+
178
+ ## PKIR and targets
179
+
180
+ [PKIR](POLYMORPHIC_IR.md) is a separate experimental execution representation.
181
+ `compileRelationToPKIR` in `backend-api.mjs` creates a relation artifact;
182
+ `executePKIR` interprets it and `specializePKIR` resolves layout accesses.
183
+
184
+ The backend compile commands accept `.pkir` input, or `--pkir` when compiling
185
+ source through that path. They also accept source, executable objects, and kVM
186
+ programs. A library still needs an entry relation.
187
+
188
+ See the [WebAssembly](../backends/wasm/README.md) and
189
+ [LLVM](../backends/llvm/README.md) guides for target compilation and execution.