@fraczak/k 8.3.0 → 8.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,85 @@ 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.1] — 2026-10-23 — Strict Pattern Validation & Autohook Removal
9
+
10
+ ### Strict Pattern Template Validation & Variable Distinction
11
+
12
+ - **Reject Undefined Pattern Applications**:
13
+ - Prohibit undefined pattern template applications (`name[...]`).
14
+ Previously, unexpanded `pattern_apply` AST nodes fell through
15
+ `skeletonizeFilter` and were silently converted into open leaf
16
+ variables (`X0`, `X1`), turning unresolved templates like
17
+ `{ missing[] x }` into existential records.
18
+ - In `canonical-pattern.mjs`, `skeletonizeFilter` now explicitly raises
19
+ `Unknown pattern template '<name>[]'` when an unexpanded
20
+ `pattern_apply` AST node is encountered, and
21
+ `resolvePatternCanonicalInfo` propagates template expansion errors
22
+ instead of silently swallowing them.
23
+ - Leaf variable generation in the linear skeleton is strictly
24
+ restricted to genuine variable nodes (`type === "name"` or untyped
25
+ leaves).
26
+ - **Eager Definition-Time Validation**:
27
+ - Introduced `validatePatternDefinitions` in `named-patterns.mjs` and
28
+ integrated it into `annotate` in `index.mjs`, rejecting undefined
29
+ templates, cyclic dependencies, and arity mismatches at module
30
+ compile time, even if no relation references them.
31
+ - **Library Compilation Metadata**:
32
+ - In `object.mjs`, compiled libraries directly preserve their canonical
33
+ pattern filters and metadata, preventing AST desynchronization.
34
+
35
+ ### Removal of Implicit Autohooks
36
+
37
+ - **Explicit Loading Across All Environments**:
38
+ - Removed all implicit file autohooks and magic dependencies across
39
+ the REPL (`repl.mjs`), LLVM CLI (`backends/llvm/src/cli.mjs`), and
40
+ Wasm CLI (`backends/wasm/src/cli.mjs`).
41
+ - Users and test suites must explicitly load dependencies (e.g.
42
+ `Examples/arithmetics.k` before `Examples/poly.k`).
43
+
44
+ ### Documentation
45
+
46
+ - Updated `DOCS/NAMED_PATTERNS.md`, `DOCS/PATTERNS.md`,
47
+ `DOCS/CANONICAL_PATTERNS.md`, `DOCS/REPL.md`, and
48
+ `DOCS/WEB_REPL_REQUIREMENTS.md`.
49
+
50
+ ## [8.4.0] — 2026-10-23 — Linear Skeletons & Parameter Diagonalization
51
+
52
+ ### Pure Linear Skeleton Model for Parameterized Patterns
53
+
54
+ - **Never Equalize Leaves in Canonical Templates**:
55
+ - The canonicalizer derives a pure linear skeleton for all
56
+ parameterized patterns, treating every open leaf position as an
57
+ independent port (`X0, X1, X2, ...`).
58
+ - Leaves are never unified in the canonical pattern graph,
59
+ guaranteeing maximum template deduplication across all variations
60
+ of a structural schema (records, products, sums).
61
+ - **Parameter Diagonalization in Aliases**:
62
+ - Non-linear equality constraints across leaves are represented as
63
+ diagonalized argument vectors (`aliasArgs`) on the alias definition
64
+ itself rather than inside the canonical template graph:
65
+ * `same_pair[T] = @hash[T, T];` (formal parameter equality)
66
+ * `closed_same_pair[] = @hash[T, T];` (existential variable equality)
67
+ * `p[X] = @hash[X, Y, Y];` (mixed formal and existential equality)
68
+ * `p[] = @hash[X, X];` (pure existential equality)
69
+ - When instantiated, shared existential variables are renamed to fresh
70
+ unification variables (`_Y_np1`), enforcing structural equality at
71
+ use-time with full type safety.
72
+ - **Canonical Sharing Across Diagonalizations**:
73
+ - `pair[A, B]`, `same_pair[T]`, `closed_same_pair[]`, and `any_pair[]`
74
+ all compile to and share the exact same canonical pattern graph and
75
+ content hash (`@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm`).
76
+ - `diag_p[] = { X x, X y }` shares the same canonical hash as
77
+ `a[]`, `b[X]`, `c[X, Y]`, `d[Y, X]`.
78
+ - **Object File Persistence**:
79
+ - Ahead-of-time `.klib` and `.ko` object files persist canonical
80
+ deduplicated linear templates under `patterns[@hash]`, alias mappings
81
+ under `patternAlias`, and diagonalized routing vectors in
82
+ `meta[hash].origins[].aliasArgs`.
83
+ - **Documentation**:
84
+ - Updated `DOCS/CANONICAL_PATTERNS.md` and
85
+ `DOCS/OBJECT_FILE_AND_PATTERN.md`.
86
+
8
87
  ## [8.3.0] — 2026-10-22 — Content-Addressable Patterns & Aliasing
