@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.
Files changed (109) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/DOCS/ARCHITECTURE.md +83 -0
  3. package/DOCS/CODECS.md +93 -204
  4. package/DOCS/DICTIONARY.md +42 -1241
  5. package/DOCS/FILE_FORMATS.md +170 -625
  6. package/DOCS/GETTING_STARTED.md +164 -0
  7. package/DOCS/KIR_V1.md +22 -33
  8. package/DOCS/KVM_EXECUTION_MODEL.md +88 -481
  9. package/DOCS/PATTERNS.md +155 -138
  10. package/DOCS/POLYMORPHIC_IR.md +83 -101
  11. package/DOCS/PROFILING_AND_TRACING.md +52 -166
  12. package/DOCS/README.md +35 -0
  13. package/DOCS/REPL.md +100 -377
  14. package/DOCS/TEXTUAL_VALUES.md +53 -81
  15. package/DOCS/TYPE_DERIVATION.md +95 -234
  16. package/DOCS/book-combined.md +3786 -0
  17. package/Examples/arithmetics.k +45 -59
  18. package/Examples/djson.k +102 -112
  19. package/Examples/karatsuba-mult.k +2 -3
  20. package/Examples/list.k +6 -7
  21. package/Examples/nat.k +6 -6
  22. package/Examples/poly.k +45 -45
  23. package/LICENSE +15 -0
  24. package/README.md +72 -410
  25. package/backends/llvm/README.md +75 -97
  26. package/backends/wasm/README.md +88 -66
  27. package/canonical-pattern.mjs +7 -3
  28. package/codecs/README.md +23 -261
  29. package/codecs/WIRE_FORMAT.md +132 -0
  30. package/core.k +5 -15
  31. package/named-patterns.mjs +19 -7
  32. package/objects/README.md +24 -109
  33. package/package.json +8 -3
  34. package/paper/Makefile +17 -0
  35. package/paper/k-paper.pdf +0 -0
  36. package/paper/k-paper.tex +435 -0
  37. package/parser.jison +0 -10
  38. package/parser.mjs +32 -43
  39. package/repl.mjs +74 -29
  40. package/scripts/benchmark-idempotency.mjs +3 -3
  41. package/scripts/run-tests.mjs +1 -1
  42. package/scripts/test-package.mjs +64 -0
  43. package/tests/README.md +66 -46
  44. package/tests/code-derivation/core.mjs +61 -0
  45. package/tests/helpers/cli.mjs +45 -0
  46. package/tests/integration.sh +2 -3
  47. package/tests/test-arithmetics.mjs +47 -237
  48. package/tests/test-djson-methods.mjs +71 -275
  49. package/tests/test-hash-normalization.mjs +22 -1
  50. package/tests/test-karatsuba.mjs +18 -126
  51. package/tests/test-named-patterns.mjs +174 -621
  52. package/tests/test-paper-examples.mjs +90 -0
  53. package/tests/test-poly.mjs +2 -2
  54. package/tests/test-repl-html.mjs +2 -2
  55. package/tests/test-repl.mjs +49 -41
  56. package/tests/test.mjs +27 -68
  57. package/AGENTS.md +0 -35
  58. package/CLAUDE.md +0 -64
  59. package/DOCS/BIG_PICTURE.md +0 -439
  60. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  61. package/DOCS/CANONICAL_PATTERNS.md +0 -362
  62. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  63. package/DOCS/CONVERGENCE.md +0 -123
  64. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  65. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  66. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  67. package/DOCS/Makefile +0 -99
  68. package/DOCS/NAMED_PATTERNS.md +0 -361
  69. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  70. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  71. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -134
  72. package/DOCS/book/01-introduction.md +0 -48
  73. package/DOCS/book/02-syntax-and-values.md +0 -110
  74. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  75. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  76. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  77. package/DOCS/book/06-values-in-memory.md +0 -1085
  78. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  79. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  80. package/DOCS/book/09-compiler-architecture.md +0 -160
  81. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  82. package/DOCS/book/14-canonical-serialization.md +0 -176
  83. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  84. package/DOCS/book/overview.txt +0 -68
  85. package/DOCS/book.md +0 -50
  86. package/Examples/bnat.k +0 -308
  87. package/Examples/buda.k +0 -66
  88. package/Examples/byte.k +0 -35
  89. package/Examples/code.k +0 -43
  90. package/Examples/vhdl_to_k.k +0 -67
  91. package/JOURNAL.md +0 -288
  92. package/TODO.md +0 -107
  93. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  94. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  95. package/backends/wasm/demo_ieee.mjs +0 -318
  96. package/browser/vfs-data.mjs +0 -21
  97. package/codecs/BINARY_FORMAT.md +0 -53
  98. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  99. package/codecs/pandoc.css +0 -71
  100. package/tests/code-derivation/blowup.mjs +0 -25
  101. package/tests/code-derivation/bnat.mjs +0 -11
  102. package/tests/code-derivation/dot.mjs +0 -37
  103. package/tests/code-derivation/index.mjs +0 -20
  104. package/tests/code-derivation/loop.mjs +0 -17
  105. package/tests/code-derivation/nat.mjs +0 -10
  106. package/tests/code-derivation/not-not.mjs +0 -14
  107. package/tests/code-derivation/product.mjs +0 -22
  108. package/tests/code-derivation/rlz.mjs +0 -13
  109. package/tests/test-fingerprint.mjs +0 -38
