@fraczak/k 8.4.0 → 8.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/DOCS/ARCHITECTURE.md +83 -0
  3. package/DOCS/CODECS.md +93 -204
  4. package/DOCS/DICTIONARY.md +42 -1241
  5. package/DOCS/FILE_FORMATS.md +170 -625
  6. package/DOCS/GETTING_STARTED.md +164 -0
  7. package/DOCS/KIR_V1.md +22 -33
  8. package/DOCS/KVM_EXECUTION_MODEL.md +88 -481
  9. package/DOCS/PATTERNS.md +156 -123
  10. package/DOCS/POLYMORPHIC_IR.md +83 -101
  11. package/DOCS/PROFILING_AND_TRACING.md +52 -166
  12. package/DOCS/README.md +35 -0
  13. package/DOCS/REPL.md +100 -371
  14. package/DOCS/TEXTUAL_VALUES.md +53 -81
  15. package/DOCS/TYPE_DERIVATION.md +95 -234
  16. package/DOCS/book-combined.md +3786 -0
  17. package/Examples/arithmetics.k +45 -59
  18. package/Examples/djson.k +102 -112
  19. package/Examples/karatsuba-mult.k +2 -3
  20. package/Examples/list.k +6 -7
  21. package/Examples/nat.k +6 -6
  22. package/Examples/poly.k +45 -45
  23. package/LICENSE +15 -0
  24. package/README.md +72 -410
  25. package/backends/llvm/README.md +75 -97
  26. package/backends/llvm/src/cli.mjs +0 -31
  27. package/backends/wasm/README.md +88 -66
  28. package/backends/wasm/src/cli.mjs +0 -31
  29. package/canonical-pattern.mjs +69 -35
  30. package/codecs/README.md +23 -261
  31. package/codecs/WIRE_FORMAT.md +132 -0
  32. package/core.k +5 -15
  33. package/index.mjs +5 -1
  34. package/named-patterns.mjs +55 -7
  35. package/object.mjs +28 -6
  36. package/objects/README.md +24 -109
  37. package/package.json +8 -3
  38. package/paper/Makefile +17 -0
  39. package/paper/k-paper.pdf +0 -0
  40. package/paper/k-paper.tex +435 -0
  41. package/parser.jison +0 -10
  42. package/parser.mjs +32 -43
  43. package/repl.mjs +79 -101
  44. package/scripts/benchmark-idempotency.mjs +3 -3
  45. package/scripts/run-tests.mjs +1 -1
  46. package/scripts/test-package.mjs +64 -0
  47. package/tests/README.md +66 -46
  48. package/tests/code-derivation/core.mjs +61 -0
  49. package/tests/helpers/cli.mjs +45 -0
  50. package/tests/integration.sh +2 -3
  51. package/tests/test-arithmetics.mjs +47 -237
  52. package/tests/test-djson-methods.mjs +71 -275
  53. package/tests/test-hash-normalization.mjs +22 -1
  54. package/tests/test-karatsuba.mjs +18 -126
  55. package/tests/test-named-patterns.mjs +174 -606
  56. package/tests/test-paper-examples.mjs +90 -0
  57. package/tests/test-poly.mjs +2 -2
  58. package/tests/test-repl-html.mjs +2 -2
  59. package/tests/test-repl.mjs +89 -38
  60. package/tests/test.mjs +27 -68
  61. package/AGENTS.md +0 -35
  62. package/CLAUDE.md +0 -64
  63. package/DOCS/BIG_PICTURE.md +0 -439
  64. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  65. package/DOCS/CANONICAL_PATTERNS.md +0 -349
  66. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  67. package/DOCS/CONVERGENCE.md +0 -123
  68. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  69. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  70. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  71. package/DOCS/Makefile +0 -99
  72. package/DOCS/NAMED_PATTERNS.md +0 -340
  73. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  74. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  75. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -136
  76. package/DOCS/book/01-introduction.md +0 -48
  77. package/DOCS/book/02-syntax-and-values.md +0 -110
  78. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  79. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  80. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  81. package/DOCS/book/06-values-in-memory.md +0 -1085
  82. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  83. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  84. package/DOCS/book/09-compiler-architecture.md +0 -160
  85. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  86. package/DOCS/book/14-canonical-serialization.md +0 -176
  87. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  88. package/DOCS/book/overview.txt +0 -68
  89. package/DOCS/book.md +0 -50
  90. package/Examples/bnat.k +0 -308
  91. package/Examples/buda.k +0 -66
  92. package/Examples/byte.k +0 -35
  93. package/Examples/code.k +0 -43
  94. package/Examples/vhdl_to_k.k +0 -67
  95. package/JOURNAL.md +0 -288
  96. package/TODO.md +0 -107
  97. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  98. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  99. package/backends/wasm/demo_ieee.mjs +0 -318
  100. package/browser/vfs-data.mjs +0 -21
  101. package/codecs/BINARY_FORMAT.md +0 -53
  102. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  103. package/codecs/pandoc.css +0 -71
  104. package/tests/code-derivation/blowup.mjs +0 -25
  105. package/tests/code-derivation/bnat.mjs +0 -11
  106. package/tests/code-derivation/dot.mjs +0 -37
  107. package/tests/code-derivation/index.mjs +0 -20
  108. package/tests/code-derivation/loop.mjs +0 -17
  109. package/tests/code-derivation/nat.mjs +0 -10
  110. package/tests/code-derivation/not-not.mjs +0 -14
  111. package/tests/code-derivation/product.mjs +0 -22
  112. package/tests/code-derivation/rlz.mjs +0 -13
  113. package/tests/test-fingerprint.mjs +0 -38
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[]
package/index.mjs CHANGED
@@ -2,7 +2,10 @@ import { parse } from "./parser.mjs";
2
2
  import { fromObject, isValue } from "./Value.mjs";