9
88
 
10
89
  ### Content-Addressable Canonical Patterns
@@ -15,102 +15,139 @@ 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
+
60
+ ### 2.2 Leaf Variables vs. Template Applications
61
+
62
+ During canonicalization, only genuine leaf type variables (`type: "name"`
63
+ or untyped leaf nodes) are assigned canonical port slots (`X0`, `X1`,
64
+ ...).
65
+
66
+ Template applications (`name[...]` or `@hash[...]`) must be fully
67
+ expanded before skeletonization. If an unexpanded `pattern_apply` AST
68
+ node reaches the skeletonizer (e.g. due to an unresolved template name),
69
+ the compiler rejects it immediately with an `Unknown pattern template`
70
+ error. An undefined pattern template application is never converted into
71
+ an open leaf variable slot.
59
72
 
60
73
  ---
61
74
 
62
- ## 3. Named Patterns as Parameter Routing Aliases
75
+ ## 3. Named Patterns as Parameter Routing and Diagonalization Aliases
63
76
 
64
77
  When an author defines an alias like:
65
78
  ```k
66
79
  p[X] = {X x, Y y, Y z};
67
80
  ```
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 `(...)`:
81
+ the definition `p[X]` does **not** create a separate canonical pattern
82
+ graph. Instead, it defines an alias that routes:
83
+ - The author's formal parameter `X` to slot `X0`.
84
+ - The shared existential variable `Y` to both slots `X1` and `X2`:
75
85
 
76
86
  ```k
77
- p[X] = @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X, (...)];
87
+ p[X] = @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X, Y, Y];
78
88
  ```
79
89
 
80
- ### 3.1 Canonical Pattern Sharing Across Permutations
90
+ When `p` is instantiated (e.g. `p[int]`), the template expansion engine:
91
+ 1. Substitutes formal parameter `X` with caller argument `int`.
92
+ 2. Renames internal existential variable `Y` to a unique fresh variable
93
+ `_Y_np1` across all occurrences in the argument list:
94
+ `@PScs...[int, _Y_np1, _Y_np1]`.
95
+ 3. Expands the canonical template with those arguments, yielding:
96
+ `{ int x, _Y_np1 y, _Y_np1 z }`.
97
+ 4. The type derivation engine unifies the type of field `y` with the type
98
+ of field `z` via the shared fresh variable `_Y_np1`.
99
+
100
+ Thus, existential equality constraints are preserved with full type-safety
101
+ at use-time, while enabling maximum structural template deduplication.
102
+
103
+ ### 3.1 Canonical Pattern Sharing Across Diagonalizations and Permutations
81
104
 
82
- Multiple alias definitions with different parameter exposures or
83
- orderings over isomorphic filter graphs share the exact same canonical
84
- hash:
105
+ Under this architecture, all variations over the same underlying product
106
+ or union structure share the **exact same canonical pattern graph and
107
+ content hash**:
85
108
 
