@fraczak/k 8.4.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 +42 -0
- package/DOCS/CANONICAL_PATTERNS.md +13 -0
- package/DOCS/NAMED_PATTERNS.md +21 -0
- package/DOCS/PATTERNS.md +16 -0
- package/DOCS/REPL.md +6 -0
- package/DOCS/WEB_REPL_REQUIREMENTS.md +10 -12
- package/backends/llvm/src/cli.mjs +0 -31
- package/backends/wasm/src/cli.mjs +0 -31
- package/canonical-pattern.mjs +65 -35
- package/index.mjs +5 -1
- package/named-patterns.mjs +36 -0
- package/object.mjs +28 -6
- package/package.json +1 -1
- package/repl.mjs +5 -72
- package/tests/test-named-patterns.mjs +15 -0
- package/tests/test-repl.mjs +47 -4
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,48 @@ 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
|
+
|
|
8
50
|
## [8.4.0] — 2026-10-23 — Linear Skeletons & Parameter Diagonalization
|
|
9
51
|
|
|
10
52
|
### Pure Linear Skeleton Model for Parameterized Patterns
|
|
@@ -57,6 +57,19 @@ The canonical pattern is the 3-port linear product:
|
|
|
57
57
|
Canonical patterns always take the full arity of all leaf positions
|
|
58
58
|
discovered in the pattern skeleton.
|
|
59
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.
|
|
72
|
+
|
|
60
73
|
---
|
|
61
74
|
|
|
62
75
|
## 3. Named Patterns as Parameter Routing and Diagonalization Aliases
|
package/DOCS/NAMED_PATTERNS.md
CHANGED
|
@@ -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
|
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
|
|
75
|
-
|
|
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:
|
|
82
|
+
### Objective 4: Explicit Loading & Code Aliasing
|
|
80
83
|
|
|
81
84
|
#### Requirements
|
|
82
|
-
1. **
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
-
|
|
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}`);
|
|
@@ -35,38 +35,7 @@ export function loadLibraryFromPath(libPath) {
|
|
|
35
35
|
return loadLibrary(decodeObject(fs.readFileSync(libPath)));
|
|
36
36
|
}
|
|
37
37
|
if (ext === ".k") {
|
|
38
|
-
let depLibs = [];
|
|
39
|
-
const baseName = path.basename(libPath);
|
|
40
|
-
if (baseName === "poly.k") {
|
|
41
|
-
const dir = path.dirname(libPath);
|
|
42
|
-
const arithPath = path.join(dir, "arithmetics.k");
|
|
43
|
-
if (fs.existsSync(arithPath)) {
|
|
44
|
-
const arithLib = loadLibrary(
|
|
45
|
-
compileLibrary(fs.readFileSync(arithPath, "utf8"), {
|
|
46
|
-
source: arithPath
|
|
47
|
-
})
|
|
48
|
-
);
|
|
49
|
-
depLibs.push(arithLib);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
38
|
const rawSource = fs.readFileSync(libPath, "utf8");
|
|
53
|
-
if (depLibs.length > 0) {
|
|
54
|
-
const neededExports = [
|
|
55
|
-
"0", "int", "inc", "dec", "nat", "zero_int?", "neg?", "GT"
|
|
56
|
-
];
|
|
57
|
-
const preamble = buildExportPreamble(neededExports, depLibs);
|
|
58
|
-
const compiled = compileLibrary(preamble + rawSource, {
|
|
59
|
-
source: libPath,
|
|
60
|
-
libraries: depLibs
|
|
61
|
-
});
|
|
62
|
-
const mergedLib = loadLibrary(compiled);
|
|
63
|
-
for (const dep of depLibs) {
|
|
64
|
-
for (const [k, v] of Object.entries(dep.relAlias || {})) {
|
|
65
|
-
if (!mergedLib.relAlias[k]) mergedLib.relAlias[k] = v;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
return mergedLib;
|
|
69
|
-
}
|
|
70
39
|
return loadLibrary(compileLibrary(rawSource, { source: libPath }));
|
|
71
40
|
}
|
|
72
41
|
throw new Error(`Unsupported library extension: ${ext}`);
|
package/canonical-pattern.mjs
CHANGED
|
@@ -58,11 +58,23 @@ function skeletonizeFilter(filter, knots) {
|
|
|
58
58
|
if (node.type === "code") {
|
|
59
59
|
return { ...node };
|
|
60
60
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
61
|
+
if (node.type === "pattern_apply") {
|
|
62
|
+
const pos = node.start
|
|
63
|
+
? ` (lines ${node.start.line}:${node.start.column})`
|
|
64
|
+
: "";
|
|
65
|
+
const suffix = node.pattern?.startsWith("@") ? "" : "[]";
|
|
66
|
+
throw new Error(
|
|
67
|
+
`Unknown pattern template '${node.pattern}${suffix}'${pos}`
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
if (node.type === "name" || node.type === null) {
|
|
71
|
+
return {
|
|
72
|
+
type: "name",
|
|
73
|
+
name: `__LEAF_${leafIdx++}__`,
|
|
74
|
+
open: true
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
return node;
|
|
66
78
|
}
|
|
67
79
|
return walk(filter);
|
|
68
80
|
}
|
|
@@ -118,21 +130,29 @@ function collectCanonicalVarPaths(canonicalFilter) {
|
|
|
118
130
|
return paths;
|
|
119
131
|
}
|
|
120
132
|
|
|
121
|
-
function toAstFilter(node) {
|
|
133
|
+
function toAstFilter(node, canonicalParams = []) {
|
|
122
134
|
if (!node || typeof node !== "object") return node;
|
|
123
135
|
const res = { ...node };
|
|
124
|
-
if (
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
136
|
+
if (res.type === null) {
|
|
137
|
+
return {
|
|
138
|
+
type: "name",
|
|
139
|
+
name: res.name,
|
|
140
|
+
open: true
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
if (res.type === "name") {
|
|
144
|
+
return {
|
|
145
|
+
type: "name",
|
|
146
|
+
name: res.name,
|
|
147
|
+
...(canonicalParams.includes(res.name)
|
|
148
|
+
? { open: true }
|
|
149
|
+
: {})
|
|
150
|
+
};
|
|
131
151
|
}
|
|
132
152
|
if (res.fields) {
|
|
133
153
|
res.fields = {};
|
|
134
154
|
for (const [k, v] of Object.entries(node.fields)) {
|
|
135
|
-
res.fields[k] = toAstFilter(v);
|
|
155
|
+
res.fields[k] = toAstFilter(v, canonicalParams);
|
|
136
156
|
}
|
|
137
157
|
}
|
|
138
158
|
return res;
|
|
@@ -155,12 +175,24 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
|
|
|
155
175
|
canonicalFilterAst: pat._canonicalFilterAst || null
|
|
156
176
|
};
|
|
157
177
|
}
|
|
158
|
-
|
|
178
|
+
const isDirectCanonical =
|
|
179
|
+
typeof name === "string" && name.startsWith("@");
|
|
180
|
+
if (isDirectCanonical) {
|
|
159
181
|
pat._canonical = name;
|
|
160
182
|
}
|
|
161
183
|
const formalParams = pat.params || [];
|
|
162
184
|
const formalCount = formalParams.length;
|
|
163
185
|
const allPatterns = { ...(options.patterns || {}) };
|
|
186
|
+
if (options.libraries) {
|
|
187
|
+
for (const lib of options.libraries) {
|
|
188
|
+
const lp =
|
|
189
|
+
lib.patterns ||
|
|
190
|
+
lib.defs?.patterns ||
|
|
191
|
+
lib.sourceDefs?.patterns ||
|
|
192
|
+
{};
|
|
193
|
+
Object.assign(allPatterns, lp);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
164
196
|
if (name && pat) allPatterns[name] = pat;
|
|
165
197
|
|
|
166
198
|
let pathMap = {};
|
|
@@ -180,13 +212,6 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
|
|
|
180
212
|
}
|
|
181
213
|
}
|
|
182
214
|
|
|
183
|
-
let expandedFilter = null;
|
|
184
|
-
try {
|
|
185
|
-
expandedFilter = expandFilter(pat.filter, allPatterns);
|
|
186
|
-
} catch {
|
|
187
|
-
expandedFilter = pat.filter;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
215
|
if (!pat.filter) {
|
|
191
216
|
return {
|
|
192
217
|
hash: pat._canonical || null,
|
|
@@ -195,8 +220,12 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
|
|
|
195
220
|
};
|
|
196
221
|
}
|
|
197
222
|
|
|
223
|
+
const expandedFilter = expandFilter(pat.filter, allPatterns);
|
|
224
|
+
|
|
198
225
|
const knots = collectFilterKnots(expandedFilter);
|
|
199
|
-
const skeletonFilter =
|
|
226
|
+
const skeletonFilter = isDirectCanonical
|
|
227
|
+
? expandedFilter
|
|
228
|
+
: skeletonizeFilter(expandedFilter, knots);
|
|
200
229
|
const source = `? ${prettyFilter(skeletonFilter)}`;
|
|
201
230
|
try {
|
|
202
231
|
const annotated = annotate(source, {
|
|
@@ -266,7 +295,10 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
|
|
|
266
295
|
formalCount > 0 ? selectedParams : [];
|
|
267
296
|
pat._graphParams = graphParams || [];
|
|
268
297
|
pat._aliasArgs = aliasArgs;
|
|
269
|
-
pat._canonicalFilterAst = toAstFilter(
|
|
298
|
+
pat._canonicalFilterAst = toAstFilter(
|
|
299
|
+
canonicalFilter,
|
|
300
|
+
graphParams || []
|
|
301
|
+
);
|
|
270
302
|
|
|
271
303
|
return {
|
|
272
304
|
hash: pat._canonical,
|
|
@@ -276,18 +308,16 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
|
|
|
276
308
|
canonicalParams: pat._graphParams,
|
|
277
309
|
canonicalFilterAst: pat._canonicalFilterAst
|
|
278
310
|
};
|
|
279
|
-
} catch {
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
311
|
+
} catch (err) {
|
|
312
|
+
if (isDirectCanonical) {
|
|
313
|
+
return {
|
|
314
|
+
hash: pat._canonical || null,
|
|
315
|
+
def: pat._canonicalDef || null,
|
|
316
|
+
params: pat._canonicalParams || null
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
throw err;
|
|
285
320
|
}
|
|
286
|
-
return {
|
|
287
|
-
hash: pat._canonical || null,
|
|
288
|
-
def: pat._canonicalDef || null,
|
|
289
|
-
params: pat._canonicalParams || null
|
|
290
|
-
};
|
|
291
321
|
}
|
|
292
322
|
|
|
293
323
|
export function canonicalPatternHash(name, pat, options = {}) {
|
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 {
|
|
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
|
package/named-patterns.mjs
CHANGED
|
@@ -293,8 +293,44 @@ export function expandPatternsInRels(rels, patterns = {}, options = {}) {
|
|
|
293
293
|
return rels;
|
|
294
294
|
}
|
|
295
295
|
|
|
296
|
+
export function validatePatternDefinitions(
|
|
297
|
+
patterns = {},
|
|
298
|
+
options = {}
|
|
299
|
+
) {
|
|
300
|
+
const allPatterns = { ...(options.patterns || {}), ...patterns };
|
|
301
|
+
if (options.libraries) {
|
|
302
|
+
for (const lib of options.libraries) {
|
|
303
|
+
const libPatterns =
|
|
304
|
+
lib.patterns ||
|
|
305
|
+
lib.defs?.patterns ||
|
|
306
|
+
lib.sourceDefs?.patterns ||
|
|
307
|
+
{};
|
|
308
|
+
for (const [name, pat] of Object.entries(libPatterns)) {
|
|
309
|
+
if (!(name in allPatterns)) {
|
|
310
|
+
allPatterns[name] = pat;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
for (const [name, hash] of Object.entries(
|
|
314
|
+
lib.patternAlias || {}
|
|
315
|
+
)) {
|
|
316
|
+
if (libPatterns[name] && !(hash in allPatterns)) {
|
|
317
|
+
allPatterns[hash] = libPatterns[name];
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
for (const [name, pat] of Object.entries(patterns)) {
|
|
324
|
+
if (name.startsWith("@")) continue;
|
|
325
|
+
if (pat?.filter) {
|
|
326
|
+
expandFilter(pat.filter, allPatterns, new Set([name]));
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
296
331
|
export default {
|
|
297
332
|
expandFilter,
|
|
298
333
|
expandExp,
|
|
299
334
|
expandPatternsInRels,
|
|
335
|
+
validatePatternDefinitions,
|
|
300
336
|
};
|
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:
|
|
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
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fraczak/k",
|
|
3
|
-
"version": "8.4.
|
|
3
|
+
"version": "8.4.1",
|
|
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"
|
package/repl.mjs
CHANGED
|
@@ -1153,15 +1153,6 @@ function loadSourceOrKlib(state, targetPath, options = {}) {
|
|
|
1153
1153
|
const normKey = normalizeFilePath(targetPath);
|
|
1154
1154
|
if (!state.loadedFiles) state.loadedFiles = new Set();
|
|
1155
1155
|
|
|
1156
|
-
// If loading poly.k, auto-load arithmetics.k first if not already loaded
|
|
1157
|
-
if (normKey === "Examples/poly.k" || normKey.endsWith("/poly.k") || normKey === "poly.k") {
|
|
1158
|
-
const arithKey = "arithmetics.k";
|
|
1159
|
-
const alreadyHasArith = Array.from(state.loadedFiles).some(f => path.basename(f) === "arithmetics.k");
|
|
1160
|
-
if (!alreadyHasArith) {
|
|
1161
|
-
loadSourceOrKlib(state, arithKey, { loadAliases });
|
|
1162
|
-
}
|
|
1163
|
-
}
|
|
1164
|
-
|
|
1165
1156
|
const loadPath = resolveKFilePath(targetPath);
|
|
1166
1157
|
if (loadPath.endsWith(".klib")) {
|
|
1167
1158
|
const lib = loadLibrary(decodeLibrary(fs.readFileSync(loadPath)));
|
|
@@ -1184,45 +1175,13 @@ function loadSourceOrKlib(state, targetPath, options = {}) {
|
|
|
1184
1175
|
lib,
|
|
1185
1176
|
compileOptions
|
|
1186
1177
|
);
|
|
1187
|
-
const { patternNames } = userDefinedNames(source);
|
|
1188
|
-
let parsedSource;
|
|
1189
|
-
try {
|
|
1190
|
-
parsedSource = parse(source);
|
|
1191
|
-
} catch {
|
|
1192
|
-
parsedSource = parse(`${source}\n()`);
|
|
1193
|
-
}
|
|
1194
|
-
const filePatterns = {};
|
|
1195
|
-
for (const name of patternNames) {
|
|
1196
|
-
const pat = parsedSource.defs?.patterns?.[name];
|
|
1197
|
-
if (pat) {
|
|
1198
|
-
filePatterns[name] = pat;
|
|
1199
|
-
if (patternAlias[name]) {
|
|
1200
|
-
const info = resolvePatternCanonicalInfo(state, name, pat);
|
|
1201
|
-
filePatterns[patternAlias[name]] = {
|
|
1202
|
-
params:
|
|
1203
|
-
info.canonicalParams ||
|
|
1204
|
-
info.params ||
|
|
1205
|
-
pat.params ||
|
|
1206
|
-
[],
|
|
1207
|
-
filter: info.canonicalFilterAst || pat.filter,
|
|
1208
|
-
_canonical: patternAlias[name],
|
|
1209
|
-
_canonicalDef: info.def,
|
|
1210
|
-
_canonicalParams: info.canonicalParams,
|
|
1211
|
-
_graphParams: info.canonicalParams,
|
|
1212
|
-
_aliasArgs: info.canonicalParams,
|
|
1213
|
-
_canonicalFilterAst: info.canonicalFilterAst
|
|
1214
|
-
};
|
|
1215
|
-
}
|
|
1216
|
-
}
|
|
1217
|
-
}
|
|
1218
1178
|
mergeLibrary(
|
|
1219
1179
|
state,
|
|
1220
1180
|
{
|
|
1221
1181
|
...lib,
|
|
1222
1182
|
relAlias,
|
|
1223
1183
|
patternAlias,
|
|
1224
|
-
meta
|
|
1225
|
-
patterns: filePatterns
|
|
1184
|
+
meta
|
|
1226
1185
|
},
|
|
1227
1186
|
targetPath,
|
|
1228
1187
|
{ loadAliases }
|
|
@@ -1298,36 +1257,10 @@ function compileSnippetArtifacts(source, state, sourceName = "<repl>") {
|
|
|
1298
1257
|
);
|
|
1299
1258
|
const annotated = annotateWithOptionalIdentity(fullSource, options);
|
|
1300
1259
|
const { patternNames } = userDefinedNames(source);
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
}
|
|
1305
|
-
parsedSnippet = parse(`${source}\n()`);
|
|
1306
|
-
}
|
|
1307
|
-
const patterns = { ...(state.patterns || {}) };
|
|
1308
|
-
for (const name of patternNames) {
|
|
1309
|
-
const pat = parsedSnippet.defs?.patterns?.[name];
|
|
1310
|
-
if (pat) {
|
|
1311
|
-
patterns[name] = pat;
|
|
1312
|
-
if (patternAlias[name]) {
|
|
1313
|
-
const info = resolvePatternCanonicalInfo(state, name, pat);
|
|
1314
|
-
patterns[patternAlias[name]] = {
|
|
1315
|
-
params:
|
|
1316
|
-
info.canonicalParams ||
|
|
1317
|
-
info.params ||
|
|
1318
|
-
pat.params ||
|
|
1319
|
-
[],
|
|
1320
|
-
filter: info.canonicalFilterAst || pat.filter,
|
|
1321
|
-
_canonical: patternAlias[name],
|
|
1322
|
-
_canonicalDef: info.def,
|
|
1323
|
-
_canonicalParams: info.canonicalParams,
|
|
1324
|
-
_graphParams: info.canonicalParams,
|
|
1325
|
-
_aliasArgs: info.canonicalParams,
|
|
1326
|
-
_canonicalFilterAst: info.canonicalFilterAst
|
|
1327
|
-
};
|
|
1328
|
-
}
|
|
1329
|
-
}
|
|
1330
|
-
}
|
|
1260
|
+
const patterns = {
|
|
1261
|
+
...(state.patterns || {}),
|
|
1262
|
+
...(lib.patterns || {})
|
|
1263
|
+
};
|
|
1331
1264
|
return {
|
|
1332
1265
|
annotated,
|
|
1333
1266
|
lib: {
|
|
@@ -183,6 +183,21 @@ console.log("--> Test 7: Error handling (unknown, arity, cycles, dupes)");
|
|
|
183
183
|
() => k.compile("dupe[X, X] = {}; ()"),
|
|
184
184
|
/Duplicate parameter 'X' in pattern 'dupe'/
|
|
185
185
|
);
|
|
186
|
+
|
|
187
|
+
assert.throws(
|
|
188
|
+
() => k.compile("p[] = { missing[] x }; ()"),
|
|
189
|
+
/Unknown pattern template 'missing\[\]'/
|
|
190
|
+
);
|
|
191
|
+
|
|
192
|
+
assert.throws(
|
|
193
|
+
() => k.compile("p[] = missing[]; ()"),
|
|
194
|
+
/Unknown pattern template 'missing\[\]'/
|
|
195
|
+
);
|
|
196
|
+
|
|
197
|
+
assert.throws(
|
|
198
|
+
() => k.compile("a[] = b[]; b[] = a[]; ()"),
|
|
199
|
+
/Cyclic pattern template dependency detected/
|
|
200
|
+
);
|
|
186
201
|
console.log(" Passed: Error conditions correctly handled.");
|
|
187
202
|
}
|
|
188
203
|
|
package/tests/test-repl.mjs
CHANGED
|
@@ -303,6 +303,18 @@ assert.equal(tcoState.value.toJSON(), "zero");
|
|
|
303
303
|
const arithState = createState();
|
|
304
304
|
output = await evaluateInput(":load Examples/arithmetics.k", arithState);
|
|
305
305
|
assert.equal(output[0], "loaded Examples/arithmetics.k");
|
|
306
|
+
output = await evaluateInput(":pat bits", arithState);
|
|
307
|
+
assert.equal(
|
|
308
|
+
output[0],
|
|
309
|
+
"bits[] = <X0 0, X0 1, {} _>=X0; -- " +
|
|
310
|
+
"@VtPHxGf5GNMzzyVFxtv7gegFfJRYapBGtCeyV56bs5Zb"
|
|
311
|
+
);
|
|
312
|
+
output = await evaluateInput(":pat bits_pair", arithState);
|
|
313
|
+
assert.equal(
|
|
314
|
+
output[0],
|
|
315
|
+
"bits_pair[] = {<X0 0, X0 1, {} _>=X0 x, X0 y}; -- " +
|
|
316
|
+
"@R7RD2sgu6yPqpCQBBcJqkzxHQMZfEJLcNW4UKBcTiC3m"
|
|
317
|
+
);
|
|
306
318
|
output = await evaluateInput("10", arithState);
|
|
307
319
|
assert.match(output[0], /^\{\}\|_\|0\|1\|0\|1/);
|
|
308
320
|
output = await evaluateInput("{10 int x, 5 int y} plus", arithState);
|
|
@@ -446,11 +458,33 @@ assert.equal(promptForState(unitState), "unit.mjs> ");
|
|
|
446
458
|
output = await evaluateInput("{}", unitState);
|
|
447
459
|
assert.match(output[0], /unit\.mjs: \{\}/);
|
|
448
460
|
|
|
449
|
-
|
|
450
|
-
|
|
461
|
+
// Verify that poly.k does NOT auto-load arithmetics.k (no autohooks)
|
|
462
|
+
const polyFreshState = createState();
|
|
463
|
+
await assert.rejects(
|
|
464
|
+
() => evaluateInput(":load Examples/poly.k", polyFreshState),
|
|
465
|
+
/Unknown pattern template 'int\[\]'/
|
|
466
|
+
);
|
|
467
|
+
|
|
468
|
+
// Explicitly loading arithmetics.k then poly.k succeeds
|
|
469
|
+
const polyExplicitState = createState();
|
|
470
|
+
output = await evaluateInput(
|
|
471
|
+
":load Examples/arithmetics.k",
|
|
472
|
+
polyExplicitState
|
|
473
|
+
);
|
|
474
|
+
assert.equal(output[0], "loaded Examples/arithmetics.k");
|
|
475
|
+
output = await evaluateInput(
|
|
476
|
+
":load Examples/poly.k",
|
|
477
|
+
polyExplicitState
|
|
478
|
+
);
|
|
451
479
|
assert.equal(output[0], "loaded Examples/poly.k");
|
|
452
|
-
assert.ok(
|
|
453
|
-
|
|
480
|
+
assert.ok(
|
|
481
|
+
polyExplicitState.relAliases.reverse,
|
|
482
|
+
"poly relations loaded"
|
|
483
|
+
);
|
|
484
|
+
assert.ok(
|
|
485
|
+
polyExplicitState.relAliases.int,
|
|
486
|
+
"arithmetics int loaded"
|
|
487
|
+
);
|
|
454
488
|
|
|
455
489
|
// Verify timing reporting is always on and reflects active engine
|
|
456
490
|
const timingState = createState();
|
|
@@ -672,6 +706,15 @@ assert.equal(
|
|
|
672
706
|
"@4ukq2gpiEBFa7WXxcfRm8pfdr2kgYLTTnwsmLHeMd9i5"
|
|
673
707
|
);
|
|
674
708
|
|
|
709
|
+
await assert.rejects(
|
|
710
|
+
() => evaluateInput("bad[] = { missing[] x };", patState),
|
|
711
|
+
/Unknown pattern template 'missing\[\]'/
|
|
712
|
+
);
|
|
713
|
+
await assert.rejects(
|
|
714
|
+
() => evaluateInput("bad[] = missing[];", patState),
|
|
715
|
+
/Unknown pattern template 'missing\[\]'/
|
|
716
|
+
);
|
|
717
|
+
|
|
675
718
|
await assert.rejects(
|
|
676
719
|
() => evaluateInput(":pattern unknown", patState),
|
|
677
720
|
/Unknown pattern 'unknown'/
|