@fraczak/k 8.3.0 → 8.4.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,43 @@ All notable changes to this project will be documented here.
5
5
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
6
6
  This project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [8.4.0] — 2026-10-23 — Linear Skeletons & Parameter Diagonalization
9
+
10
+ ### Pure Linear Skeleton Model for Parameterized Patterns
11
+
12
+ - **Never Equalize Leaves in Canonical Templates**:
13
+ - The canonicalizer derives a pure linear skeleton for all
14
+ parameterized patterns, treating every open leaf position as an
15
+ independent port (`X0, X1, X2, ...`).
16
+ - Leaves are never unified in the canonical pattern graph,
17
+ guaranteeing maximum template deduplication across all variations
18
+ of a structural schema (records, products, sums).
19
+ - **Parameter Diagonalization in Aliases**:
20
+ - Non-linear equality constraints across leaves are represented as
21
+ diagonalized argument vectors (`aliasArgs`) on the alias definition
22
+ itself rather than inside the canonical template graph:
23
+ * `same_pair[T] = @hash[T, T];` (formal parameter equality)
24
+ * `closed_same_pair[] = @hash[T, T];` (existential variable equality)
25
+ * `p[X] = @hash[X, Y, Y];` (mixed formal and existential equality)
26
+ * `p[] = @hash[X, X];` (pure existential equality)
27
+ - When instantiated, shared existential variables are renamed to fresh
28
+ unification variables (`_Y_np1`), enforcing structural equality at
29
+ use-time with full type safety.
30
+ - **Canonical Sharing Across Diagonalizations**:
31
+ - `pair[A, B]`, `same_pair[T]`, `closed_same_pair[]`, and `any_pair[]`
32
+ all compile to and share the exact same canonical pattern graph and
33
+ content hash (`@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm`).
34
+ - `diag_p[] = { X x, X y }` shares the same canonical hash as
35
+ `a[]`, `b[X]`, `c[X, Y]`, `d[Y, X]`.
36
+ - **Object File Persistence**:
37
+ - Ahead-of-time `.klib` and `.ko` object files persist canonical
38
+ deduplicated linear templates under `patterns[@hash]`, alias mappings
39
+ under `patternAlias`, and diagonalized routing vectors in
40
+ `meta[hash].origins[].aliasArgs`.
41
+ - **Documentation**:
42
+ - Updated `DOCS/CANONICAL_PATTERNS.md` and
43
+ `DOCS/OBJECT_FILE_AND_PATTERN.md`.
44
+
8
45
  ## [8.3.0] — 2026-10-22 — Content-Addressable Patterns & Aliasing
9
46
 
10
47
  ### Content-Addressable Canonical Patterns
@@ -15,102 +15,126 @@ This document specifies:
15
15
  3. Why the variable pointing to the root of a recursive pattern graph
16
16
  (and cycle knots in general) is an internal structural fixed-point
17
17
  and cannot be exposed as an external parameter.
18
+ 4. How canonical patterns, aliases, and argument routing are persisted
19
+ in object files (`.klib` and `.ko`).
18
20
 
19
21
  ---
20
22
 
21
- ## 2. Canonical Pattern Derivation
23
+ ## 2. Canonical Pattern Derivation: The Pure Linear Skeleton
22
24
 
23
25
  When a pattern is compiled:
24
26
  ```k
25
27
  p[X] = {X x, Y y, Y z};
26
28
  ```
27
- the compiler evaluates the right-hand filter into a minimal directed
28
- graph (regular tree automaton).
29
-
30
- ### 2.1 Full Variable Node Discovery
31
-
32
- In the graph representation:
33
- - `X` is an open port referenced at field `x`.
34
- - `Y` is an existential variable shared between fields `y` and `z`,
35
- constraining them to identical subtrees.
36
-
37
- The canonicalizer walks the minimal automaton in deterministic
38
- breadth-first traversal order, assigning canonical variable names
39
- `X0`, `X1`, `X2`, ... to each open variable node discovered in the
40
- graph.
41
-
42
- Crucially, **all** variable nodes present in the filter graph are
43
- retained in the canonical pattern definition. In the example above:
44
- - `X` becomes canonical port `X0`.
45
- - `Y` becomes canonical port `X1`.
46
-
47
- The resulting minimal canonical pattern graph produces a deterministic
48
- content hash (e.g. `@A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P`).
49
- The canonical pattern definition is therefore:
50
-
29
+ the compiler evaluates the right-hand filter into a
30
+ **pure linear skeleton**.
31
+
32
+ ### 2.1 Never Equalizing Pattern Leaves
33
+
34
+ In the pure skeleton model, two leaves of a pattern graph are **never
35
+ equalized** in the canonical template:
36
+ - Even if an author repeats an existential variable (like `Y` at fields
37
+ `y` and `z`), or repeats a formal parameter (like `T` in
38
+ `same_pair[T] = { T first, T second }`), the canonicalizer assigns an
39
+ independent, distinct canonical port `X0, X1, X2, ...` to every open
40
+ leaf slot.
41
+ - Any non-linear equality constraint between leaves is represented
42
+ outside the canonical graph, in the **diagonalized argument vector** of
43
+ the alias definition.
44
+
45
+ In the example `p[X] = {X x, Y y, Y z}`:
46
+ - Field `x` becomes canonical port `X0`.
47
+ - Field `y` becomes canonical port `X1`.
48
+ - Field `z` becomes canonical port `X2`.
49
+
50
+ The canonical pattern is the 3-port linear product:
51
51
  ```k
52
- @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X0, X1] = {
53
- X0 x, X1 y, X1 z
52
+ @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X0, X1, X2] = {
53
+ X0 x, X1 y, X2 z
54
54
  };
55
55
  ```
