@fraczak/k 8.4.1 → 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 (109) hide show
  1. package/CHANGELOG.md +17 -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 +155 -138
  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 -377
  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/wasm/README.md +88 -66
  27. package/canonical-pattern.mjs +7 -3
  28. package/codecs/README.md +23 -261
  29. package/codecs/WIRE_FORMAT.md +132 -0
  30. package/core.k +5 -15
  31. package/named-patterns.mjs +19 -7
  32. package/objects/README.md +24 -109
  33. package/package.json +8 -3
  34. package/paper/Makefile +17 -0
  35. package/paper/k-paper.pdf +0 -0
  36. package/paper/k-paper.tex +435 -0
  37. package/parser.jison +0 -10
  38. package/parser.mjs +32 -43
  39. package/repl.mjs +74 -29
  40. package/scripts/benchmark-idempotency.mjs +3 -3
  41. package/scripts/run-tests.mjs +1 -1
  42. package/scripts/test-package.mjs +64 -0
  43. package/tests/README.md +66 -46
  44. package/tests/code-derivation/core.mjs +61 -0
  45. package/tests/helpers/cli.mjs +45 -0
  46. package/tests/integration.sh +2 -3
  47. package/tests/test-arithmetics.mjs +47 -237
  48. package/tests/test-djson-methods.mjs +71 -275
  49. package/tests/test-hash-normalization.mjs +22 -1
  50. package/tests/test-karatsuba.mjs +18 -126
  51. package/tests/test-named-patterns.mjs +174 -621
  52. package/tests/test-paper-examples.mjs +90 -0
  53. package/tests/test-poly.mjs +2 -2
  54. package/tests/test-repl-html.mjs +2 -2
  55. package/tests/test-repl.mjs +49 -41
  56. package/tests/test.mjs +27 -68
  57. package/AGENTS.md +0 -35
  58. package/CLAUDE.md +0 -64
  59. package/DOCS/BIG_PICTURE.md +0 -439
  60. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  61. package/DOCS/CANONICAL_PATTERNS.md +0 -362
  62. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  63. package/DOCS/CONVERGENCE.md +0 -123
  64. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  65. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  66. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  67. package/DOCS/Makefile +0 -99
  68. package/DOCS/NAMED_PATTERNS.md +0 -361
  69. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  70. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  71. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -134
  72. package/DOCS/book/01-introduction.md +0 -48
  73. package/DOCS/book/02-syntax-and-values.md +0 -110
  74. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  75. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  76. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  77. package/DOCS/book/06-values-in-memory.md +0 -1085
  78. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  79. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  80. package/DOCS/book/09-compiler-architecture.md +0 -160
  81. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  82. package/DOCS/book/14-canonical-serialization.md +0 -176
  83. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  84. package/DOCS/book/overview.txt +0 -68
  85. package/DOCS/book.md +0 -50
  86. package/Examples/bnat.k +0 -308
  87. package/Examples/buda.k +0 -66
  88. package/Examples/byte.k +0 -35
  89. package/Examples/code.k +0 -43
  90. package/Examples/vhdl_to_k.k +0 -67
  91. package/JOURNAL.md +0 -288
  92. package/TODO.md +0 -107
  93. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  94. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  95. package/backends/wasm/demo_ieee.mjs +0 -318
  96. package/browser/vfs-data.mjs +0 -21
  97. package/codecs/BINARY_FORMAT.md +0 -53
  98. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  99. package/codecs/pandoc.css +0 -71
  100. package/tests/code-derivation/blowup.mjs +0 -25
  101. package/tests/code-derivation/bnat.mjs +0 -11
  102. package/tests/code-derivation/dot.mjs +0 -37
  103. package/tests/code-derivation/index.mjs +0 -20
  104. package/tests/code-derivation/loop.mjs +0 -17
  105. package/tests/code-derivation/nat.mjs +0 -10
  106. package/tests/code-derivation/not-not.mjs +0 -14
  107. package/tests/code-derivation/product.mjs +0 -22
  108. package/tests/code-derivation/rlz.mjs +0 -13
  109. package/tests/test-fingerprint.mjs +0 -38
