@fraczak/k 8.1.0 → 8.2.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,33 @@ 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.2.0] — 2026-10-21 — Canonical Pattern Decompilation & Parameters
9
+
10
+ ### Interactive REPL & Tooling
11
+
12
+ - **Canonical Pattern Decompilation (`:pattern`, `:pat`)**:
13
+ - `:pattern <name>` (or `:pat <name>`) prints the canonical pattern
14
+ definition decompiled from its underlying minimal automaton,
15
+ rather than echoing user-defined construction syntax.
16
+ - Automatically erases author-chosen parameter and knot names,
17
+ introducing canonical variables (`X0`, `X1`, `X2`, ...) in
18
+ deterministic traversal (discovery) order.
19
+ - Open type holes (`(...)`) are recorded as introduced parameters
20
+ in the pattern header in discovery order:
21
+ * `pair[X0, X1] = {X0 first, X1 second}; -- @hash`
22
+ * `list[X1] = <{X1 car, X0 cdr} cons, {} nil>=X0; -- @hash`
23
+ * `same_pair[X0] = {X0 first, X0 second}; -- @hash`
24
+ * `dict[X1, X2] = <{{X1 first, X2 second} car, X0 cdr} cons,`
25
+ `{} nil>=X0; -- @hash`
26
+ - Added `patternGraphToCanonical` to `pretty.mjs` for decompiling
27
+ pattern graphs with introduced canonical variables.
28
+ - Supports direct pattern lookup by content-addressed hash
29
+ (`:pattern @hash`, `:pat @hash`).
30
+ - Displays canonical content-addressed digest comments (`-- @hash`).
31
+ - Added comprehensive unit tests in `tests/test-repl.mjs`.
32
+ - Updated documentation across `DOCS/REPL.md`,
33
+ `DOCS/NAMED_PATTERNS.md`, and `DOCS/PATTERNS.md`.
34
+
8
35
  ## [8.1.0] — 2026-10-20 — Dynamic JSON Bit-Trie & json? Standard Library
9
36
 
10
37
  ### Dynamic JSON (djson) Consolidation
@@ -208,6 +208,29 @@ To guarantee decidability and termination:
208
208
  that yield isomorphic regular tree automata produce identical
209
209
  canonical hashes and wire encoders.
210
210
 
211
+ 4. **Canonical Form and REPL Decompilation**:
212
+ In the interactive REPL, inspecting a pattern via `:pattern <name>`
213
+ (or `:pat <name>`) displays its **canonical definition** rather than
214
+ the source syntax used to define it:
215
+ - User-defined parameter names (`A`, `B`, `X`) and knot names (`Y`,
216
+ `T`) are erased.
217
+ - The canonical decompiler introduces fresh variables (`X0`, `X1`,
218
+ `X2`, ...) in deterministic traversal (discovery) order.
219
+ - Open type ports are introduced in the pattern header (`name[...]`)
220
+ in order of discovery:
221
+ ```k
222
+ -- pair[A, B] = { A first, B second };
223
+ pair[X0, X1] = {X0 first, X1 second}; -- @...
224
+
225
+ -- list[X] = < {} nil, { X car, Y cdr } cons > = Y;
226
+ list[X1] = <{X1 car, X0 cdr} cons, {} nil>=X0; -- @...
227
+
228
+ -- same_pair[T] = { T first, T second };
229
+ same_pair[X0] = {X0 first, X0 second}; -- @...
230
+ ```
231
+ - Two syntactically different definitions yielding isomorphic
232
+ automata produce the exact same canonical definition and hash.
233
+
211
234
  ---
212
235
 
213
236
  ## 7. Concrete Library Examples
package/DOCS/PATTERNS.md CHANGED
@@ -85,6 +85,11 @@ Direct or mutual recursion among templates (`bits[]` calling `bits[]`)
85
85
  is disallowed to ensure every template dependency graph is an acyclic
86
86
  DAG, guaranteeing finite regular tree automaton compilation.
87
87
 
88
+ In the interactive REPL, inspecting a pattern with `:pattern <name>` (or
89
+ `:pat <name>`) displays its canonical decompiled form with newly
90
+ introduced variables in discovery order (e.g.
91
+ `list[X1] = <{X1 car, X0 cdr} cons, {} nil>=X0; -- @...`).
92
+
88
93
  ## Filters and Terminal Positions
