@fraczak/k 8.4.1 → 8.5.1

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 (116) hide show
  1. package/CHANGELOG.md +32 -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/llvm/src/kvm2llvm.mjs +5 -4
  27. package/backends/llvm/src/llvm.mjs +2 -1
  28. package/backends/llvm/tests/integration.sh +7 -0
  29. package/backends/llvm/tests/test-llvm.mjs +20 -0
  30. package/backends/wasm/README.md +88 -66
  31. package/backends/wasm/src/kvm2wasm.mjs +64 -18
  32. package/backends/wasm/tests/integration.sh +5 -0
  33. package/backends/wasm/tests/test-wasm.mjs +86 -2
  34. package/canonical-pattern.mjs +7 -3
  35. package/codecs/README.md +23 -261
  36. package/codecs/WIRE_FORMAT.md +132 -0
  37. package/core.k +5 -15
  38. package/named-patterns.mjs +19 -7
  39. package/objects/README.md +24 -109
  40. package/package.json +8 -3
  41. package/paper/Makefile +17 -0
  42. package/paper/k-paper.pdf +0 -0
  43. package/paper/k-paper.tex +435 -0
  44. package/parser.jison +0 -10
  45. package/parser.mjs +32 -43
  46. package/repl.mjs +74 -29
  47. package/scripts/benchmark-idempotency.mjs +3 -3
  48. package/scripts/run-tests.mjs +1 -1
  49. package/scripts/test-package.mjs +64 -0
  50. package/tests/README.md +66 -46
  51. package/tests/code-derivation/core.mjs +61 -0
  52. package/tests/helpers/cli.mjs +45 -0
  53. package/tests/integration.sh +2 -3
  54. package/tests/test-arithmetics.mjs +47 -237
  55. package/tests/test-djson-methods.mjs +71 -275
  56. package/tests/test-hash-normalization.mjs +22 -1
  57. package/tests/test-karatsuba.mjs +18 -126
  58. package/tests/test-named-patterns.mjs +174 -621
  59. package/tests/test-paper-examples.mjs +90 -0
  60. package/tests/test-poly.mjs +2 -2
  61. package/tests/test-repl-html.mjs +22 -10
  62. package/tests/test-repl.mjs +49 -41
  63. package/tests/test.mjs +27 -68
  64. package/AGENTS.md +0 -35
  65. package/CLAUDE.md +0 -64
  66. package/DOCS/BIG_PICTURE.md +0 -439
  67. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  68. package/DOCS/CANONICAL_PATTERNS.md +0 -362
  69. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  70. package/DOCS/CONVERGENCE.md +0 -123
  71. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  72. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  73. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  74. package/DOCS/Makefile +0 -99
  75. package/DOCS/NAMED_PATTERNS.md +0 -361
  76. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  77. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  78. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -134
  79. package/DOCS/book/01-introduction.md +0 -48
  80. package/DOCS/book/02-syntax-and-values.md +0 -110
  81. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  82. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  83. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  84. package/DOCS/book/06-values-in-memory.md +0 -1085
  85. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  86. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  87. package/DOCS/book/09-compiler-architecture.md +0 -160
  88. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  89. package/DOCS/book/14-canonical-serialization.md +0 -176
  90. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  91. package/DOCS/book/overview.txt +0 -68
  92. package/DOCS/book.md +0 -50
  93. package/Examples/bnat.k +0 -308
  94. package/Examples/buda.k +0 -66
  95. package/Examples/byte.k +0 -35
  96. package/Examples/code.k +0 -43
  97. package/Examples/vhdl_to_k.k +0 -67
  98. package/JOURNAL.md +0 -288
  99. package/TODO.md +0 -107
  100. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  101. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  102. package/backends/wasm/demo_ieee.mjs +0 -318
  103. package/browser/vfs-data.mjs +0 -21
  104. package/codecs/BINARY_FORMAT.md +0 -53
  105. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  106. package/codecs/pandoc.css +0 -71
  107. package/tests/code-derivation/blowup.mjs +0 -25
  108. package/tests/code-derivation/bnat.mjs +0 -11
  109. package/tests/code-derivation/dot.mjs +0 -37
  110. package/tests/code-derivation/index.mjs +0 -20
  111. package/tests/code-derivation/loop.mjs +0 -17
  112. package/tests/code-derivation/nat.mjs +0 -10
  113. package/tests/code-derivation/not-not.mjs +0 -14
  114. package/tests/code-derivation/product.mjs +0 -22
  115. package/tests/code-derivation/rlz.mjs +0 -13
  116. package/tests/test-fingerprint.mjs +0 -38
