@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,362 +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
- ### 2.2 Leaf Variables vs. Template Applications
61
-
62
- During canonicalization, only genuine leaf type variables (`type: "name"`
63
- or untyped leaf nodes) are assigned canonical port slots (`X0`, `X1`,
64
- ...).
65
-
66
- Template applications (`name[...]` or `@hash[...]`) must be fully
67
- expanded before skeletonization. If an unexpanded `pattern_apply` AST
68
- node reaches the skeletonizer (e.g. due to an unresolved template name),
69
- the compiler rejects it immediately with an `Unknown pattern template`
70
- error. An undefined pattern template application is never converted into
71
- an open leaf variable slot.
72
-
73
- ---
74
-
75
- ## 3. Named Patterns as Parameter Routing and Diagonalization Aliases
76
-
77
- When an author defines an alias like:
78
- ```k
79
- p[X] = {X x, Y y, Y z};
80
- ```
81
- the definition `p[X]` does **not** create a separate canonical pattern
82
- graph. Instead, it defines an alias that routes:
83
- - The author's formal parameter `X` to slot `X0`.
84
- - The shared existential variable `Y` to both slots `X1` and `X2`:
85
-
86
- ```k
87
- p[X] = @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X, Y, Y];
88
- ```
89
-
90
- When `p` is instantiated (e.g. `p[int]`), the template expansion engine:
91
- 1. Substitutes formal parameter `X` with caller argument `int`.
92
- 2. Renames internal existential variable `Y` to a unique fresh variable
93
- `_Y_np1` across all occurrences in the argument list:
94
- `@PScs...[int, _Y_np1, _Y_np1]`.
95
- 3. Expands the canonical template with those arguments, yielding:
96
- `{ int x, _Y_np1 y, _Y_np1 z }`.
97
- 4. The type derivation engine unifies the type of field `y` with the type
98
- of field `z` via the shared fresh variable `_Y_np1`.
99
-
100
- Thus, existential equality constraints are preserved with full type-safety
101
- at use-time, while enabling maximum structural template deduplication.
102
-
103
- ### 3.1 Canonical Pattern Sharing Across Diagonalizations and Permutations
104
-
105
- Under this architecture, all variations over the same underlying product
106
- or union structure share the **exact same canonical pattern graph and
107
- content hash**:
108
-
109
- #### Example 1: Pair Variations
110
- ```k
111
- pair[A, B] = { A first, B second };
112
- same_pair[T] = { T first, T second };
113
- closed_same_pair[] = { T first, T second };
114
- any_pair[] = { (...) first, (...) second };
115
- ```
116
- All four compile to the single canonical skeleton:
117
- ```k
118
- @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[X0, X1] = {
119
- X0 first, X1 second
120
- };
121
- ```
122
-
123
- Their `:pats` alias representations reflect their respective parameter
124
- routings and diagonalizations:
125
- ```text
126
- > :pats
127
- any_pair[] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[(...),(...)]
128
- closed_same_pair[] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T,T]
129
- pair[A,B] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[A,B]
130
- same_pair[T] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T,T]
131
- ```
132
-
133
- #### Example 2: Record `{ x, y }` Variations
134
- ```k
135
- a[] = { (...) x, (...) y };
136
- b[X] = { X x, (...) y };
137
- c[X,Y] = { X x, Y y };
138
- d[Y,X] = { X x, Y y };
139
- diag_p[] = { X x, X y };
140
- ```
141
- All five share `@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x`:
142
- ```text
143
- > :pats
144
- a[] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[(...),(...)]
145
- b[X] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,(...)]
146
- c[X,Y] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,Y]
147
- d[Y,X] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,Y]
148
- diag_p[] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,X]
149
- ```
150
-
151
- ---
152
-
153
- ## 4. Direct Usability of Canonical Patterns
154
-
155
- Because the alias is just an abbreviation, canonical patterns can be used
156
- everywhere relations and aliases can be used:
157
-
158
- 1. **Direct Inspection**:
159
- ```text
160
- > :pat @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR
161
- @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X0, X1, X2] = {
162
- X0 x, X1 y, X2 z
163
- };
164
- ```
165
-
166
- 2. **Direct Matching in Expressions**:
167
- Callers can instantiate canonical patterns directly by passing all
168
- canonical arguments:
169
- ```k
170
- { {} x, {} y, {} z } ? @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[
171
- {}, {}, {}
172
- ];
173
- ```
174
-
175
- 3. **Explicit Definition by Hash**:
176
- Canonical pattern definitions are accepted directly by the grammar:
177
- ```k
178
- @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X0, X1, X2] = {
179
- X0 x, X1 y, X2 z
180
- };
181
- ```
182
-
183
- ---
184
-
185
- ## 5. Alias Argument Generation Rules
186
-
187
- For every canonical port `Xi` at path `P` in the canonical filter:
188
- Let `t` be the token found at path `P` in the author's filter.
189
- The corresponding alias argument is determined by:
190
- 1. **Wildcard leaf**: If `t` is absent or an explicit `(...)` wildcard,
191
- the argument is `"(...)"`.
192
- 2. **Formal parameter**: If `t` is declared in `pattern_params`, the
193
- argument is `t` (e.g. `[T, T]` for diagonalized parameter `T`).
194
- 3. **Repeated existential variable**: If `t` is an internal variable
195
- appearing $> 1$ times in the filter, the argument is `t` (e.g. `[X, X]`
196
- or `[Z, Y, Y]`), preserving existential equality across fields.
197
- 4. **Single-occurrence internal variable**: If `t` is an internal variable
198
- appearing only once, it imposes no constraints and is normalized to
199
- `"(...)"`.
200
-
201
- ---
202
-
203
- ## 6. Why Knots (and Root Knots) Cannot Be Exposed as Parameters
204
-
205
- Consider the recursive linked list pattern:
206
- ```k
207
- list[X] = < {} nil, { X car, Y cdr } cons > = Y;
208
- ```
209
-
210
- In this definition:
211
- - `= Y` binds the variable `Y` to the root union node of the pattern
212
- graph.
213
- - Inside the second variant `{ X car, Y cdr } cons`, the field `cdr`
214
- references `Y`.
215
- - This creates a directed back-edge from `cdr` to the root union, forming
216
- a recursive cycle ($\mu$-fixpoint).
217
-
218
- ### 6.1 The Fundamental Distinction: Open Ports vs. Bound Knots
219
-
220
- There is a fundamental semantic contradiction between **parameters** and
221
- **knots**:
222
-
223
- | Feature | Parameter (`[P]`) | Knot (`= KnotName`) |
224
- | :--- | :--- | :--- |
225
- | **Quantification** | Universal ($\forall$) | Fixed-point ($\mu$) |
226
- | **Binding State** | **Unbound / Open Port** | **Bound / Node** |
227
- | **Role** | Hole to fill by caller | Internal back-edge cycle |
228
- | **Scope** | Caller interface | Purely internal topology |
229
-
230
- - An **external parameter** is an open socket waiting for caller input.
231
- - A **cycle knot** is an internal wire already soldered to a concrete
232
- node in the graph.
233
-
234
- ### 6.2 The Shadowing Hazard: Destruction of Recursion
235
-
236
- What happens if an author attempts to expose the root knot `Y` as a
237
- parameter?
238
- ```k
239
- list[X, Y] = < {} nil, { X car, Y cdr } cons > = Y; -- INVALID!
240
- ```
241
-
242
- If this definition were permitted:
243
- 1. `Y` would appear in the formal parameter list `[X, Y]`.
244
- 2. When the template is instantiated (e.g. `list[int[], MyTail]`), the
245
- argument `MyTail` would substitute every occurrence of `Y` in the
246
- body.
247
- 3. Consequently, `{ X car, Y cdr }` would become
248
- `{ int[] car, MyTail cdr }`.
249
- 4. The back-edge to the root union would be severed!
250
- 5. The recursive cycle would be destroyed, silently corrupting the
251
- recursive list into a non-recursive pair
252
- `<{} nil, {int[] car, MyTail cdr} cons>`.
253
-
254
- ### 6.3 Enforced Invariant: Conflict Rejection at Parse Time
255
-
256
- Because cycle knots represent bound internal topology, exposing a knot
257
- name in `pattern_params` is a direct contradiction.
258
-
259
- The compiler strictly enforces that no formal parameter name may
260
- conflict with any knot identifier in the filter:
261
-
262
- ```k
263
- list[X, Y] = < {} nil, { X car, Y cdr } cons > = Y;
264
- -- Parse Error: Pattern parameter 'Y' in pattern 'list'
265
- -- conflicts with knot 'Y'. Knot variables cannot be pattern parameters.
266
- ```
267
-
268
- The root node of a pattern graph is matched against incoming data by the
269
- runtime; it is never an open parameter port.
270
-
271
- ---
272
-
273
- ## 7. Reflection of Patterns in Object Files (`.klib` and `.ko`)
274
-
275
- Ahead-of-time compiled libraries (`.klib`) and executables (`.ko`) store
276
- patterns in their top-level object container (`format: "k-object"`).
277
- Patterns are persisted across three coordinated structures:
278
-
279
- ### 7.1 `patternAlias` (Lexical Names to Content Hashes)
280
-
281
- Maps human-readable pattern names to their canonical content hashes.
282
- All aliases sharing the same linear skeleton point to the same hash:
283
-
284
- ```json
285
- "patternAlias": {
286
- "pair": "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm",
287
- "same_pair": "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm",
288
- "closed_same_pair": "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm",
289
- "p": "@PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR"
290
- }
291
- ```
292
-
293
- ### 7.2 `patterns` (Deduplicated Canonical ASTs)
294
-
295
- The `patterns` dictionary stores the canonical template definition under
296
- its content hash `@hash`:
297
- - **Deduplicated**: Even if a program defines multiple variations over a
298
- pair or record, the canonical template is stored exactly once under
299
- its `@hash`.
300
- - **Linear Multi-Hole Functor**: Every leaf position is an independent
301
- canonical parameter (`X0, X1, ...`), with no leaves unified in the
302
- persisted filter AST.
303
-
304
- ```json
305
- "patterns": {
306
- "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm": {
307
- "params": ["X0", "X1"],
308
- "filter": {
309
- "type": "product",
310
- "fields": {
311
- "first": { "type": "name", "name": "X0", "open": true },
312
- "second": { "type": "name", "name": "X1", "open": true }
313
- }
314
- }
315
- }
316
- }
317
- ```
318
-
319
- ### 7.3 `meta` (Provenance & `aliasArgs` Routing Vectors)
320
-
321
- The `meta` dictionary maps each `@hash` to its canonical port list
322
- and an `origins` array recording how every alias projects caller
323
- parameters into the linear skeleton:
324
-
325
- ```json
326
- "meta": {
327
- "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm": {
328
- "type": "pattern",
329
- "params": ["X0", "X1"],
330
- "origins": [
331
- {
332
- "name": "pair",
333
- "params": ["A", "B"],
334
- "aliasArgs": ["A", "B"],
335
- "compiledAt": "2026-10-23T19:38:29.691Z"
336
- },
337
- {
338
- "name": "same_pair",
339
- "params": ["T"],
340
- "aliasArgs": ["T", "T"],
341
- "compiledAt": "2026-10-23T19:38:29.691Z"
342
- },
343
- {
344
- "name": "closed_same_pair",
345
- "params": [],
346
- "aliasArgs": ["T", "T"],
347
- "compiledAt": "2026-10-23T19:38:29.691Z"
348
- }
349
- ]
350
- }
351
- }
352
- ```
353
-
354
- The `aliasArgs` vector:
355
- 1. Records **parameter diagonalization** (e.g. `["T", "T"]`), instructing
356
- the runtime to supply formal argument `T` to both canonical ports.
357
- 2. Preserves **existential constraints** (e.g. `["X", "Y", "Y"]`),
358
- ensuring `Y` is renamed to a shared fresh variable when instantiated.
359
- 3. Enables **lossless alias export**: when generating `--export` preambles
360
- or exporting `.klib` files, `buildExportPreamble` reads `origin.params`
361
- and `origin.aliasArgs` to recreate the exact source-level alias
362
- 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