@fraczak/k 8.4.1 → 8.5.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.
Files changed (116) hide show
  1. package/CHANGELOG.md +32 -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/llvm/src/kvm2llvm.mjs +5 -4
  27. package/backends/llvm/src/llvm.mjs +2 -1
  28. package/backends/llvm/tests/integration.sh +7 -0
  29. package/backends/llvm/tests/test-llvm.mjs +20 -0
  30. package/backends/wasm/README.md +88 -66
  31. package/backends/wasm/src/kvm2wasm.mjs +64 -18
  32. package/backends/wasm/tests/integration.sh +5 -0
  33. package/backends/wasm/tests/test-wasm.mjs +86 -2
  34. package/canonical-pattern.mjs +7 -3
  35. package/codecs/README.md +23 -261
  36. package/codecs/WIRE_FORMAT.md +132 -0
  37. package/core.k +5 -15
  38. package/named-patterns.mjs +19 -7
  39. package/objects/README.md +24 -109
  40. package/package.json +8 -3
  41. package/paper/Makefile +17 -0
  42. package/paper/k-paper.pdf +0 -0
  43. package/paper/k-paper.tex +435 -0
  44. package/parser.jison +0 -10
  45. package/parser.mjs +32 -43
  46. package/repl.mjs +74 -29
  47. package/scripts/benchmark-idempotency.mjs +3 -3
  48. package/scripts/run-tests.mjs +1 -1
  49. package/scripts/test-package.mjs +64 -0
  50. package/tests/README.md +66 -46
  51. package/tests/code-derivation/core.mjs +61 -0
  52. package/tests/helpers/cli.mjs +45 -0
  53. package/tests/integration.sh +2 -3
  54. package/tests/test-arithmetics.mjs +47 -237
  55. package/tests/test-djson-methods.mjs +71 -275
  56. package/tests/test-hash-normalization.mjs +22 -1
  57. package/tests/test-karatsuba.mjs +18 -126
  58. package/tests/test-named-patterns.mjs +174 -621
  59. package/tests/test-paper-examples.mjs +90 -0
  60. package/tests/test-poly.mjs +2 -2
  61. package/tests/test-repl-html.mjs +22 -10
  62. package/tests/test-repl.mjs +49 -41
  63. package/tests/test.mjs +27 -68
  64. package/AGENTS.md +0 -35
  65. package/CLAUDE.md +0 -64
  66. package/DOCS/BIG_PICTURE.md +0 -439
  67. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  68. package/DOCS/CANONICAL_PATTERNS.md +0 -362
  69. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  70. package/DOCS/CONVERGENCE.md +0 -123
  71. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  72. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  73. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  74. package/DOCS/Makefile +0 -99
  75. package/DOCS/NAMED_PATTERNS.md +0 -361
  76. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  77. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  78. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -134
  79. package/DOCS/book/01-introduction.md +0 -48
  80. package/DOCS/book/02-syntax-and-values.md +0 -110
  81. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  82. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  83. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  84. package/DOCS/book/06-values-in-memory.md +0 -1085
  85. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  86. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  87. package/DOCS/book/09-compiler-architecture.md +0 -160
  88. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  89. package/DOCS/book/14-canonical-serialization.md +0 -176
  90. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  91. package/DOCS/book/overview.txt +0 -68
  92. package/DOCS/book.md +0 -50
  93. package/Examples/bnat.k +0 -308
  94. package/Examples/buda.k +0 -66
  95. package/Examples/byte.k +0 -35
  96. package/Examples/code.k +0 -43
  97. package/Examples/vhdl_to_k.k +0 -67
  98. package/JOURNAL.md +0 -288
  99. package/TODO.md +0 -107
  100. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  101. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  102. package/backends/wasm/demo_ieee.mjs +0 -318
  103. package/browser/vfs-data.mjs +0 -21
  104. package/codecs/BINARY_FORMAT.md +0 -53
  105. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  106. package/codecs/pandoc.css +0 -71
  107. package/tests/code-derivation/blowup.mjs +0 -25
  108. package/tests/code-derivation/bnat.mjs +0 -11
  109. package/tests/code-derivation/dot.mjs +0 -37
  110. package/tests/code-derivation/index.mjs +0 -20
  111. package/tests/code-derivation/loop.mjs +0 -17
  112. package/tests/code-derivation/nat.mjs +0 -10
  113. package/tests/code-derivation/not-not.mjs +0 -14
  114. package/tests/code-derivation/product.mjs +0 -22
  115. package/tests/code-derivation/rlz.mjs +0 -13
  116. package/tests/test-fingerprint.mjs +0 -38