@@ -1,643 +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.");
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 })]));
35
22
  }
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.");
23
+ function check(info, expected) {
24
+ for (const [key, value] of Object.entries(expected)) {
25
+ assert.deepEqual(info[key], value, key);
26
+ }
63
27
  }
64
28
 
65
- // Test 3: Multi-parameter templates and composition
66
- console.log("--> Test 3: Multi-parameter templates (pair, dict)");
29
+ // Runtime template applications: products, lists, dictionaries, sharing, knots.
67
30
  {
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
-
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
- );
201
- console.log(" Passed: Error conditions correctly handled.");
202
- }
203
-
204
- // Test 8: Canonical pattern references and aliasing
205
- console.log("--> Test 8: Canonical pattern references and aliasing");
206
- {
207
- const { compileLibrary } = await import("../object.mjs");
208
- const baseLib = compileLibrary(`
209
- bit[] = < {}0, {}1 >;
210
- list[X] = < {}nil, { X car, Y cdr } cons > = Y;
211
- `, { exports: ["bit", "list"] });
212
-
213
- const script1 = `
214
- -- Canonical hash application with and without arguments
215
- is_bit = ? @MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg[];
216
- is_bit2 = ? @MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg;
217
- is_bit_list = ? @JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[
218
- @MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg[]
219
- ];
220
-
221
- b0 = {}|0 is_bit;
222
- b1 = {}|1 is_bit2;
223
- l = { b1 car, {}|nil cdr }|cons is_bit_list;
224
- { b0 b0, b1 b1, l l }
225
- `;
226
- const fn1 = k.compile(script1, { libraries: [baseLib] });
227
- const out1 = fn1(Value.product({}));
228
- assert.equal(out1.product.b0.tag, "0");
229
- assert.equal(out1.product.b1.tag, "1");
230
- assert.equal(out1.product.l.tag, "cons");
231
-
232
- // Aliasing canonical patterns
233
- const script2 = `
234
- my_bit[] = @MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg[];
235
- my_bit2[] = @MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg;
236
- my_list[T] = @JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[T];
237
-
238
- is_my_list = ? my_list[my_bit[]];
239
- val = { {}|0 car, {}|nil cdr }|cons is_my_list;
240
- val
241
- `;
242
- const fn2 = k.compile(script2, { libraries: [baseLib] });
243
- const out2 = fn2(Value.product({}));
244
- assert.equal(out2.tag, "cons");
245
- console.log(" Passed: Canonical pattern references and aliasing.");
246
- }
247
-
248
- // Test 9: Library export, validation, and multi-library consumption
249
- console.log("--> Test 9: Library export and canonical pattern metadata");
250
- {
251
- const { compileLibrary, extractAliasesFromObject } =
252
- await import("../object.mjs");
253
- const { validateObjectPayload } =
254
- await import("../objects/validate.mjs");
255
- const { buildExportPreamble } =
256
- await import("../canonical-pattern.mjs");
257
-
258
- const libSource = `
259
- bit[] = < {}0, {}1 >;
260
- list[X] = < {}nil, { X car, Y cdr } cons > = Y;
261
- pair[A, B] = { A first, B second };
262
- `;
263
- const lib = compileLibrary(libSource, {
264
- exports: ["bit", "list", "pair"]
265
- });
266
-
267
- validateObjectPayload(lib);
268
-
269
- assert.equal(
270
- lib.patternAlias.bit,
271
- "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg"
272
- );
273
- assert.equal(
274
- lib.patternAlias.list,
275
- "@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe"
276
- );
277
- assert.equal(
278
- lib.patternAlias.pair,
279
- "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm"
280
- );
281
-
282
- const bitHash = "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg";
283
- const listHash = "@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe";
284
- assert.equal(lib.meta[bitHash].type, "pattern");
285
- assert.equal(lib.meta[listHash].type, "pattern");
286
-
287
- const aliases = extractAliasesFromObject(lib);
288
- assert.match(aliases, /bit\[\] = @Mjusy/);
289
- assert.match(aliases, /list\[X\] = @JagVex/);
290
- assert.match(aliases, /pair\[A, B\] = @KqTB/);
291
-
292
- const preamble = buildExportPreamble(
293
- ["bit", "list:my_list"],
294
- [lib]
295
- );
296
- assert.match(preamble, /bit\[\] = @Mjusy/);
297
- assert.match(preamble, /my_list\[X\] = @JagVex/);
298
-
299
- const consumerSource = `
300
- is_bit = ? bit[];
301
- is_pair = ? @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[
302
- bit[], bit[]
303
- ];
304
- is_pair_list = ? list[@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[
305
- bit[], bit[]
306
- ]];
307
-
308
- b = {}|0 is_bit;
309
- p = { b first, {}|1 second } is_pair;
310
- l = { p car, {}|nil cdr }|cons is_pair_list;
311
- l
312
- `;
313
- const fnConsumer = k.compile(consumerSource, {
314
- libraries: [lib]
315
- });
316
- const outConsumer = fnConsumer(Value.product({}));
317
- assert.equal(outConsumer.tag, "cons");
318
- console.log(" Passed: Library export and pattern metadata.");
319
- }
320
-
321
- // Test 10: Canonical pattern sharing & parameter aliasing
322
- console.log(
323
- "--> Test 10: Canonical pattern sharing (a[], b[X], c[X,Y], d[Y,X])"
324
- );
325
- {
326
- const { resolvePatternCanonicalInfo } =
327
- await import("../canonical-pattern.mjs");
328
- const { parse } = await import("../parser.mjs");
329
-
330
- const ast = parse(`
331
- a[] = {X x, Y y};
332
- b[X] = {X x, Y y};
333
- c[X,Y] = {X x, Y y};
334
- d[Y,X] = {X x, Y y};
335
- ()
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
336
37
  `);
337
- const aInfo = resolvePatternCanonicalInfo(
338
- "a",
339
- ast.defs.patterns.a,
340
- { patterns: ast.defs.patterns }
341
- );
342
- const bInfo = resolvePatternCanonicalInfo(
343
- "b",
344
- ast.defs.patterns.b,
345
- { patterns: ast.defs.patterns }
346
- );
347
- const cInfo = resolvePatternCanonicalInfo(
348
- "c",
349
- ast.defs.patterns.c,
350
- { patterns: ast.defs.patterns }
351
- );
352
- const dInfo = resolvePatternCanonicalInfo(
353
- "d",
354
- ast.defs.patterns.d,
355
- { patterns: ast.defs.patterns }
356
- );
357
-
358
- const sharedHash = "@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x";
359
- assert.equal(aInfo.hash, sharedHash);
360
- assert.equal(bInfo.hash, sharedHash);
361
- assert.equal(cInfo.hash, sharedHash);
362
- assert.equal(dInfo.hash, sharedHash);
363
-
364
- assert.equal(aInfo.def, "{X0 x, X1 y}");
365
- assert.equal(bInfo.def, "{X0 x, X1 y}");
366
- assert.equal(cInfo.def, "{X0 x, X1 y}");
367
- assert.equal(dInfo.def, "{X0 x, X1 y}");
368
-
369
- assert.deepEqual(aInfo.aliasArgs, ["(...)", "(...)"]);
370
- assert.deepEqual(bInfo.aliasArgs, ["X", "(...)"]);
371
- assert.deepEqual(cInfo.aliasArgs, ["X", "Y"]);
372
- assert.deepEqual(dInfo.aliasArgs, ["X", "Y"]);
373
-
374
- assert.deepEqual(aInfo.params, []);
375
- assert.deepEqual(bInfo.params, ["X0"]);
376
- assert.deepEqual(cInfo.params, ["X0", "X1"]);
377
- assert.deepEqual(dInfo.params, ["X1", "X0"]);
378
- console.log(
379
- " Passed: Canonical pattern sharing & parameter aliasing."
380
- );
38
+ assert.deepEqual([out.type, out.product.b0.tag, out.product.b1.tag], ["{}", "0", "1"]);
381
39
  }
