@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,340 +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
- ---
108
-
109
- ## 4. Internal Variables as Unification Knots
110
-
111
- A critical insight of k's graph-based model is that unparameterized
112
- patterns can contain internal variables to express equality
113
- constraints across fields:
114
-
115
- ```k
116
- byte[] = { bit 0, bit 1, ... };
117
- ```
118
-
119
- Here:
120
- - `bit` does not have `[]`, so it is a **variable**, not a pattern.
121
- - `bit` is not in the parameter list `byte[]`, so it is an **internal
122
- node**.
123
- - Because `bit` appears at both field `0` and field `1`, it asserts
124
- that **field `0` and field `1` must share the exact same type**,
125
- without constraining what that type must be.
126
-
127
- ### 4.1 Comparison of Pattern Declarations
128
-
129
- ```k
130
- -- 1. Homogeneous pair of two fields of the SAME arbitrary type:
131
- same_pair[] = { T first, T second };
132
-
133
- -- 2. Heterogeneous pair parameterized by the caller:
134
- pair[A, B] = { A first, B second };
135
-
136
- -- 3. Pair of concrete bits:
137
- bit_pair[] = { bit[] first, bit[] second };
138
-
139
- -- 4. Instantiation enforcing equality via shared variable:
140
- diagonal_pair[] = pair[T, T];
141
- ```
142
-
143
- In `diagonal_pair[] = pair[T, T]`:
144
- - `T` is an internal variable.
145
- - Instantiating `pair` with `T` for both arguments unifies both ports,
146
- producing a closed pattern requiring equal elements.
147
-
148
- ---
149
-
150
- ## 5. Instantiation Semantics (Option B)
151
-
152
- Arguments inside `[...]` may be either **variables** or **patterns**:
153
-
154
- 1. **Passing a Variable (`T`, `X`)**:
155
- Connects the template's input port directly to that existing node in
156
- the pattern graph, enabling node sharing, unification, and
157
- polymorphic relations.
158
-
159
- 2. **Passing an Inline Pattern (`int[]`, `pair[K, V]`, `<{}0, {}1>`)**:
160
- Creates an anonymous node representing the pattern and connects the
161
- input port to it.
162
-
163
- ### 5.1 Equivalence to Variable Binding
164
-
165
- Passing an inline pattern `P` is semantically equivalent to introducing
166
- a fresh internal node variable:
167
-
168
- $$name[P] \;\;\Longleftrightarrow\;\; (P = \_anon) \; name[\_anon]$$
169
-
170
- Both forms construct isomorphic graph structures that minimize to the
171
- exact same canonical DFA representation in `codes.mjs`.
172
-
173
- ### 5.2 Single-Step Finite Graph Substitution
174
-
175
- Because recursive cycles are closed internally via knots (`= Y`),
176
- instantiating a template does **not** require recursive unrolling or
177
- fixpoint searching.
178
-
179
- Instantiation is a single-step graph substitution:
180
- 1. Copy the template's graph structure (fresh private IDs for internal
181
- knots).
182
- 2. Substitute the caller's arguments into the designated open port nodes.
183
- 3. Minimize via Hopcroft/Moore DFA partition refinement in `codes.mjs`.
184
-
185
- ---
186
-
187
- ## 6. Safety Invariants and Termination
188
-
189
- To guarantee decidability and termination:
190
-
191
- 1. **Acyclic Template Dependency Rule**:
192
- A pattern template `$ name[...]` cannot reference `name` in its own
193
- definition.
194
- - All recursion **must** be expressed through internal knots (`= Y`).
195
- - Consequently, the template dependency graph is a Strictly Acyclic
196
- Directed Graph (DAG).
197
- - Non-regular polymorphic recursion (nested datatypes) is structurally
198
- impossible, guaranteeing that every instantiated pattern is a
199
- finite regular tree automaton.
200
-
201
- 2. **Lexical Scope Independence**:
202
- Internal variable names and knot names are strictly private to each
203
- definition. Two patterns may both use knot name `Y` or variable `T`
204
- without collision.
205
-
206
- 3. **Canonical Confluence**:
207
- In k, type codes are structural, not nominal. Any two instantiations
208
- that yield isomorphic regular tree automata produce identical
209
- canonical hashes and wire encoders.
210
-
211
- 4. **Canonical Form and REPL Decompilation**:
212
- In the interactive REPL, inspecting a pattern via `:pattern <name>`
213
- (or `:pat <name>`) displays its **canonical definition** rather than
214
- the source syntax used to define it:
215
- - User-defined parameter names (`A`, `B`, `X`) and knot names (`Y`,
216
- `T`) are erased.
217
- - The canonical decompiler introduces fresh variables (`X0`, `X1`,
218
- `X2`, ...) in deterministic traversal (discovery) order.
219
- - Open type ports are introduced in the pattern header (`name[...]`)
220
- in order of discovery:
221
- ```k
222
- -- pair[A, B] = { A first, B second };
223
- pair[X0, X1] = {X0 first, X1 second}; -- @...
224
-
225
- -- list[X] = < {} nil, { X car, Y cdr } cons > = Y;
226
- list[X1] = <{X1 car, X0 cdr} cons, {} nil>=X0; -- @...
227
-
228
- -- same_pair[T] = { T first, T second };
229
- same_pair[X0] = {X0 first, X0 second}; -- @...
230
- ```
231
- - Two syntactically different definitions yielding isomorphic
232
- automata produce the exact same canonical definition and hash.
233
-
234
- ---
235
-
236
- ## 7. Concrete Library Examples
237
-
238
- ### 7.1 Core Data Types
239
-
240
- ```k
241
- -- Canonical bit and bit-path numbers:
242
- bit[] = < {}0, {}1 >;
243
- bits[] = < {} _, B 0, B 1 > = B;
244
-
245
- -- Byte as an 8-bit octet product:
246
- byte[] = {
247
- bit[] 0, bit[] 1, bit[] 2, bit[] 3,
248
- bit[] 4, bit[] 5, bit[] 6, bit[] 7
249
- };
250
-
251
- -- 7-bit ASCII code points:
252
- ascii[] = {
253
- bit[] 6, bit[] 5, bit[] 4, bit[] 3,
254
- bit[] 2, bit[] 1, bit[] 0
255
- };
256
- ```
257
-
258
- ### 7.2 Generic Data Structures
259
-
260
- ```k
261
- -- Generic pair:
262
- pair[A, B] = { A fst, B snd };
263
-
264
- -- Generic singly-linked list:
265
- list[X] = < {}nil, { X car, Y cdr } cons > = Y;
266
-
267
- -- Generic dictionary:
268
- dict[K, V] = list[pair[K, V]];
269
-
270
- -- Generic binary tree with internal knot T:
271
- tree[X] = < {}nil, { X val, T left, T right } node > = T;
272
- ```
273
-
274
- ### 7.3 Usage in Relations
275
-
276
- ```k
277
- -- Type guard filter:
278
- int? = ? int[];
279
-
280
- -- Polymorphic list destructuring with type unification:
281
- head = ? { X car, list[X] cdr } X;
282
-
283
- -- Concrete typed list destructuring:
284
- sum = ? { int[] = T car, list[T] cdr } ...;
285
-
286
- -- Anonymous pattern matching:
287
- validate_ints = ? list[int[]];
288
- ```
289
-
290
- ---
291
-
292
- ## 8. Summary of Grammar Extensions
293
-
294
- ### 8.1 Lexer Tokens
295
-
296
- ```
297
- "[" return 'LB';
298
- "]" return 'RB';
299
- ```
300
-
301
- ### 8.2 Top-Level Definitions
302
-
303
- ```
304
- defs
305
- : /* empty */
306
- | defs name eq comp sc
307
- | defs name lb pattern_params rb eq filter sc
308
- ;
309
-
310
- pattern_params
311
- : /* empty */
312
- | non_empty_pattern_params
313
- ;
314
-
315
- non_empty_pattern_params
316
- : name
317
- | non_empty_pattern_params comma name
318
- ;
319
- ```
320
-
321
- ### 8.3 Pattern References and Instantiations
322
-
323
- ```
324
- filter_
325
- : lp dots rp
326
- | la labelled_filters ra
327
- | lc labelled_filters rc
328
- | name lb pattern_args rb
329
- ;
330
-
331
- pattern_args
332
- : /* empty */
333
- | non_empty_pattern_args
334
- ;
335
-
336
- non_empty_pattern_args
337
- : filter
338
- | non_empty_pattern_args comma filter
339
- ;
340
- ```
@@ -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.