56
56
 
57
- Canonical patterns always take the full arity of all variable nodes
58
- discovered in the graph.
57
+ Canonical patterns always take the full arity of all leaf positions
58
+ discovered in the pattern skeleton.
59
59
 
60
60
  ---
61
61
 
62
- ## 3. Named Patterns as Parameter Routing Aliases
62
+ ## 3. Named Patterns as Parameter Routing and Diagonalization Aliases
63
63
 
64
64
  When an author defines an alias like:
65
65
  ```k
66
66
  p[X] = {X x, Y y, Y z};
67
67
  ```
68
- the user only exposed `X` in the parameter list `[X]`, leaving `Y`
69
- unexposed.
70
-
71
- The definition `p[X]` does **not** create a separate pattern graph.
72
- Instead, it defines an alias that instantiates the underlying canonical
73
- pattern `@A6vr...`, routing the author's parameter `X` to slot `X0`, and
74
- plugging unexposed slots (here `X1`) with the open wildcard `(...)`:
68
+ the definition `p[X]` does **not** create a separate canonical pattern
69
+ graph. Instead, it defines an alias that routes:
70
+ - The author's formal parameter `X` to slot `X0`.
71
+ - The shared existential variable `Y` to both slots `X1` and `X2`:
75
72
 
76
73
  ```k
77
- p[X] = @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X, (...)];
74
+ p[X] = @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X, Y, Y];
78
75
  ```
79
76
 
80
- ### 3.1 Canonical Pattern Sharing Across Permutations
77
+ When `p` is instantiated (e.g. `p[int]`), the template expansion engine:
78
+ 1. Substitutes formal parameter `X` with caller argument `int`.
79
+ 2. Renames internal existential variable `Y` to a unique fresh variable
80
+ `_Y_np1` across all occurrences in the argument list:
81
+ `@PScs...[int, _Y_np1, _Y_np1]`.
82
+ 3. Expands the canonical template with those arguments, yielding:
83
+ `{ int x, _Y_np1 y, _Y_np1 z }`.
84
+ 4. The type derivation engine unifies the type of field `y` with the type
85
+ of field `z` via the shared fresh variable `_Y_np1`.
86
+
87
+ Thus, existential equality constraints are preserved with full type-safety
88
+ at use-time, while enabling maximum structural template deduplication.
81
89
 
82
- Multiple alias definitions with different parameter exposures or
83
- orderings over isomorphic filter graphs share the exact same canonical
84
- hash:
90
+ ### 3.1 Canonical Pattern Sharing Across Diagonalizations and Permutations
85
91
 
92
+ Under this architecture, all variations over the same underlying product
93
+ or union structure share the **exact same canonical pattern graph and
94
+ content hash**:
95
+
96
+ #### Example 1: Pair Variations
86
97
  ```k
87
- a[] = {X x, Y y};
88
- b[X] = {X x, Y y};
89
- c[X,Y] = {X x, Y y};
90
- d[Y,X] = {X x, Y y};
98
+ pair[A, B] = { A first, B second };
99
+ same_pair[T] = { T first, T second };
100
+ closed_same_pair[] = { T first, T second };
101
+ any_pair[] = { (...) first, (...) second };
102
+ ```
103
+ All four compile to the single canonical skeleton:
104
+ ```k
105
+ @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[X0, X1] = {
106
+ X0 first, X1 second
107
+ };
91
108
  ```
92
109
 
93
- All four patterns compile to the identical canonical graph:
94
- `@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X0, X1] = {X0 x, X1 y};`
95
-
96
- Inspecting the aliases with `:pats` shows how each alias projects its
97
- arguments into the shared canonical template:
110
+ Their `:pats` alias representations reflect their respective parameter
111
+ routings and diagonalizations:
112
+ ```text
113
+ > :pats
114
+ any_pair[] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[(...),(...)]
115
+ closed_same_pair[] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T,T]
116
+ pair[A,B] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[A,B]
117
+ same_pair[T] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T,T]
118
+ ```
98
119
 