89
94
 
90
95
  A k script can describe a pattern through:
package/DOCS/REPL.md CHANGED
@@ -37,7 +37,7 @@ is complete.
37
37
  | `:wasm` / `:pkir` / `:js` | Shortcut to switch engine |
38
38
  | `:rel name` | Show relation definition |
39
39
  | `:rels` | List relation aliases |
40
- | `:pattern name` | Show named pattern definition (alias: `:pat`) |
40
+ | `:pattern name` | Show canonical definition of pattern (alias: `:pat`) |
41
41
  | `:patterns` | List defined named pattern templates (alias: `:pats`) |
42
42
  | `:limit [num\|none]` | Set maximum characters for value output (default: 4096) |
43
43
  | `:codec load file` | Load a codec from an ES module file (e.g. `:codec load codecs/int.mjs`) |
@@ -155,6 +155,47 @@ Reads the plain-JSON library file and merges its codes, relations,
155
155
  aliases, and metadata into the session. Aliases are recovered from
156
156
  `meta[hash].origins[]` unless `--no-alias` is used.
157
157
 
158
+ ## Pattern Inspection
159
+
160
+ ### `:patterns` (or `:pats`)
161
+
162
+ Lists all currently defined named pattern templates along with their
163
+ declared parameter signatures (e.g. `bit[]`, `list[X]`, `pair[A, B]`).
164
+
165
+ ### `:pattern <name>` (or `:pat <name>`, `:pat @hash`)
166
+
167
+ Displays the **canonical definition** of a named pattern template:
168
+
169
+ ```text
170
+ > pair[A, B] = { A first, B second };
171
+ > :pat pair
172
+ pair[X0, X1] = {X0 first, X1 second}; -- @...
173
+
174
+ > list[T] = < {} nil, { T car, Y cdr } cons > = Y;
175
+ > :pat list
176
+ list[X1] = <{X1 car, X0 cdr} cons, {} nil>=X0; -- @...
177
+
178
+ > same_pair[T] = { T first, T second };
179
+ > :pat same_pair
180
+ same_pair[X0] = {X0 first, X0 second}; -- @...
181
+ ```
182
+
183
+ Rather than echoing the syntax used to construct the template, the
184
+ canonical definition decompiles the underlying minimal finite tree
185
+ automaton. Local parameter and knot names chosen by the author are
186
+ erased; instead, the canonical definition introduces its own variables
187
+ (`X0`, `X1`, `X2`, ...) in deterministic traversal (discovery) order:
188
+
189
+ - **External Ports**: Open type holes (`(...)`) are recorded as
190
+ canonical parameters in the template header (`[X0, X1]`, `[X1]`, etc.)
191
+ in discovery order.
192
+ - **Recursive Knots**: Cycles back to existing nodes are bound using
193
+ knot variables (`=X0`).
194
+ - **Content Hash**: Every canonical definition is annotated with its
195
+ deterministic content-addressed hash (`-- @hash`).
196
+
197
+ Lookup by canonical hash is also supported: `:pattern @hash`.
198
+
158
199
  ## Codecs and Numerical Values
159
200
 
160
201
  In `k`, there are no primitive numbers or built-in numerical literals.
@@ -334,6 +375,9 @@ instantly without exhausting stack or terminal buffers. Use
334
375
  {}|0 ?<{} 0, ...>
335
376
  > :rel inc
336
377
  inc = | +1; -- @...
378
+ > pair[A, B] = { A first, B second };
379
+ > :pat pair
380
+ pair[X0, X1] = {X0 first, X1 second}; -- @...
337
381
  > :klib nat.klib
338
382
  saved nat.klib
339
383
  > :ko inc.ko inc
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fraczak/k",
3
- "version": "8.1.0",
3
+ "version": "8.2.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"
package/pretty.mjs CHANGED
@@ -178,5 +178,113 @@ function patterns2filters(typePatternGraph, ...patternIds) {
178
178
 
179
179
  }
180
180
 