@@ -0,0 +1,90 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFileSync } from "node:fs";
3
+ import { createState, evaluateInput } from "../repl.mjs";
4
+ import k from "../index.mjs";
5
+ import { resolvePatternCanonicalInfo } from "../canonical-pattern.mjs";
6
+ import { valueToK } from "../codecs/runtime/show-value.mjs";
7
+
8
+ const source = readFileSync(new URL("../paper/k-paper.tex", import.meta.url), "utf8");
9
+ const listings = [...source.matchAll(/\\begin\{lstlisting\}(?:\[[^\]]*\])?\s*([\s\S]*?)\\end\{lstlisting\}/g)]
10
+ .map((match) => match[1]);
11
+ function listing(needle) {
12
+ const source = listings.find((source) => source.includes(needle));
13
+ assert.ok(source, `paper listing containing ${needle}`);
14
+ return source.split("\n").filter((line) => !line.trimStart().startsWith("--"))
15
+ .join("\n").trim();
16
+ }
17
+
18
+ // Section 2: combinators and constant relations.
19
+ {
20
+ const state = createState();
21
+ for (const [source, expected] of [
22
+ ["{}", "{}"], ["()", "{}"], ["<>", undefined],
23
+ ["{} |true", "{}|true"], ["{} |zero", "{}|zero"]
24
+ ]) {
25
+ const output = await evaluateInput(source, state);
26
+ if (expected === undefined) assert.ok(output.some((line) => line.includes("undefined")));
27
+ else assert.equal(valueToK(state.value), expected, source);
28
+ }
29
+ }
30
+
31
+ // Sections 4–6: published declarations, exact hashes, and routing.
32
+ const declarations = listing("-- Arity-0 leaf patterns:");
33
+ const pairs = listing("closed_same_pair[]");
34
+ {
35
+ const state = createState();
36
+ await evaluateInput(declarations, state);
37
+ const output = (await evaluateInput(":patterns", state)).join("\n");
38
+ for (const name of ["bit[]", "bits[]", "pair[A,B]", "list[X]"]) {
39
+ assert.ok(output.includes(name), name);
40
+ }
41
+
42
+ const { defs: { patterns } } = k.parse(pairs + "\n()");
43
+ for (const [name, args] of [
44
+ ["pair", ["A", "B"]], ["same_pair", ["T", "T"]],
45
+ ["closed_same_pair", ["T", "T"]], ["any_pair", ["(...)", "(...)"]]
46
+ ]) {
47
+ const info = resolvePatternCanonicalInfo(name, patterns[name], { patterns });
48
+ assert.deepEqual([info.hash, info.def, info.aliasArgs],
49
+ ["@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm",
50
+ "{X0 first, X1 second}", args], name);
51
+ }
52
+ }
53
+ {
54
+ const state = createState();
55
+ await evaluateInput(declarations, state);
56
+ await evaluateInput(pairs, state);
57
+ await evaluateInput("{({} |0) first, ({} |1) second} ?same_pair[bit[]]", state);
58
+ assert.equal(valueToK(state.value), "{{}|0 first, {}|1 second}");
59
+ await assert.rejects(() =>
60
+ evaluateInput("{({} |0) first, {} second} ?same_pair[bit[]]", state), /Type Error/);
61
+
62
+ await evaluateInput("nil = {} |nil ?list[bit[]];", state);
63
+ await evaluateInput("cons = {({} |0) car, nil cdr} |cons ?list[bit[]];", state);
64
+ await evaluateInput("cons", state);
65
+ assert.equal(valueToK(state.value), "{{}|0 car, {}|nil cdr}|cons");
66
+ }
67
+
68
+ // Section 7: execute the actual half-adder listing through Wasm.
69
+ {
70
+ const state = createState();
71
+ await evaluateInput(listing("half_add ="), state);
72
+ for (const [a, b, sum, carry] of [
73
+ [0, 0, 0, 0], [0, 1, 1, 0], [1, 0, 1, 0], [1, 1, 0, 1]
74
+ ]) {
75
+ await evaluateInput(`{${a} a, ${b} b} half_add`, state);
76
+ assert.deepEqual([state.value.product.sum.tag, state.value.product.carry.tag],
77
+ [String(sum), String(carry)], `${a} + ${b}`);
78
+ }
79
+ }
80
+
81
+ // Appendix: verify the publication's pattern schema against the real Unicode core.
82
+ {
83
+ const state = createState();
84
+ await evaluateInput(":load core.k", state);
85
+ const expected = await evaluateInput(":pattern pattern", state);
86
+ await evaluateInput(listing("edge[]"), state);
87
+ assert.deepEqual(await evaluateInput(":pattern pattern", state), expected);
88
+ }
89
+
90
+ console.log("paper examples: ok");
@@ -154,13 +154,13 @@ async function evalK(snippet) {
154
154
  } .then,
