@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,349 +0,0 @@
1
- # Content-Addressable Canonical Patterns and Parameter Aliasing
2
-
3
- ## 1. Overview and Core Philosophy
4
-
5
- In k, all relations, codes, and patterns are **content-addressable**.
6
- A human-readable name assigned to a pattern template (such as
7
- `list[X]` or `pair[A, B]`) is purely a lexical **alias** pointing to an
8
- underlying, uniquely identified canonical pattern graph addressed by its
9
- cryptographic hash `@hash`.
10
-
11
- This document specifies:
12
- 1. How canonical patterns are derived and hashed from directed graphs.
13
- 2. How user-defined named patterns act as parameter routing aliases
14
- using wildcards `(...)` for unexposed internal holes.
15
- 3. Why the variable pointing to the root of a recursive pattern graph
16
- (and cycle knots in general) is an internal structural fixed-point
17
- and cannot be exposed as an external parameter.
18
- 4. How canonical patterns, aliases, and argument routing are persisted
19
- in object files (`.klib` and `.ko`).
20
-
21
- ---
22
-
23
- ## 2. Canonical Pattern Derivation: The Pure Linear Skeleton
24
-
25
- When a pattern is compiled:
26
- ```k
27
- p[X] = {X x, Y y, Y z};
28
- ```
29
- the compiler evaluates the right-hand filter into a
30
- **pure linear skeleton**.
31
-
32
- ### 2.1 Never Equalizing Pattern Leaves
33
-
34
- In the pure skeleton model, two leaves of a pattern graph are **never
35
- equalized** in the canonical template:
36
- - Even if an author repeats an existential variable (like `Y` at fields
37
- `y` and `z`), or repeats a formal parameter (like `T` in
38
- `same_pair[T] = { T first, T second }`), the canonicalizer assigns an
39
- independent, distinct canonical port `X0, X1, X2, ...` to every open
40
- leaf slot.
41
- - Any non-linear equality constraint between leaves is represented
42
- outside the canonical graph, in the **diagonalized argument vector** of
43
- the alias definition.
44
-
45
- In the example `p[X] = {X x, Y y, Y z}`:
46
- - Field `x` becomes canonical port `X0`.
47
- - Field `y` becomes canonical port `X1`.
48
- - Field `z` becomes canonical port `X2`.
49
-
50
- The canonical pattern is the 3-port linear product:
51
- ```k
52
- @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X0, X1, X2] = {
53
- X0 x, X1 y, X2 z
54
- };
55
- ```
56
-
57
- Canonical patterns always take the full arity of all leaf positions
58
- discovered in the pattern skeleton.
59
-
60
- ---
61
-
62
- ## 3. Named Patterns as Parameter Routing and Diagonalization Aliases
63
-
64
- When an author defines an alias like:
65
- ```k
66
- p[X] = {X x, Y y, Y z};
67
- ```
68
- the definition `p[X]` does **not** create a separate canonical pattern
69
- graph. Instead, it defines an alias that routes:
70
- - The author's formal parameter `X` to slot `X0`.
71
- - The shared existential variable `Y` to both slots `X1` and `X2`:
72
-
73
- ```k
74
- p[X] = @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X, Y, Y];
75
- ```
76
-
77
- When `p` is instantiated (e.g. `p[int]`), the template expansion engine:
78
- 1. Substitutes formal parameter `X` with caller argument `int`.
79
- 2. Renames internal existential variable `Y` to a unique fresh variable
80
- `_Y_np1` across all occurrences in the argument list:
81
- `@PScs...[int, _Y_np1, _Y_np1]`.
82
- 3. Expands the canonical template with those arguments, yielding:
83
- `{ int x, _Y_np1 y, _Y_np1 z }`.
84
- 4. The type derivation engine unifies the type of field `y` with the type
85
- of field `z` via the shared fresh variable `_Y_np1`.
86
-
87
- Thus, existential equality constraints are preserved with full type-safety
88
- at use-time, while enabling maximum structural template deduplication.
89
-
90
- ### 3.1 Canonical Pattern Sharing Across Diagonalizations and Permutations
91
-
92
- Under this architecture, all variations over the same underlying product
93
- or union structure share the **exact same canonical pattern graph and
94
- content hash**:
95
-
96
- #### Example 1: Pair Variations
97
- ```k
98
- pair[A, B] = { A first, B second };
99
- same_pair[T] = { T first, T second };
100
- closed_same_pair[] = { T first, T second };
101
- any_pair[] = { (...) first, (...) second };
102
- ```
103
- All four compile to the single canonical skeleton:
104
- ```k
105
- @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[X0, X1] = {
106
- X0 first, X1 second
107
- };
108
- ```
109
-
110
- Their `:pats` alias representations reflect their respective parameter
111
- routings and diagonalizations:
112
- ```text
113
- > :pats
114
- any_pair[] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[(...),(...)]
115
- closed_same_pair[] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T,T]
116
- pair[A,B] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[A,B]
117
- same_pair[T] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T,T]
118
- ```
119
-
120
- #### Example 2: Record `{ x, y }` Variations
121
- ```k
122
- a[] = { (...) x, (...) y };
123
- b[X] = { X x, (...) y };
124
- c[X,Y] = { X x, Y y };
125
- d[Y,X] = { X x, Y y };
126
- diag_p[] = { X x, X y };
127
- ```
128
- All five share `@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x`:
129
- ```text
130
- > :pats
131
- a[] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[(...),(...)]
132
- b[X] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,(...)]
133
- c[X,Y] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,Y]
134
- d[Y,X] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,Y]
135
- diag_p[] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,X]
136
- ```
137
-
138
- ---
139
-
140
- ## 4. Direct Usability of Canonical Patterns
141
-
142
- Because the alias is just an abbreviation, canonical patterns can be used
143
- everywhere relations and aliases can be used:
144
-
145
- 1. **Direct Inspection**:
146
- ```text
147
- > :pat @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR
148
- @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X0, X1, X2] = {
149
- X0 x, X1 y, X2 z
150
- };
151
- ```
152
-
153
- 2. **Direct Matching in Expressions**:
154
- Callers can instantiate canonical patterns directly by passing all
155
- canonical arguments:
156
- ```k
157
- { {} x, {} y, {} z } ? @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[
158
- {}, {}, {}
159
- ];
160
- ```
161
-
162
- 3. **Explicit Definition by Hash**:
163
- Canonical pattern definitions are accepted directly by the grammar:
164
- ```k
165
- @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X0, X1, X2] = {
166
- X0 x, X1 y, X2 z
167
- };
168
- ```
169
-
170
- ---
171
-
172
- ## 5. Alias Argument Generation Rules
173
-
174
- For every canonical port `Xi` at path `P` in the canonical filter:
175
- Let `t` be the token found at path `P` in the author's filter.
176
- The corresponding alias argument is determined by:
177
- 1. **Wildcard leaf**: If `t` is absent or an explicit `(...)` wildcard,
178
- the argument is `"(...)"`.
179
- 2. **Formal parameter**: If `t` is declared in `pattern_params`, the
180
- argument is `t` (e.g. `[T, T]` for diagonalized parameter `T`).
181
- 3. **Repeated existential variable**: If `t` is an internal variable
182
- appearing $> 1$ times in the filter, the argument is `t` (e.g. `[X, X]`
183
- or `[Z, Y, Y]`), preserving existential equality across fields.
184
- 4. **Single-occurrence internal variable**: If `t` is an internal variable
185
- appearing only once, it imposes no constraints and is normalized to
186
- `"(...)"`.
187
-
188
- ---
189
-
190
- ## 6. Why Knots (and Root Knots) Cannot Be Exposed as Parameters
191
-
192
- Consider the recursive linked list pattern:
193
- ```k
194
- list[X] = < {} nil, { X car, Y cdr } cons > = Y;
195
- ```
196
-
197
- In this definition:
198
- - `= Y` binds the variable `Y` to the root union node of the pattern
199
- graph.
200
- - Inside the second variant `{ X car, Y cdr } cons`, the field `cdr`
201
- references `Y`.
202
- - This creates a directed back-edge from `cdr` to the root union, forming
203
- a recursive cycle ($\mu$-fixpoint).
204
-
205
- ### 6.1 The Fundamental Distinction: Open Ports vs. Bound Knots
206
-
207
- There is a fundamental semantic contradiction between **parameters** and
208
- **knots**:
209
-
210
- | Feature | Parameter (`[P]`) | Knot (`= KnotName`) |
211
- | :--- | :--- | :--- |
212
- | **Quantification** | Universal ($\forall$) | Fixed-point ($\mu$) |
213
- | **Binding State** | **Unbound / Open Port** | **Bound / Node** |
214
- | **Role** | Hole to fill by caller | Internal back-edge cycle |
215
- | **Scope** | Caller interface | Purely internal topology |
216
-
217
- - An **external parameter** is an open socket waiting for caller input.
218
- - A **cycle knot** is an internal wire already soldered to a concrete
219
- node in the graph.
220
-
221
- ### 6.2 The Shadowing Hazard: Destruction of Recursion
222
-
223
- What happens if an author attempts to expose the root knot `Y` as a
224
- parameter?
225
- ```k
226
- list[X, Y] = < {} nil, { X car, Y cdr } cons > = Y; -- INVALID!
227
- ```
228
-
229
- If this definition were permitted:
230
- 1. `Y` would appear in the formal parameter list `[X, Y]`.
231
- 2. When the template is instantiated (e.g. `list[int[], MyTail]`), the
232
- argument `MyTail` would substitute every occurrence of `Y` in the
233
- body.
234
- 3. Consequently, `{ X car, Y cdr }` would become
235
- `{ int[] car, MyTail cdr }`.
236
- 4. The back-edge to the root union would be severed!
237
- 5. The recursive cycle would be destroyed, silently corrupting the
238
- recursive list into a non-recursive pair
239
- `<{} nil, {int[] car, MyTail cdr} cons>`.
240
-
241
- ### 6.3 Enforced Invariant: Conflict Rejection at Parse Time
242
-
243
- Because cycle knots represent bound internal topology, exposing a knot
244
- name in `pattern_params` is a direct contradiction.
245
-
246
- The compiler strictly enforces that no formal parameter name may
247
- conflict with any knot identifier in the filter:
248
-
249
- ```k
250
- list[X, Y] = < {} nil, { X car, Y cdr } cons > = Y;
251
- -- Parse Error: Pattern parameter 'Y' in pattern 'list'
252
- -- conflicts with knot 'Y'. Knot variables cannot be pattern parameters.
253
- ```
254
-
255
- The root node of a pattern graph is matched against incoming data by the
256
- runtime; it is never an open parameter port.
257
-
258
- ---
259
-
260
- ## 7. Reflection of Patterns in Object Files (`.klib` and `.ko`)
261
-
262
- Ahead-of-time compiled libraries (`.klib`) and executables (`.ko`) store
263
- patterns in their top-level object container (`format: "k-object"`).
264
- Patterns are persisted across three coordinated structures:
265
-
266
- ### 7.1 `patternAlias` (Lexical Names to Content Hashes)
267
-
268
- Maps human-readable pattern names to their canonical content hashes.
269
- All aliases sharing the same linear skeleton point to the same hash:
270
-
271
- ```json
272
- "patternAlias": {
273
- "pair": "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm",
274
- "same_pair": "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm",
275
- "closed_same_pair": "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm",
276
- "p": "@PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR"
277
- }
278
- ```
279
-
280
- ### 7.2 `patterns` (Deduplicated Canonical ASTs)
281
-
282
- The `patterns` dictionary stores the canonical template definition under
283
- its content hash `@hash`:
284
- - **Deduplicated**: Even if a program defines multiple variations over a
285
- pair or record, the canonical template is stored exactly once under
286
- its `@hash`.
287
- - **Linear Multi-Hole Functor**: Every leaf position is an independent
288
- canonical parameter (`X0, X1, ...`), with no leaves unified in the
289
- persisted filter AST.
290
-
291
- ```json
292
- "patterns": {
293
- "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm": {
294
- "params": ["X0", "X1"],
295
- "filter": {
296
- "type": "product",
297
- "fields": {
298
- "first": { "type": "name", "name": "X0", "open": true },
299
- "second": { "type": "name", "name": "X1", "open": true }
300
- }
301
- }
302
- }
303
- }
304
- ```
305
-
306
- ### 7.3 `meta` (Provenance & `aliasArgs` Routing Vectors)
307
-
308
- The `meta` dictionary maps each `@hash` to its canonical port list
309
- and an `origins` array recording how every alias projects caller
310
- parameters into the linear skeleton:
311
-
312
- ```json
313
- "meta": {
314
- "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm": {
315
- "type": "pattern",
316
- "params": ["X0", "X1"],
317
- "origins": [
318
- {
319
- "name": "pair",
320
- "params": ["A", "B"],
321
- "aliasArgs": ["A", "B"],
322
- "compiledAt": "2026-10-23T19:38:29.691Z"
323
- },
324
- {
325
- "name": "same_pair",
326
- "params": ["T"],
327
- "aliasArgs": ["T", "T"],
328
- "compiledAt": "2026-10-23T19:38:29.691Z"
329
- },
330
- {
331
- "name": "closed_same_pair",
332
- "params": [],
333
- "aliasArgs": ["T", "T"],
334
- "compiledAt": "2026-10-23T19:38:29.691Z"
335
- }
336
- ]
337
- }
338
- }
339
- ```
340
-
341
- The `aliasArgs` vector:
342
- 1. Records **parameter diagonalization** (e.g. `["T", "T"]`), instructing
343
- the runtime to supply formal argument `T` to both canonical ports.
344
- 2. Preserves **existential constraints** (e.g. `["X", "Y", "Y"]`),
345
- ensuring `Y` is renamed to a shared fresh variable when instantiated.
346
- 3. Enables **lossless alias export**: when generating `--export` preambles
347
- or exporting `.klib` files, `buildExportPreamble` reads `origin.params`
348
- and `origin.aliasArgs` to recreate the exact source-level alias
349
- definitions.
@@ -1,257 +0,0 @@
1
- # Reusable Codec Architecture
2
-
3
- ## 1. Overview & Objectives
4
-
5
- In **k**, a **codec** is a two-way translator between external domain
6
- data (e.g. decimal integers, JSON, UTF-8 text, IEEE 754 floats) and **k**
7
- enveloped values (a structural `Value` tree paired with a closed pattern
8
- graph).
9
-
10
- In **k**, there are no primitive numbers or built-in numerical types.
11
- Numbers are nullary relations mapping the unit to bit trees
12
- (`{} -> bits`), and arithmetic relations operate on signed
13
- integer variants (`int`). Codecs like `int.mjs` bridge human
14
- decimal representations and these algebraic structures.
15
-
16
- Every codec in the **k** ecosystem is designed to serve three unified
17
- objectives from a single module definition:
18
-
19
- 1. **Document the Codec**: Formally specify the external syntax and its
20
- semantics as an enveloped **k** value `(P, v)`.
21
- 2. **REPL Module**: Provide interactive input parsing (`:input
22
- <codec.mjs>`) and multi-codec output inspection (`<codec.mjs>:
23
- <formatted>`) in both Node.js and browser REPLs.
24
- 3. **Standalone Shell Executable**: Function as a first-class Unix filter
25
- (`--parse`, `--print`, `--help`) for composition in command-line
26
- pipelines.
27
-
28
- ```text
29
- +---------------------------------------+
30
- | External Domain Data |
31
- | (JSON, Decimals, UTF-8, IEEE floats) |
32
- +---------------------------------------+
33
- | ^
34
- parse(text) | | print(value)
35
- v |
36
- +---------------------------------------+
37
- | k Codec |
38
- | (Syntax & Value Mapper) |
39
- +---------------------------------------+
40
- | ^
41
- CLI: --parse | | CLI: --print
42
- REPL: :input v | REPL: output
43
- +---------------------------------------+
44
- | Enveloped k Value |
45
- | (pattern graph P, value tree v) |
46
- | Binary Wire Stream (P, v) |
47
- +---------------------------------------+
48
- ```
49
-
50
- ---
51
-
52
- ## 2. Objective 1: Documentation & Specification
53
-
54
- Every codec defines what external text it accepts and how that text
55
- maps to an enveloped **k** value.
56
-
57
- ### 2.1 External Syntax
58
- The syntax specification defines the valid textual forms accepted by
59
- the codec:
60
- - **Grammar & Rules**: Defines the accepted language. While regular
61
- expressions offer simple examples, the syntax can be an arbitrary
62
- formal language (context-free, recursive, JSON RFC 8259, etc.).
63
- - **Normalization**: Rules for whitespace, casing, or escaping.
64
- - **Rejection Criteria**: Explicit errors when invalid input is
65
- encountered.
66
-
67
- ### 2.2 Semantics as an Enveloped k Value
68
- Parsing external text produces an **enveloped value** `(P, v)`:
69
- - **Pattern Graph ($P$)**: A closed pattern graph specifying the
70
- algebraic structure.
71
- - **Value Tree ($v$)**: A concrete tree matching $P$, constructed from
72
- products (`{...}`) and variants (`<...>`).
73
-
74
- A codec does not produce an ungrounded type; it performs a concrete
75
- transformation from text to an enveloped value `(P, v)`.
76
-
77
- ### 2.3 Pattern Derivation via k Type System (`patternFromFilter`)
78
- Pattern graphs ($P$) must never be handwritten as raw property-list
79
- JSON arrays (e.g. `[["closed-union", ...]]`). Instead, codecs derive
80
- pattern graphs directly through the **k** type system from filter or
81
- type expressions using `patternFromFilter`:
82
-
83
- ```js
84
- import { patternFromFilter } from "./runtime/codec-sdk.mjs";
85
-
86
- // Derived from k filter expression
87
- const INT_PATTERN = patternFromFilter(
88
- '?< <bits 0, bits 1, {} _>=bits "+", bits "-">'
89
- );
90
- ```
91
-
92
- This guarantees:
93
- 1. All patterns are verified, normalized, and canonicalized by **k**'s
94
- type derivation and graph unification engine.
95
- 2. Codecs remain concise, declarative, and maintainable.
96
- 3. Codecs run identically in Node.js and in the Web REPL (via the browser
97
- runtime shim).
98
-
99
- ### 2.4 Documentation Contract
100
- A codec is identified solely by the file loaded—there is no artificial
101
- `name` export or `patterns` list export. A codec may optionally export
102
- a `doc` string:
103
- - Describes accepted syntax, options, and representation.
104
- - Displayed by `--help` in shell invocations.
105
- - Displayed by `:help <codec.mjs>` or documentation commands in REPLs.
106
-
107
- ---
108
-
109
- ## 3. Objective 2: REPL Module Interface
110
-
111
- In the REPL, codecs are loaded dynamically on demand:
112
- ```text
113
- > :codec load int.mjs
114
- ```
115
-
116
- ### 3.1 Module Exports
117
- A codec module exports:
118
-
119
- | Export | Type | Required | Description |
120
- | :--- | :--- | :--- | :--- |
121
- | `parse` | `(text: string) => EnvelopedValue \| Value` | **Yes** | Parses external text into an enveloped `Value`. Throws on syntax error. |
122
- | `print` | `(value: Value) => string` | **Yes** | Formats a `Value` into external text. Throws if value is not representable. |
123
- | `doc` | `string` | Optional | Documentation of syntax and usage for CLI help and REPL inspections. |
124
-
125
- ### 3.2 REPL Input Protocol
126
- The user specifies the codec to parse an input payload:
127
- - **Interactive Mode**:
128
- ```text
129
- > :input int.mjs
130
- int.mjs> 42
131
- {}|_|0|1|0|1|0|1|+ ?<{} _, ...>
132
- int.mjs: 42
133
- ```
134
- - **One-Line Mode**:
135
- ```text
136
- > :input int.mjs 42
137
- {}|_|0|1|0|1|0|1|+ ?<{} _, ...>
138
- int.mjs: 42
139
- ```
140
-
141
- ### 3.3 REPL Output Protocol (Multi-Codec Inspection)
142
- Whenever an evaluation produces a resulting **k** `Value`:
143
- 1. The primary representation is the standard **k** value envelope.
144
- 2. The REPL iterates over loaded codecs and calls `codec.print(value)`.
145
- 3. If `codec.print(value)` succeeds, the REPL displays
146
- `<codec>: <formattedString>`.
147
- 4. If `codec.print(value)` throws, the codec is silently ignored for
148
- that value.
149
-
150
- ---
151
-
152
- ## 4. Objective 3: Standalone Shell Executable Contract
153
-
154
- Every codec file is directly executable from the command line:
155
- ```bash
156
- chmod +x codecs/int.mjs
157
- ```
158
-
159
- ### 4.1 CLI Invocations
160
-
161
- 1. **Parse Mode (`--parse`)**:
162
- - Reads external text from `stdin`.
163
- - Parses it into an enveloped value `(P, v)`.
164
- - Writes the binary wire encoding of `(P, v)` to `stdout`.
165
- - Diagnostics and errors are written to `stderr`.
166
- - Exit code: `0` on success, non-zero on error.
167
-
168
- 2. **Print Mode (`--print`)**:
169
- - Reads binary wire bytes `(P, v)` from `stdin`.
170
- - Decodes the wire stream and calls `print(value)`.
171
- - Writes formatted text to `stdout`.
172
- - Exit code: `0` on success, non-zero if not representable under this
173
- codec.
174
-
175
- 3. **Help Mode (`-h`, `--help`)**:
176
- - Outputs CLI usage and the codec's `doc` string to `stdout`.
177
-
178
- ---
179
-
180
- ## 5. Implementation: Codec CLI Runner
181
-
182
- To avoid duplicating stdin/stdout stream handling and CLI flag parsing
183
- across codecs, a helper is provided:
184
-
185
- ```javascript
186
- runCodecCLI(import.meta.url, { parse, print, doc });
187
- ```
188
-
189
- ### Responsibilities of `runCodecCLI`:
190
- 1. **Entrypoint Detection**: Checks if the module is invoked directly
191
- from the CLI (e.g. `import.meta.url ===
192
- pathToFileURL(process.argv[1]).href`). If imported as a module or
193
- running in a browser, it is a no-op.
194
- 2. **Flag Parsing**: Handles `--parse`, `--print`, and `-h` / `--help`.
195
- 3. **Stream Piping & Lazy Wire Decoding**:
196
- - For `--parse`: reads `stdin` to string, calls `parse(text)`, encodes
197
- enveloped value `(P, v)` to binary wire format on `stdout`.
198
- - For `--print`: lazily decodes the wire format from `stdin` into
199
- bitstream-backed `Value` proxies (`LazyGeneralProduct`,
200
- `LazyGeneralVariant`) with precomputed fixed-width bit sizes and
201
- static field offsets, calls `print(value)`, and writes formatted text
202
- to `stdout`.
203
- - Cleanly exits on `EPIPE` when piped into downstream consumers like
204
- `head`.
205
-
206
- ---
207
-
208
- ## 6. Directory Layout
209
-
210
- To make `codecs/` intuitive and self-contained:
211
-
212
- ```text
213
- codecs/
214
- ├── int.mjs # Integer & list codec
215
- ├── json.mjs # JSON codec (schema-specializing)
216
- ├── djson.mjs # Dynamic JSON codec (binary bit-trie)
217
- ├── utf8.mjs # UTF-8 string codec
218
- ├── utf16.mjs # UTF-16 string codec
219
- ├── ieee.mjs # IEEE 754 float codec
220
- ├── unit.mjs # Unit {} codec
221
- ├── k-parse.mjs # Textual k value {...} -> binary wire stream
222
- ├── k-print.mjs # Binary wire stream -> textual k value
223
- ├── show.mjs # Wire stream pass-through inspector
224
- └── runtime/ # Shared codec infrastructure
225
- ├── codec-sdk.mjs # runCodecCLI, Value, encodeToWire, decodeWire
226
- ├── prefix-codec.mjs # Low-level bitstream wire serialization
227
- ├── codec.mjs # Abstract pattern graph algorithms
228
- └── cli-entry.mjs # Entrypoint detection
229
- ```
230
-
231
- Each codec file directly under `codecs/` is both an executable CLI
232
- script and an importable module.
233
-
234
- ---
235
-
236
- ## 7. Web REPL & VFS Bundling Architecture
237
-
238
- In the browser REPL (`repl.html`):
239
- - **Self-Contained Modules**: At build time
240
- (`scripts/build-repl-html.mjs`), verified codecs in `codecs/` are
241
- compiled via `esbuild` into 100% self-contained ES modules with **zero
242
- imports**.
243
- - **No Runtime Files in VFS**: `codecs/runtime/*` is not included in the
244
- browser VFS. The VFS only contains verified, self-contained user-facing
245
- files (`int.mjs`, `json.mjs`, `djson.mjs`, `utf8.mjs`, `unit.mjs`,
246
- `ieee.mjs`).
247
- - **Native Browser Loading**: In `repl-codecs.mjs`, the browser reads the
248
- codec source from VFS, wraps it in a Blob, and invokes native `await
249
- import(blobUrl)`. No regex manipulation, import stripping, or global
250
- environment injection is required.
251
-
252
- ## Further Reading
253
-
254
- - [DOCS/FILE_FORMATS.md](./FILE_FORMATS.md) — guide to
255
- .k, .ko, .klib, and .kvm formats
256
- - [DOCS/CODECS.md](./CODECS.md) — guide to writing codecs
257
- - [DOCS/DICTIONARY.md](./DICTIONARY.md) — concept names and terminology