382
-
383
- // Test 11: Knot parameter conflict rejection and canonical patterns
384
- console.log(
385
- "--> Test 11: Knot conflict rejection & direct canonical patterns"
386
- );
387
40
  {
388
- assert.throws(
389
- () =>
390
- k.compile("list[X,Y] = <{}nil,{X car, Y cdr} cons> = Y; ()"),
391
- /conflicts with knot 'Y'/
392
- );
393
-
394
- const directDefSource = `
395
- @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X, Y] = {
396
- X x, Y y, Y z
397
- };
398
- is_p = ? @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[
399
- {}, {}
400
- ];
401
- { {} x, {} y, {} z } is_p
402
- `;
403
- const fnDirect = k.compile(directDefSource);
404
- const outDirect = fnDirect(Value.product({}));
405
- assert.equal(outDirect != null, true);
406
- console.log(
407
- " Passed: Knot conflict rejection and canonical patterns."
408
- );
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"]);
409
52
  }
410
-
411
- // Test 12: Unrestricted pattern (...) unification with variable ports
412
- console.log(
413
- "--> Test 12: Wildcard (...) unification with canonical variables"
414
- );
415
53
  {
416
- const { resolvePatternCanonicalInfo } =
417
- await import("../canonical-pattern.mjs");
418
- const { parse } = await import("../parser.mjs");
419
-
420
- const ast = parse(`
421
- c[X,Y] = {X x, Y y};
422
- p[X] = {X x, (...) y};
423
- q[X,Y,Z] = {X x, Y y, Z z};
424
- t[] = {(...) x, (...) y, (...) z};
425
- ()
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
426
60
  `);
427
- const cInfo = resolvePatternCanonicalInfo(
428
- "c",
429
- ast.defs.patterns.c,
430
- { patterns: ast.defs.patterns }
431
- );
432
- const pInfo = resolvePatternCanonicalInfo(
433
- "p",
434
- ast.defs.patterns.p,
435
- { patterns: ast.defs.patterns }
436
- );
437
- const qInfo = resolvePatternCanonicalInfo(
438
- "q",
439
- ast.defs.patterns.q,
440
- { patterns: ast.defs.patterns }
441
- );
442
- const tInfo = resolvePatternCanonicalInfo(
443
- "t",
444
- ast.defs.patterns.t,
445
- { patterns: ast.defs.patterns }
446
- );
447
-
448
- assert.equal(cInfo.hash, pInfo.hash);
449
- assert.equal(qInfo.hash, tInfo.hash);
450
-
451
- assert.equal(pInfo.def, "{X0 x, X1 y}");
452
- assert.equal(tInfo.def, "{X0 x, X1 y, X2 z}");
453
-
454
- assert.deepEqual(pInfo.aliasArgs, ["X", "(...)"]);
455
- assert.deepEqual(tInfo.aliasArgs, ["(...)", "(...)", "(...)"]);
456
- console.log(
457
- " Passed: Wildcard (...) unification with canonical variables."
458
- );
61
+ assert.deepEqual([out.tag, out.value.product.car.product.key.tag,
62
+ out.value.product.car.product.val.tag], ["cons", "0", "1"]);
459
63
  }