@@ -448,8 +448,8 @@ console.log("==> Running End-to-End Peano Addition & Serialization Tests");
448
448
  inc = | +1 nat?;
449
449
  dec = nat? / +1;
450
450
  add = ?{ nat? x, nat? y } = X <
451
- { . x dec x, . y inc y } ?X add,
452
- . y
451
+ { . x / 0 a, . y then } . then,
452
+ { . x dec x, . y inc y } ?X add
453
453
  >;
454
454
  ()
455
455
  `;
@@ -625,4 +625,88 @@ console.log("==> Running End-to-End Peano Addition & Serialization Tests");
625
625
  console.log("End-to-End Peano Addition & Serialization tests passed successfully!");
626
626
  }
627
627
 
628
+ console.log("==> Running Union Non-Final Branch Recursion & Factored Tail-Call Tests (Issue #3)");
629
+ {
630
+ const runtimeWat = fs.readFileSync("runtime.wat", "utf8");
631
+
632
+ // 1. Issue #3: Self-call in a non-final union branch must NOT be tail-call optimized,
633
+ // because failure of the recursive call must backtrack to subsequent union branches
634
+ // with the original input.
635
+ const backtrackDefs = annotate(`
636
+ t[] = < {} a, { T x } b > = T;
637
+ f = ?t[] <
638
+ /b .x f,
639
+ /b {} |a
640
+ > ?t[];
641
+ main = ?t[] /b .x f;
642
+ ()
643
+ `, { convergence: { strategy: "auto" } });
644
+
645
+ const fWat = lowerToWasm(backtrackDefs.rels.f, "f");
646
+ const mainWat = lowerToWasm(backtrackDefs.rels.main, "main");
647
+ assert.match(fWat, /\bcall \$f\b/, "Self-call in non-final union branch must emit a regular call");
648
+ assert.doesNotMatch(fWat, /\bbr \$tail_loop\b/, "Self-call in non-final union branch must not jump to $tail_loop");
649
+
650
+ const fullBacktrackWat = runtimeWat.trim().slice(0, -1) + "\n" + fWat + "\n" + mainWat + "\n)";
651
+ const binaryBacktrack = compileWat("union_backtrack.wat", fullBacktrackWat);
652
+ const exportsBacktrack = await instantiateWasm(binaryBacktrack);
653
+
654
+ function writeUnit(exports) {
655
+ const ptr = exports.alloc(8);
656
+ const view = new DataView(exports.memory.buffer);
657
+ view.setUint32(ptr, 8, true);
658
+ view.setUint32(ptr + 4, 0, true);
659
+ return ptr;
660
+ }
661
+
662
+ function writeVariant(exports, tag, payloadPtr) {
663
+ const ptr = exports.alloc(12);
664
+ const view = new DataView(exports.memory.buffer);
665
+ view.setUint32(ptr, 12, true);
666
+ view.setUint32(ptr + 4, getTagId(tag), true);
667
+ view.setUint32(ptr + 8, payloadPtr, true);
668
+ return ptr;
669
+ }
670
+
671
+ function writeSingleFieldProduct(exports, label, valPtr) {
672
+ const ptr = exports.alloc(16);
673
+ const view = new DataView(exports.memory.buffer);
674
+ view.setUint32(ptr, 16, true);
675
+ view.setUint32(ptr + 4, 1, true);
676
+ view.setUint32(ptr + 8, getTagId(label), true);
677
+ view.setUint32(ptr + 12, valPtr, true);
678
+ return ptr;
679
+ }
680
+
681
+ // Construct b(b(a)) = {{{} |a x} |b x} |b
682
+ const aPtr = writeVariant(exportsBacktrack, "a", writeUnit(exportsBacktrack));
683
+ const baPtr = writeVariant(exportsBacktrack, "b", writeSingleFieldProduct(exportsBacktrack, "x", aPtr));
684
+ const bbaPtr = writeVariant(exportsBacktrack, "b", writeSingleFieldProduct(exportsBacktrack, "x", baPtr));
685
+
686
+ const resBacktrack = exportsBacktrack.main(bbaPtr);
687
+ assert.equal(resBacktrack[1], 1, "main(b(b(a))) must succeed by backtracking to branch 2 of f(b(a))");
688
+ const viewBacktrack = new DataView(exportsBacktrack.memory.buffer);
689
+ assert.equal(viewBacktrack.getUint32(resBacktrack[0] + 4, true), getTagId("a"), "main(b(b(a))) must return variant |a");
690
+
691
+ // 2. Factored tail-recursive union `< { ... }, { ... } > self` in the final branch of a union
692
+ // must forward product fields directly into $tail_in_* locals without allocating a product.
693
+ const factoredDefs = annotate(`
694
+ bits[] = < {} _, B 0, B 1 > = B;
695
+ eat = ?{ bits[] x, bits[] y } <
696
+ { .x /_ a, .y then } .then,
697
+ <
698
+ { .x /0 x, .y |0 y },
699
+ { .x /1 x, .y |1 y }
700
+ > eat
701
+ > ?bits[];
702
+ ()
703
+ `, { convergence: { strategy: "auto" } });
704
+
705
+ const eatWat = lowerToWasm(factoredDefs.rels.eat, "eat");
706
+ assert.doesNotMatch(eatWat, /\bcall \$eat\b/, "Factored tail-recursive union must not emit a Wasm self-call");
707
+ assert.match(eatWat, /;; tail-call field x/, "Factored tail-recursive union branches must forward product fields directly to $tail_in_*");
708
+
709
+ console.log("Union Non-Final Branch Recursion & Factored Tail-Call tests passed successfully!");
710
+ }
711
+
628
712
  console.log("==> Harness ready.");
@@ -59,9 +59,13 @@ function skeletonizeFilter(filter, knots) {
59
59
  return { ...node };
60
60
  }
61
61
  if (node.type === "pattern_apply") {
62
- const pos = node.start
63
- ? ` (lines ${node.start.line}:${node.start.column})`
64
- : "";
62
+ const pos =
63
+ node.start && node.end
64
+ ? ` (lines ${node.start.line}:${node.start.column}...` +
65
+ `${node.end.line}:${node.end.column})`
66
+ : node.start
67
+ ? ` (lines ${node.start.line}:${node.start.column})`
68
+ : "";
65
69
  const suffix = node.pattern?.startsWith("@") ? "" : "[]";
66
70
  throw new Error(
67
71
  `Unknown pattern template '${node.pattern}${suffix}'${pos}`
package/codecs/README.md CHANGED
@@ -1,268 +1,30 @@
1
- # K Codecs
1
+ # Codecs
2
2
 
3
- This directory is centered on the codec design:
3
+ These tools translate text or external data to/from k's binary
4
+ schema+payload stream.
4
5
 
5
- ```text
6
- abstract pattern graph + prefix-free tree encoding
7
- ```
8
-
9
- The default concrete format is now the binary encoding of a `pattern`
10
- value, using the `pattern` relation from [`../core.k`](../core.k),
11
- immediately followed by the binary encoding of the value under that
12
- decoded pattern.
13
-
14
- `core.k` is not loaded automatically as a library when user programs
15
- run. The codec only depends on the canonical `pattern` definition from
16
- that file as the schema for the leading pattern value.
17
-
18
- There is no separate JSON container format.
19
-
20
- ## Objectives
21
-
22
- The design is guided by two hard requirements:
23
-
24
- 1. compactness close to the structural lower bound,
25
- 2. efficient `k` projections, especially `.field` and `/tag`.
26
-
27
- The current target architecture is the pattern graph plus prefix-free
28
- value-tree stream described here and in
29
- [`POLYMORPHIC_BINARY_FORMAT.md`](./POLYMORPHIC_BINARY_FORMAT.md).
30
-
31
- ## Core Idea
32
-
33
- The semantic object serialized by the codec is:
34
-
35
- ```text
36
- (P, v)
37
- ```
38
-
39
- where:
40
-
41
- - `P` is an abstract rooted pattern graph,
42
- - `v` is a value tree compatible with `P`.
43
-
44
- The same pair is the in-memory runtime model as well. Decoding a stream
45
- attaches `P` to the resulting `Value` as `value.pattern`; evaluation
46
- propagates that pattern through projections and constructors; encoding
47
- a `Value` uses its carried pattern unless an explicit pattern is
48
- supplied.
49
-
50
- The base value encoding is:
51
-
52
- - tree-based, not DAG-based,
53
- - prefix-free,
54
- - interpreted relative to the pattern graph,
55
- - free of repeated field names and tag names in the value payload.
56
-
57
- The base codec does **not** perform DAG compression. If sharing is
58
- desired, it should happen as a higher-level transform, not inside the
59
- primitive value format.
6
+ | Command | Boundary |
7
+ | --- | --- |
8
+ | `k-parse` / `k-print` | Textual k values ↔ binary stream |
9
+ | `k-show` | Pass through a stream while inspecting its value and pattern on stderr |
10
+ | `k-unit` | Unit |
11
+ | `k-int` | Decimal integers and integer lists |
12
+ | `k-ieee` | Floating-point text |
13
+ | `k-utf8` / `k-utf16` | External Unicode text encodings |
14
+ | `k-json` | JSON with a document-specific schema |
15
+ | `k-djson` | JSON with a universal recursive representation |
60
16
 
61
- ## Wire Format
17
+ The external codecs use `--parse` and `--print`. All commands support
18
+ `--help`. From the repository root:
62
19
 
63
- The default transport format is:
64
-
65
- ```text
66
- encode(pattern_value : pattern) encode(value : decoded_pattern)
67
- ```
68
-
69
- `pattern_value` is a normal k value whose shape is defined in `core.k`.
70
- After that value is decoded, it becomes the pattern used to decode the
71
- remaining value payload.
72
-
73
- The runtime boundary is therefore:
74
-
75
- ```text
76
- binary pattern+value stream <-> Value(pattern, tree)
77
- ```
78
-
79
- At the command-line boundary, `k-parse` and `k-print` use a JSON-like
80
- textual notation for k values. That notation is documented in
81
- [`../DOCS/TEXTUAL_VALUES.md`](../DOCS/TEXTUAL_VALUES.md). It is a
82
- readable notation for k values, not a separate JSON container format.
83
-
84
- For the codec architecture and specification, see
85
- [`../DOCS/CODEC_ARCHITECTURE.md`](../DOCS/CODEC_ARCHITECTURE.md).
86
- For the contributor-facing guide to writing a new external codec module,
87
- see [`../DOCS/CODECS.md`](../DOCS/CODECS.md).
88
- For the broader view of all artifacts and compilation targets, see
89
- [`../DOCS/FILE_FORMATS.md`](../DOCS/FILE_FORMATS.md).
90
-
91
- `k.mjs` is only the command-line adapter for that boundary. The
92
- operational runtime sees and preserves the pattern on the `Value`
93
- itself.
94
-
95
- ## Command-Line Tools
96
-
97
- Installed codec binaries use the `k-` prefix followed by the source
98
- basename without `.mjs`. Source names that already include `k-`, such
99
- as `k-parse.mjs`, keep that name. Every installed codec binary supports
100
- `-h` and `--help`.
101
-
102
- | Binary | Source | Purpose |
103
- | --- | --- | --- |
104
- | `k-parse` | `k-parse.mjs` | Read a textual k value and write a binary pattern+value stream. Use `--input-type` or `--input-pattern` to supply the input envelope. |
105
- | `k-print` | `k-print.mjs` | Read a binary pattern+value stream and write the decoded JSON-like value. Use `--debug` to include the decoded pattern. |
106
- | `k-show` | `show.mjs` | Pass the wire stream through unchanged on stdout while printing the decoded value and filter to stderr. |
107
- | `k-json` | `json.mjs` | Convert JSON to/from the binary stream with `--parse` or `--print`. |
108
- | `k-djson` | `djson.mjs` | Dynamic binary bit-trie JSON codec. |
109
- | `k-int` | `int.mjs` | Convert decimal integers to/from the binary stream with `--parse` or `--print`. |
110
- | `k-ieee` | `ieee.mjs` | Convert float literals to/from the binary stream with `--parse` or `--print`. |
111
- | `k-unit` | `unit.mjs` | Write or validate the unit value `{}` with `--parse` or `--print`. |
112
- | `k-utf8` | `utf8.mjs` | Convert UTF-8 text to/from a k string stream with `--parse` or `--print`. |
113
- | `k-utf16` | `utf16.mjs` | Convert BOM-aware UTF-16 input or UTF-16LE output to/from a k string stream with `--parse` or `--print`. |
114
-
115
- ## Pattern Graph Representation
116
-
117
- For documentation and tests, a pattern graph may be shown as a
118
- property-list style vector of nodes:
119
-
120
- ```text
121
- [kind, edges]
20
+ ```sh
21
+ printf '42\n' | node codecs/int.mjs --parse | node codecs/int.mjs --print
122
22
  ```