109
+ #### Example 1: Pair Variations
86
110
  ```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};
111
+ pair[A, B] = { A first, B second };
112
+ same_pair[T] = { T first, T second };
113
+ closed_same_pair[] = { T first, T second };
114
+ any_pair[] = { (...) first, (...) second };
115
+ ```
116
+ All four compile to the single canonical skeleton:
117
+ ```k
118
+ @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[X0, X1] = {
119
+ X0 first, X1 second
120
+ };
91
121
  ```
92
122
 
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:
123
+ Their `:pats` alias representations reflect their respective parameter
124
+ routings and diagonalizations:
125
+ ```text
126
+ > :pats
127
+ any_pair[] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[(...),(...)]
128
+ closed_same_pair[] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T,T]
129
+ pair[A,B] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[A,B]
130
+ same_pair[T] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T,T]
131
+ ```
98
132
 
133
+ #### Example 2: Record `{ x, y }` Variations
134
+ ```k
135
+ a[] = { (...) x, (...) y };
136
+ b[X] = { X x, (...) y };
137
+ c[X,Y] = { X x, Y y };
138
+ d[Y,X] = { X x, Y y };
139
+ diag_p[] = { X x, X y };
140
+ ```
141
+ All five share `@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x`:
99
142
  ```text
100
143
  > :pats
101
144
  a[] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[(...),(...)]
102
145
  b[X] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,(...)]
103
146
  c[X,Y] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,Y]
104
147
  d[Y,X] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,Y]
148
+ diag_p[] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,X]
105
149
  ```
106
150
 
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
151
  ---
115
152
 
116
153
  ## 4. Direct Usability of Canonical Patterns
@@ -120,9 +157,9 @@ everywhere relations and aliases can be used:
120
157
 
121
158
  1. **Direct Inspection**:
122
159
  ```text
123
- > :pat @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P
124
- @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X0, X1] = {
125
- X0 x, X1 y, X1 z
160
+ > :pat @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR
161
+ @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X0, X1, X2] = {
162
+ X0 x, X1 y, X2 z
126
163
  };
127
164
  ```
128
165
 
@@ -130,56 +167,36 @@ everywhere relations and aliases can be used:
130
167
  Callers can instantiate canonical patterns directly by passing all
131
168
  canonical arguments:
132
169
  ```k
133
- { {} x, {} y, {} z } ? @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[
134
- {}, {}
170
+ { {} x, {} y, {} z } ? @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[
171
+ {}, {}, {}
135
172
  ];
136
173
  ```
137
174
 
138
175
  3. **Explicit Definition by Hash**:
139
176
  Canonical pattern definitions are accepted directly by the grammar:
140
177
  ```k
141
- @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X, Y] = {
142
- X x, Y y, Y z
178
+ @PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X0, X1, X2] = {
179
+ X0 x, X1 y, X2 z
143
180
  };
144
181
  ```
145
182
 
146
183
  ---
147
184
 
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.
185
+ ## 5. Alias Argument Generation Rules
186
+
187
+ For every canonical port `Xi` at path `P` in the canonical filter:
188
+ Let `t` be the token found at path `P` in the author's filter.
189
+ The corresponding alias argument is determined by:
190
+ 1. **Wildcard leaf**: If `t` is absent or an explicit `(...)` wildcard,
191
+ the argument is `"(...)"`.
192
+ 2. **Formal parameter**: If `t` is declared in `pattern_params`, the
193
+ argument is `t` (e.g. `[T, T]` for diagonalized parameter `T`).
194
+ 3. **Repeated existential variable**: If `t` is an internal variable
195
+ appearing $> 1$ times in the filter, the argument is `t` (e.g. `[X, X]`
196
+ or `[Z, Y, Y]`), preserving existential equality across fields.
197
+ 4. **Single-occurrence internal variable**: If `t` is an internal variable
198
+ appearing only once, it imposes no constraints and is normalized to
199
+ `"(...)"`.
183
200
 