120
+ #### Example 2: Record `{ x, y }` Variations
121
+ ```k
122
+ a[] = { (...) x, (...) y };
123
+ b[X] = { X x, (...) y };
124
+ c[X,Y] = { X x, Y y };
125
+ d[Y,X] = { X x, Y y };
126
+ diag_p[] = { X x, X y };
127
+ ```
128
+ All five share `@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x`:
99
129
  ```text
100
130
  > :pats
101
131
  a[] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[(...),(...)]
102
132
  b[X] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,(...)]
103
133
  c[X,Y] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,Y]
104
134
  d[Y,X] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,Y]
135
+ diag_p[] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,X]
105
136
  ```
106
137
 
107
- Notice:
108
- - `a[]` exposes no parameters, so both canonical ports are `(...)`.
109
- - `b[X]` exposes only `X` (slot `X0`), so slot `X1` is filled with
110
- `(...)`.
111
- - `c[X,Y]` routes caller arguments `[X, Y]` to canonical slots `[X0, X1]`.
112
- - `d[Y,X]` routes caller arguments `[Y, X]` to canonical slots `[X0, X1]`.
113
-
114
138
  ---
115
139
 
116
140
  ## 4. Direct Usability of Canonical Patterns
@@ -120,9 +144,9 @@ everywhere relations and aliases can be used:
120
144
 
121
145
  1. **Direct Inspection**:
122
146
  ```text
123
- > :pat @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P
124
- @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X0, X1] = {
125
- X0 x, X1 y, X1 z
147
+ > :pat @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR
148
+ @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X0, X1, X2] = {
149
+ X0 x, X1 y, X2 z
126
150
  };
127
151
  ```
128
152
 
@@ -130,56 +154,36 @@ everywhere relations and aliases can be used:
130
154
  Callers can instantiate canonical patterns directly by passing all
131
155
  canonical arguments:
132
156
  ```k
133
- { {} x, {} y, {} z } ? @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[
134
- {}, {}
157
+ { {} x, {} y, {} z } ? @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[
158
+ {}, {}, {}
135
159
  ];
136
160
  ```
137
161
 
138
162
  3. **Explicit Definition by Hash**:
139
163
  Canonical pattern definitions are accepted directly by the grammar:
140
164
  ```k
141
- @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X, Y] = {
142
- X x, Y y, Y z
165
+ @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X0, X1, X2] = {
166
+ X0 x, X1 y, X2 z
143
167
  };
144
168
  ```
145
169
 
146
170
  ---
147
171
 
148
- ## 5. Unrestricted Patterns `(...)` as Anonymous Canonical Ports
149
-
150
- An unrestricted pattern `(...)` represents an open wildcard hole with no
151
- type constraints. In the type pattern graph, an unrestricted pattern
152
- `(...)` and an unbound variable `X` lower to the exact same node type:
153
- `{ pattern: '(...)' }`.
154
-
155
- The canonicalizer treats every unrestricted node in the graph as an open
156
- variable port. Consequently:
157
- - Writing `{(...) x, (...) y, (...) z}` produces the **exact same
158
- canonical pattern** as `{X x, Y y, Z z}`:
159
- ```k
160
- @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X0, X1, X2] = {
161
- X0 x, X1 y, X2 z
162
- };
163
- ```
164
- - An alias definition like:
165
- ```k
166
- p[X] = {X x, (...) y};
167
- ```
168
- derives the generic canonical pattern for `{X x, Y y}`:
169
- ```k
170
- @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X0, X1] = {
171
- X0 x, X1 y
172
- };
173
- ```
174
- and defines the alias routing `X` to port `X0` and wildcard `(...)`
175
- to port `X1`:
176
- ```k
177
- p[X] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X, (...)];
178
- ```
179
-
180
- This guarantees maximal canonical sharing: whether a hole is written as
181
- a named variable or an inline `(...)`, both share the identical underlying
182
- canonical template.
172
+ ## 5. Alias Argument Generation Rules
173
+
174
+ For every canonical port `Xi` at path `P` in the canonical filter:
175
+ Let `t` be the token found at path `P` in the author's filter.
176
+ The corresponding alias argument is determined by:
177
+ 1. **Wildcard leaf**: If `t` is absent or an explicit `(...)` wildcard,
178
+ the argument is `"(...)"`.
179
+ 2. **Formal parameter**: If `t` is declared in `pattern_params`, the
180
+ argument is `t` (e.g. `[T, T]` for diagonalized parameter `T`).
181
+ 3. **Repeated existential variable**: If `t` is an internal variable
182
+ appearing $> 1$ times in the filter, the argument is `t` (e.g. `[X, X]`
183
+ or `[Z, Y, Y]`), preserving existential equality across fields.
184
+ 4. **Single-occurrence internal variable**: If `t` is an internal variable
185
+ appearing only once, it imposes no constraints and is normalized to
186
+ `"(...)"`.
183
187
 