460
-
461
- // Test 13: Nested template composition & parameter routing
462
- console.log(
463
- "--> Test 13: Nested composition & parameter routing"
464
- );
465
64
  {
466
- const { resolvePatternCanonicalInfo } =
467
- await import("../canonical-pattern.mjs");
468
- const { parse } = await import("../parser.mjs");
469
-
470
- const ast = parse(`
471
- pair[A, B] = { A a, B b };
472
- flip[Y, X] = pair[X, Y];
473
- outer[Z] = pair[pair[Z, (...)], (...)];
474
- deep[] = pair[pair[(...), (...)], (...)];
475
- ()
476
- `);
477
- const flipInfo = resolvePatternCanonicalInfo(
478
- "flip",
479
- ast.defs.patterns.flip,
480
- { patterns: ast.defs.patterns }
481
- );
482
- const pairInfo = resolvePatternCanonicalInfo(
483
- "pair",
484
- ast.defs.patterns.pair,
485
- { patterns: ast.defs.patterns }
486
- );
487
- const outerInfo = resolvePatternCanonicalInfo(
488
- "outer",
489
- ast.defs.patterns.outer,
490
- { patterns: ast.defs.patterns }
491
- );
492
- const deepInfo = resolvePatternCanonicalInfo(
493
- "deep",
494
- ast.defs.patterns.deep,
495
- { patterns: ast.defs.patterns }
496
- );
497
-
498
- assert.equal(flipInfo.hash, pairInfo.hash);
499
- assert.deepEqual(flipInfo.params, ["X1", "X0"]);
500
- assert.deepEqual(flipInfo.aliasArgs, ["X", "Y"]);
501
-
502
- assert.equal(outerInfo.hash, deepInfo.hash);
503
- assert.equal(outerInfo.def, "{{X0 a, X1 b} a, X2 b}");
504
- assert.deepEqual(outerInfo.params, ["X0"]);
505
- assert.deepEqual(outerInfo.aliasArgs, ["Z", "(...)", "(...)"]);
506
- assert.deepEqual(deepInfo.params, []);
507
- assert.deepEqual(deepInfo.aliasArgs, ["(...)", "(...)", "(...)"]);
508
- console.log(
509
- " Passed: Nested composition and parameter routing."
510
- );
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"]);
511
68
  }