155
155
  {.xs car car, {.xs cdr xs, .ys ys} _merge cdr} cons
156
156
  >;
157
- _sort = list? <
157
+ _sort = ? list[X] <
158
158
  /nil nil,
159
159
  /cons <
160
160
  {.cdr /nil if, .car singleton then} .then,
161
161
  |cons split {.first _sort xs, .second _sort ys} _merge
162
162
  >
163
- > list?;
163
+ > ? list[X];
164
164
  l = {5 int car, {2 int car, {4 int car, {1 int car, {3 int car, nil cdr} cons cdr} cons cdr} cons cdr} cons cdr} cons;
165
165
  l _sort
166
166
  `);
@@ -1,5 +1,6 @@
1
1
  import assert from "node:assert";
2
2
  import fs from "node:fs";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { spawn, spawnSync } from "node:child_process";
5
6
  import { fileURLToPath } from "node:url";
@@ -43,32 +44,43 @@ assert(!html.includes("input-popup-modal"), "repl.html must NOT contain input po
43
44
  console.log(" repl.html is valid, self-contained, and has size:", (html.length / 1024).toFixed(1), "KB");
44
45
 
45
46
  // 3. If Chromium is available, run end-to-end browser test
46
- const chromiumBin = ["chromium-browser", "chromium", "google-chrome"].find(bin => {
47
- const res = spawnSync("which", [bin], { stdio: "ignore" });
47
+ const chromiumBin = ["google-chrome", "chromium-browser", "chromium"].find(bin => {
48
+ const res = spawnSync(bin, ["--version"], { stdio: "ignore" });
48
49
  return res.status === 0;
49
50
  });
50
51
 
51
52
  if (chromiumBin) {
52
53
  console.log(`3. Running browser verification with ${chromiumBin}...`);
53
- const tmpDir = `/tmp/chrome-test-${Date.now()}`;
54
- fs.mkdirSync(tmpDir, { recursive: true });
54
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-browser-test-"));
55
55
 
56
- const cdpPort = 9333 + Math.floor(Math.random() * 500);
57
56
  const chrome = spawn(chromiumBin, [
58
57
  "--headless=new",
59
58
  "--disable-gpu",
60
- `--remote-debugging-port=${cdpPort}`,
59
+ "--remote-debugging-port=0",
61
60
  "--no-sandbox",
62
61
  "--disable-extensions",
63
62
  `--user-data-dir=${tmpDir}`,
64
63
  `file://${replHtmlPath}`
65
- ]);
64
+ ], { stdio: ["ignore", "ignore", "pipe"] });
65
+ let launchError;
66
+ let diagnostics = "";
67
+ chrome.on("error", error => { launchError = error; });
68
+ chrome.stderr.setEncoding("utf8");
69
+ chrome.stderr.on("data", chunk => { diagnostics = (diagnostics + chunk).slice(-16384); });
66
70
 