184
201
  ---
185
202
 
@@ -250,3 +267,96 @@ list[X, Y] = < {} nil, { X car, Y cdr } cons > = Y;
250
267
 
251
268
  The root node of a pattern graph is matched against incoming data by the
252
269
  runtime; it is never an open parameter port.
270
+
271
+ ---
272
+
273
+ ## 7. Reflection of Patterns in Object Files (`.klib` and `.ko`)
274
+
275
+ Ahead-of-time compiled libraries (`.klib`) and executables (`.ko`) store
276
+ patterns in their top-level object container (`format: "k-object"`).
277
+ Patterns are persisted across three coordinated structures:
278
+
279
+ ### 7.1 `patternAlias` (Lexical Names to Content Hashes)
280
+
281
+ Maps human-readable pattern names to their canonical content hashes.
282
+ All aliases sharing the same linear skeleton point to the same hash:
283
+
284
+ ```json
285
+ "patternAlias": {
286
+ "pair": "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm",
287
+ "same_pair": "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm",
288
+ "closed_same_pair": "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm",
289
+ "p": "@PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR"
290
+ }
291
+ ```
292
+
293
+ ### 7.2 `patterns` (Deduplicated Canonical ASTs)
294
+
295
+ The `patterns` dictionary stores the canonical template definition under
296
+ its content hash `@hash`:
297
+ - **Deduplicated**: Even if a program defines multiple variations over a
298
+ pair or record, the canonical template is stored exactly once under
299
+ its `@hash`.
300
+ - **Linear Multi-Hole Functor**: Every leaf position is an independent
301
+ canonical parameter (`X0, X1, ...`), with no leaves unified in the
302
+ persisted filter AST.
303
+
304
+ ```json
305
+ "patterns": {
306
+ "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm": {
307
+ "params": ["X0", "X1"],
308
+ "filter": {
309
+ "type": "product",
310
+ "fields": {
311
+ "first": { "type": "name", "name": "X0", "open": true },
312
+ "second": { "type": "name", "name": "X1", "open": true }
313
+ }
314
+ }
315
+ }
316
+ }
317
+ ```
318
+
319
+ ### 7.3 `meta` (Provenance & `aliasArgs` Routing Vectors)
320
+
321
+ The `meta` dictionary maps each `@hash` to its canonical port list
322
+ and an `origins` array recording how every alias projects caller
323
+ parameters into the linear skeleton:
324
+
325
+ ```json
326
+ "meta": {
327
+ "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm": {
328
+ "type": "pattern",
329
+ "params": ["X0", "X1"],
330
+ "origins": [
331
+ {
332
+ "name": "pair",
333
+ "params": ["A", "B"],
334
+ "aliasArgs": ["A", "B"],
335
+ "compiledAt": "2026-10-23T19:38:29.691Z"
336
+ },
337
+ {
338
+ "name": "same_pair",
339
+ "params": ["T"],
340
+ "aliasArgs": ["T", "T"],
341
+ "compiledAt": "2026-10-23T19:38:29.691Z"
342
+ },
343
+ {
344
+ "name": "closed_same_pair",
345
+ "params": [],
346
+ "aliasArgs": ["T", "T"],
347
+ "compiledAt": "2026-10-23T19:38:29.691Z"
348
+ }
349
+ ]
350
+ }
351
+ }
352
+ ```
353
+
354
+ The `aliasArgs` vector:
355
+ 1. Records **parameter diagonalization** (e.g. `["T", "T"]`), instructing
356
+ the runtime to supply formal argument `T` to both canonical ports.
357
+ 2. Preserves **existential constraints** (e.g. `["X", "Y", "Y"]`),
358
+ ensuring `Y` is renamed to a shared fresh variable when instantiated.
359
+ 3. Enables **lossless alias export**: when generating `--export` preambles
360
+ or exporting `.klib` files, `buildExportPreamble` reads `origin.params`
361
+ and `origin.aliasArgs` to recreate the exact source-level alias
362
+ definitions.
@@ -104,6 +104,18 @@ between variables and patterns is 100% deterministic:
104
104
  - **Identifier with `[...]`** (`bit[]`, `list[T]`, `pair[A, B]`):