184
188
  ---
185
189
 
@@ -250,3 +254,96 @@ list[X, Y] = < {} nil, { X car, Y cdr } cons > = Y;
250
254
 
251
255
  The root node of a pattern graph is matched against incoming data by the
252
256
  runtime; it is never an open parameter port.
257
+
258
+ ---
259
+
260
+ ## 7. Reflection of Patterns in Object Files (`.klib` and `.ko`)
261
+
262
+ Ahead-of-time compiled libraries (`.klib`) and executables (`.ko`) store
263
+ patterns in their top-level object container (`format: "k-object"`).
264
+ Patterns are persisted across three coordinated structures:
265
+
266
+ ### 7.1 `patternAlias` (Lexical Names to Content Hashes)
267
+
268
+ Maps human-readable pattern names to their canonical content hashes.
269
+ All aliases sharing the same linear skeleton point to the same hash:
270
+
271
+ ```json
272
+ "patternAlias": {
273
+ "pair": "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm",
274
+ "same_pair": "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm",
275
+ "closed_same_pair": "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm",
276
+ "p": "@PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR"
277
+ }
278
+ ```
279
+
280
+ ### 7.2 `patterns` (Deduplicated Canonical ASTs)
281
+
282
+ The `patterns` dictionary stores the canonical template definition under
283
+ its content hash `@hash`:
284
+ - **Deduplicated**: Even if a program defines multiple variations over a
285
+ pair or record, the canonical template is stored exactly once under
286
+ its `@hash`.
287
+ - **Linear Multi-Hole Functor**: Every leaf position is an independent
288
+ canonical parameter (`X0, X1, ...`), with no leaves unified in the
289
+ persisted filter AST.
290
+
291
+ ```json
292
+ "patterns": {
293
+ "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm": {
294
+ "params": ["X0", "X1"],
295
+ "filter": {
296
+ "type": "product",
297
+ "fields": {
298
+ "first": { "type": "name", "name": "X0", "open": true },
299
+ "second": { "type": "name", "name": "X1", "open": true }
300
+ }
301
+ }
302
+ }
303
+ }
304
+ ```
305
+
306
+ ### 7.3 `meta` (Provenance & `aliasArgs` Routing Vectors)
307
+
308
+ The `meta` dictionary maps each `@hash` to its canonical port list
309
+ and an `origins` array recording how every alias projects caller
310
+ parameters into the linear skeleton:
311
+
312
+ ```json
313
+ "meta": {
314
+ "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm": {
315
+ "type": "pattern",
316
+ "params": ["X0", "X1"],
317
+ "origins": [
318
+ {
319
+ "name": "pair",
320
+ "params": ["A", "B"],
321
+ "aliasArgs": ["A", "B"],
322
+ "compiledAt": "2026-10-23T19:38:29.691Z"
323
+ },
324
+ {
325
+ "name": "same_pair",
326
+ "params": ["T"],
327
+ "aliasArgs": ["T", "T"],
328
+ "compiledAt": "2026-10-23T19:38:29.691Z"
329
+ },
330
+ {
331
+ "name": "closed_same_pair",
332
+ "params": [],
333
+ "aliasArgs": ["T", "T"],
334
+ "compiledAt": "2026-10-23T19:38:29.691Z"
335
+ }
336
+ ]
337
+ }
338
+ }
339
+ ```
340
+
341
+ The `aliasArgs` vector:
342
+ 1. Records **parameter diagonalization** (e.g. `["T", "T"]`), instructing
343
+ the runtime to supply formal argument `T` to both canonical ports.
344
+ 2. Preserves **existential constraints** (e.g. `["X", "Y", "Y"]`),
345
+ ensuring `Y` is renamed to a shared fresh variable when instantiated.
346
+ 3. Enables **lossless alias export**: when generating `--export` preambles
347
+ or exporting `.klib` files, `buildExportPreamble` reads `origin.params`
348
+ and `origin.aliasArgs` to recreate the exact source-level alias
349
+ definitions.
@@ -124,15 +124,23 @@ The payload stores:
124
124
  - each relation's type-pattern graph state,
125
125
  - each relation's `typeDerivation.status`,
126
126
  - relation aliases in `relAlias`,