181
- export default { prettyCode, prettyRel, prettyFilter, patterns2filters };
182
- export { prettyCode, prettyRel, prettyFilter, patterns2filters };
181
+ function patternGraphToCanonical(typePatternGraph, rootId) {
182
+ const newTypePatternGraph = new TypePatternGraph(
183
+ typePatternGraph.registerCodeDef,
184
+ typePatternGraph.findCode
185
+ );
186
+ const renamed = typePatternGraph.clone([rootId], newTypePatternGraph);
187
+ const newRootId = newTypePatternGraph.find(renamed[rootId]);
188
+
189
+ const inDegree = newTypePatternGraph.patterns.nodes.map(() => 0);
190
+ inDegree[newRootId]++;
191
+ newTypePatternGraph.edges.forEach((outEdges) =>
192
+ Object.values(outEdges).forEach((destMap) =>
193
+ Object.values(destMap).forEach((dst) => inDegree[dst]++)
194
+ )
195
+ );
196
+
197
+ const variables = inDegree.reduce((vars, degree, i) => {
198
+ const p = newTypePatternGraph.get_pattern(i);
199
+ if (degree > 1 || p.pattern === "(...)") {
200
+ vars[i] = true;
201
+ }
202
+ return vars;
203
+ }, {});
204
+
205
+ const filterVars = {};
206
+ const canonicalParams = [];
207
+
208
+ const buildFilter = (path, patternId) => {
209
+ let named_filter = {};
210
+ const pattern = newTypePatternGraph.get_pattern(patternId);
211
+ if (variables[patternId]) {
212
+ if (filterVars[patternId]) {
213
+ return { type: "name", name: filterVars[patternId] };
214
+ }
215
+ const varName = `X${Object.keys(filterVars).length}`;
216
+ filterVars[patternId] = varName;
217
+ named_filter = { name: varName };
218
+ if (pattern.pattern === "(...)") {
219
+ canonicalParams.push(varName);
220
+ }
221
+ }
222
+
223
+ const edges = newTypePatternGraph.edges[patternId] || {};
224
+ const fields = () =>
225
+ Object.keys(edges)
226
+ .sort()
227
+ .reduce((flds, key) => {
228
+ flds[key] = buildFilter(
229
+ [...path, key],
230
+ Object.values(edges[key])[0]
231
+ );
232
+ return flds;
233
+ }, {});
234
+
235
+ switch (pattern.pattern) {
236
+ case "type": {
237
+ const code = newTypePatternGraph.findCode(pattern.type);
238
+ if (code?.code === "product") {
239
+ return { type: "product", fields: fields(), ...named_filter };
240
+ } else if (code?.code === "union") {
241
+ return { type: "union", fields: fields(), ...named_filter };
242
+ }
243
+ return { type: "code", code: pattern.type, ...named_filter };
244
+ }
245
+ case "(...)":
246
+ return {
247
+ type: null,
248
+ open: true,
249
+ fields: fields(),
250
+ ...named_filter
251
+ };
252
+ case "{...}":
253
+ return {
254
+ type: "product",
255
+ open: true,
256
+ fields: fields(),
257
+ ...named_filter
258
+ };
259
+ case "<...>":
260
+ return {
261
+ type: "union",
262
+ open: true,
263
+ fields: fields(),
264
+ ...named_filter
265
+ };
266
+ case "{}":
267
+ return { type: "product", fields: fields(), ...named_filter };
268
+ case "<>":
269
+ return { type: "union", fields: fields(), ...named_filter };
270
+ }
271
+ };
272
+
273
+ const filter = buildFilter([], newRootId);
274
+ return { filter, canonicalParams };
275
+ }
276
+
277
+ export default {
278
+ prettyCode,
279
+ prettyRel,
280
+ prettyFilter,
281
+ patterns2filters,
282
+ patternGraphToCanonical
283
+ };
284
+ export {
285
+ prettyCode,
286
+ prettyRel,
287
+ prettyFilter,
288
+ patterns2filters,
289
+ patternGraphToCanonical
290
+ };
package/repl.mjs CHANGED
@@ -21,7 +21,12 @@ if (typeof globalThis !== "undefined") {
21
21
  globalThis.isVariant = isVariant;
22
22
  globalThis.patternFromFilter = patternFromFilter;
23
23
  }
