@fraczak/k 8.4.0 → 8.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/DOCS/ARCHITECTURE.md +83 -0
  3. package/DOCS/CODECS.md +93 -204
  4. package/DOCS/DICTIONARY.md +42 -1241
  5. package/DOCS/FILE_FORMATS.md +170 -625
  6. package/DOCS/GETTING_STARTED.md +164 -0
  7. package/DOCS/KIR_V1.md +22 -33
  8. package/DOCS/KVM_EXECUTION_MODEL.md +88 -481
  9. package/DOCS/PATTERNS.md +156 -123
  10. package/DOCS/POLYMORPHIC_IR.md +83 -101
  11. package/DOCS/PROFILING_AND_TRACING.md +52 -166
  12. package/DOCS/README.md +35 -0
  13. package/DOCS/REPL.md +100 -371
  14. package/DOCS/TEXTUAL_VALUES.md +53 -81
  15. package/DOCS/TYPE_DERIVATION.md +95 -234
  16. package/DOCS/book-combined.md +3786 -0
  17. package/Examples/arithmetics.k +45 -59
  18. package/Examples/djson.k +102 -112
  19. package/Examples/karatsuba-mult.k +2 -3
  20. package/Examples/list.k +6 -7
  21. package/Examples/nat.k +6 -6
  22. package/Examples/poly.k +45 -45
  23. package/LICENSE +15 -0
  24. package/README.md +72 -410
  25. package/backends/llvm/README.md +75 -97
  26. package/backends/llvm/src/cli.mjs +0 -31
  27. package/backends/wasm/README.md +88 -66
  28. package/backends/wasm/src/cli.mjs +0 -31
  29. package/canonical-pattern.mjs +69 -35
  30. package/codecs/README.md +23 -261
  31. package/codecs/WIRE_FORMAT.md +132 -0
  32. package/core.k +5 -15
  33. package/index.mjs +5 -1
  34. package/named-patterns.mjs +55 -7
  35. package/object.mjs +28 -6
  36. package/objects/README.md +24 -109
  37. package/package.json +8 -3
  38. package/paper/Makefile +17 -0
  39. package/paper/k-paper.pdf +0 -0
  40. package/paper/k-paper.tex +435 -0
  41. package/parser.jison +0 -10
  42. package/parser.mjs +32 -43
  43. package/repl.mjs +79 -101
  44. package/scripts/benchmark-idempotency.mjs +3 -3
  45. package/scripts/run-tests.mjs +1 -1
  46. package/scripts/test-package.mjs +64 -0
  47. package/tests/README.md +66 -46
  48. package/tests/code-derivation/core.mjs +61 -0
  49. package/tests/helpers/cli.mjs +45 -0
  50. package/tests/integration.sh +2 -3
  51. package/tests/test-arithmetics.mjs +47 -237
  52. package/tests/test-djson-methods.mjs +71 -275
  53. package/tests/test-hash-normalization.mjs +22 -1
  54. package/tests/test-karatsuba.mjs +18 -126
  55. package/tests/test-named-patterns.mjs +174 -606
  56. package/tests/test-paper-examples.mjs +90 -0
  57. package/tests/test-poly.mjs +2 -2
  58. package/tests/test-repl-html.mjs +2 -2
  59. package/tests/test-repl.mjs +89 -38
  60. package/tests/test.mjs +27 -68
  61. package/AGENTS.md +0 -35
  62. package/CLAUDE.md +0 -64
  63. package/DOCS/BIG_PICTURE.md +0 -439
  64. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  65. package/DOCS/CANONICAL_PATTERNS.md +0 -349
  66. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  67. package/DOCS/CONVERGENCE.md +0 -123
  68. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  69. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  70. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  71. package/DOCS/Makefile +0 -99
  72. package/DOCS/NAMED_PATTERNS.md +0 -340
  73. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  74. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  75. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -136
  76. package/DOCS/book/01-introduction.md +0 -48
  77. package/DOCS/book/02-syntax-and-values.md +0 -110
  78. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  79. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  80. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  81. package/DOCS/book/06-values-in-memory.md +0 -1085
  82. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  83. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  84. package/DOCS/book/09-compiler-architecture.md +0 -160
  85. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  86. package/DOCS/book/14-canonical-serialization.md +0 -176
  87. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  88. package/DOCS/book/overview.txt +0 -68
  89. package/DOCS/book.md +0 -50
  90. package/Examples/bnat.k +0 -308
  91. package/Examples/buda.k +0 -66
  92. package/Examples/byte.k +0 -35
  93. package/Examples/code.k +0 -43
  94. package/Examples/vhdl_to_k.k +0 -67
  95. package/JOURNAL.md +0 -288
  96. package/TODO.md +0 -107
  97. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  98. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  99. package/backends/wasm/demo_ieee.mjs +0 -318
  100. package/browser/vfs-data.mjs +0 -21
  101. package/codecs/BINARY_FORMAT.md +0 -53
  102. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  103. package/codecs/pandoc.css +0 -71
  104. package/tests/code-derivation/blowup.mjs +0 -25
  105. package/tests/code-derivation/bnat.mjs +0 -11
  106. package/tests/code-derivation/dot.mjs +0 -37
  107. package/tests/code-derivation/index.mjs +0 -20
  108. package/tests/code-derivation/loop.mjs +0 -17
  109. package/tests/code-derivation/nat.mjs +0 -10
  110. package/tests/code-derivation/not-not.mjs +0 -14
  111. package/tests/code-derivation/product.mjs +0 -22
  112. package/tests/code-derivation/rlz.mjs +0 -13
  113. package/tests/test-fingerprint.mjs +0 -38