3
3
  import { parseValue } from "./valueIO.mjs";
4
4
  import { compileTypes } from "./compiler.mjs";
5
- import { expandPatternsInRels } from "./named-patterns.mjs";
5
+ import {
6
+ expandPatternsInRels,
7
+ validatePatternDefinitions
8
+ } from "./named-patterns.mjs";
6
9
  import run from "./run.mjs";
7
10
  import codes from "./codes.mjs";
8
11
 
@@ -38,6 +41,7 @@ function annotate(script, options = {}) {
38
41
  const representatives = codes.register(defs.codes);
39
42
  const rels = {...defs.rels, "__main__": {def: exp}};
40
43
 
44
+ validatePatternDefinitions(defs.patterns || {}, options);
41
45
  expandPatternsInRels(rels, defs.patterns || {}, options);
42
46
 
43
47
  // Inject library relations into the rels table so @hash refs resolve
@@ -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
 
@@ -293,8 +305,44 @@ export function expandPatternsInRels(rels, patterns = {}, options = {}) {
293
305
  return rels;
294
306
  }
295
307
 
308
+ export function validatePatternDefinitions(
309
+ patterns = {},
310
+ options = {}
311
+ ) {
312
+ const allPatterns = { ...(options.patterns || {}), ...patterns };
313
+ if (options.libraries) {
314
+ for (const lib of options.libraries) {
315
+ const libPatterns =
316
+ lib.patterns ||
317
+ lib.defs?.patterns ||
318
+ lib.sourceDefs?.patterns ||
319
+ {};
320
+ for (const [name, pat] of Object.entries(libPatterns)) {
321
+ if (!(name in allPatterns)) {
322
+ allPatterns[name] = pat;
323
+ }
324
+ }
325
+ for (const [name, hash] of Object.entries(
326
+ lib.patternAlias || {}
327
+ )) {
328
+ if (libPatterns[name] && !(hash in allPatterns)) {
329
+ allPatterns[hash] = libPatterns[name];
330
+ }
331
+ }
332
+ }
333
+ }
334
+
335
+ for (const [name, pat] of Object.entries(patterns)) {
336
+ if (name.startsWith("@")) continue;
337
+ if (pat?.filter) {
338
+ expandFilter(pat.filter, allPatterns, new Set([name]));
339
+ }
340
+ }
341
+ }
342
+
296
343
  export default {
297
344
  expandFilter,
298
345
  expandExp,
299
346
  expandPatternsInRels,
347
+ validatePatternDefinitions,
300
348
  };
package/object.mjs CHANGED
@@ -336,7 +336,7 @@ function patternOrigin(source, name, compiledAt, pat, info) {
336
336
  };
337
337
  }
338
338
 
339
- function buildMeta(annotated, source) {
339
+ function buildMeta(annotated, source, options = {}) {
340
340
  const meta = {};
341
341
  const representatives = annotated.representatives || {};
342
342
  const relAlias = annotated.relAlias || {};
@@ -361,11 +361,27 @@ function buildMeta(annotated, source) {
361
361
  }
362
362
 
363
363
  const patterns = annotated.sourceDefs?.patterns || {};
364
+ const allPatterns = {};
365
+ if (options.libraries) {
366
+ for (const lib of options.libraries) {
367
+ const lp =
368
+ lib.patterns ||
369
+ lib.defs?.patterns ||
370
+ lib.sourceDefs?.patterns ||
371
+ {};
372
+ Object.assign(allPatterns, lp);
373
+ }
374
+ }
375
+ if (options.patterns) {
376
+ Object.assign(allPatterns, options.patterns);
377
+ }
378
+ Object.assign(allPatterns, patterns);
379
+
364
380
  for (const [name, pat] of Object.entries(patterns)) {
365
381
  if (!isSourceName(name)) continue;
366
382
  const info = resolvePatternCanonicalInfo(name, pat, {
367
- patterns,
368
- libraries: annotated.libraries || []
383
+ patterns: allPatterns,
384
+ libraries: options.libraries || []
369
385
  });
370
386
  if (info.hash) {
371
387
  addOrigin(
@@ -464,7 +480,7 @@ function compileObject(script, options = {}) {
464
480
  const serialized = serializeAnnotated(annotated);
465
481
  const meta = mergeMetaEntries(
466
482
  importedLibraryMeta(options.libraries),
467
- buildMeta(annotated, options.source || null)
483
+ buildMeta(annotated, options.source || null, options)
468
484
  );
469
485
 
470
486
  // Prune to reachable from main
@@ -521,7 +537,7 @@ function compileLibrary(script, options = {}) {
521
537
  const serialized = serializeAnnotated(annotated);
522
538
  const meta = mergeMetaEntries(
523
539
  importedLibraryMeta(options.libraries),
524
- buildMeta(annotated, options.source || null)
540
+ buildMeta(annotated, options.source || null, options)
525
541
  );
526
542
  const relAlias = serialized.relAlias || {};
527
543
 
@@ -571,7 +587,13 @@ function compileLibrary(script, options = {}) {
571
587
  info.params ||
572
588
  pat.params ||
573
589
  [],
574
- filter: info.canonicalFilterAst || pat.filter
590
+ filter: info.canonicalFilterAst || pat.filter,
591
+ _canonical: info.hash,
592
+ _canonicalDef: info.def,
593
+ _canonicalParams: info.canonicalParams,
594
+ _graphParams: info.canonicalParams,
595
+ _aliasArgs: info.aliasArgs,
596
+ _canonicalFilterAst: info.canonicalFilterAst
575
597
  };
576
598
  }
577
599
  }