24
- import { prettyCode, prettyFilter } from "./pretty.mjs";
24
+ import {
25
+ patternGraphToCanonical,
26
+ patterns2filters,
27
+ prettyCode,
28
+ prettyFilter
29
+ } from "./pretty.mjs";
25
30
  import {
26
31
  compileObject,
27
32
  compileLibrary,
@@ -366,9 +371,15 @@ function listAliases(aliases) {
366
371
  return entries.map(([name, hash]) => `${name} = ${hash}`).join("\n");
367
372
  }
368
373
 
369
- function resolvePatternCanonicalName(state, name, pat) {
370
- if (!state || !pat) return null;
371
- if (pat._canonical) return pat._canonical;
374
+ function resolvePatternCanonicalInfo(state, name, pat) {
375
+ if (!state || !pat) return { hash: null, def: null, params: null };
376
+ if (pat._canonical && pat._canonicalDef) {
377
+ return {
378
+ hash: pat._canonical,
379
+ def: pat._canonicalDef,
380
+ params: pat._canonicalParams || null
381
+ };
382
+ }
372
383
  const params = pat.params || [];
373
384
  const source = `? ${name}[${params.join(", ")}]`;
374
385
  try {
@@ -385,6 +396,12 @@ function resolvePatternCanonicalName(state, name, pat) {
385
396
  const rootId = mainRel.typePatternGraph.find(
386
397
  mainRel.def.patterns[0]
387
398
  );
399
+ const { filter: canonicalFilter, canonicalParams } =
400
+ patternGraphToCanonical(mainRel.typePatternGraph, rootId);
401
+ if (canonicalFilter) {
402
+ pat._canonicalDef = prettyFilter(canonicalFilter);
403
+ pat._canonicalParams = canonicalParams;
404
+ }
388
405
  const propList = patternToPropertyList(
389
406
  exportPatternGraph(mainRel.typePatternGraph, rootId)
390
407
  );
@@ -392,26 +409,46 @@ function resolvePatternCanonicalName(state, name, pat) {
392
409
  if (codeHash) {
393
410
  state.codes = codes.dump();
394
411
  pat._canonical = codeHash;
395
- return codeHash;
412
+ return {
413
+ hash: codeHash,
414
+ def: pat._canonicalDef || null,
415
+ params: pat._canonicalParams || null
416
+ };
396
417
  }
397
418
  }
398
419
  const relHash = annotated.relAlias?.__main__ || null;
399
420
  if (relHash) {
400
421
  pat._canonical = relHash;
401
- return relHash;
422
+ return {
423
+ hash: relHash,
424
+ def: pat._canonicalDef || null,
425
+ params: pat._canonicalParams || null
426
+ };
402
427
  }
403
428
  } catch {
404
429
  restoreCodes(state);
405
- return null;
430
+ return { hash: null, def: null, params: null };
406
431
  }
407
- return null;
432
+ return {
433
+ hash: null,
434
+ def: pat._canonicalDef || null,
435
+ params: pat._canonicalParams || null
436
+ };
437
+ }
438
+
439
+ function resolvePatternCanonicalName(state, name, pat) {
440
+ return resolvePatternCanonicalInfo(state, name, pat).hash;
408
441
  }
409
442
 
410
443
  function prettyPattern(name, pat, state = null) {
411
- const params = (pat?.params || []).join(", ");
412
- const filterStr = pat?.filter ? prettyFilter(pat.filter) : "()";
413
- const canonical = resolvePatternCanonicalName(state, name, pat);
414
- const suffix = canonical ? ` -- ${canonical}` : "";
444
+ const info = resolvePatternCanonicalInfo(state, name, pat);
445
+ const paramList = info.params != null
446
+ ? info.params
447
+ : (pat?.params || []);
448
+ const params = paramList.join(", ");
449
+ const filterStr = info.def ||
450
+ (pat?.filter ? prettyFilter(pat.filter) : "()");
451
+ const suffix = info.hash ? ` -- ${info.hash}` : "";
415
452
  return `${name}[${params}] = ${filterStr};${suffix}`;
416
453
  }
417
454
 
@@ -627,19 +627,19 @@ assert.equal(output[0], "bit[]");
627
627
  output = await evaluateInput(":pattern bit", patState);
628
628
  assert.equal(
629
629
  output[0],
630
- "bit[] = <{} 0, {} 1>; -- " +
630
+ "bit[] = <{}=X0 0, X0 1>; -- " +
631
631
  "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg"
632
632
  );
633
633
  output = await evaluateInput(":pattern bit[]", patState);
634
634
  assert.equal(
635
635
  output[0],
636
- "bit[] = <{} 0, {} 1>; -- " +
636
+ "bit[] = <{}=X0 0, X0 1>; -- " +
637
637
  "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg"
638
638
  );
639
639
  output = await evaluateInput(":pat bit", patState);
640
640
  assert.equal(
641
641
  output[0],
642
- "bit[] = <{} 0, {} 1>; -- " +
642
+ "bit[] = <{}=X0 0, X0 1>; -- " +
643
643
  "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg"
644
644
  );
645
645
  output = await evaluateInput(
@@ -648,10 +648,25 @@ output = await evaluateInput(
648
648
  );
649
649
  assert.equal(
650
650
  output[0],
651
- "bit[] = <{} 0, {} 1>; -- " +
651
+ "bit[] = <{}=X0 0, X0 1>; -- " +
652
652
  "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg"
653
653
  );
654
654
 
655
+ output = await evaluateInput(
656
+ "byte[] = { " +
657
+ "bit[] b0, bit[] b1, bit[] b2, bit[] b3, " +
658
+ "bit[] b4, bit[] b5, bit[] b6, bit[] b7 " +
659
+ "};",
660
+ patState
661
+ );
662
+ output = await evaluateInput(":pattern byte", patState);
663
+ assert.equal(
664
+ output[0],
665
+ "byte[] = {<{}=X1 0, X1 1>=X0 b0, X0 b1, X0 b2, X0 b3, " +
666
+ "X0 b4, X0 b5, X0 b6, X0 b7}; -- " +
667
+ "@4ukq2gpiEBFa7WXxcfRm8pfdr2kgYLTTnwsmLHeMd9i5"
668
+ );
669
+
655
670
  await assert.rejects(
656
671
  () => evaluateInput(":pattern unknown", patState),
657
672
  /Unknown pattern 'unknown'/
@@ -688,7 +703,7 @@ output = await evaluateInput(
688
703
  output = await evaluateInput(":pattern pair", patState);
689
704
  assert.equal(
690
705
  output[0],
691
- "pair[A, B] = {A first, B second}; -- " +
706
+ "pair[X0, X1] = {X0 first, X1 second}; -- " +
692
707
  "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm"
693
708
  );
694
709
 
@@ -702,7 +717,7 @@ assert(output[0].includes("pair[A, B]"));
702
717
  output = await evaluateInput(":pattern list", patState);
703
718
  assert.equal(
704
719
  output[0],
705
- "list[X] = <{} nil, {X car, Y cdr} cons>=Y; -- " +
720
+ "list[X1] = <{X1 car, X0 cdr} cons, {} nil>=X0; -- " +
706
721
  "@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe"
707
722
  );
708
723
 
@@ -724,9 +739,31 @@ assert(output[0].includes("list[X]"));
724
739
  output = await evaluateInput(":pattern bit", freshState);
725
740
  assert.equal(
726
741
  output[0],
727
- "bit[] = <{} 0, {} 1>; -- " +
742
+ "bit[] = <{}=X0 0, X0 1>; -- " +
728
743
  "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg"
729
744
  );
745
+ output = await evaluateInput(":pattern pair", freshState);
746
+ assert.equal(
747
+ output[0],
748
+ "pair[X0, X1] = {X0 first, X1 second}; -- " +
749
+ "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm"
750
+ );
751
+ output = await evaluateInput(":pattern list", freshState);
752
+ assert.equal(
753
+ output[0],
754
+ "list[X1] = <{X1 car, X0 cdr} cons, {} nil>=X0; -- " +
755
+ "@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe"
756
+ );
757
+ output = await evaluateInput(
758
+ "same_pair[T] = { T first, T second };",
759
+ freshState
760
+ );
761
+ output = await evaluateInput(":pattern same_pair", freshState);
762
+ assert.equal(
763
+ output[0],
764
+ "same_pair[X0] = {X0 first, X0 second}; -- " +
765
+ "@TyjJDJuYAbp56mytRMzu2HMTfQq7rKLcGsaQtFG28yhW"
766
+ );
730
767
  output = await evaluateInput("{} | nil ? list[bit[]]", freshState);
731
768
  assert.match(output[0], /\{\}\|nil/);
732
769