105
105
  - Always a pattern template lookup or instantiation.
106
106
 
107
+ ### 3.2 Undefined Pattern Application Prohibition
108
+
109
+ An identifier with `[...]` (e.g. `missing[]` or `dict[K, V]`) **must**
110
+ refer to a defined pattern template in scope or in an imported library.
111
+
112
+ - An undefined pattern application is a compile-time error
113
+ (`Unknown pattern template 'missing[]'`).
114
+ - An undefined pattern application is **never** silently converted into
115
+ a variable or open leaf slot (`X0`, `X1`, etc.).
116
+ - Identifiers intended as existential type variables must appear
117
+ without brackets (e.g. `T` or `X`).
118
+
107
119
  ---
108
120
 
109
121
  ## 4. Internal Variables as Unification Knots
@@ -231,6 +243,15 @@ To guarantee decidability and termination:
231
243
  - Two syntactically different definitions yielding isomorphic
232
244
  automata produce the exact same canonical definition and hash.
233
245
 
246
+ 5. **Eager Definition-Time Validation**:
247
+ All pattern definitions are strictly validated at script/module
248
+ compilation time, even if no relation in the file references them:
249
+ - Undefined template lookups raise `Unknown pattern template`.
250
+ - Mutually recursive template definitions raise
251
+ `Cyclic pattern template dependency detected`.
252
+ - Arity mismatches raise
253
+ `Pattern '...' expects N parameters, got M`.
254
+
234
255
  ---
235
256
 
236
257
  ## 7. Concrete Library Examples
@@ -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
package/DOCS/PATTERNS.md CHANGED
@@ -90,6 +90,22 @@ In the interactive REPL, inspecting a pattern with `:pattern <name>` (or
90
90
  introduced variables in discovery order (e.g.
91
91
  `list[X1] = <{X1 car, X0 cdr} cons, {} nil>=X0; -- @...`).
92
92
 
93
+ ### Template Applications vs. Type Variables
94
+
95
+ Identifiers with square brackets (`name[...]`) are strictly pattern
96
+ template applications. A referenced pattern template must exist in scope
97
+ or in an imported library. An undefined template lookup raises an
98
+ `Unknown pattern template` error immediately and is **never** silently
99
+ treated as an open variable or leaf.
100
+
101
+ In contrast, bare identifiers without brackets in pattern positions (e.g.
102
+ `X`, `T`, `Y`) represent formal parameters, cycle knots (`= Y`), or
103
+ existential type variables asserting type equality across fields.
104
+
105
+ Pattern definitions are validated eagerly at compile time: undefined
106
+ references, cyclic template dependencies, and arity mismatches are
107
+ rejected before code generation or canonical hashing.
108
+
93
109
  ## Filters and Terminal Positions
94
110
 
95
111
  A k script can describe a pattern through:
package/DOCS/REPL.md CHANGED
@@ -207,6 +207,12 @@ c[X,Y] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,Y]
207
207
  d[Y,X] = @NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X,Y]