512
-
513
- // Test 14: Repeated variable unification with wildcards
514
- console.log(
515
- "--> Test 14: Repeated existential variable wildcard constraints"
516
- );
517
69
  {
518
- const { resolvePatternCanonicalInfo } =
519
- await import("../canonical-pattern.mjs");
520
- const { parse } = await import("../parser.mjs");
521
-
522
- const ast = parse(`
523
- pair_equal[Z] = { Z a, Y b, Y c };
524
- full_equal[A, B] = { A a, B b, B c };
525
- ()
526
- `);
527
- const peInfo = resolvePatternCanonicalInfo(
528
- "pair_equal",
529
- ast.defs.patterns.pair_equal,
530
- { patterns: ast.defs.patterns }
531
- );
532
- const feInfo = resolvePatternCanonicalInfo(
533
- "full_equal",
534
- ast.defs.patterns.full_equal,
535
- { patterns: ast.defs.patterns }
536
- );
537
-
538
- assert.equal(peInfo.hash, feInfo.hash);
539
- assert.equal(peInfo.def, "{X0 a, X1 b, X2 c}");
540
- assert.deepEqual(peInfo.params, ["X0"]);
541
- assert.deepEqual(peInfo.aliasArgs, ["Z", "Y", "Y"]);
542
- assert.deepEqual(feInfo.params, ["X0", "X1"]);
543
- assert.deepEqual(feInfo.aliasArgs, ["A", "B", "B"]);
544
-
545
- // Verify that pair_equal enforces equality between b and c
546
- const fnOk = k.compile(`
547
- pair_equal[Z] = { Z a, Y b, Y c };
548
- check = ? pair_equal[{}];
549
- { {} 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}
550
76
  `);
551
- assert.doesNotThrow(() => fnOk());
552
-
553
- assert.throws(
554
- () =>
555
- k.compile(`
556
- pair_equal[Z] = { Z a, Y b, Y c };
557
- check = ? pair_equal[{}];
558
- { {} a, {} b, {}|0 c } check
559
- `),
560
- /Cannot unify/
561
- );
562
- console.log(
563
- " Passed: Repeated existential variable wildcard constraints."
564
- );
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);
565
113
  }