123
23
 
124
- where:
125
-
126
- - `kind` is one of:
127
- - `"any"`
128
- - `"open-product"`
129
- - `"open-union"`
130
- - `"closed-product"`
131
- - `"closed-union"`
132
- - `edges` is a list of:
133
- - `[label, target_node_id]`
134
-
135
- Example:
136
-
137
- ```json
138
- [
139
- ["closed-union", [["nil", 1], ["cons", 2]]],
140
- ["closed-product", []],
141
- ["closed-product", [["car", 3], ["cdr", 0]]],
142
- ["closed-union", [["_", 1], ["0", 3], ["1", 3]]]
143
- ]
144
- ```
145
-
146
- Canonical rules:
147
-
148
- - root node is node `0`,
149
- - node list order is canonical graph-discovery order,
150
- - edges are sorted by label,
151
- - edge labels are unique within a node,
152
- - `"any"` must have no outgoing edges.
153
-
154
- This JSON-like graph is only a readable notation. The wire
155
- representation is the ordinary k `pattern` value from `core.k`.
156
-
157
- For pattern export, see [`../DOCS/PATTERNS.md`](../DOCS/PATTERNS.md) and
158
- the repository helper `patterns/from-k.mjs`.
159
-
160
- ## Witness-Derived Patterns
161
-
162
- When `k-parse` is used without an explicit input pattern or type, the
163
- wire pattern is derived from the parsed value tree.
164
-
165
- - An empty textual node is a closed product: `{}`.
166
- - A textual node with multiple children is a closed product.
167
- - A textual node with one child is interpreted as an open union by
168
- default.
169
- - An explicit product input pattern may force such a node to be
170
- treated as a singleton product instead.
171
-
172
- For example, parsing:
173
-
174
- ```text
175
- {a:{b:x,c:{}}}
176
- ```
177
-
178
- without an input pattern derives:
179
-
180
- ```json
181
- [
182
- ["open-union", [["a", 1]]],
183
- ["closed-product", [["b", 2], ["c", 3]]],
184
- ["open-union", [["x", 3]]],
185
- ["closed-product", []]
186
- ]
187
- ```
188
-
189
- During this construction, finite closed pattern subtrees are hash-consed
190
- from the leaves upward. The starting closed leaf is `["closed-product",
191
- []]`. Two closed nodes collapse only when they have the same closed
192
- kind, the same labels, and the same already-collapsed child targets.
193
- Open nodes keep their identity, and recursive closed nodes are not
194
- collapsed by this witness-tree rule.
195
-
196
- This is canonicalization of the pattern graph carried in the wire
197
- stream. It is not DAG compression of the value payload.
198
-
199
- ## Prefix-Free Value Encoding
200
-
201
- The value payload is a bitstream interpreted relative to the pattern
202
- graph.
203
-
204
- Base rules:
205
-
206
- - closed or open product:
207
- - encode child values in canonical edge order,
208
- - closed or open union:
209
- - encode the selected tag position,
210
- - then encode the selected payload,
211
- - `any`:
212
- - not directly value-carrying in the base format.
213
-
214
- The initial concrete union encoding rule is:
215
-
216
- ```text
217
- width = ceil(log2(cardinality))
218
- emit tag ordinal in width bits
219
- ```
220
-
221
- This is the simplest canonical prefix-free choice encoding. It is not
222
- the final word on compression, but it gives a regular and compact base
223
- encoding that can later be refined without changing the abstract
224
- pattern/value model.
225
-
226
- ## Projections
227
-
228
- The base tree encoding is chosen so that:
229
-
230
- - `/tag` only needs to read the union choice at the current node,
231
- - `.field` follows canonical product order and may later be accelerated
232
- by higher-level indexes if necessary.
233
-
234
- In the materialized runtime, projections also project the carried
235
- pattern: `.field` returns the subpattern at that product field, and
236
- `/tag` returns the subpattern at that union tag. If no carried subpattern
237
- is available, later encoding can still derive a witness pattern from
238
- the result tree.
239
-
240
- The primitive codec stays minimal. Projection indexes, framing, or
241
- sharing schemes are explicitly separate concerns.
242
-
243
- ## Design Boundary
244
-
245
- The new codec work is split into layers:
246
-
247
- 1. abstract pattern graph semantics,
248
- 2. prefix-free value-tree semantics relative to that graph,
249
- 3. self-hosted `k` representation of the pattern graph,
250
- 4. optional higher-level optimizations.
251
-
252
- ## Files
253
-
254
- - [`../DOCS/FILE_FORMATS.md`](../DOCS/FILE_FORMATS.md):
255
- comprehensive guide to file formats and compilation pipelines.
256
- - [`../DOCS/CODEC_ARCHITECTURE.md`](../DOCS/CODEC_ARCHITECTURE.md):
257
- comprehensive architecture specification for k codecs.
258
- - [`../DOCS/CODECS.md`](../DOCS/CODECS.md):
259
- practical guide to writing, running, and testing codecs.
260
- - [`POLYMORPHIC_BINARY_FORMAT.md`](./POLYMORPHIC_BINARY_FORMAT.md):
261
- main design document for the pattern-plus-prefix-tree codec.
262
- - [`BINARY_FORMAT.md`](./BINARY_FORMAT.md):
263
- notes on future binary packaging of the same abstract semantics.
264
-
265
- ## Status
24
+ The runtime carries the envelope as `value.pattern`. The leading wire pattern
25
+ is encoded under the fixed `pattern[]` schema defined in
26
+ [core.k](../core.k); user programs do not automatically import that library.
266
27
 