@@ -1,361 +0,0 @@
1
- # Named Patterns and Parameterized Type Schemes in k
2
-
3
- ## 1. Overview and Motivation
4
-
5
- Following commit `a4eec258`, type code expressions (`$ code`) were
6
- removed in favor of pure filter relations (`? <...> = Self;`).
7
- While this eliminated the redundant dual syntax of static codes versus
8
- runtime filters, practical development (notably in `djson` variants and
9
- standard libraries) revealed a major drawback: **loss of pattern
10
- composition and reuse**.
11
-
12
- Without named, reusable patterns:
13
- - Monolithic structures (such as UTF-8 decoding and IEEE-754 bit
14
- partitions) had to be copy-pasted inline across dozens of files.
15
- - Common algebraic shapes like linked lists, pairs, dictionaries, and
16
- tries could not be defined generically; each variant had to inline
17
- its own structural definition.
18
- - Filter relations (`rel?(x)`) perform runtime filtering but cannot be
19
- used directly as structural type shapes inside other pattern
20
- definitions.
21
-
22
- This document establishes the specification for **Named Patterns**:
23
- parameterized, compositional regular tree grammar templates that re-enable
24
- reusable type definitions with zero syntax bloat, guaranteed
25
- termination, and full integration with k's graph-based type system.
26
-
27
- ---
28
-
29
- ## 2. The Core Model: Patterns as Open Directed Graphs
30
-
31
- In k, all values, patterns, and type codes are directed graphs
32
- representing regular tree languages. A named pattern definition:
33
-
34
- ```k
35
- name[ P1, P2, ... Pn ] = pattern_graph;
36
- ```
37
-
38
- defines an **open directed graph** with an explicit boundary interface.
39
-
40
- ### 2.1 The Three Classes of Variables
41
-
42
- Within a pattern definition, every variable identifier falls into one
43
- of three orthogonal categories:
44
-
45
- 1. **External Ports ($\forall$ / Parameters)**:
46
- Any variable listed in the header brackets `[ P1, ... Pn ]` is an
47
- **external port**. These represent open inputs to be supplied by the
48
- caller upon instantiation.
49
-
50
- 2. **Internal Variables ($\exists$ / Unification Nodes)**:
51
- Any variable appearing on the right-hand side that is **not** listed
52
- in `[ P1, ... Pn ]` is an **internal variable**.
53
- - If an internal variable appears in multiple locations, it asserts
54
- **structural type equality (unification)** between those sites.
55
- - Internal variables are existentially quantified ($\exists$) and
56
- scoped strictly to the pattern definition.
57
-
58
- 3. **Cycle Knots ($\mu$ / Fixpoints)**:
59
- Any variable bound via `= KnotName` is an internal recursive knot.
60
- It creates a back-edge in the directed graph, closing a loop.
61
- Its scope is purely local: callers cannot see or reference it.
62
-
63
- ### 2.2 Knot and Variable Hiding ($\alpha$-Equivalence)
64
-
65
- In:
66
-
67
- ```k
68
- list[X] = < {}nil, { X car, Y cdr } cons > = Y;
69
- ```
70
-
71
- - `X` is listed in `list[X]` $\implies$ **External Port**.
72
- - `Y` is bound by `= Y` and omitted from `list[X]` $\implies$
73
- **Internal Knot**.
74
-
75
- `Y` is strictly encapsulated. It can be $\alpha$-renamed to any
76
- internal node ID (`#knot_0`) without changing the pattern's external
77
- interface or behavior. Callers only interact with the port `X`.
78
-
79
- ---
80
-
81
- ## 3. The Four-Bracket Symmetry of k
82
-
83
- Named patterns introduce square brackets `[...]` into k's grammar.
84
- This completes an orthogonal four-bracket architecture where each
85
- bracket style has a dedicated, non-overlapping semantic domain:
86
-
87
- | Bracket Pair | Semantic Domain | Concrete Purpose |
88
- | :--- | :--- | :--- |
89
- | **`{ ... }`** | **Products** | Records, tuples, structs |
90
- | **`< ... >`** | **Unions** | Variants, sums, choices |
91
- | **`( ... )`** | **Relations** | Composition, grouping, identity |
92
- | **`[ ... ]`** | **Patterns** | Type templates, instantiations |
93
-
94
- No dollar prefix (`$`) is needed anywhere in the language.
95
-
96
- ### 3.1 Unambiguous Lexical Distinction
97
-
98
- Because all pattern references carry `[...]`, the lexical distinction
99
- between variables and patterns is 100% deterministic:
100
-
101
- - **Identifier without `[...]`** (`X`, `T`, `car`, `Y`):
102
- - In label position: field or variant tag (`car`, `cdr`, `nil`).
103
- - In pattern position: variable node (`X`, `T`, knot `Y`).
104
- - **Identifier with `[...]`** (`bit[]`, `list[T]`, `pair[A, B]`):
105
- - Always a pattern template lookup or instantiation.
106
-
107
- ### 3.2 Undefined Pattern Application Prohibition
108
-
109
- An identifier with `[...]` (e.g. `missing[]` or `dict[K, V]`) **must**
110
- refer to a defined pattern template in scope or in an imported library.
111
-
112
- - An undefined pattern application is a compile-time error
113
- (`Unknown pattern template 'missing[]'`).
114
- - An undefined pattern application is **never** silently converted into
115
- a variable or open leaf slot (`X0`, `X1`, etc.).
116
- - Identifiers intended as existential type variables must appear
117
- without brackets (e.g. `T` or `X`).
118
-
119
- ---
120
-
121
- ## 4. Internal Variables as Unification Knots
122
-
123
- A critical insight of k's graph-based model is that unparameterized
124
- patterns can contain internal variables to express equality
125
- constraints across fields:
126
-
127
- ```k
128
- byte[] = { bit 0, bit 1, ... };
129
- ```
130
-
131
- Here:
132
- - `bit` does not have `[]`, so it is a **variable**, not a pattern.
133
- - `bit` is not in the parameter list `byte[]`, so it is an **internal
134
- node**.
135
- - Because `bit` appears at both field `0` and field `1`, it asserts
136
- that **field `0` and field `1` must share the exact same type**,
137
- without constraining what that type must be.
138
-
139
- ### 4.1 Comparison of Pattern Declarations
140
-
141
- ```k
142
- -- 1. Homogeneous pair of two fields of the SAME arbitrary type:
143
- same_pair[] = { T first, T second };
144
-
145
- -- 2. Heterogeneous pair parameterized by the caller:
146
- pair[A, B] = { A first, B second };
147
-
148
- -- 3. Pair of concrete bits:
149
- bit_pair[] = { bit[] first, bit[] second };
150
-
151
- -- 4. Instantiation enforcing equality via shared variable:
152
- diagonal_pair[] = pair[T, T];
153
- ```
154
-
155
- In `diagonal_pair[] = pair[T, T]`:
156
- - `T` is an internal variable.
157
- - Instantiating `pair` with `T` for both arguments unifies both ports,
158
- producing a closed pattern requiring equal elements.
159
-
160
- ---
161
-
162
- ## 5. Instantiation Semantics (Option B)
163
-
164
- Arguments inside `[...]` may be either **variables** or **patterns**:
165
-
166
- 1. **Passing a Variable (`T`, `X`)**:
167
- Connects the template's input port directly to that existing node in
168
- the pattern graph, enabling node sharing, unification, and
169
- polymorphic relations.
170
-
171
- 2. **Passing an Inline Pattern (`int[]`, `pair[K, V]`, `<{}0, {}1>`)**:
172
- Creates an anonymous node representing the pattern and connects the
173
- input port to it.
174
-
175
- ### 5.1 Equivalence to Variable Binding
176
-
177
- Passing an inline pattern `P` is semantically equivalent to introducing
178
- a fresh internal node variable:
179
-
180
- $$name[P] \;\;\Longleftrightarrow\;\; (P = \_anon) \; name[\_anon]$$
181
-
182
- Both forms construct isomorphic graph structures that minimize to the
183
- exact same canonical DFA representation in `codes.mjs`.
184
-
185
- ### 5.2 Single-Step Finite Graph Substitution
186
-
187
- Because recursive cycles are closed internally via knots (`= Y`),
188
- instantiating a template does **not** require recursive unrolling or
189
- fixpoint searching.
190
-
191
- Instantiation is a single-step graph substitution:
192
- 1. Copy the template's graph structure (fresh private IDs for internal
193
- knots).
194
- 2. Substitute the caller's arguments into the designated open port nodes.
195
- 3. Minimize via Hopcroft/Moore DFA partition refinement in `codes.mjs`.
196
-
197
- ---
198
-
199
- ## 6. Safety Invariants and Termination
200
-
201
- To guarantee decidability and termination:
202
-
203
- 1. **Acyclic Template Dependency Rule**:
204
- A pattern template `$ name[...]` cannot reference `name` in its own
205
- definition.
206
- - All recursion **must** be expressed through internal knots (`= Y`).
207
- - Consequently, the template dependency graph is a Strictly Acyclic
208
- Directed Graph (DAG).
209
- - Non-regular polymorphic recursion (nested datatypes) is structurally
210
- impossible, guaranteeing that every instantiated pattern is a
211
- finite regular tree automaton.
212
-
213
- 2. **Lexical Scope Independence**:
214
- Internal variable names and knot names are strictly private to each
215
- definition. Two patterns may both use knot name `Y` or variable `T`
216
- without collision.
217
-
218
- 3. **Canonical Confluence**:
219
- In k, type codes are structural, not nominal. Any two instantiations
220
- that yield isomorphic regular tree automata produce identical
221
- canonical hashes and wire encoders.
222
-
223
- 4. **Canonical Form and REPL Decompilation**:
224
- In the interactive REPL, inspecting a pattern via `:pattern <name>`
225
- (or `:pat <name>`) displays its **canonical definition** rather than
226
- the source syntax used to define it:
227
- - User-defined parameter names (`A`, `B`, `X`) and knot names (`Y`,
228
- `T`) are erased.
229
- - The canonical decompiler introduces fresh variables (`X0`, `X1`,
230
- `X2`, ...) in deterministic traversal (discovery) order.
231
- - Open type ports are introduced in the pattern header (`name[...]`)
232
- in order of discovery:
233
- ```k
234
- -- pair[A, B] = { A first, B second };
235
- pair[X0, X1] = {X0 first, X1 second}; -- @...
236
-
237
- -- list[X] = < {} nil, { X car, Y cdr } cons > = Y;
238
- list[X1] = <{X1 car, X0 cdr} cons, {} nil>=X0; -- @...
239
-
240
- -- same_pair[T] = { T first, T second };
241
- same_pair[X0] = {X0 first, X0 second}; -- @...
242
- ```
243
- - Two syntactically different definitions yielding isomorphic
244
- automata produce the exact same canonical definition and hash.
245
-
246
- 5. **Eager Definition-Time Validation**:
247
- All pattern definitions are strictly validated at script/module
248
- compilation time, even if no relation in the file references them:
249
- - Undefined template lookups raise `Unknown pattern template`.
250
- - Mutually recursive template definitions raise
251
- `Cyclic pattern template dependency detected`.
252
- - Arity mismatches raise
253
- `Pattern '...' expects N parameters, got M`.
254
-
255
- ---
256
-
257
- ## 7. Concrete Library Examples
258
-
259
- ### 7.1 Core Data Types
260
-
261
- ```k
262
- -- Canonical bit and bit-path numbers:
263
- bit[] = < {}0, {}1 >;
264
- bits[] = < {} _, B 0, B 1 > = B;
265
-
266
- -- Byte as an 8-bit octet product:
267
- byte[] = {
268
- bit[] 0, bit[] 1, bit[] 2, bit[] 3,
269
- bit[] 4, bit[] 5, bit[] 6, bit[] 7
270
- };
271
-
272
- -- 7-bit ASCII code points:
273
- ascii[] = {
274
- bit[] 6, bit[] 5, bit[] 4, bit[] 3,
275
- bit[] 2, bit[] 1, bit[] 0
276
- };
277
- ```
278
-
279
- ### 7.2 Generic Data Structures
280
-
281
- ```k
282
- -- Generic pair:
283
- pair[A, B] = { A fst, B snd };
284
-
285
- -- Generic singly-linked list:
286
- list[X] = < {}nil, { X car, Y cdr } cons > = Y;
287
-
288
- -- Generic dictionary:
289
- dict[K, V] = list[pair[K, V]];
290
-
291
- -- Generic binary tree with internal knot T:
292
- tree[X] = < {}nil, { X val, T left, T right } node > = T;
293
- ```
294
-
295
- ### 7.3 Usage in Relations
296
-
297
- ```k
298
- -- Type guard filter:
299
- int? = ? int[];
300
-
301
- -- Polymorphic list destructuring with type unification:
302
- head = ? { X car, list[X] cdr } X;
303
-
304
- -- Concrete typed list destructuring:
305
- sum = ? { int[] = T car, list[T] cdr } ...;
306
-
307
- -- Anonymous pattern matching:
308
- validate_ints = ? list[int[]];
309
- ```
310
-
311
- ---
312
-
313
- ## 8. Summary of Grammar Extensions
314
-
315
- ### 8.1 Lexer Tokens
316
-
317
- ```
318
- "[" return 'LB';
319
- "]" return 'RB';
320
- ```
321
-
322
- ### 8.2 Top-Level Definitions
323
-
324
- ```
325
- defs
326
- : /* empty */
327
- | defs name eq comp sc
328
- | defs name lb pattern_params rb eq filter sc
329
- ;
330
-
331
- pattern_params
332
- : /* empty */
333
- | non_empty_pattern_params
334
- ;
335
-
336
- non_empty_pattern_params
337
- : name
338
- | non_empty_pattern_params comma name
339
- ;
340
- ```
341
-
342
- ### 8.3 Pattern References and Instantiations
343
-
344
- ```
345
- filter_
346
- : lp dots rp
347
- | la labelled_filters ra
348
- | lc labelled_filters rc
349
- | name lb pattern_args rb
350
- ;
351
-
352
- pattern_args
353
- : /* empty */
354
- | non_empty_pattern_args
355
- ;
356
-
357
- non_empty_pattern_args
358
- : filter
359
- | non_empty_pattern_args comma filter
360
- ;
361
- ```
@@ -1,343 +0,0 @@
1
- # Object File And Pattern Type
2
-
3
- This note records the representation boundary after parsing and type derivation.
4
- The codec boundary is no longer a JSON object. A serialized value is one binary
5
- stream:
6
-
7
- ```text
8
- encode(pattern_value : pattern) encode(value : decoded_pattern)
9
- ```
10
-
11
- The pattern is the framing protocol. There is no separate envelope type.
12
-
13
- ## Pattern Schema
14
-
15
- [`core.k`](../core.k) defines the canonical self-hosted pattern type:
16
-
17
- ```k
18
- edge? = ?{ string? label, bits? target };
19
- edges? = ?< {} nil, { edge? car, E cdr } cons > = E;
20
-
21
- pattern-node? = ?<
22
- {} any,
23
- edges? open-product,
24
- edges? open-union,
25
- edges? closed-product,
26
- edges? closed-union
27
- >;
28
-
29
- pattern? = ?< {} nil, { pattern-node? car, P cdr } cons > = P;
30
- ```
31
-
32
- This does not mean `core.k` is pre-loaded into ordinary program execution. The
33
- special role of `core.k` here is that the wire codec relies on the canonical
34
- `pattern` definition from that file.
35
-
36
- In this schema:
37
-
38
- - the first pattern-list element is node `0`, the root,
39
- - an edge target is a node index encoded as `bits`,
40
- - labels are `string` values and therefore Unicode scalar-value strings,
41
- - edge lists are sorted by label,
42
- - `any` carries no edges,
43
- - the four product/union node kinds carry their edge list directly.
44
-
45
- The fixed singleton pattern of `pattern` is the first decoder context for all
46
- k wire values. Decoding any value first decodes a `pattern` value under that
47
- constant, then decodes the remaining bits under the pattern just obtained.
48
-
49
- ## Debug Notation
50
-
51
- Documentation and tests often show patterns as property-list JSON because it is
52
- compact to read:
53
-
54
- ```json
55
- [
56
- ["open-union", [["a", 1]]],
57
- ["closed-product", [["b", 2], ["c", 3]]],
58
- ["open-union", [["x", 3]]],
59
- ["closed-product", []]
60
- ]
61
- ```
62
-
63
- That notation is not a transport format. It is only a host-side rendering of
64
- the same abstract graph.
65
-
66
- ## Object File Direction
67
-
68
- The parser plus type-derivation phase should eventually emit an object value
69
- rather than executable JavaScript structures. A minimal first object shape is:
70
-
71
- ```k
72
- object-file = ?{
73
- pattern input-pattern,
74
- pattern output-pattern,
75
- pattern value-pattern
76
- };
77
- ```
78
-
79
- The concrete input payload is then stored in the same binary stream form:
80
- `encode(value-pattern) encode(input : value-pattern)`. The exact object-file
81
- type still needs design work because the concrete input value is typed by the
82
- decoded pattern. The important boundary is that object files should carry
83
- ordinary k values and patterns, not a JSON codec object.
84
-
85
- The format can add relation IR, constant tables, symbol dictionaries,
86
- relocation/linking records, optimization metadata, and optional indexes as the
87
- implementation changes.
88
-
89
- ## Object And Library Containers
90
-
91
- For a comprehensive specification of all file types, see
92
- [`DOCS/FILE_FORMATS.md`](./FILE_FORMATS.md).
93
-
94
- Both `.ko` and `.klib` are ahead-of-time (AOT) type-checked artifacts.
95
- In `k`, ahead-of-time type checking means parsing, relation expansion,
96
- structural type derivation, and constraint convergence are performed
97
- beforehand during compilation. The resulting artifact stores fully
98
- converged principal pattern graphs, allowing downstream execution to
99
- bypass cold-start type derivation.
100
-
101
- All relations and types are identified canonically by immutable
102
- content-addressed hashes (`@hash`). There is no global symbol namespace;
103
- human-readable names are local aliases recorded in `relAlias` and
104
- `typeAliases` metadata.
105
-
106
- The executable `.ko` format is a small binary container:
107
-
108
- ```text
109
- "KOBJ" 0x0a
110
- uint32-be payload-byte-length
111
- utf8-json-payload
112
- ```
113
-
114
- Library files (`.klib`) are plain UTF-8 JSON with no binary header.
115
-
116
- Both containers use the same JSON payload shape. Executable `.ko` files
117
- set `main` to the entry relation name (usually `"__main__"`). Library
118
- `.klib` files set `main` to `null`. There is no payload version field.
119
-
120
- The payload stores:
121
-
122
- - the normalized code repository needed by the object,
123
- - the compiled relation IR without generated boundary filters,
124
- - each relation's type-pattern graph state,
125
- - each relation's `typeDerivation.status`,
126
- - relation aliases in `relAlias`,
127
- - pattern aliases in `patternAlias`,
128
- - deduplicated canonical pattern ASTs in `patterns`,
129
- - compiler convergence details in top-level `compileStats`,
130
- - metadata (`meta`), including aliases, origin source locations, and
131
- pattern parameter routing vectors (`aliasArgs`),
132
- - the main relation name.
133
-
134
- Relation `def` values do not store source `start` / `end` markers. Source
135
- locations live on `meta[hash].origins[]` entries. Each metadata entry has
136
- `type: "code"`, `type: "rel"`, or `type: "pattern"`. Origin entries hold
137
- `source`, `name`, `compiledAt`, optional `start` / `end`, and for
138
- patterns, `params` and `aliasArgs` (recording parameter routing and
139
- diagonalization). Origin entries do not have `kind`.
140
-
141
- For complete details on canonical pattern skeletons, alias argument
142
- routing, and object reflection, see
143
- [`DOCS/CANONICAL_PATTERNS.md`](./CANONICAL_PATTERNS.md).
144
-
145
- Relation `def` values also do not store generated input/output filters.
146
- Those filters are derived from `def.patterns` and `typePatternGraph` when
147
- printing or enforcing relation boundaries.
148
-
149
- Codes/types do not carry `typeDerivation`. Type derivation is a relation
150
- property, and the persisted `typeDerivation` object currently contains
151
- only `status`.
152
-
153
- Loading an object hydrates the type-pattern graphs back into runtime
154
- `TypePatternGraph` instances and executes relation boundaries through
155
- `run.mjs`. This avoids source parsing and type derivation on the
156
- execution path.
157
-
158
- Object execution through `k.mjs`:
159
-
160
- ```sh
161
- echo "..." | some-codec --parse | \
162
- k path/to/program.ko | some-codec --print
163
- ```
164
-
165
- When the first positional argument names an existing file, `k.mjs`
166
- loads it as either an object file or a source `.k` file. It tries to load
167
- the file as an object first, then falls back to source parsing and
168
- compilation.
169
-
170
- Standalone helpers live in `objects/`:
171
-
172
- ```sh
173
- k-compile path/to/program.k path/to/program.ko
174
- k-compile path/to/library.k path/to/library.klib
175
- k-compile --format kvm path/to/program.k path/to/program.kvm
176
- k-decompile path/to/program.ko path/to/program.decompiled.k
177
- k-extract-aliases path/to/library.klib path/to/aliases.k
178
- ```
179
-
180
- `k-compile` also accepts inline source snippets. With no arguments,
181
- the helpers read from stdin and write to stdout:
182
-
183
- ```sh
184
- k-compile 'x = |x; x x' > path/to/program.ko
185
- cat path/to/program.k | k-compile > path/to/program.ko
186
- cat path/to/program.ko | k-decompile > path/to/program.decompiled.k
187
- ```
188
-
189
- The decompiled source is canonical source regenerated from object IR. It uses
190
- shortest unique prefixes of the object's hash-based names for type and relation
191
- definitions, with a minimum prefix length of `4`. It is intended to be runnable
192
- and inspectable, not a byte-for-byte reconstruction of the original source.
193
-
194
- ## Small Object Example
195
-
196
- For a tiny source file:
197
-
198
- ```k
199
- -- id.k
200
- ()
201
- ```
202
-
203
- compile it with:
204
-
205
- ```sh
206
- k-compile id.k id.ko
207
- ```
208
-
209
- The first bytes of `id.ko` are the binary container header:
210
-
211
- ```text
212
- 4b 4f 42 4a 0a 00 00 03 0b ...
213
- K O B J \n payload-length
214
- ```
215
-
216
- After the header, the payload is UTF-8 JSON. Pretty-printed and shortened, the
217
- payload has this shape:
218
-
219
- ```json
220
- {
221
- "format": "k-object",
222
- "codes": {},
223
- "main": "__main__",
224
- "rels": {
225
- "__main__": {
226
- "def": { "op": "identity", "patterns": [0, 0] },
227
- "typeDerivation": {
228
- "status": "converged"
229
- },
230
- "typePatternGraph": {
231
- "patterns": {
232
- "nodes": [{ "pattern": "(...)", "fields": [] }],
233
- "parent": []
234
- },
235
- "edges": [{}],
236
- "codeId": {}
237
- }
238
- }
239
- },
240
- "relAlias": { "__main__": "@QfyLpmn56wuppuGvrrUJz8LKtgaXfbMtad7RnzBcFk2S" },
241
- "compileStats": { "sccs": [...], "sccCount": 1 },
242
- "meta": {
243
- "@QfyLpmn56wuppuGvrrUJz8LKtgaXfbMtad7RnzBcFk2S": {
244
- "type": "rel",
245
- "origins": [
246
- {
247
- "source": "id.k",
248
- "name": "__main__",
249
- "compiledAt": "2026-05-20T00:00:00.000Z",
250
- "start": { "line": 1, "column": 1 },
251
- "end": { "line": 1, "column": 3 }
252
- }
253
- ]
254
- }
255
- }
256
- }
257
- ```
258
-
259
- The `codes` field is the type repository snapshot needed by this object. The
260
- `rels.__main__.def` field is the executable relation body. The
261
- `typePatternGraph` field is the compiled pattern graph used by `run.mjs` for
262
- relation-boundary refinement. Loading the object reconstructs live
263
- `TypePatternGraph` instances from this JSON state and then evaluates the input
264
- value against the compiled IR.
265
-
266
- Decompiling this object produces canonical source with generated prefix names:
267
-
268
- ```k
269
- ----- codes -----
270
- ----- rels -----
271
- QfyL = ?(...) () ?(...);
272
- ----- main -----
273
- ?(...) QfyL ?(...)
274
- ```
275
-
276
- In the `rels` section, relation definitions are printed in the same SCC order
277
- recorded during compilation. Non-empty SCC groups are separated by a blank line.
278
-
279
- ## Small Library Example
280
-
281
- For a definitions-only source file:
282
-
283
- ```k
284
- -- defs.k
285
- nat? = ?< {} zero, N succ > = N;
286
- succ = |succ;
287
- ```
288
-
289
- compile it with:
290
-
291
- ```sh
292
- k-compile defs.k defs.klib
293
- ```
294
-
295
- The output file is plain JSON and starts with `{`, not a binary prefix. Its
296
- shape is the same object payload shape with `main: null`:
297
-
298
- ```json
299
- {
300
- "format": "k-object",
301
- "codes": {
302
- "@...": {
303
- "code": "union",
304
- "union": { "zero": "@...", "succ": "@..." },
305
- "def": "$C0=<C1\"succ\",C2\"zero\">;..."
306
- }
307
- },
308
- "rels": {
309
- "@...": {
310
- "def": { "op": "vid", "vid": "succ", "patterns": [0, 1] },
311
- "typeDerivation": { "status": "converged" },
312
- "typePatternGraph": { "patterns": "...", "edges": "...", "codeId": "..." }
313
- }
314
- },
315
- "relAlias": { "succ": "@..." },
316
- "compileStats": { "sccs": [...], "sccCount": 1 },
317
- "meta": {
318
- "@...": {
319
- "type": "rel",
320
- "origins": [
321
- {
322
- "source": "defs.k",
323
- "name": "succ",
324
- "compiledAt": "2026-05-20T00:00:00.000Z",
325
- "start": { "line": 3, "column": 8 },
326
- "end": { "line": 3, "column": 13 }
327
- }
328
- ]
329
- }
330
- },
331
- "main": null
332
- }
333
- ```
334
-
335
- When a library is compiled with `--lib`, the output is the merged library
336
- closure. Imported codes, relations, aliases, and metadata are preserved, and the
337
- new source adds its own origins.
338
-
339
- The REPL `:klib` command uses active relation aliases as roots. It stores their
340
- transitive relation closure and omits historical content-addressed relations
341
- that remain in the live session after alias rebinding but are no longer
342
- reachable from an active alias. Its `codes` field remains the registered code
343
- snapshot needed to reload the library.