127
+ - pattern aliases in `patternAlias`,
128
+ - deduplicated canonical pattern ASTs in `patterns`,
127
129
  - compiler convergence details in top-level `compileStats`,
128
- - metadata, including aliases and origin source locations,
130
+ - metadata (`meta`), including aliases, origin source locations, and
131
+ pattern parameter routing vectors (`aliasArgs`),
129
132
  - the main relation name.
130
133
 
131
134
  Relation `def` values do not store source `start` / `end` markers. Source
132
135
  locations live on `meta[hash].origins[]` entries. Each metadata entry has
133
- `type: "code"` or `type: "rel"`. Origin entries hold `source`, `name`,
134
- `compiledAt`, and optional `start` / `end`; origin entries do not have
135
- `kind`.
136
+ `type: "code"`, `type: "rel"`, or `type: "pattern"`. Origin entries hold
137
+ `source`, `name`, `compiledAt`, optional `start` / `end`, and for
138
+ patterns, `params` and `aliasArgs` (recording parameter routing and
139
+ diagonalization). Origin entries do not have `kind`.
140
+
141
+ For complete details on canonical pattern skeletons, alias argument
142
+ routing, and object reflection, see
143
+ [`DOCS/CANONICAL_PATTERNS.md`](./CANONICAL_PATTERNS.md).
136
144
 
137
145
  Relation `def` values also do not store generated input/output filters.
138
146
  Those filters are derived from `def.patterns` and `typePatternGraph` when
@@ -8,6 +8,65 @@ import { exportPatternGraph } from "./codecs/runtime/codec.mjs";
8
8
  import { closedPatternToCodeHash } from "./repl-codecs.mjs";
9
9
  import { expandFilter } from "./named-patterns.mjs";
10
10
 
11
+ function collectFilterKnots(filter) {
12
+ const knots = new Set();
13
+ function walk(node) {
14
+ if (!node || typeof node !== "object") return;
15
+ if (node.name && node.type !== "name") {
16
+ knots.add(node.name);
17
+ }
18
+ if (node.fields) {
19
+ for (const child of Object.values(node.fields)) {
20
+ walk(child);
21
+ }
22
+ }
23
+ if (node.args) {
24
+ for (const arg of node.args) {
25
+ walk(arg);
26
+ }
27
+ }
28
+ }
29
+ walk(filter);
30
+ return knots;
31
+ }
32
+
33
+ function skeletonizeFilter(filter, knots) {
34
+ let leafIdx = 0;
35
+ function walk(node) {
36
+ if (!node || typeof node !== "object") return node;
37
+ if (node.type === "name" && knots.has(node.name)) {
38
+ return { ...node };
39
+ }
40
+ if (node.name && node.type !== "name") {
41
+ const knotName = node.name;
42
+ if (node.fields) {
43
+ const newFields = {};
44
+ for (const [k, v] of Object.entries(node.fields)) {
45
+ newFields[k] = walk(v);
46
+ }
47
+ return { ...node, name: knotName, fields: newFields };
48
+ }
49
+ return { ...node };
50
+ }
51
+ if (node.type === "product" || node.type === "union") {
52
+ const newFields = {};
53
+ for (const [k, v] of Object.entries(node.fields || {})) {
54
+ newFields[k] = walk(v);
55
+ }
56
+ return { ...node, fields: newFields };
57
+ }
58
+ if (node.type === "code") {
59
+ return { ...node };
60
+ }
61
+ return {
62
+ type: "name",
63
+ name: `__LEAF_${leafIdx++}__`,
64
+ open: true
65
+ };
66
+ }
67
+ return walk(filter);
68
+ }
69
+
11
70
  function collectParamPaths(filter) {
12
71
  const map = {};
13
72
  function walk(node, path) {
@@ -121,8 +180,24 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
121
180
  }
122
181
  }
123
182
 
