@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
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
 
package/objects/README.md CHANGED
@@ -1,112 +1,27 @@
1
- # objects/
2
-
3
- CLI tools for compiling and inspecting k object files (`.ko`), library
4
- files (`.klib`), and polymorphic kVM template files (`.kvm`).
5
-
6
- ## Tools
7
-
8
- ### `k-compile`
9
-
10
- Compiles `.k` source into an executable object file (`.ko`), library
11
- file (`.klib`), or polymorphic kVM backend artifact (`.kvm`). Output
12
- format is inferred from the output extension, or from `--format`.
13
-
14
- ```bash
15
- k-compile [--lib lib-file] [--export spec]... \
16
- [--format ko|klib|kvm] [source-snippet | input-file [output-file]]
17
- ```
18
-
19
- Existing input paths are read as files. A non-existing input with `.k`,
20
- `.ko`, or `.klib` extension is reported as a missing file; otherwise it
21
- is compiled as inline k source, in the same style as `k.mjs`.
22
-
23
- `.kvm` is a polymorphic kVM template artifact (`layer: "KVM-P"`). It
24
- carries relational function definitions, principal pattern graphs,
25
- and lowered kVM instruction streams ready for runtime specialization
26
- when enveloped values arrive (`specializeKVM`).
27
-
28
- When linking a `--lib` dependency, all relations are loaded under their
29
- canonical content-addressed hashes (`@hash`). To use human-readable
30
- alias names in an expression or script, explicitly map them into the
31
- local scope using `--export <alias>` or
32
- `--export <libAlias>:<localAlias>`.
33
- Alternatively, canonical `@hash` names may always be referenced directly.
34
-
35
- ### `k-decompile`
36
-
37
- Decompiles a `.ko` or `.klib` back into human-readable k source.
38
-
39
- ```bash
40
- k-decompile [object-file [k-file]]
41
- ```
42
-
43
- ### `k-extract-aliases`
44
-
45
- Extracts metadata aliases from a `.ko` or `.klib` as a valid k
46
- definition snippet. Output is grouped by metadata type (`code`, then
47
- `rel`), then sorted by alias name and `compiledAt`.
48
-
49
- ```bash
50
- k-extract-aliases [object-file [k-file]]
51
- ```
52
-
53
- ### `k-inspect-object`
54
-
55
- Inspects a `.ko` or `.klib`. By default it prints a compact object
56
- summary. With `--kir`, it prints the current KIR-P export used by
57
- backend experiments.
58
-
59
- ```bash
60
- k-inspect-object [--summary | --kir] [object-file]
61
- ```
62
-
63
- For scripts that only need KIR-P export, `k-kir [object-file]` is the
64
- direct exporter backed by `kir.mjs`.
65
-
66
- ### `k-validate-object`
67
-
68
- Validates a `.ko` or `.klib` object and its derived KIR-P export. With
69
- `--kir`, it validates an already exported KIR-P artifact.
70
-
71
- ```bash
72
- k-validate-object [--kir] [input-file]
1
+ # Object tools
2
+
3
+ Run these modules with `node` from a checkout, or use the installed names after
4
+ `npm link`.
5
+
6
+ | Command | Purpose |
7
+ | --- | --- |
8
+ | `k-compile` | Compile source into `.ko`, `.klib`, or `.kvm`; infer output format from the extension |
9
+ | `k-decompile` | Render object/library definitions as k source |
10
+ | `k-extract-aliases` | Recover aliases as source definitions |
11
+ | `k-inspect-object` | Inspect a summary, or export KIR-P with `--kir` |
12
+ | `k-validate-object` | Validate an object, library, or exported KIR-P (`--kir`) |
13
+ | `k-kir` | Export KIR-P directly |
14
+
15
+ ```sh
16
+ node objects/compile.mjs '{} |ok' /tmp/k-ok.ko
17
+ node objects/inspect.mjs /tmp/k-ok.ko
18
+ node objects/validate.mjs /tmp/k-ok.ko
73
19
  ```
74
20
 
75
- The installed names are `k-` plus the source basename without `.mjs`.
76
- Every installed object binary supports `-h` and `--help`.
77
-
78
- ## Current Format Notes
79
-
80
- - For full specifications, see
81
- [`DOCS/FILE_FORMATS.md`](../DOCS/FILE_FORMATS.md).
82
- - Both `.ko` and `.klib` are ahead-of-time (AOT) type-checked artifacts.
83
- Parsing, relation expansion, type derivation, and constraint
84
- convergence are completed in advance.
85
- - `.klib` files are plain UTF-8 JSON, not binary containers
86
- (`main: null`).
87
- - `.ko` files use the `KOBJ\n` binary header followed by a JSON payload
88
- (`main: "__main__"`).
89
- - There is no object payload version field in either format.
90
- - `typeDerivation` belongs only to relations and currently stores only
91
- `status`.
92
- - Source `start` / `end` ranges live on `meta[hash].origins[]` entries.
93
- - Origin entries do not have `kind`; the metadata entry has `type: "code"`
94
- or `type: "rel"`.
95
- - Stored relation bodies do not include generated input/output filters.
96
- - KIR-P is available as an inspection/export contract; it does not change
97
- the stored `.ko` or `.klib` payload.
98
- - `.kvm` is a polymorphic backend template artifact (`layer: "KVM-P"`),
99
- lowered from KIR-P for runtime execution and JIT specialization.
100
-
101
- ## Further reading
21
+ `--lib` loads a dependency. It does not select library output; use a `.klib`
22
+ output filename or `--format klib`. Friendly library names need explicit
23
+ `--export` mappings.
102
24
 
103
- - [DOCS/FILE_FORMATS.md](../DOCS/FILE_FORMATS.md) — guide to
104
- .k, .ko, .klib, and .kvm formats
105
- - [DOCS/OBJECT_FILE_AND_PATTERN.md](../DOCS/OBJECT_FILE_AND_PATTERN.md) —
106
- object file format and pattern encoding
107
- - [DOCS/KIR_V1.md](../DOCS/KIR_V1.md) — KIR-P inspection/export contract
108
- for backends
109
- - [DOCS/TYPE_DERIVATION.md](../DOCS/TYPE_DERIVATION.md) — type
110
- derivation (what compilation skips when loading a `.ko`/`.klib`)
111
- - [DOCS/CONVERGENCE.md](../DOCS/CONVERGENCE.md) — convergence strategies
112
- for type inference
25
+ The [file-format reference](../DOCS/FILE_FORMATS.md) is the source for container
26
+ fields, executable/library distinctions, aliases, and complete workflows.
27
+ [KIR-P](../DOCS/KIR_V1.md) documents the portable backend export.