267
- The active command-line pipeline emits and consumes the self-hosted
268
- binary pattern+value stream.
28
+ Read the [wire specification](WIRE_FORMAT.md) for encoding, the
29
+ [textual-value guide](../DOCS/TEXTUAL_VALUES.md) for `k-parse` notation, or
30
+ [Writing codecs](../DOCS/CODECS.md) to add a module.
@@ -0,0 +1,132 @@
1
+ # Wire format
2
+
3
+ A k wire value is a pattern envelope followed by a payload tree encoded under
4
+ that pattern:
5
+
6
+ ```text
7
+ encode(pattern_value : pattern[]) encode(payload : decoded_pattern)
8
+ ```
9
+
10
+ There is no JSON transport container or value-DAG table in this format.
11
+ Property-list graphs shown below are host-side inspection notation.
12
+
13
+ ## Pattern framing
14
+
15
+ [core.k](../core.k) defines `pattern[]` as a list of graph nodes. Each node
16
+ is one of five tagged variants:
17
+
18
+ | Kind | Edges mean |
19
+ | --- | --- |
20
+ | `any` | Unconstrained position; no edges |
21
+ | `open-product` | Required fields, permitting additional schema fields |
22
+ | `closed-product` | Exactly the listed fields |
23
+ | `open-union` | Required tags, permitting additional schema tags |
24
+ | `closed-union` | Exactly the listed tags |
25
+
26
+ Edges pair a Unicode `string[]` label with a target node index encoded as
27
+ `bits[]`. Node zero is the root. Edge labels are unique within a node and use
28
+ canonical label order; graph nodes use canonical discovery order.
29
+
30
+ The complete closed schema of `pattern[]` is a fixed decoder context, shared
31
+ by both ends of the stream. It admits many pattern values; it is not a schema
32
+ with only one possible document. Its concrete graph is
33
+ `CORE_PATTERN_PROPERTY_LIST` in
34
+ [prefix-codec.mjs](runtime/prefix-codec.mjs).
35
+
36
+ The decoder first reads a pattern value under that context, then uses the
37
+ decoded graph for the payload.
38
+
39
+ ## Graph notation
40
+
41
+ The host representation is an array of `[kind, edges]` nodes, where each
42
+ edge is `[label, targetIndex]`. For a list of units:
43
+
44
+ ```json
45
+ [
46
+ ["closed-union", [["cons", 1], ["nil", 2]]],
47
+ ["closed-product", [["car", 2], ["cdr", 0]]],
48
+ ["closed-product", []]
49
+ ]
50
+ ```
51
+
52
+ This is the graph exported by the
53
+ [pattern helper](../DOCS/PATTERNS.md#inspection-and-persistence), not the bytes
54
+ written to a stream.
55
+
56
+ ## Payload bits
57
+
58
+ For a product, encode each field payload in canonical edge order, concatenated
59
+ without separators or repeated field names.
60
+
61
+ For a union with `n` tags, encode the selected tag's zero-based ordinal using:
62
+
63
+ ```text
64
+ width = ceil(log2(n))
65
+ ```
66
+
67
+ Then encode the selected payload under its target pattern. Invalid ordinals
68
+ are rejected. An empty union has no encodable values.
69
+
70
+ | Case | Choice/payload cost |
71
+ | --- | --- |
72
+ | Unit `{}` | Zero bits |
73
+ | Singleton union | Zero choice bits |
74
+ | Two-tag union | One choice bit |
75
+ | Three- or four-tag union | Two choice bits |
76
+
77
+ Bits are packed most significant first. Header and payload share one bitstream;
78
+ there is no byte-alignment gap between them. Output zero-pads the final byte.
79
+ The decoder rejects truncation, invalid choices, and nonzero trailing padding.
80
+
81
+ `any` cannot directly encode a payload. The pattern must first be refined with
82
+ enough structure for each position reached by the value.
83
+
84
+ ## Witness-derived patterns
85
+
86
+ Without an explicit pattern, textual k values use these witness rules:
87
+
88
+ - an empty node becomes a closed product;
89
+ - a node with multiple children becomes a closed product;
90
+ - a single-child node becomes an open union.
91
+
92
+ An open product input filter disambiguates a parsed singleton product;
93
+ fully closed patterns instead expect the value to already have the right kind.
94
+ For example,
95
+ `{a:{b:x,c:{}}}` derives:
96
+
97
+ ```json
98
+ [
99
+ ["open-union", [["a", 1]]],
100
+ ["closed-product", [["b", 2], ["c", 3]]],
101
+ ["open-union", [["x", 3]]],
102
+ ["closed-product", []]
103
+ ]
104
+ ```
105
+
106
+ Finite closed subgraphs are collapsed from the leaves upward when their kinds,
107
+ labels, and children agree. Open nodes retain distinct positions and their
108
+ constraints. This is graph normalization of the pattern, not compression of
109
+ repeated payload subtrees.
110
+
111
+ When encoding an enveloped runtime `Value`, `encodeToWire` uses the carried
112
+ pattern by default, or an explicitly supplied compatible pattern. Open or
113
+ incomplete patterns are refined against the value; closed graphs are
114
+ canonicalized and encoded directly.
115
+
116
+ ## Navigation and runtime values
117
+
118
+ `/tag` reads a choice code and continues into the matching payload.
119
+ `.field` locates the field in the pattern and decodes or skips preceding
120
+ children. The base format has no field-offset index or back-references.
121
+
122
+ Recursive graphs are encoded by following the finite payload tree, not by
123
+ unrolling the pattern into a table of value nodes. The in-memory evaluator
124
+ carries the selected subpattern through projections and constructs envelopes
125
+ for new products and variants.
126
+
127
+ `decodeWire` materializes a value; `decodeWireLazy` supports bitstream-backed
128
+ access. These are implementation choices over the same wire representation.
129
+
130
+ See [textual values](../DOCS/TEXTUAL_VALUES.md),
131
+ [codec authoring](../DOCS/CODECS.md), and
132
+ [file formats](../DOCS/FILE_FORMATS.md) for the surrounding boundaries.
package/core.k CHANGED
@@ -1,9 +1,9 @@
1
1
  -- core.k — the k standard core library
2
2
  --
3
3
  -- Defines:
4
- -- 1. bits? — canonical binary number / bit-path relation
5
- -- 2. string? — unicode strings relation (used for labels)
6
- -- 3. pattern? — pattern graph relation
4
+ -- 1. bits[] — canonical binary number / bit-path relation
5
+ -- 2. string[] — unicode strings relation (used for labels)
6
+ -- 3. pattern[] — pattern graph relation
7
7
 
8
8
  ---------------------------------------------------------------
9
9
  -- §1. Bits
@@ -12,14 +12,6 @@
12
12
  bit[] = < {} 0, {} 1 >;
13
13
  bits[] = < {} _, B 0, B 1 > = B;
14
14
 
15
- bit? = ? bit[];
16
- bits? = ? bits[];
17
-
18
- _ = {}|_;
19
-
20
- 0 = _ |0;
21
- 1 = _ |1;
22
-
23
15
  ---------------------------------------------------------------
24
16
  -- §2. Unicode and String
25
17
  ---------------------------------------------------------------
@@ -83,8 +75,6 @@ unicode[] = <
83
75
  -- Linked-list string: nil or (unicode car, string cdr).
84
76
  string[] = < {} nil, { unicode[] car, S cdr } cons > = S;
85
77
 
86
- string? = ? string[];
87
-
88
78
  ---------------------------------------------------------------
89
79
  -- §3. Pattern
90
80
  ---------------------------------------------------------------
@@ -112,6 +102,6 @@ node[] = <
112
102
 
113
103
  pattern[] = < {} nil, { node[] car, P cdr } cons > = P;
114
104
 
115
- pattern? = ? pattern[];
105
+ ---
116
106
 
117
- pattern?
107
+ ? pattern[]
@@ -34,10 +34,14 @@ export function expandFilter(
34
34
  template = patterns["@" + patternName];
35
35
  }
36
36
  if (!template) {
37
- const pos = filter.start
38
- ? ` (lines ${filter.start.line}:${filter.start.column})`
39
- : "";
40
- const suffix = patternName.startsWith("@") ? "" : "[]";
37
+ const pos =
38
+ filter.start && filter.end
39
+ ? ` (lines ${filter.start.line}:${filter.start.column}...` +
40
+ `${filter.end.line}:${filter.end.column})`
41
+ : filter.start
42
+ ? ` (lines ${filter.start.line}:${filter.start.column})`
43
+ : "";
44
+ const suffix = "[]";
41
45
  throw new Error(
42
46
  `Unknown pattern template '${patternName}${suffix}'${pos}`
43
47
  );
@@ -53,9 +57,13 @@ export function expandFilter(
53
57
  const expectedArity = template.params.length;
54
58
  const actualArity = (filter.args || []).length;
55
59
  if (expectedArity !== actualArity) {
56
- const pos = filter.start
57
- ? ` (lines ${filter.start.line}:${filter.start.column})`
58
- : "";
60
+ const pos =
61
+ filter.start && filter.end
62
+ ? ` (lines ${filter.start.line}:${filter.start.column}...` +
63
+ `${filter.end.line}:${filter.end.column})`
64
+ : filter.start
65
+ ? ` (lines ${filter.start.line}:${filter.start.column})`
66
+ : "";
59
67
  throw new Error(
60
68
  `Pattern '${patternName}' expects ${expectedArity} ` +
61
69
  `argument${expectedArity === 1 ? "" : "s"}, ` +
@@ -186,6 +194,10 @@ export function expandFilter(
186
194
  if (filter.name) {
187
195
  instantiated.name = filter.name;
188
196
  }
197
+ if (filter.start) {
198
+ instantiated.start = filter.start;
199
+ instantiated.end = filter.end || filter.start;
200
+ }
189
201
  return instantiated;
190
202
  }
191
203