67
71
  try {
68
72
  let wsUrl = null;
69
- for (let i = 0; i < 30; i++) {
73
+ const deadline = Date.now() + 30000;
74
+ while (Date.now() < deadline) {
75
+ if (launchError) throw launchError;
76
+ if (chrome.exitCode !== null || chrome.signalCode !== null) {
77
+ throw new Error(`Chrome exited before startup (${chrome.exitCode ?? chrome.signalCode})\n${diagnostics}`);
78
+ }
70
79
  try {
71
- const res = await fetch(`http://127.0.0.1:${cdpPort}/json/list`);
80
+ const cdpPort = fs.readFileSync(path.join(tmpDir, "DevToolsActivePort"), "utf8").split("\n")[0];
81
+ const res = await fetch(`http://127.0.0.1:${cdpPort}/json/list`, {
82
+ signal: AbortSignal.timeout(1000)
83
+ });
72
84
  const list = await res.json();
73
85
  const page = list.find(item => item.url && item.url.includes("repl.html"));
74
86
  if (page && page.webSocketDebuggerUrl) {
@@ -79,7 +91,7 @@ if (chromiumBin) {
79
91
  await new Promise(r => setTimeout(r, 200));
80
92
  }
81
93
 
82
- assert(wsUrl, `Could not connect to Chromium CDP on port ${cdpPort}`);
94
+ assert(wsUrl, `Chrome debugging connection was not ready within 30 seconds\n${diagnostics}`);
83
95
 
84
96
  const ws = new WebSocket(wsUrl);
85
97
  await new Promise(r => ws.onopen = r);
@@ -306,14 +306,20 @@ assert.equal(output[0], "loaded Examples/arithmetics.k");
306
306
  output = await evaluateInput(":pat bits", arithState);
307
307
  assert.equal(
308
308
  output[0],
309
- "bits[] = <X0 0, X0 1, {} _>=X0; -- " +
310
- "@VtPHxGf5GNMzzyVFxtv7gegFfJRYapBGtCeyV56bs5Zb"
311
- );
312
- output = await evaluateInput(":pat bits_pair", arithState);
309
+ "bits[] = <B 0, B 1, {} _>=B; -- " +
310
+ "@VtPHxGf5GNMzzyVFxtv7gegFfJRYapBGtCeyV56bs5Zb[]"
311
+ );
312
+ // output = await evaluateInput(":pat bit", arithState);
313
+ // assert.equal(
314
+ // output[0],
315
+ // "bit[] = <{} 0, {} 1>; -- " +
316
+ // "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg[]"
317
+ // );
318
+ output = await evaluateInput(":pat int[]", arithState);
313
319
  assert.equal(
314
320
  output[0],
315
- "bits_pair[] = {<X0 0, X0 1, {} _>=X0 x, X0 y}; -- " +
316
- "@R7RD2sgu6yPqpCQBBcJqkzxHQMZfEJLcNW4UKBcTiC3m"
321
+ "int[] = <bits[] +, bits[] ->; -- " +
322
+ "@Nws3vysWqC9PznraTP4kWPp44Rd77NAqrx9dgbtHAjGA[]"
317
323
  );
318
324
  output = await evaluateInput("10", arithState);
319
325
  assert.match(output[0], /^\{\}\|_\|0\|1\|0\|1/);
@@ -408,12 +414,14 @@ await evaluateInput(":codec load ./codecs/json.mjs", jsonInputState);
408
414
  output = await evaluateInput(':input json.mjs {"a":"Woj","n":123}', jsonInputState);
409
415
  assert.match(output[0], /json\.mjs: \{"a":"Woj","n":123\}/);
410
416
 
417
+ console.log("==> All REPL tests passed successfully");
411
418
  // Verify standalone codec input, one-line and interactive modes, and multi-codec printing
412
419
  const multiCodecState = createState();
413
420
  await evaluateInput(":codec load ./codecs/json.mjs", multiCodecState);
414
421
  await evaluateInput(":codec load ./codecs/utf8.mjs", multiCodecState);
415
422
  await evaluateInput(":codec load ./codecs/int.mjs", multiCodecState);
416
423
 
424
+ console.log("==> Running REPL :input command test suite");
417
425
  // 1. One-line JSON input: :input json.mjs {"hello":"world"}
418
426
  output = await evaluateInput(':input json.mjs {"hello":"world"}', multiCodecState);
419
427
  assert.match(output[0], /json\.mjs: \{"hello":"world"\}/);
@@ -462,7 +470,7 @@ assert.match(output[0], /unit\.mjs: \{\}/);
462
470
  const polyFreshState = createState();
463
471
  await assert.rejects(
464
472
  () => evaluateInput(":load Examples/poly.k", polyFreshState),
465
- /Unknown pattern template 'int\[\]'/
473
+ /Unknown pattern template/
466
474
  );
467
475
 
468
476
  // Explicitly loading arithmetics.k then poly.k succeeds
@@ -667,20 +675,20 @@ assert.equal(
667
675
  output = await evaluateInput(":pattern bit", patState);
668
676
  assert.equal(
669
677
  output[0],
670
- "bit[] = <{}=X0 0, X0 1>; -- " +
671
- "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg"
678
+ "bit[] = <{} 0, {} 1>; -- " +
679
+ "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg[]"
672
680
  );
673
681
  output = await evaluateInput(":pattern bit[]", patState);
674
682
  assert.equal(
675
683
  output[0],
676
- "bit[] = <{}=X0 0, X0 1>; -- " +
677
- "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg"
684
+ "bit[] = <{} 0, {} 1>; -- " +
685
+ "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg[]"
678
686
  );
679
687
  output = await evaluateInput(":pat bit", patState);
680
688
  assert.equal(
681
689
  output[0],
682
- "bit[] = <{}=X0 0, X0 1>; -- " +
683
- "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg"
690
+ "bit[] = <{} 0, {} 1>; -- " +
691
+ "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg[]"
684
692
  );
685
693
  output = await evaluateInput(
686
694
  ":pattern @MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg",
@@ -701,9 +709,9 @@ output = await evaluateInput(
701
709
  output = await evaluateInput(":pattern byte", patState);
702
710
  assert.equal(
703
711
  output[0],
704
- "byte[] = {<{}=X1 0, X1 1>=X0 b0, X0 b1, X0 b2, X0 b3, " +
705
- "X0 b4, X0 b5, X0 b6, X0 b7}; -- " +
706
- "@4ukq2gpiEBFa7WXxcfRm8pfdr2kgYLTTnwsmLHeMd9i5"
712
+ "byte[] = {bit[] b0, bit[] b1, bit[] b2, bit[] b3, " +
713
+ "bit[] b4, bit[] b5, bit[] b6, bit[] b7}; -- " +
714
+ "@4ukq2gpiEBFa7WXxcfRm8pfdr2kgYLTTnwsmLHeMd9i5[]"
707
715
  );
708
716
 
709
717
  await assert.rejects(
@@ -751,8 +759,8 @@ output = await evaluateInput(
751
759
  output = await evaluateInput(":pattern pair", patState);
752
760
  assert.equal(
753
761
  output[0],
754
- "pair[X0, X1] = {X0 first, X1 second}; -- " +
755
- "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm"
762
+ "pair[A, B] = {A first, B second}; -- " +
763
+ "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[A, B]"
756
764
  );
757
765
 
758
766
  output = await evaluateInput(":load Examples/list.k", patState);
@@ -765,8 +773,8 @@ assert(output[0].includes("pair[A,B] = @KqTB"));
765
773
  output = await evaluateInput(":pattern list", patState);
766
774
  assert.equal(
767
775
  output[0],
768
- "list[X1] = <{X1 car, X0 cdr} cons, {} nil>=X0; -- " +
769
- "@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe"
776
+ "list[X] = <{} nil, {X car, Y cdr} cons>=Y; -- " +
777
+ "@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[X]"
770
778
  );
771
779
 
772
780
  output = await evaluateInput("{} | nil ? list[bit[]]", patState);
@@ -788,19 +796,19 @@ output = await evaluateInput(":pattern bit", freshState);
788
796
  assert.equal(
789
797
  output[0],
790
798
  "bit[] = <{}=X0 0, X0 1>; -- " +
791
- "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg"
799
+ "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg[]"
792
800
  );
793
801
  output = await evaluateInput(":pattern pair", freshState);
794
802
  assert.equal(
795
803
  output[0],
796
- "pair[X0, X1] = {X0 first, X1 second}; -- " +
797
- "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm"
804
+ "pair[A, B] = {X0 first, X1 second}; -- " +
805
+ "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[A, B]"
798
806
  );
799
807
  output = await evaluateInput(":pattern list", freshState);
800
808
  assert.equal(
801
809
  output[0],
802
- "list[X1] = <{X1 car, X0 cdr} cons, {} nil>=X0; -- " +
803
- "@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe"
810
+ "list[X] = <{X1 car, X0 cdr} cons, {} nil>=X0; -- " +
811
+ "@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[X]"
804
812
  );
805
813
  output = await evaluateInput(
806
814
  "same_pair[T] = { T first, T second };",
@@ -809,8 +817,8 @@ output = await evaluateInput(
809
817
  output = await evaluateInput(":pattern same_pair", freshState);
810
818
  assert.equal(
811
819
  output[0],
812
- "same_pair[X0] = {X0 first, X1 second}; -- " +
813
- "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm"
820
+ "same_pair[T] = {T first, T second}; -- " +
821
+ "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T, T]"
814
822
  );
815
823
  output = await evaluateInput("{} | nil ? list[bit[]]", freshState);
816
824
  assert.match(output[0], /\{\}\|nil/);
@@ -819,8 +827,8 @@ output = await evaluateInput("a[] = x;", freshState);
819
827
  output = await evaluateInput(":pattern a", freshState);
820
828
  assert.equal(
821
829
  output[0],
822
- "a[] = X0; -- " +
823
- "@QfyLpmn56wuppuGvrrUJz8LKtgaXfbMtad7RnzBcFk2S"
830
+ "a[] = x; -- " +
831
+ "@QfyLpmn56wuppuGvrrUJz8LKtgaXfbMtad7RnzBcFk2S[(...)]"
824
832
  );
825
833
  output = await evaluateInput(
826
834
  "closed_same_pair[] = { T first, T second };",
@@ -829,8 +837,8 @@ output = await evaluateInput(
829
837
  output = await evaluateInput(":pattern closed_same_pair", freshState);
830
838
  assert.equal(
831
839
  output[0],
832
- "closed_same_pair[] = {X0 first, X1 second}; -- " +
833
- "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm"
840
+ "closed_same_pair[] = {T first, T second}; -- " +
841
+ "@KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T, T]"
834
842
  );
835
843
 
836
844
  output = await evaluateInput(
@@ -841,26 +849,26 @@ output = await evaluateInput(
841
849
  output = await evaluateInput(":pat a", freshState);
842
850
  assert.equal(
843
851
  output[0],
844
- "a[] = {X0 x, X1 y}; -- " +
845
- "@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x"
852
+ "a[] = {X x, Y y}; -- " +
853
+ "@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[(...), (...)]"
846
854
  );
847
855
  output = await evaluateInput(":pat b", freshState);
848
856
  assert.equal(
849
857
  output[0],
850
- "b[X0] = {X0 x, X1 y}; -- " +
851
- "@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x"
858
+ "b[X] = {X x, Y y}; -- " +
859
+ "@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X, (...)]"
852
860
  );
853
861
  output = await evaluateInput(":pat c", freshState);
854
862
  assert.equal(
855
863
  output[0],
856
- "c[X0, X1] = {X0 x, X1 y}; -- " +
857
- "@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x"
864
+ "c[X, Y] = {X x, Y y}; -- " +
865
+ "@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X, Y]"
858
866
  );
859
867
  output = await evaluateInput(":pat d", freshState);
860
868
  assert.equal(
861
869
  output[0],
862
- "d[X1, X0] = {X0 x, X1 y}; -- " +
863
- "@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x"
870
+ "d[Y, X] = {X x, Y y}; -- " +
871
+ "@NPSHm9HbPgXmGHVGMJGJFq7rq4LiFiavPX27mUwyE26x[X, Y]"
864
872
  );
865
873
  output = await evaluateInput(":pats", freshState);
866
874
  assert(
@@ -915,8 +923,8 @@ assert(
915
923
  output = await evaluateInput(":pat p", freshState);
916
924
  assert.equal(
917
925
  output[0],
918
- "p[X0] = {X0 x, X1 y, X2 z}; -- " +
919
- "@PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR"
926
+ "p[X] = {X x, Y y, Y z}; -- " +
927
+ "@PScsPA3xYv4kSXUqHafwVQr5Cxkmspf3bj46KAcmyxmR[X, Y, Y]"
920
928
  );
921
929
 
922
930
  output = await evaluateInput(
package/tests/test.mjs CHANGED
@@ -1,75 +1,34 @@
1
+ import assert from "node:assert/strict";
1
2
  import k from "../index.mjs";
3
+ import { valueToK } from "../codecs/runtime/show-value.mjs";
2
4
 
3
- [
4
- [{"unit": {}}, "()"],
5
- [{"name": {"ala": {}}, "age": {"twentythree": {}}}, '{.name name, .age age}'],
6
- [
7
- {
8
- "year": {"twothousandtwo": {}},
9
- "age": {"nineteen": {}},
10
- },
11
- "{.year year, .age age}",
12
- ],
13
- [{"duplicate": {}}, "()"],
14
- [{"nesting": {}}, "()"],
15
- [{"test": {"parseunit": {}}}, "()"],
16
- ].map(function ([data, script]) {
17
- console.log(`k_expression = '${script}';`);
18
- console.log(`k.run(k_expression,data});`);
19
- console.log(`// RETURNS: ${JSON.stringify(k.run(script, data))}`);
20
- return console.log("");
21
- });
5
+ for (const [data, source] of [
6
+ [{ unit: {} }, "()"],
7
+ [{ name: { ala: {} }, age: { twentythree: {} } }, "{.name name, .age age}"],
8
+ [{ year: { twothousandtwo: {} }, age: { nineteen: {} } }, "{.year year, .age age}"],
9
+ [{ test: { parseunit: {} } }, "()"]
10
+ ]) {
11
+ assert.equal(valueToK(k.run(source, data)), valueToK(k.fromObject(data)), source);
12
+ }
22
13
 
23
-
24
- let k_expression = `
25
- true = {} | true;
26
- false = {} | false;
27
-
14
+ const list = k.compile(`
15
+ true = {} |true;
16
+ false = {} |false;
28
17
  list? = ?< {} nil, {X car, Y cdr} cons > = Y;
29
18
  nil = {}|nil list?;
30
19
  nil? = list? /nil nil;
31
20
  car = list? /cons .car;
32
- list? {
33
- < nil? true, false > nil_test,
34
- < car, {}|none > car
35
- }
36
- `
37
- ;
38
-
39
- let k_fn = k.compile(k_expression);
40
-
41
- console.log(`var k_fn = k.compile('${k_expression}');`);
42
-
43
- console.log("");
44
-
45
- [
46
- {"None": {}},
47
- {"nil": {}},
48
- {
49
- "cons": {
50
- "car": {"unit": {}},
51
- "cdr": {
52
- "cons": {
53
- "car": {"unit": {}},
54
- "cdr": {"nil": {}}
55
- }
56
- }
57
- },
58
- },
59
- {
60
- "cons": {
61
- "car": {"on": {}},
62
- "cdr": {
63
- "cons": {
64
- "car": {"off": {}},
65
- "cdr": {"nil": {}}
66
-
67
- }
68
- }
69
- },
70
- },
71
- ].map(function (data) {
72
- console.log(`k_fn(${JSON.stringify(data)});`);
73
- console.log(`// RETURNS: ${JSON.stringify(k_fn(k.fromObject(data)))}`);
74
- return console.log("");
75
- });
21
+ list? { <nil? true, false> nil_test, <car, {}|none> car }
22
+ `);
23
+ for (const [data, isNil, head] of [
24
+ [{ None: {} }, "false", "none"],
25
+ [{ nil: {} }, "true", "none"],
26
+ [{ cons: { car: { unit: {} }, cdr: { cons: { car: { unit: {} }, cdr: { nil: {} } } } } }, "false", "unit"],
27
+ [{ cons: { car: { on: {} }, cdr: { cons: { car: { off: {} }, cdr: { nil: {} } } } } }, "false", "on"]
28
+ ]) {
29
+ const { product } = list(k.fromObject(data));
30
+ assert.equal(product.nil_test.tag, isNil);
31
+ assert.equal(product.car.tag, head);
32
+ }
33
+ assert.equal(k.compile("{} |ok")(k.fromObject({})).tag, "ok");
34
+ console.log("runtime API: ok");
package/AGENTS.md DELETED
@@ -1,35 +0,0 @@
1
- # Repository Guidelines
2
-
3
- ## Project Structure & Module Organization
4
- - Root `.mjs` files hold the core runtime and library entry points (e.g., `index.mjs`, `run.mjs`, `codes.mjs`, `typing.mjs`).
5
- - `k_compiler/` contains the Python prototype compiler and supporting modules.
6
- - `type_registry/` houses registry experiments and grammar artifacts.
7
- - `Examples/` and `DOCS/` provide sample programs and design notes.
8
- - Tests live in `tests/`, with type-derivation cases in `tests/code-derivation/`.
9
-
10
- ## Build, Test, and Development Commands
11
- - `npm install` installs dev dependencies and runs `prepare` to generate parsers.
12
- - `npm run prepare` regenerates `parser.mjs` and `valueParser.mjs` from `.jison` grammars.
13
- - `npm test` runs the full suite through `scripts/run-tests.mjs`.
14
- - `node repl.mjs` (or `k-repl`) starts the interactive REPL.
15
- - `./k.mjs <file.k>` executes a k source/object file on binary pattern+value stream input from stdin or a file; if the argument is not an existing file, it is treated as an inline k expression.
16
-
17
- ## Coding Style & Naming Conventions
18
- - JavaScript uses ES modules (`.mjs`) with 2-space indentation and semicolons.
19
- - Prefer `const`/`let`, small focused modules, and descriptive lower-case filenames.
20
- - Python modules in `k_compiler/` follow 4-space indentation and standard snake_case.
21
- - Grammar sources are `parser.jison` and `valueParser.jison`; generated files should not be hand-edited.
22
-
23
- ## Testing Guidelines
24
- - Add runtime tests alongside `tests/test.mjs` or new `tests/test-*.mjs` files.
25
- - Add type-derivation coverage in `tests/code-derivation/` (one case per file is typical).
26
- - Verify locally with `npm test` before opening a PR.
27
-
28
- ## Commit & Pull Request Guidelines
29
- - Commits use short, imperative, sentence-case summaries (e.g., "Improve type derivation").
30
- - PRs should include: a clear description, the commands run (`npm test` or specific subsets), and any relevant examples or docs updates.
31
- - If changes touch parsing or grammars, note whether `npm run prepare` was run.
32
-
33
- ## Configuration Notes
34
- - Requires Node.js 18+.
35
- - The REPL and CLI binaries are `k-repl` and `k` (see `package.json` for mappings).
package/CLAUDE.md DELETED
@@ -1,64 +0,0 @@
1
- # CLAUDE.md
2
-
3
- This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
-
5
- ## Project Overview
6
-
7
- k is an experimental language for describing algebraic data shapes and composing typed transformations over them. Data descriptions and transformations share one syntax; the native k-like notation is canonical, and a JSON-like notation is available as a convenience for textual values.
8
-
9
- ## Essential Commands
10
-
11
- **Build/Parser Generation:**
12
- ```bash
13
- npm run prepare # Generate parsers from Jison grammar files
14
- ```
15
-
16
- **Testing:**
17
- ```bash
18
- npm test # Run comprehensive test suite (unit tests, derivation tests, shell tests)
19
- ```
20
-
21
- **Running k programs:**
22
- ```bash
23
- ./k.mjs <file.k> # Execute k source/object file
24
- ./repl.mjs # Start interactive REPL (or: k-repl)
25
- ```
26
-
27
- ## Architecture
28
-
29
- ### Core Language Concepts
30
- - **Partial Functions**: Functions may be undefined for some inputs (e.g., `.field` projection)
31
- - **Function Composition**: `(f g h)` - sequential application
32
- - **Union/Merge**: `<f, g>` - try f first, fallback to g
33
- - **Product**: `{f label1, g label2}` - parallel application building records
34
- - **Types (Codes)**: Finite tree automata defining value sets, no built-in types
35
- - **Notation**: Prefer native k-like for products `{A l, ...}` and unions `<A t, ...>`; JSON-like `{l: A, ...}` and `<t: A, ...>` is supported for convenience
36
- - **Variant value literals**: Use single-field product notation. Unit: `{{} tag}`; with payload `v`: `{ v tag }`. Angle brackets are for types/merge, not value literals.
37
-
38
- ### Key Implementation Files
39
- - `parser.mjs` / `parser.jison` - Language parser (generated from Jison grammar)
40
- - `run.mjs` - Runtime execution engine for partial functions
41
- - `codes.mjs` - Type/code management and canonicalization
42
- - `TypePatternGraph.mjs` - Core pattern graph data structure for type derivation
43
- - `typing.mjs` - Type compression and advanced type system operations
44
- - `Value.mjs` - Value representation and operations
45
- - `index.mjs` - Main library entry point
46
-
47
- ### Multi-Stage Processing Pipeline
48
- 1. **Parsing**: Text → AST via Jison-generated parser
49
- 2. **Type Derivation**: Pattern-based type inference across expressions
50
- 3. **Canonicalization**: Types/functions get hash-based canonical names
51
- 4. **Execution**: Runtime evaluation with partial function semantics
52
-
53
- ### Type System
54
- - **Product types**: `{type1 label1, type2 label2}` with projections `.label1`
55
- - **Union types**: `<type1 label1, type2 label2>` with variant selection
56
- - **Pattern matching**: Sophisticated constraint derivation system
57
- - **Canonical names**: Hash-based universal registry for content-addressed modules
58
-
59
- ## Development Notes
60
-
61
- - No external runtime dependencies (only jiwson for parser generation)
62
- - Uses ES6 modules (.mjs files) throughout
63
- - Extensive test suite in `tests/code-derivation/` for type system validation
64
- - REPL supports commands like `:rel name` (show relation definition), `:rels`, etc.