114
+ const preamble = buildExportPreamble(["bit", "list:my_list"], [library]);
115
+ assert.match(preamble, /bit\[\] = @Mjusy/);
116
+ assert.match(preamble, /my_list\[X\] = @JagVex/);
566
117
 
567
- // Test 15: Diagonalized leaves share canonical linear skeleton
568
- console.log(
569
- "--> Test 15: Diagonalized leaves share canonical linear skeleton"
570
- );
571
118
  {
572
- const { resolvePatternCanonicalInfo } =
573
- await import("../canonical-pattern.mjs");
574
- const { parse } = await import("../parser.mjs");
575
-
576
- const ast = parse(`
577
- pair[A, B] = { A first, B second };
578
- same_pair[T] = { T first, T second };
579
- closed_same_pair[] = { T first, T second };
580
- any_pair[] = { (...) first, (...) second };
581
- diag_p[] = { X x, X y };
582
- ()
583
- `);
584
- const pairInfo = resolvePatternCanonicalInfo(
585
- "pair",
586
- ast.defs.patterns.pair,
587
- { patterns: ast.defs.patterns }
588
- );
589
- const sameInfo = resolvePatternCanonicalInfo(
590
- "same_pair",
591
- ast.defs.patterns.same_pair,
592
- { patterns: ast.defs.patterns }
593
- );
594
- const closedSameInfo = resolvePatternCanonicalInfo(
595
- "closed_same_pair",
596
- ast.defs.patterns.closed_same_pair,
597
- { patterns: ast.defs.patterns }
598
- );
599
- const anyInfo = resolvePatternCanonicalInfo(
600
- "any_pair",
601
- ast.defs.patterns.any_pair,
602
- { patterns: ast.defs.patterns }
603
- );
604
- const diagPInfo = resolvePatternCanonicalInfo(
605
- "diag_p",
606
- ast.defs.patterns.diag_p,
607
- { patterns: ast.defs.patterns }
608
- );
609
-
610
- const pairHash = "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm";
611
- assert.equal(pairInfo.hash, pairHash);
612
- assert.equal(sameInfo.hash, pairHash);
613
- assert.equal(closedSameInfo.hash, pairHash);
614
- assert.equal(anyInfo.hash, pairHash);
615
-
616
- assert.equal(pairInfo.def, "{X0 first, X1 second}");
617
- assert.equal(sameInfo.def, "{X0 first, X1 second}");
618
- assert.equal(closedSameInfo.def, "{X0 first, X1 second}");
619
- assert.equal(anyInfo.def, "{X0 first, X1 second}");
620
-
621
- assert.deepEqual(pairInfo.aliasArgs, ["A", "B"]);
622
- assert.deepEqual(sameInfo.aliasArgs, ["T", "T"]);
623
- assert.deepEqual(closedSameInfo.aliasArgs, ["T", "T"]);
624
- assert.deepEqual(anyInfo.aliasArgs, ["(...)", "(...)"]);
625
-
626
- assert.deepEqual(pairInfo.params, ["X0", "X1"]);
627
- assert.deepEqual(sameInfo.params, ["X0"]);
628
- assert.deepEqual(closedSameInfo.params, []);
629
- assert.deepEqual(anyInfo.params, []);
630
-
631
- // diag_p[] shares canonical skeleton with a, b, c, d
632
- const xyHash = "@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x";
633
- assert.equal(diagPInfo.hash, xyHash);
634
- assert.equal(diagPInfo.def, "{X0 x, X1 y}");
635
- assert.deepEqual(diagPInfo.params, []);
636
- assert.deepEqual(diagPInfo.aliasArgs, ["X", "X"]);
637
-
638
- console.log(
639
- " Passed: Diagonalized leaves share canonical linear skeleton."
640
- );
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"]);
641
127
  }
642
-
643
- 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");