@@ -1,628 +1,196 @@
1
- // tests/test-named-patterns.mjs
2
- // Comprehensive test suite for named patterns and type schemes.
3
-
4
1
  import assert from "node:assert/strict";
5
2
  import k from "../index.mjs";
6
3
  import { Value } from "../Value.mjs";
7
-
8
- console.log("==> Running Named Patterns Test Suite");
9
-
10
- // Test 1: 0-arity pattern and composite product
11
- console.log("--> Test 1: 0-arity pattern (bit[]) and product (byte[])");
12
- {
13
- const script = `
14
- bit[] = < {}0, {}1 >;
15
- byte[] = {
16
- bit[] b0, bit[] b1, bit[] b2, bit[] b3,
17
- bit[] b4, bit[] b5, bit[] b6, bit[] b7
18
- };
19
-
20
- is_byte = ? byte[];
21
-
22
- sample = {
23
- {}|0 b0, {}|1 b1, {}|0 b2, {}|1 b3,
24
- {}|0 b4, {}|1 b5, {}|0 b6, {}|1 b7
25
- };
26
-
27
- sample is_byte
28
- `;
29
- const fn = k.compile(script);
30
- const out = fn(Value.product({}));
31
- assert.equal(out.type, "{}");
32
- assert.equal(out.product.b0.tag, "0");
33
- assert.equal(out.product.b1.tag, "1");
34
- console.log(" Passed: 0-arity patterns and composition.");
35
- }
36
-
37
- // Test 2: Parameterized list pattern
38
- console.log("--> Test 2: Parameterized pattern (list[X])");
39
- {
40
- const script = `
41
- bit[] = < {}0, {}1 >;
42
- list[X] = < {}nil, { X car, Y cdr } cons > = Y;
43
-
44
- is_bit_list = ? list[bit[]];
45
-
46
- empty = {}|nil is_bit_list;
47
- one = { {}|1 car, {}|nil cdr }|cons is_bit_list;
48
- two = {
49
- {}|0 car,
50
- { {}|1 car, {}|nil cdr }|cons cdr
51
- }|cons is_bit_list;
52
-
53
- { empty empty, one one, two two }
54
- `;
55
- const fn = k.compile(script);
56
- const out = fn(Value.product({}));
57
- assert.equal(out.product.empty.tag, "nil");
58
- assert.equal(out.product.one.tag, "cons");
59
- assert.equal(out.product.one.value.product.car.tag, "1");
60
- assert.equal(out.product.two.tag, "cons");
61
- assert.equal(out.product.two.value.product.car.tag, "0");
62
- console.log(" Passed: Parameterized list pattern.");
63
- }
64
-
65
- // Test 3: Multi-parameter templates and composition
66
- console.log("--> Test 3: Multi-parameter templates (pair, dict)");
67
- {
68
- const script = `
69
- bit[] = < {}0, {}1 >;
70
- pair[A, B] = { A key, B val };
71
- list[X] = < {}nil, { X car, Y cdr } cons > = Y;
72
- dict[K, V] = list[pair[K, V]];
73
-
74
- is_dict = ? dict[bit[], bit[]];
75
-
76
- entry = { {}|0 key, {}|1 val };
77
- d = { entry car, {}|nil cdr }|cons is_dict;
78
-
79
- d
80
- `;
81
- const fn = k.compile(script);
82
- const out = fn(Value.product({}));
83
- assert.equal(out.tag, "cons");
84
- assert.equal(out.value.product.car.product.key.tag, "0");
85
- assert.equal(out.value.product.car.product.val.tag, "1");
86
- console.log(" Passed: Multi-parameter template composition.");
87
- }
88
-
89
- // Test 4: Existential internal variables (type unification across fields)
90
- console.log("--> Test 4: Existential variables (same_pair[])");
91
- {
92
- const scriptOk = `
93
- same_pair[] = { T first, T second };
94
- check = ? same_pair[];
95
- { {}|0 first, {}|1 second } check
96
- `;
97
- const fnOk = k.compile(scriptOk);
98
- const outOk = fnOk(Value.product({}));
99
- assert.equal(outOk.product.first.tag, "0");
100
- assert.equal(outOk.product.second.tag, "1");
101
-
102
- const scriptBad = `
103
- same_pair[] = { T first, T second };
104
- check = ? same_pair[];
105
- { {} first, {}|0 second } check
106
- `;
107
- assert.throws(
108
- () => k.compile(scriptBad),
109
- /Cannot unify/
110
- );
111
- console.log(" Passed: Existential variables unified across fields.");
112
- }
113
-
114
- // Test 5: Recursive tree with internal knot and list
115
- console.log("--> Test 5: Recursive tree with knot T (tree[X])");
116
- {
117
- const script = `
118
- list[X] = < {}nil, { X car, Y cdr } cons > = Y;
119
- tree[X] = < {}nil, { X val, list[T] children } node > = T;
120
-
121
- bit[] = < {}0, {}1 >;
122
- is_tree = ? tree[bit[]];
123
-
124
- leaf = { {}|1 val, {}|nil children }|node is_tree;
125
- root = {
126
- {}|0 val,
127
- { leaf car, {}|nil cdr }|cons children
128
- }|node is_tree;
129
-
130
- { leaf leaf, root root }
131
- `;
132
- const fn = k.compile(script);
133
- const out = fn(Value.product({}));
134
- assert.equal(out.product.leaf.tag, "node");
135
- assert.equal(out.product.leaf.value.product.val.tag, "1");
136
- assert.equal(out.product.root.tag, "node");
137
- assert.equal(out.product.root.value.product.val.tag, "0");
138
- console.log(" Passed: Recursive tree template with list port.");
139
- }
140
-
141
- // Test 6: Polymorphic relation with shared type variable
142
- console.log("--> Test 6: Polymorphic relation ({ X car, list[X] cdr })");
143
- {
144
- const script = `
145
- list[X] = < {}nil, { X car, Y cdr } cons > = Y;
146
- head = ? { X car, list[X] cdr } .car;
147
-
148
- bit[] = < {}0, {}1 >;
149
- h1 = { {}|1 car, {}|nil cdr } head;
150
-
151
- h1
152
- `;
153
- const fn = k.compile(script);
154
- const out = fn(Value.product({}));
155
- assert.equal(out.tag, "1");
156
- console.log(" Passed: Polymorphic relation head with list[X].");
157
- }
158
-
159
- // Test 7: Error handling for templates
160
- console.log("--> Test 7: Error handling (unknown, arity, cycles, dupes)");
161
- {
162
- assert.throws(
163
- () => k.compile("check = ? missing[]; ()"),
164
- /Unknown pattern template 'missing\[\]'/
165
- );
166
-
167
- assert.throws(
168
- () => k.compile("list[X] = {}; check = ? list[]; ()"),
169
- /Pattern 'list' expects 1 argument, got 0/
170
- );
171
-
172
- assert.throws(
173
- () => k.compile("pair[A, B] = {}; check = ? pair[{}]; ()"),
174
- /Pattern 'pair' expects 2 arguments, got 1/
175
- );
176
-
177
- assert.throws(
178
- () => k.compile("a[] = b[]; b[] = a[]; check = ? a[]; ()"),
179
- /Cyclic pattern template dependency detected/
180
- );
181
-
182
- assert.throws(
183
- () => k.compile("dupe[X, X] = {}; ()"),
184
- /Duplicate parameter 'X' in pattern 'dupe'/
185
- );
186
- console.log(" Passed: Error conditions correctly handled.");
187
- }
188
-
189
- // Test 8: Canonical pattern references and aliasing
190
- console.log("--> Test 8: Canonical pattern references and aliasing");
191
- {
192
- const { compileLibrary } = await import("../object.mjs");
193
- const baseLib = compileLibrary(`
194
- bit[] = < {}0, {}1 >;
195
- list[X] = < {}nil, { X car, Y cdr } cons > = Y;
196
- `, { exports: ["bit", "list"] });
197
-
198
- const script1 = `
199
- -- Canonical hash application with and without arguments
200
- is_bit = ? @MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg[];
201
- is_bit2 = ? @MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg;
202
- is_bit_list = ? @JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[
203
- @MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg[]
204
- ];
205
-
206
- b0 = {}|0 is_bit;
207
- b1 = {}|1 is_bit2;
208
- l = { b1 car, {}|nil cdr }|cons is_bit_list;
209
- { b0 b0, b1 b1, l l }
210
- `;
211
- const fn1 = k.compile(script1, { libraries: [baseLib] });
212
- const out1 = fn1(Value.product({}));
213
- assert.equal(out1.product.b0.tag, "0");
214
- assert.equal(out1.product.b1.tag, "1");
215
- assert.equal(out1.product.l.tag, "cons");
216
-
217
- // Aliasing canonical patterns
218
- const script2 = `
219
- my_bit[] = @MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg[];
220
- my_bit2[] = @MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg;
221
- my_list[T] = @JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[T];
222
-
223
- is_my_list = ? my_list[my_bit[]];
224
- val = { {}|0 car, {}|nil cdr }|cons is_my_list;
225
- val
226
- `;
227
- const fn2 = k.compile(script2, { libraries: [baseLib] });
228
- const out2 = fn2(Value.product({}));
229
- assert.equal(out2.tag, "cons");
230
- console.log(" Passed: Canonical pattern references and aliasing.");
4
+ import { compileLibrary, extractAliasesFromObject } from "../object.mjs";
5
+ import { validateObjectPayload } from "../objects/validate.mjs";
6
+ import { buildExportPreamble, resolvePatternCanonicalInfo } from "../canonical-pattern.mjs";
7
+
8
+ const BIT = "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg";
9
+ const LIST = "@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe";
10
+ const PAIR = "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm";
11
+ const XY = "@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x";
12
+ const BASE = `
13
+ bit[] = <{} 0, {} 1>;
14
+ list[X] = <{} nil, {X car, Y cdr} cons> = Y;
15
+ `;
16
+ const evaluate = (source, options) => k.compile(source, options)(Value.product({}));
17
+
18
+ function patterns(source) {
19
+ const { defs: { patterns } } = k.parse(source + "\n()");
20
+ return Object.fromEntries(Object.entries(patterns).map(([name, def]) =>
21
+ [name, resolvePatternCanonicalInfo(name, def, { patterns })]));
231
22
  }
232
-
233
- // Test 9: Library export, validation, and multi-library consumption
234
- console.log("--> Test 9: Library export and canonical pattern metadata");
235
- {
236
- const { compileLibrary, extractAliasesFromObject } =
237
- await import("../object.mjs");
238
- const { validateObjectPayload } =
239
- await import("../objects/validate.mjs");
240
- const { buildExportPreamble } =
241
- await import("../canonical-pattern.mjs");
242
-
243
- const libSource = `
244
- bit[] = < {}0, {}1 >;
245
- list[X] = < {}nil, { X car, Y cdr } cons > = Y;
246
- pair[A, B] = { A first, B second };
247
- `;
248
- const lib = compileLibrary(libSource, {
249
- exports: ["bit", "list", "pair"]
250
- });
251
-
252
- validateObjectPayload(lib);
253
-
254
- assert.equal(
255
- lib.patternAlias.bit,
256
- "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg"
257
- );
258
- assert.equal(
259
- lib.patternAlias.list,
260
- "@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe"
261
- );
262
- assert.equal(
263
- lib.patternAlias.pair,
264
- "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm"
265
- );
266
-
267
- const bitHash = "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg";
268
- const listHash = "@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe";
269
- assert.equal(lib.meta[bitHash].type, "pattern");
270
- assert.equal(lib.meta[listHash].type, "pattern");
271
-
272
- const aliases = extractAliasesFromObject(lib);
273
- assert.match(aliases, /bit\[\] = @Mjusy/);
274
- assert.match(aliases, /list\[X\] = @JagVex/);
275
- assert.match(aliases, /pair\[A, B\] = @KqTB/);
276
-
277
- const preamble = buildExportPreamble(
278
- ["bit", "list:my_list"],
279
- [lib]
280
- );
281
- assert.match(preamble, /bit\[\] = @Mjusy/);
282
- assert.match(preamble, /my_list\[X\] = @JagVex/);
283
-
284
- const consumerSource = `
285
- is_bit = ? bit[];
286
- is_pair = ? @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[
287
- bit[], bit[]
288
- ];
289
- is_pair_list = ? list[@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[
290
- bit[], bit[]
291
- ]];
292
-
293
- b = {}|0 is_bit;
294
- p = { b first, {}|1 second } is_pair;
295
- l = { p car, {}|nil cdr }|cons is_pair_list;
296
- l
297
- `;
298
- const fnConsumer = k.compile(consumerSource, {
299
- libraries: [lib]
300
- });
301
- const outConsumer = fnConsumer(Value.product({}));
302
- assert.equal(outConsumer.tag, "cons");
303
- console.log(" Passed: Library export and pattern metadata.");
23
+ function check(info, expected) {
24
+ for (const [key, value] of Object.entries(expected)) {
25
+ assert.deepEqual(info[key], value, key);
26
+ }
304
27
  }
305
28
 
306
- // Test 10: Canonical pattern sharing & parameter aliasing
307
- console.log(
308
- "--> Test 10: Canonical pattern sharing (a[], b[X], c[X,Y], d[Y,X])"
309
- );
29
+ // Runtime template applications: products, lists, dictionaries, sharing, knots.
310
30
  {
311
- const { resolvePatternCanonicalInfo } =
312
- await import("../canonical-pattern.mjs");
313
- const { parse } = await import("../parser.mjs");
314
-
315
- const ast = parse(`
316
- a[] = {X x, Y y};
317
- b[X] = {X x, Y y};
318
- c[X,Y] = {X x, Y y};
319
- d[Y,X] = {X x, Y y};
320
- ()
31
+ const out = evaluate(BASE + `
32
+ byte[] = {bit[] b0, bit[] b1, bit[] b2, bit[] b3,
33
+ bit[] b4, bit[] b5, bit[] b6, bit[] b7};
34
+ is_byte = ?byte[];
35
+ {{}|0 b0, {}|1 b1, {}|0 b2, {}|1 b3,
36
+ {}|0 b4, {}|1 b5, {}|0 b6, {}|1 b7} is_byte
321
37
  `);
322
- const aInfo = resolvePatternCanonicalInfo(
323
- "a",
324
- ast.defs.patterns.a,
325
- { patterns: ast.defs.patterns }
326
- );
327
- const bInfo = resolvePatternCanonicalInfo(
328
- "b",
329
- ast.defs.patterns.b,
330
- { patterns: ast.defs.patterns }
331
- );
332
- const cInfo = resolvePatternCanonicalInfo(
333
- "c",
334
- ast.defs.patterns.c,
335
- { patterns: ast.defs.patterns }
336
- );
337
- const dInfo = resolvePatternCanonicalInfo(
338
- "d",
339
- ast.defs.patterns.d,
340
- { patterns: ast.defs.patterns }
341
- );
342
-
343
- const sharedHash = "@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x";
344
- assert.equal(aInfo.hash, sharedHash);
345
- assert.equal(bInfo.hash, sharedHash);
346
- assert.equal(cInfo.hash, sharedHash);
347
- assert.equal(dInfo.hash, sharedHash);
348
-
349
- assert.equal(aInfo.def, "{X0 x, X1 y}");
350
- assert.equal(bInfo.def, "{X0 x, X1 y}");
351
- assert.equal(cInfo.def, "{X0 x, X1 y}");
352
- assert.equal(dInfo.def, "{X0 x, X1 y}");
353
-
354
- assert.deepEqual(aInfo.aliasArgs, ["(...)", "(...)"]);
355
- assert.deepEqual(bInfo.aliasArgs, ["X", "(...)"]);
356
- assert.deepEqual(cInfo.aliasArgs, ["X", "Y"]);
357
- assert.deepEqual(dInfo.aliasArgs, ["X", "Y"]);
358
-
359
- assert.deepEqual(aInfo.params, []);
360
- assert.deepEqual(bInfo.params, ["X0"]);
361
- assert.deepEqual(cInfo.params, ["X0", "X1"]);
362
- assert.deepEqual(dInfo.params, ["X1", "X0"]);
363
- console.log(
364
- " Passed: Canonical pattern sharing & parameter aliasing."
365
- );
38
+ assert.deepEqual([out.type, out.product.b0.tag, out.product.b1.tag], ["{}", "0", "1"]);
366
39
  }
367
-
368
- // Test 11: Knot parameter conflict rejection and canonical patterns
369
- console.log(
370
- "--> Test 11: Knot conflict rejection & direct canonical patterns"
371
- );
372
40
  {
373
- assert.throws(
374
- () =>
375
- k.compile("list[X,Y] = <{}nil,{X car, Y cdr} cons> = Y; ()"),
376
- /conflicts with knot 'Y'/
377
- );
378
-
379
- const directDefSource = `
380
- @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X, Y] = {
381
- X x, Y y, Y z
382
- };
383
- is_p = ? @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[
384
- {}, {}
385
- ];
386
- { {} x, {} y, {} z } is_p
387
- `;
388
- const fnDirect = k.compile(directDefSource);
389
- const outDirect = fnDirect(Value.product({}));
390
- assert.equal(outDirect != null, true);
391
- console.log(
392
- " Passed: Knot conflict rejection and canonical patterns."
393
- );
41
+ const out = evaluate(BASE + `
42
+ is_bit_list = ?list[bit[]];
43
+ empty = {}|nil is_bit_list;
44
+ one = {{}|1 car, {}|nil cdr}|cons is_bit_list;
45
+ two = {{}|0 car, {{}|1 car, {}|nil cdr}|cons cdr}|cons is_bit_list;
46
+ {empty empty, one one, two two}
47
+ `);
48
+ assert.deepEqual([
49
+ out.product.empty.tag, out.product.one.tag, out.product.one.value.product.car.tag,
50
+ out.product.two.tag, out.product.two.value.product.car.tag
51
+ ], ["nil", "cons", "1", "cons", "0"]);
394
52
  }
395
-
396
- // Test 12: Unrestricted pattern (...) unification with variable ports
397
- console.log(
398
- "--> Test 12: Wildcard (...) unification with canonical variables"
399
- );
400
53
  {
401
- const { resolvePatternCanonicalInfo } =
402
- await import("../canonical-pattern.mjs");
403
- const { parse } = await import("../parser.mjs");
404
-
405
- const ast = parse(`
406
- c[X,Y] = {X x, Y y};
407
- p[X] = {X x, (...) y};
408
- q[X,Y,Z] = {X x, Y y, Z z};
409
- t[] = {(...) x, (...) y, (...) z};
410
- ()
54
+ const out = evaluate(BASE + `
55
+ pair[A,B] = {A key, B val};
56
+ dict[K,V] = list[pair[K,V]];
57
+ is_dict = ?dict[bit[],bit[]];
58
+ entry = {{}|0 key, {}|1 val};
59
+ {entry car, {}|nil cdr}|cons is_dict
411
60
  `);
412
- const cInfo = resolvePatternCanonicalInfo(
413
- "c",
414
- ast.defs.patterns.c,
415
- { patterns: ast.defs.patterns }
416
- );
417
- const pInfo = resolvePatternCanonicalInfo(
418
- "p",
419
- ast.defs.patterns.p,
420
- { patterns: ast.defs.patterns }
421
- );
422
- const qInfo = resolvePatternCanonicalInfo(
423
- "q",
424
- ast.defs.patterns.q,
425
- { patterns: ast.defs.patterns }
426
- );
427
- const tInfo = resolvePatternCanonicalInfo(
428
- "t",
429
- ast.defs.patterns.t,
430
- { patterns: ast.defs.patterns }
431
- );
432
-
433
- assert.equal(cInfo.hash, pInfo.hash);
434
- assert.equal(qInfo.hash, tInfo.hash);
435
-
436
- assert.equal(pInfo.def, "{X0 x, X1 y}");
437
- assert.equal(tInfo.def, "{X0 x, X1 y, X2 z}");
438
-
439
- assert.deepEqual(pInfo.aliasArgs, ["X", "(...)"]);
440
- assert.deepEqual(tInfo.aliasArgs, ["(...)", "(...)", "(...)"]);
441
- console.log(
442
- " Passed: Wildcard (...) unification with canonical variables."
443
- );
61
+ assert.deepEqual([out.tag, out.value.product.car.product.key.tag,
62
+ out.value.product.car.product.val.tag], ["cons", "0", "1"]);
444
63
  }
445
-
446
- // Test 13: Nested template composition & parameter routing
447
- console.log(
448
- "--> Test 13: Nested composition & parameter routing"
449
- );
450
64
  {
451
- const { resolvePatternCanonicalInfo } =
452
- await import("../canonical-pattern.mjs");
453
- const { parse } = await import("../parser.mjs");
454
-
455
- const ast = parse(`
456
- pair[A, B] = { A a, B b };
457
- flip[Y, X] = pair[X, Y];
458
- outer[Z] = pair[pair[Z, (...)], (...)];
459
- deep[] = pair[pair[(...), (...)], (...)];
460
- ()
461
- `);
462
- const flipInfo = resolvePatternCanonicalInfo(
463
- "flip",
464
- ast.defs.patterns.flip,
465
- { patterns: ast.defs.patterns }
466
- );
467
- const pairInfo = resolvePatternCanonicalInfo(
468
- "pair",
469
- ast.defs.patterns.pair,
470
- { patterns: ast.defs.patterns }
471
- );
472
- const outerInfo = resolvePatternCanonicalInfo(
473
- "outer",
474
- ast.defs.patterns.outer,
475
- { patterns: ast.defs.patterns }
476
- );
477
- const deepInfo = resolvePatternCanonicalInfo(
478
- "deep",
479
- ast.defs.patterns.deep,
480
- { patterns: ast.defs.patterns }
481
- );
482
-
483
- assert.equal(flipInfo.hash, pairInfo.hash);
484
- assert.deepEqual(flipInfo.params, ["X1", "X0"]);
485
- assert.deepEqual(flipInfo.aliasArgs, ["X", "Y"]);
486
-
487
- assert.equal(outerInfo.hash, deepInfo.hash);
488
- assert.equal(outerInfo.def, "{{X0 a, X1 b} a, X2 b}");
489
- assert.deepEqual(outerInfo.params, ["X0"]);
490
- assert.deepEqual(outerInfo.aliasArgs, ["Z", "(...)", "(...)"]);
491
- assert.deepEqual(deepInfo.params, []);
492
- assert.deepEqual(deepInfo.aliasArgs, ["(...)", "(...)", "(...)"]);
493
- console.log(
494
- " Passed: Nested composition and parameter routing."
495
- );
65
+ const out = evaluate(`same_pair[] = {T first, T second};
66
+ {{}|0 first, {}|1 second} ?same_pair[]`);
67
+ assert.deepEqual([out.product.first.tag, out.product.second.tag], ["0", "1"]);
496
68
  }
497
-
498
- // Test 14: Repeated variable unification with wildcards
499
- console.log(
500
- "--> Test 14: Repeated existential variable wildcard constraints"
501
- );
502
69
  {
503
- const { resolvePatternCanonicalInfo } =
504
- await import("../canonical-pattern.mjs");
505
- const { parse } = await import("../parser.mjs");
506
-
507
- const ast = parse(`
508
- pair_equal[Z] = { Z a, Y b, Y c };
509
- full_equal[A, B] = { A a, B b, B c };
510
- ()
511
- `);
512
- const peInfo = resolvePatternCanonicalInfo(
513
- "pair_equal",
514
- ast.defs.patterns.pair_equal,
515
- { patterns: ast.defs.patterns }
516
- );
517
- const feInfo = resolvePatternCanonicalInfo(
518
- "full_equal",
519
- ast.defs.patterns.full_equal,
520
- { patterns: ast.defs.patterns }
521
- );
522
-
523
- assert.equal(peInfo.hash, feInfo.hash);
524
- assert.equal(peInfo.def, "{X0 a, X1 b, X2 c}");
525
- assert.deepEqual(peInfo.params, ["X0"]);
526
- assert.deepEqual(peInfo.aliasArgs, ["Z", "Y", "Y"]);
527
- assert.deepEqual(feInfo.params, ["X0", "X1"]);
528
- assert.deepEqual(feInfo.aliasArgs, ["A", "B", "B"]);
529
-
530
- // Verify that pair_equal enforces equality between b and c
531
- const fnOk = k.compile(`
532
- pair_equal[Z] = { Z a, Y b, Y c };
533
- check = ? pair_equal[{}];
534
- { {} a, {} b, {} c } check
70
+ const out = evaluate(BASE + `
71
+ tree[X] = <{} nil, {X val, list[T] children} node> = T;
72
+ is_tree = ?tree[bit[]];
73
+ leaf = {{}|1 val, {}|nil children}|node is_tree;
74
+ root = {{}|0 val, {leaf car, {}|nil cdr}|cons children}|node is_tree;
75
+ {leaf leaf, root root}
535
76
  `);
536
- assert.doesNotThrow(() => fnOk());
537
-
538
- assert.throws(
539
- () =>
540
- k.compile(`
541
- pair_equal[Z] = { Z a, Y b, Y c };
542
- check = ? pair_equal[{}];
543
- { {} a, {} b, {}|0 c } check
544
- `),
545
- /Cannot unify/
546
- );
547
- console.log(
548
- " Passed: Repeated existential variable wildcard constraints."
549
- );
77
+ assert.deepEqual([out.product.leaf.tag, out.product.leaf.value.product.val.tag,
78
+ out.product.root.tag, out.product.root.value.product.val.tag], ["node", "1", "node", "0"]);
79
+ }
80
+ assert.equal(evaluate(BASE + `
81
+ head = ?{X car, list[X] cdr} .car;
82
+ {{}|1 car, {}|nil cdr} head
83
+ `).tag, "1");
84
+
85
+ // Used and unused definitions must both be validated eagerly.
86
+ for (const [source, error] of [
87
+ ["check = ?missing[]; ()", /Unknown pattern template 'missing\[\]'/],
88
+ ["list[X] = {}; check = ?list[]; ()", /Pattern 'list' expects 1 argument, got 0/],
89
+ ["pair[A,B] = {}; check = ?pair[{}]; ()", /Pattern 'pair' expects 2 arguments, got 1/],
90
+ ["a[] = b[]; b[] = a[]; check = ?a[]; ()", /Cyclic pattern template dependency detected/],
91
+ ["dupe[X,X] = {}; ()", /Duplicate parameter 'X' in pattern 'dupe'/],
92
+ ["p[] = {missing[] x}; ()", /Unknown pattern template 'missing\[\]'/],
93
+ ["p[] = missing[]; ()", /Unknown pattern template 'missing\[\]'/],
94
+ ["a[] = b[]; b[] = a[]; ()", /Cyclic pattern template dependency detected/],
95
+ ["list[X,Y] = <{} nil,{X car,Y cdr} cons>=Y; ()", /conflicts with knot 'Y'/],
96
+ ["same_pair[] = {T first,T second}; {{} first,{}|0 second} ?same_pair[]", /Cannot unify/],
97
+ [`is_bit = ?${BIT}; ()`, /Parse error[\s\S]*Expecting 'LB'/],
98
+ [`my_bit[] = ${BIT}; ()`, /Parse error[\s\S]*Expecting 'LB'/]
99
+ ]) assert.throws(() => k.compile(source), error, source);
100
+
101
+ // Canonical applications, alias export, metadata, and library consumption.
102
+ const library = compileLibrary(BASE + "pair[A,B] = {A first,B second};", {
103
+ exports: ["bit", "list", "pair"]
104
+ });
105
+ validateObjectPayload(library);
106
+ assert.deepEqual([library.patternAlias.bit, library.patternAlias.list,
107
+ library.patternAlias.pair], [BIT, LIST, PAIR]);
108
+ for (const hash of [BIT, LIST]) assert.equal(library.meta[hash].type, "pattern");
109
+
110
+ const aliases = extractAliasesFromObject(library);
111
+ for (const expected of [/bit\[\] = @Mjusy/, /list\[X\] = @JagVex/, /pair\[A, B\] = @KqTB/]) {
112
+ assert.match(aliases, expected);
550
113
  }
114
+ const preamble = buildExportPreamble(["bit", "list:my_list"], [library]);
115
+ assert.match(preamble, /bit\[\] = @Mjusy/);
116
+ assert.match(preamble, /my_list\[X\] = @JagVex/);
551
117
 
552
- // Test 15: Diagonalized leaves share canonical linear skeleton
553
- console.log(
554
- "--> Test 15: Diagonalized leaves share canonical linear skeleton"
555
- );
556
118
  {
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
- );
119
+ const out = evaluate(`
120
+ is_bit = ?${BIT}[];
121
+ is_bit_list = ?${LIST}[${BIT}[]];
122
+ b0 = {}|0 is_bit; b1 = {}|1 is_bit;
123
+ l = {b1 car, {}|nil cdr}|cons is_bit_list;
124
+ {b0 b0, b1 b1, l l}
125
+ `, { libraries: [library] });
126
+ assert.deepEqual([out.product.b0.tag, out.product.b1.tag, out.product.l.tag], ["0", "1", "cons"]);
626
127
  }
627
-
628
- console.log("==> All Named Patterns Tests Passed Successfully!");
128
+ assert.equal(evaluate(`
129
+ my_bit[] = ${BIT}[];
130
+ my_list[T] = ${LIST}[T];
131
+ {{}|0 car, {}|nil cdr}|cons ?my_list[my_bit[]]
132
+ `, { libraries: [library] }).tag, "cons");
133
+ assert.equal(evaluate(`
134
+ is_bit = ?bit[];
135
+ is_pair = ?${PAIR}[bit[],bit[]];
136
+ is_pair_list = ?list[${PAIR}[bit[],bit[]]];
137
+ b = {}|0 is_bit;
138
+ p = {b first, {}|1 second} is_pair;
139
+ {p car, {}|nil cdr}|cons is_pair_list
140
+ `, { libraries: [library] }).tag, "cons");
141
+ assert.ok(evaluate(`
142
+ @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X,Y] = {X x,Y y,Y z};
143
+ {{} x,{} y,{} z} ?@A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[{},{}]
144
+ `));
145
+
146
+ // Each alias retains its routing, while all variations share their skeleton.
147
+ const shapes = patterns(`
148
+ a[] = {X x,Y y}; b[X] = {X x,Y y};
149
+ c[X,Y] = {X x,Y y}; d[Y,X] = {X x,Y y}; diag_p[] = {X x,X y};
150
+ pair[A,B] = {A first,B second}; same_pair[T] = {T first,T second};
151
+ closed_same_pair[] = {T first,T second}; any_pair[] = {(...) first,(...) second};
152
+ `);
153
+ for (const [name, params, aliasArgs] of [
154
+ ["a", [], ["(...)", "(...)"]], ["b", ["X0"], ["X", "(...)"]],
155
+ ["c", ["X0", "X1"], ["X", "Y"]], ["d", ["X1", "X0"], ["X", "Y"]],
156
+ ["diag_p", [], ["X", "X"]]
157
+ ]) check(shapes[name], { hash: XY, def: "{X0 x, X1 y}", params, aliasArgs });
158
+ for (const [name, params, aliasArgs] of [
159
+ ["pair", ["X0", "X1"], ["A", "B"]], ["same_pair", ["X0"], ["T", "T"]],
160
+ ["closed_same_pair", [], ["T", "T"]], ["any_pair", [], ["(...)", "(...)"]]
161
+ ]) check(shapes[name], { hash: PAIR, def: "{X0 first, X1 second}", params, aliasArgs });
162
+
163
+ const wildcards = patterns(`
164
+ c[X,Y] = {X x,Y y}; p[X] = {X x,(...) y};
165
+ q[X,Y,Z] = {X x,Y y,Z z}; t[] = {(...) x,(...) y,(...) z};
166
+ `);
167
+ assert.equal(wildcards.c.hash, wildcards.p.hash);
168
+ assert.equal(wildcards.q.hash, wildcards.t.hash);
169
+ check(wildcards.p, { def: "{X0 x, X1 y}", aliasArgs: ["X", "(...)"] });
170
+ check(wildcards.t, { def: "{X0 x, X1 y, X2 z}", aliasArgs: ["(...)", "(...)", "(...)"] });
171
+
172
+ const nested = patterns(`
173
+ pair[A,B] = {A a,B b}; flip[Y,X] = pair[X,Y];
174
+ outer[Z] = pair[pair[Z,(...)],(...)];
175
+ deep[] = pair[pair[(...),(... )],(...)];
176
+ `);
177
+ assert.equal(nested.flip.hash, nested.pair.hash);
178
+ check(nested.flip, { params: ["X1", "X0"], aliasArgs: ["X", "Y"] });
179
+ assert.equal(nested.outer.hash, nested.deep.hash);
180
+ check(nested.outer, { def: "{{X0 a, X1 b} a, X2 b}",
181
+ params: ["X0"], aliasArgs: ["Z", "(...)", "(...)"] });
182
+ check(nested.deep, { params: [], aliasArgs: ["(...)", "(...)", "(...)"] });
183
+
184
+ const repeated = patterns(`
185
+ pair_equal[Z] = {Z a,Y b,Y c}; full_equal[A,B] = {A a,B b,B c};
186
+ `);
187
+ assert.equal(repeated.pair_equal.hash, repeated.full_equal.hash);
188
+ check(repeated.pair_equal, { def: "{X0 a, X1 b, X2 c}",
189
+ params: ["X0"], aliasArgs: ["Z", "Y", "Y"] });
190
+ check(repeated.full_equal, { params: ["X0", "X1"], aliasArgs: ["A", "B", "B"] });
191
+ assert.ok(evaluate(`pair_equal[Z] = {Z a,Y b,Y c}; {{} a,{} b,{} c} ?pair_equal[{}]`));
192
+ assert.throws(() => k.compile(`
193
+ pair_equal[Z] = {Z a,Y b,Y c}; {{} a,{} b,{}|0 c} ?pair_equal[{}]
194
+ `), /Cannot unify/);
195
+
196
+ console.log("named patterns: ok");