@fraczak/k 8.4.1 → 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.
- package/CHANGELOG.md +17 -0
- package/DOCS/ARCHITECTURE.md +83 -0
- package/DOCS/CODECS.md +93 -204
- package/DOCS/DICTIONARY.md +42 -1241
- package/DOCS/FILE_FORMATS.md +170 -625
- package/DOCS/GETTING_STARTED.md +164 -0
- package/DOCS/KIR_V1.md +22 -33
- package/DOCS/KVM_EXECUTION_MODEL.md +88 -481
- package/DOCS/PATTERNS.md +155 -138
- package/DOCS/POLYMORPHIC_IR.md +83 -101
- package/DOCS/PROFILING_AND_TRACING.md +52 -166
- package/DOCS/README.md +35 -0
- package/DOCS/REPL.md +100 -377
- package/DOCS/TEXTUAL_VALUES.md +53 -81
- package/DOCS/TYPE_DERIVATION.md +95 -234
- package/DOCS/book-combined.md +3786 -0
- package/Examples/arithmetics.k +45 -59
- package/Examples/djson.k +102 -112
- package/Examples/karatsuba-mult.k +2 -3
- package/Examples/list.k +6 -7
- package/Examples/nat.k +6 -6
- package/Examples/poly.k +45 -45
- package/LICENSE +15 -0
- package/README.md +72 -410
- package/backends/llvm/README.md +75 -97
- package/backends/wasm/README.md +88 -66
- package/canonical-pattern.mjs +7 -3
- package/codecs/README.md +23 -261
- package/codecs/WIRE_FORMAT.md +132 -0
- package/core.k +5 -15
- package/named-patterns.mjs +19 -7
- package/objects/README.md +24 -109
- package/package.json +8 -3
- package/paper/Makefile +17 -0
- package/paper/k-paper.pdf +0 -0
- package/paper/k-paper.tex +435 -0
- package/parser.jison +0 -10
- package/parser.mjs +32 -43
- package/repl.mjs +74 -29
- package/scripts/benchmark-idempotency.mjs +3 -3
- package/scripts/run-tests.mjs +1 -1
- package/scripts/test-package.mjs +64 -0
- package/tests/README.md +66 -46
- package/tests/code-derivation/core.mjs +61 -0
- package/tests/helpers/cli.mjs +45 -0
- package/tests/integration.sh +2 -3
- package/tests/test-arithmetics.mjs +47 -237
- package/tests/test-djson-methods.mjs +71 -275
- package/tests/test-hash-normalization.mjs +22 -1
- package/tests/test-karatsuba.mjs +18 -126
- package/tests/test-named-patterns.mjs +174 -621
- package/tests/test-paper-examples.mjs +90 -0
- package/tests/test-poly.mjs +2 -2
- package/tests/test-repl-html.mjs +2 -2
- package/tests/test-repl.mjs +49 -41
- package/tests/test.mjs +27 -68
- package/AGENTS.md +0 -35
- package/CLAUDE.md +0 -64
- package/DOCS/BIG_PICTURE.md +0 -439
- package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
- package/DOCS/CANONICAL_PATTERNS.md +0 -362
- package/DOCS/CODEC_ARCHITECTURE.md +0 -257
- package/DOCS/CONVERGENCE.md +0 -123
- package/DOCS/DIVERGENCE_DETECTION.md +0 -23
- package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
- package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
- package/DOCS/Makefile +0 -99
- package/DOCS/NAMED_PATTERNS.md +0 -361
- package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
- package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
- package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -134
- package/DOCS/book/01-introduction.md +0 -48
- package/DOCS/book/02-syntax-and-values.md +0 -110
- package/DOCS/book/03-types-as-finite-automata.md +0 -155
- package/DOCS/book/04-partial-functions-and-composition.md +0 -145
- package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
- package/DOCS/book/06-values-in-memory.md +0 -1085
- package/DOCS/book/07-the-partial-function-abi.md +0 -143
- package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
- package/DOCS/book/09-compiler-architecture.md +0 -160
- package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
- package/DOCS/book/14-canonical-serialization.md +0 -176
- package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
- package/DOCS/book/overview.txt +0 -68
- package/DOCS/book.md +0 -50
- package/Examples/bnat.k +0 -308
- package/Examples/buda.k +0 -66
- package/Examples/byte.k +0 -35
- package/Examples/code.k +0 -43
- package/Examples/vhdl_to_k.k +0 -67
- package/JOURNAL.md +0 -288
- package/TODO.md +0 -107
- package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
- package/backends/wasm/TECHNICAL-DEBT.md +0 -58
- package/backends/wasm/demo_ieee.mjs +0 -318
- package/browser/vfs-data.mjs +0 -21
- package/codecs/BINARY_FORMAT.md +0 -53
- package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
- package/codecs/pandoc.css +0 -71
- package/tests/code-derivation/blowup.mjs +0 -25
- package/tests/code-derivation/bnat.mjs +0 -11
- package/tests/code-derivation/dot.mjs +0 -37
- package/tests/code-derivation/index.mjs +0 -20
- package/tests/code-derivation/loop.mjs +0 -17
- package/tests/code-derivation/nat.mjs +0 -10
- package/tests/code-derivation/not-not.mjs +0 -14
- package/tests/code-derivation/product.mjs +0 -22
- package/tests/code-derivation/rlz.mjs +0 -13
- package/tests/test-fingerprint.mjs +0 -38
package/DOCS/FILE_FORMATS.md
CHANGED
|
@@ -1,644 +1,189 @@
|
|
|
1
|
-
# File
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
|
14
|
-
|
|
15
|
-
|
|
|
16
|
-
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
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
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
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
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
:
|
|
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
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
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
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
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
|
-
|
|
456
|
-
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
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
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
-
|
|
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
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
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.
|