124
- const dummyParams = formalParams.map((_, i) => `P${i}`);
125
- const source = `? ${name}[${dummyParams.join(", ")}]`;
183
+ let expandedFilter = null;
184
+ try {
185
+ expandedFilter = expandFilter(pat.filter, allPatterns);
186
+ } catch {
187
+ expandedFilter = pat.filter;
188
+ }
189
+
190
+ if (!pat.filter) {
191
+ return {
192
+ hash: pat._canonical || null,
193
+ def: null,
194
+ params: formalParams
195
+ };
196
+ }
197
+
198
+ const knots = collectFilterKnots(expandedFilter);
199
+ const skeletonFilter = skeletonizeFilter(expandedFilter, knots);
200
+ const source = `? ${prettyFilter(skeletonFilter)}`;
126
201
  try {
127
202
  const annotated = annotate(source, {
128
203
  libraries: options.libraries || [],
@@ -131,6 +206,7 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
131
206
  const mainRel = annotated.rels.__main__;
132
207
  let canonicalFilter = null;
133
208
  let graphParams = null;
209
+ let codeHash = null;
134
210
  if (
135
211
  mainRel?.typePatternGraph &&
136
212
  mainRel?.def?.patterns?.[0] != null
@@ -138,11 +214,10 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
138
214
  const rootId = mainRel.typePatternGraph.find(
139
215
  mainRel.def.patterns[0]
140
216
  );
141
- const paramLimit = null;
142
217
  const res = patternGraphToCanonical(
143
218
  mainRel.typePatternGraph,
144
219
  rootId,
145
- paramLimit
220
+ null
146
221
  );
147
222
  canonicalFilter = res.filter;
148
223
  graphParams = res.canonicalParams;
@@ -150,45 +225,26 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
150
225
  const propList = patternToPropertyList(
151
226
  exportPatternGraph(mainRel.typePatternGraph, rootId)
152
227
  );
153
- const codeHash = closedPatternToCodeHash(propList);
154
- if (codeHash) {
155
- pat._canonical = codeHash;
156
- pat._canonicalDef = prettyFilter(canonicalFilter);
157
- pat._canonicalParams = graphParams;
158
- pat._aliasArgs = [];
159
- pat._graphParams = graphParams;
160
- pat._canonicalFilterAst = toAstFilter(canonicalFilter);
161
- return {
162
- hash: codeHash,
163
- def: pat._canonicalDef,
164
- params: pat._canonicalParams,
165
- aliasArgs: pat._aliasArgs,
166
- canonicalParams: graphParams,
167
- canonicalFilterAst: pat._canonicalFilterAst
168
- };
169
- }
228
+ codeHash = closedPatternToCodeHash(propList);
170
229
  }
171
230
 
172
231
  if (canonicalFilter) {
173
232
  pat._canonicalDef = prettyFilter(canonicalFilter);
174
233
  }
175
234
 
176
- let expandedFilter = null;
177
- try {
178
- expandedFilter = expandFilter(pat.filter, allPatterns);
179
- } catch {
180
- expandedFilter = pat.filter;
181
- }
182
-
183
235
  const varPaths = collectCanonicalVarPaths(canonicalFilter);
184
- const aliasArgs = (graphParams || []).map((cVar) => {
236
+ const tokens = (graphParams || []).map((cVar) => {
185
237
  const path = varPaths[cVar];
186
- const origVar = path
187
- ? findVarAtPath(expandedFilter, path)
188
- : null;
189
- if (origVar && formalParams.includes(origVar)) {
190
- return origVar;
191
- }
238
+ return path ? findVarAtPath(expandedFilter, path) : null;
239
+ });
240
+ const tokenCounts = {};
241
+ for (const t of tokens) {
242
+ if (t) tokenCounts[t] = (tokenCounts[t] || 0) + 1;
243
+ }
244
+ const aliasArgs = tokens.map((t) => {
245
+ if (!t) return "(...)";
246
+ if (formalParams.includes(t)) return t;
247
+ if (tokenCounts[t] > 1) return t;
192
248
  return "(...)";
193
249
  });
194
250
 
@@ -201,24 +257,25 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
201
257
  return graphParams?.[i] || `X${i}`;
202
258
  });
203
259
 
260
+ const relHash = annotated.relAlias?.__main__ || null;
261
+ const finalHash =
262
+ codeHash || relHash || pat._canonical || null;
263
+
264
+ pat._canonical = finalHash;
204
265
  pat._canonicalParams =
205
266
  formalCount > 0 ? selectedParams : [];
206
267
  pat._graphParams = graphParams || [];
207
268
  pat._aliasArgs = aliasArgs;
208
269
  pat._canonicalFilterAst = toAstFilter(canonicalFilter);
209
270
 
210
- const relHash = annotated.relAlias?.__main__ || null;
211
- if (relHash) {
212
- pat._canonical = relHash;
213
- return {
214
- hash: relHash,
215
- def: pat._canonicalDef || null,
216
- params: pat._canonicalParams,
217
- aliasArgs: pat._aliasArgs,
218
- canonicalParams: pat._graphParams,
219
- canonicalFilterAst: pat._canonicalFilterAst
220
- };
221
- }
271
+ return {
272
+ hash: pat._canonical,
273
+ def: pat._canonicalDef || null,
274
+ params: pat._canonicalParams,
275
+ aliasArgs: pat._aliasArgs,
276
+ canonicalParams: pat._graphParams,
277
+ canonicalFilterAst: pat._canonicalFilterAst
278
+ };
222
279
  } catch {
223
280
  return {
224
281
  hash: pat._canonical || null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fraczak/k",
3
- "version": "8.3.0",
3
+ "version": "8.4.0",
4
4
  "description": "k — a language for content-addressable schemas and data transformations over algebraic data types (products and tagged unions); includes runtime, contract derivation, REPL, and codec toolchain",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -521,11 +521,11 @@ console.log(
521
521
  );
522
522
 
523
523
  assert.equal(peInfo.hash, feInfo.hash);
524
- assert.equal(peInfo.def, "{X0 a, X1 b, X1 c}");
524
+ assert.equal(peInfo.def, "{X0 a, X1 b, X2 c}");
525
525
  assert.deepEqual(peInfo.params, ["X0"]);
526
- assert.deepEqual(peInfo.aliasArgs, ["Z", "(...)"]);
526
+ assert.deepEqual(peInfo.aliasArgs, ["Z", "Y", "Y"]);
527
527
  assert.deepEqual(feInfo.params, ["X0", "X1"]);
528
- assert.deepEqual(feInfo.aliasArgs, ["A", "B"]);
528
+ assert.deepEqual(feInfo.aliasArgs, ["A", "B", "B"]);
529
529
 
530
530
  // Verify that pair_equal enforces equality between b and c
531
531
  const fnOk = k.compile(`
@@ -549,4 +549,80 @@ console.log(
549
549
  );
550
550
  }
551
551
 
552
+ // Test 15: Diagonalized leaves share canonical linear skeleton
553
+ console.log(
554
+ "--> Test 15: Diagonalized leaves share canonical linear skeleton"
555
+ );
556
+ {
557
+ const { resolvePatternCanonicalInfo } =
558
+ await import("../canonical-pattern.mjs");
559
+ const { parse } = await import("../parser.mjs");
560
+
561
+ const ast = parse(`
562
+ pair[A, B] = { A first, B second };
563
+ same_pair[T] = { T first, T second };
564
+ closed_same_pair[] = { T first, T second };
565
+ any_pair[] = { (...) first, (...) second };
566
+ diag_p[] = { X x, X y };
567
+ ()
568
+ `);
569
+ const pairInfo = resolvePatternCanonicalInfo(
570
+ "pair",
571
+ ast.defs.patterns.pair,
572
+ { patterns: ast.defs.patterns }
573
+ );
574
+ const sameInfo = resolvePatternCanonicalInfo(
575
+ "same_pair",
576
+ ast.defs.patterns.same_pair,
577
+ { patterns: ast.defs.patterns }
578
+ );
579
+ const closedSameInfo = resolvePatternCanonicalInfo(
580
+ "closed_same_pair",
581
+ ast.defs.patterns.closed_same_pair,
582
+ { patterns: ast.defs.patterns }
583
+ );
584
+ const anyInfo = resolvePatternCanonicalInfo(
585
+ "any_pair",
586
+ ast.defs.patterns.any_pair,
587
+ { patterns: ast.defs.patterns }
588
+ );
589
+ const diagPInfo = resolvePatternCanonicalInfo(
590
+ "diag_p",
591
+ ast.defs.patterns.diag_p,
592
+ { patterns: ast.defs.patterns }
593
+ );
594
+
595
+ const pairHash = "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm";
596
+ assert.equal(pairInfo.hash, pairHash);
597
+ assert.equal(sameInfo.hash, pairHash);
598
+ assert.equal(closedSameInfo.hash, pairHash);
599
+ assert.equal(anyInfo.hash, pairHash);
600
+
601
+ assert.equal(pairInfo.def, "{X0 first, X1 second}");
602
+ assert.equal(sameInfo.def, "{X0 first, X1 second}");
603
+ assert.equal(closedSameInfo.def, "{X0 first, X1 second}");
604
+ assert.equal(anyInfo.def, "{X0 first, X1 second}");
605
+
606
+ assert.deepEqual(pairInfo.aliasArgs, ["A", "B"]);
607
+ assert.deepEqual(sameInfo.aliasArgs, ["T", "T"]);
608
+ assert.deepEqual(closedSameInfo.aliasArgs, ["T", "T"]);
609
+ assert.deepEqual(anyInfo.aliasArgs, ["(...)", "(...)"]);
610
+
611
+ assert.deepEqual(pairInfo.params, ["X0", "X1"]);
612
+ assert.deepEqual(sameInfo.params, ["X0"]);
613
+ assert.deepEqual(closedSameInfo.params, []);
614
+ assert.deepEqual(anyInfo.params, []);
615
+
616
+ // diag_p[] shares canonical skeleton with a, b, c, d
617
+ const xyHash = "@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x";
618
+ assert.equal(diagPInfo.hash, xyHash);
619
+ assert.equal(diagPInfo.def, "{X0 x, X1 y}");
620
+ assert.deepEqual(diagPInfo.params, []);
621
+ assert.deepEqual(diagPInfo.aliasArgs, ["X", "X"]);
622
+
623
+ console.log(
624
+ " Passed: Diagonalized leaves share canonical linear skeleton."
625
+ );
626
+ }
627
+
552
628
  console.log("==> All Named Patterns Tests Passed Successfully!");
@@ -766,8 +766,8 @@ output = await evaluateInput(
766
766
  output = await evaluateInput(":pattern same_pair", freshState);
767
767
  assert.equal(
768
768
  output[0],
769
- "same_pair[X0] = {X0 first, X0 second}; -- " +
770
- "@TyjJDJuYAbp56mytRMzu2HMTfQq7rKLcGsaQtFG28yhW"
769
+ "same_pair[X0] = {X0 first, X1 second}; -- " +
770
+ "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm"
771
771
  );
772
772
  output = await evaluateInput("{} | nil ? list[bit[]]", freshState);
773
773
  assert.match(output[0], /\{\}\|nil/);
@@ -786,8 +786,8 @@ output = await evaluateInput(
786
786
  output = await evaluateInput(":pattern closed_same_pair", freshState);
787
787
  assert.equal(
788
788
  output[0],
789
- "closed_same_pair[] = {X0 first, X0 second}; -- " +
790
- "@TyjJDJuYAbp56mytRMzu2HMTfQq7rKLcGsaQtFG28yhW"
789
+ "closed_same_pair[] = {X0 first, X1 second}; -- " +
790
+ "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm"
791
791
  );
792
792
 
793
793
  output = await evaluateInput(
@@ -840,6 +840,17 @@ assert(
840
840
  "d[Y,X] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,Y]"
841
841
  )
842
842
  );
843
+ assert(
844
+ output[0].includes(
845
+ "same_pair[T] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T,T]"
846
+ )
847
+ );
848
+ assert(
849
+ output[0].includes(
850
+ "closed_same_pair[] = " +
851
+ "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T,T]"
852
+ )
853
+ );
843
854
 
844
855
  await assert.rejects(
845
856
  () =>
@@ -854,30 +865,30 @@ await evaluateInput("p[X]= {X x, Y y, Y z};", freshState);
854
865
  output = await evaluateInput(":pats", freshState);
855
866
  assert(
856
867
  output[0].includes(
857
- "p[X] = @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X,(...)]"
868
+ "p[X] = @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X,Y,Y]"
858
869
  )
859
870
  );
860
871
 
861
872
  output = await evaluateInput(":pat p", freshState);
862
873
  assert.equal(
863
874
  output[0],
864
- "p[X0] = {X0 x, X1 y, X1 z}; -- " +
865
- "@A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P"
875
+ "p[X0] = {X0 x, X1 y, X2 z}; -- " +
876
+ "@PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR"
866
877
  );
867
878
 
868
879
  output = await evaluateInput(
869
- ":pat @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P",
880
+ ":pat @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR",
870
881
  freshState
871
882
  );
872
883
  assert.equal(
873
884
  output[0],
874
- "@A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X0, X1] = " +
875
- "{X0 x, X1 y, X1 z};"
885
+ "@PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X0, X1, X2] = " +
886
+ "{X0 x, X1 y, X2 z};"
876
887
  );
877
888
 
878
889
  output = await evaluateInput(
879
890
  "{{} x, {} y, {} z} ? " +
880
- "@A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[{}, {}]",
891
+ "@PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[{}, {}, {}]",
881
892
  freshState
882
893
  );
883
894
  assert.match(output[0], /\{\{\} x, \{\} y, \{\} z\}/);
@@ -893,17 +904,17 @@ await evaluateInput(`:klib ${testKlibPath2}`, freshState);
893
904
  const freshState2 = createState({ engine: "wasm" });
894
905
  await evaluateInput(`:load ${testKlibPath2}`, freshState2);
895
906
  const pHash = freshState2.patternAliases.p;
896
- assert.equal(pHash, "@A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P");
907
+ assert.equal(pHash, "@PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR");
897
908
  const pOrigins = freshState2.meta[pHash]?.origins?.filter(
898
909
  (o) => o.name === "p"
899
910
  );
900
911
  assert.equal(pOrigins?.length, 1);
901
912
  assert.deepEqual(pOrigins[0].params, ["X"]);
902
- assert.deepEqual(pOrigins[0].aliasArgs, ["X", "(...)"]);
913
+ assert.deepEqual(pOrigins[0].aliasArgs, ["X", "Y", "Y"]);
903
914
  output = await evaluateInput(":pats", freshState2);
904
915
  assert(
905
916
  output[0].includes(
906
- "p[X] = @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X,(...)]"
917
+ "p[X] = @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X,Y,Y]"
907
918
  )
908
919
  );
909
920