208
208
  ```
209
209
 
210
+ Note: In `a[] = {X x, Y y}`, `X` and `Y` are bare identifiers and thus
211
+ treated as existential type variables. If an author writes `missing[]`,
212
+ the REPL rejects the definition with an error
213
+ (`Unknown pattern template 'missing[]'`). Undefined pattern applications
214
+ are never treated as open variables or leaves.
215
+
210
216
  Rather than echoing the syntax used to construct the template, the
211
217
  canonical definition decompiles the underlying minimal finite tree
212
218
  automaton. Local parameter and knot names chosen by the author are
@@ -71,23 +71,21 @@ The bundled VFS and UI examples must include only verified useful files:
71
71
  - `Examples/poly.k` — Polymorphic list functions (`concat`, `reverse`, `length`, `get_nth`, `split_by`, `take`, `drop`, `zip`).
72
72
 
73
73
  #### Dependency Management for `poly.k`
74
- - `Examples/poly.k` depends on `dec`, `nat`, and `zero_int?` from `Examples/arithmetics.k`.
75
- - Loading `Examples/poly.k` on a fresh session will automatically ensure `Examples/arithmetics.k` is loaded first if not already loaded in the session.
74
+ - `Examples/poly.k` depends on `dec`, `nat`, and `zero_int?` from
75
+ `Examples/arithmetics.k`.
76
+ - Dependencies are loaded explicitly: users load
77
+ `Examples/arithmetics.k` before `Examples/poly.k`.
78
+ No autohooks or implicit loading are performed.
76
79
 
77
80
  ---
78
81
 
79
- ### Objective 4: Auto-Loading `.k` Files on Codec Load & Code Aliasing
82
+ ### Objective 4: Explicit Loading & Code Aliasing
80
83
 
81
84
  #### Requirements
82
- 1. **Codec-to-File Auto-Loading**:
83
- When a codec is registered or loaded (via `:codec load <name>`, REPL initialization, or UI action):
84
- - Check if the required `.k` file is already loaded in `state.loadedFiles`.
85
- - If not loaded, automatically load and evaluate the corresponding `.k` file before completing codec registration:
86
- - `int` -> auto-loads `Examples/arithmetics.k`
87
- - `utf8` -> auto-loads `core.k`
88
- - `json` -> auto-loads `core.k`
89
- - `ieee` -> auto-loads `Examples/ieee.k`
90
- - Print an informative message, e.g.: `(auto-loaded Examples/arithmetics.k for codec 'int')`.
85
+ 1. **Explicit Loading (No Autohooks)**:
86
+ - Codecs and `.k` files must be loaded explicitly by the user
87
+ (e.g. `:load Examples/arithmetics.k` then `:load Examples/poly.k`).
88
+ - The REPL does not perform implicit or hidden auto-loading.
91
89
 
92
90
  2. **Bidirectional Code Aliasing**:
93
91
  Establish code aliasing so that codec names and their standard type names are both valid aliases pointing to the same canonical type hash:
@@ -27,38 +27,7 @@ export function loadLibraryFromPath(libPath) {
27
27
  return loadLibrary(decodeObject(fs.readFileSync(libPath)));
28
28
  }
29
29
  if (ext === ".k") {
30
- let depLibs = [];
31
- const baseName = path.basename(libPath);
32
- if (baseName === "poly.k") {
33
- const dir = path.dirname(libPath);
34
- const arithPath = path.join(dir, "arithmetics.k");
35
- if (fs.existsSync(arithPath)) {
36
- const arithLib = loadLibrary(
37
- compileLibrary(fs.readFileSync(arithPath, "utf8"), {
38
- source: arithPath
39
- })
40
- );
41
- depLibs.push(arithLib);
42
- }
43
- }
44
30
  const rawSource = fs.readFileSync(libPath, "utf8");
45
- if (depLibs.length > 0) {
46
- const neededExports = [
47
- "0", "int", "inc", "dec", "nat", "zero_int?", "neg?", "GT"
48
- ];
49
- const preamble = buildExportPreamble(neededExports, depLibs);
50
- const compiled = compileLibrary(preamble + rawSource, {
51
- source: libPath,
52
- libraries: depLibs
53
- });
54
- const mergedLib = loadLibrary(compiled);
55
- for (const dep of depLibs) {
56
- for (const [k, v] of Object.entries(dep.relAlias || {})) {
57
- if (!mergedLib.relAlias[k]) mergedLib.relAlias[k] = v;
58
- }
59
- }
60
- return mergedLib;
61
- }
62
31
  return loadLibrary(compileLibrary(rawSource, { source: libPath }));
63
32
  }
64
33
  throw new Error(`Unsupported library extension: ${ext}`);