@fraczak/k 8.7.1 → 8.8.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 (65) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/DOCS/CODECS.md +42 -40
  3. package/DOCS/FILE_FORMATS.md +28 -25
  4. package/DOCS/GETTING_STARTED.md +10 -15
  5. package/DOCS/PATTERNS.md +3 -3
  6. package/DOCS/REPL.md +3 -6
  7. package/Examples/ieee-arithmetics.k +14 -29
  8. package/Examples/poly.k +18 -29
  9. package/README.md +14 -18
  10. package/backend-api.mjs +1 -3
  11. package/backends/llvm/src/cli.mjs +1 -2
  12. package/backends/llvm/tests/integration.sh +2 -6
  13. package/backends/wasm/tests/integration.sh +5 -10
  14. package/browser/shims/fs.mjs +2 -6
  15. package/canonical-pattern.mjs +9 -29
  16. package/compiler.mjs +22 -12
  17. package/harness/suites/poly.mjs +9 -11
  18. package/index.mjs +119 -50
  19. package/lib/djson.k +981 -295
  20. package/lib/generic.k +701 -0
  21. package/lib/ieee.k +662 -638
  22. package/lib/integer.k +542 -0
  23. package/object.mjs +19 -12
  24. package/objects/README.md +6 -6
  25. package/package.json +1 -1
  26. package/scripts/benchmark-idempotency.mjs +16 -17
  27. package/scripts/benchmark.mjs +39 -29
  28. package/scripts/build-repl-html.mjs +45 -35
  29. package/scripts/perf-ieee.mjs +1 -5
  30. package/scripts/perf-int.mjs +12 -27
  31. package/scripts/perf-multiplication.mjs +8 -9
  32. package/scripts/perf-poly.mjs +7 -10
  33. package/scripts/render-benchmark.mjs +1 -1
  34. package/scripts/run-tests.mjs +4 -2
  35. package/scripts/test-package.mjs +4 -10
  36. package/tests/README.md +4 -5
  37. package/tests/helpers/cli.mjs +30 -7
  38. package/tests/integration.sh +5 -10
  39. package/tests/test-arithmetics.mjs +23 -16
  40. package/tests/test-djson-methods.mjs +17 -25
  41. package/tests/test-djson.mjs +273 -0
  42. package/tests/test-generic.mjs +239 -0
  43. package/tests/test-ieee-arithmetic.mjs +1 -5
  44. package/tests/test-ieee.mjs +153 -0
  45. package/tests/test-integer.mjs +264 -0
  46. package/tests/test-k-object.mjs +12 -18
  47. package/tests/test-kvm-polymorphic.mjs +6 -7
  48. package/tests/test-lib.mjs +62 -52
  49. package/tests/test-library-isolation.mjs +349 -26
  50. package/tests/test-parse-json.mjs +15 -24
  51. package/tests/test-poly.mjs +21 -16
  52. package/tests/test-repl-html.mjs +39 -44
  53. package/tests/test-repl.mjs +46 -59
  54. package/DOCS/book-combined.md +0 -3786
  55. package/DOCS/dependency-graph.md +0 -144
  56. package/Examples/arithmetics.k +0 -108
  57. package/Examples/esc.k +0 -9
  58. package/lib/arithmetics.k +0 -286
  59. package/lib/bit.k +0 -68
  60. package/lib/bits.k +0 -227
  61. package/lib/btrie.k +0 -187
  62. package/lib/list.k +0 -49
  63. package/lib/string.k +0 -588
  64. package/tests/test-ieee-text.mjs +0 -74
  65. package/tests/test-karatsuba.mjs +0 -25
@@ -1,15 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { spawnSync } from "node:child_process";
4
- import { mkdtempSync, rmSync, statSync } from "node:fs";
4
+ import { readFileSync, mkdtempSync, rmSync, statSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join, resolve } from "node:path";
7
7
  import { performance } from "node:perf_hooks";
8
+ import { useSpecsFor } from "../tests/helpers/cli.mjs";
8
9
 
9
10
  const DEFAULT_EXAMPLES = [
10
11
  "Examples/nat.k",
11
- "lib/list.k",
12
- "lib/arithmetics.k",
12
+ "lib/generic.k",
13
+ "lib/integer.k",
13
14
  "lib/ieee.k",
14
15
  "Examples/ieee-arithmetics.k"
15
16
  ];
@@ -24,8 +25,8 @@ for K source files through the .klib object format.
24
25
  Arguments:
25
26
  example.k ...
26
27
  One or more .k source files to benchmark.
27
- (default: Examples/nat.k lib/list.k
28
- lib/arithmetics.k lib/ieee.k
28
+ (default: Examples/nat.k lib/generic.k
29
+ lib/integer.k lib/ieee.k
29
30
  Examples/ieee-arithmetics.k)
30
31
 
31
32
  Options:
@@ -84,25 +85,23 @@ for (const example of benchmarkExamples) {
84
85
  const out = mkdtempSync(join(tmpdir(), `k-idempotency-bench-${example.replaceAll("/", "_")}-`));
85
86
  try {
86
87
  const depsByTarget = new Map([
87
- [resolve("lib/bits.k"), ["lib/bit.k"]],
88
- [resolve("lib/arithmetics.k"), ["lib/bit.k", "lib/bits.k"]],
89
- [resolve("Examples/arithmetics.k"), ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"]],
90
- [resolve("lib/list.k"), ["lib/bit.k", "lib/bits.k"]],
91
- [resolve("Examples/poly.k"), ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k", "lib/list.k"]],
92
- [resolve("lib/btrie.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k"]],
93
- [resolve("lib/string.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k"]],
94
- [resolve("lib/ieee.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k"]],
95
- [resolve("lib/djson.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k", "lib/ieee.k"]],
96
- [resolve("Examples/ieee-arithmetics.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k", "lib/ieee.k"]]
88
+ [resolve("lib/generic.k"), ["core.k"]],
89
+ [resolve("lib/integer.k"), []],
90
+ [resolve("Examples/poly.k"), ["lib/integer.k"]],
91
+ [resolve("lib/ieee.k"), ["core.k"]],
92
+ [resolve("lib/djson.k"), ["core.k", "lib/generic.k", "lib/ieee.k"]],
93
+ [resolve("Examples/ieee-arithmetics.k"), ["core.k", "lib/ieee.k"]]
97
94
  ]);
95
+ const useArgsFor = (filePath) =>
96
+ useSpecsFor(filePath).flatMap((u) => ["--use", u]);
98
97
  const deps = depsByTarget.get(resolve(example)) || [];
99
98
  let dependency;
100
99
  for (const [idx, dep] of deps.entries()) {
101
100
  const nextDep = join(out, `dep-${idx}.klib`);
102
- run(["objects/compile.mjs", ...(dependency ? ["--lib", dependency] : []), dep, nextDep]);
101
+ run(["objects/compile.mjs", ...(dependency ? ["--lib", dependency, ...useArgsFor(dep)] : []), dep, nextDep]);
103
102
  dependency = nextDep;
104
103
  }
105
- const library = dependency ? ["--lib", dependency] : [];
104
+ const library = dependency ? ["--lib", dependency, ...useArgsFor(example)] : [];
106
105
  const t0 = performance.now();
107
106
  run(["objects/compile.mjs", ...library, example, join(out, "1.klib")]);
108
107
  run(["objects/decompile.mjs", join(out, "1.klib"), join(out, "1.k")]);
@@ -64,7 +64,7 @@ const cases = [
64
64
  { name: "ieee.mul", suite: "ieee", rel: "mul", input: { x: "-2", y: "4" } },
65
65
  { name: "ieee.div", suite: "ieee", rel: "div", input: { x: "1", y: "2" } },
66
66
  { name: "int.times.220d", suite: "arithmetics", rel: "times", input: { shape: "int-pair", x: bigA, y: bigB } },
67
- { name: "int.gcd.90d", suite: "arithmetics", rel: "gcd", input: { shape: "bits-pair", x: gcdA, y: gcdB } },
67
+ { name: "int.gcd.90d", suite: "arithmetics", rel: "gcd", input: { shape: "int-pair", x: gcdA, y: gcdB } },
68
68
  { name: "int.factorial.101", suite: "arithmetics", rel: "factorial", input: { shape: "int", x: "101" } },
69
69
  { name: "int.factorial.242", suite: "arithmetics", rel: "factorial", input: { shape: "int", x: "242" } },
70
70
  { name: "int.factorial.1174", suite: "arithmetics", rel: "factorial", input: { shape: "int", x: "1174" } }
@@ -150,41 +150,48 @@ function sha256() {
150
150
  return crypto.createHash("sha256");
151
151
  }
152
152
 
153
+ const ARITHMETIC_FACTORIAL_SOURCE = `
154
+ _factorial = ?{ int[] n, int[] acc } <
155
+ { .n zero? _n, .acc acc } .acc,
156
+ { .n pos? dec n, { .n x, .acc y } times acc } _factorial
157
+ > ?int[];
158
+ factorial = ?int[] { () n, 1 acc } _factorial ?int[];
159
+ `;
160
+
153
161
  function suiteSourcePath(suite) {
154
162
  return path.join(kRoot, sourceNameForSuite(suite));
155
163
  }
156
164
 
157
165
  function sourceNameForSuite(suite) {
158
- return suite === "ieee" ? "Examples/ieee-arithmetics.k" : "Examples/arithmetics.k";
166
+ return suite === "ieee" ? "Examples/ieee-arithmetics.k" : "lib/integer.k";
159
167
  }
160
168
 
161
169
  let ieeeDependencies;
162
- let arithDependencies;
170
+ const EXPLICIT_USES = {
171
+ "lib/ieee.k": ["bit[] bits[]"]
172
+ };
173
+ function compileDepChain(files) {
174
+ let prev = null;
175
+ for (const f of files) {
176
+ const src = fs.readFileSync(path.join(kRoot, f), "utf8");
177
+ const use = EXPLICIT_USES[f] || [];
178
+ prev = loadLibrary(compileLibrary(src, {
179
+ source: f,
180
+ libraries: prev ? [prev] : [],
181
+ use
182
+ }));
183
+ }
184
+ return [prev];
185
+ }
186
+
163
187
  function dependenciesForSuite(suite) {
164
188
  if (suite === "ieee") {
165
189
  if (!ieeeDependencies) {
166
- let prev = null;
167
- for (const f of ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k", "lib/ieee.k"]) {
168
- prev = loadLibrary(compileLibrary(fs.readFileSync(path.join(kRoot, f), "utf8"), {
169
- source: f,
170
- libraries: prev ? [prev] : []
171
- }));
172
- }
173
- ieeeDependencies = [prev];
190
+ ieeeDependencies = compileDepChain(["core.k", "lib/ieee.k"]);
174
191
  }
175
192
  return ieeeDependencies;
176
193
  }
177
- if (!arithDependencies) {
178
- let prev = null;
179
- for (const f of ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"]) {
180
- prev = loadLibrary(compileLibrary(fs.readFileSync(path.join(kRoot, f), "utf8"), {
181
- source: f,
182
- libraries: prev ? [prev] : []
183
- }));
184
- }
185
- arithDependencies = [prev];
186
- }
187
- return arithDependencies;
194
+ return [];
188
195
  }
189
196
 
190
197
  function stripTrailingUnitMain(source) {
@@ -194,7 +201,8 @@ function stripTrailingUnitMain(source) {
194
201
  function sourceForCase(testCase) {
195
202
  const sourcePath = suiteSourcePath(testCase.suite);
196
203
  const source = stripTrailingUnitMain(fs.readFileSync(sourcePath, "utf8"));
197
- return `${source}\n${testCase.rel}\n`;
204
+ const extra = testCase.rel === "factorial" ? ARITHMETIC_FACTORIAL_SOURCE : "";
205
+ return `${source}${extra}\n${testCase.rel}\n`;
198
206
  }
199
207
 
200
208
  function relationPattern(relDef, index) {
@@ -489,13 +497,15 @@ async function prepareBackendRunner(job, relation, inputVal, state) {
489
497
 
490
498
  async function prepareState(suite) {
491
499
  const state = createState();
492
- const deps = suite === "ieee"
493
- ? ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k", "lib/ieee.k"]
494
- : ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"];
495
- for (const dep of deps) {
496
- await evaluateInput(`:load ${path.join(kRoot, dep)}`, state);
500
+ if (suite === "ieee") {
501
+ for (const dep of ["core.k", "lib/ieee.k"]) {
502
+ await evaluateInput(`:load ${path.join(kRoot, dep)}`, state);
503
+ }
504
+ await evaluateInput(`:load ${suiteSourcePath(suite)}`, state);
505
+ return state;
497
506
  }
498
- await evaluateInput(`:load ${suiteSourcePath(suite)}`, state);
507
+ await evaluateInput(`:load ${path.join(kRoot, "lib/integer.k")}`, state);
508
+ await evaluateInput(ARITHMETIC_FACTORIAL_SOURCE, state);
499
509
  return state;
500
510
  }
501
511
 
@@ -14,7 +14,7 @@ function printHelp() {
14
14
  console.log(`Usage: node scripts/build-repl-html.mjs [options]
15
15
 
16
16
  Builds the standalone, self-contained K web REPL (repl.html).
17
- Bundles browser shims, virtual file system (core.k, Examples, Wasm),
17
+ Bundles browser shims, virtual file system (core.k, lib, Examples, Wasm),
18
18
  and UI components into a single zero-dependency HTML file.
19
19
 
20
20
  Options:
@@ -80,12 +80,8 @@ if (fs.existsSync(coreKPath)) {
80
80
 
81
81
  // Add verified lib/ k-code files
82
82
  const verifiedLibs = [
83
- "bit.k",
84
- "bits.k",
85
- "arithmetics.k",
86
- "list.k",
87
- "btrie.k",
88
- "string.k",
83
+ "generic.k",
84
+ "integer.k",
89
85
  "ieee.k",
90
86
  "djson.k"
91
87
  ];
@@ -101,9 +97,9 @@ for (const filename of verifiedLibs) {
101
97
 
102
98
  // Add verified Examples/ k-code files
103
99
  const verifiedExamples = [
104
- "arithmetics.k",
105
- "ieee-arithmetics.k",
106
- "poly.k"
100
+ "nat.k",
101
+ "poly.k",
102
+ "ieee-arithmetics.k"
107
103
  ];
108
104
  const examplesDir = path.join(projectRoot, "Examples");
109
105
  for (const filename of verifiedExamples) {
@@ -1709,28 +1705,24 @@ const htmlContent = `<!DOCTYPE html>
1709
1705
  <select id="example-select" title="Choose an example or expression">
1710
1706
  <option value="">-- Example / Expression --</option>
1711
1707
  <optgroup label="Standard Libraries (lib/)">
1712
- <option value="lib/bit.k">lib/bit.k</option>
1713
- <option value="lib/bits.k">lib/bits.k</option>
1714
- <option value="lib/arithmetics.k">lib/arithmetics.k</option>
1715
- <option value="lib/list.k">lib/list.k</option>
1716
- <option value="lib/btrie.k">lib/btrie.k</option>
1717
- <option value="lib/string.k">lib/string.k</option>
1708
+ <option value="core.k">core.k</option>
1709
+ <option value="lib/generic.k">lib/generic.k</option>
1710
+ <option value="lib/integer.k">lib/integer.k</option>
1718
1711
  <option value="lib/ieee.k">lib/ieee.k</option>
1719
1712
  <option value="lib/djson.k">lib/djson.k</option>
1720
1713
  </optgroup>
1721
1714
  <optgroup label="Examples">
1722
- <option value="core.k">core.k</option>
1723
1715
  <option value="Examples/nat.k">Examples/nat.k</option>
1724
- <option value="Examples/arithmetics.k">Examples/arithmetics.k</option>
1725
1716
  <option value="Examples/poly.k">Examples/poly.k</option>
1726
1717
  <option value="Examples/ieee-arithmetics.k">Examples/ieee-arithmetics.k</option>
1727
1718
  </optgroup>
1728
1719
  <optgroup label="Quick Expressions">
1729
1720
  <option value="expr:{} | ok">{} | ok</option>
1730
1721
  <option value="expr:not = &lt; / true | false, / false | true &gt;; {} | true not">not (boolean relation)</option>
1731
- <option value="expr:1 succ">1 succ</option>
1732
- <option value="expr:{10 int x, 5 int y} plus">{10 int x, 5 int y} plus (int)</option>
1733
- <option value="expr:{10 int x, 5 int y} karatsuba">{10 int x, 5 int y} karatsuba</option>
1722
+ <option value="expr:0 succ">0 succ (nat)</option>
1723
+ <option value="expr:1 inc">1 inc (int)</option>
1724
+ <option value="expr:{{}|_|0|1|0|1 nat x, {}|_|1|0|1 nat y} plus">{10 x, 5 y} plus (int)</option>
1725
+ <option value="expr:{{}|_|0|1|0|1 nat x, {}|_|1|0|1 nat y} times">{10 x, 5 y} times (Karatsuba)</option>
1734
1726
  <option value="expr::rels">:rels (list relations)</option>
1735
1727
  <option value="expr::engine">:engine (show engine)</option>
1736
1728
  <option value="expr::engine wasm">:engine wasm</option>
@@ -1880,7 +1872,7 @@ const htmlContent = `<!DOCTYPE html>
1880
1872
  <tbody>
1881
1873
  <tr>
1882
1874
  <td><code>name = relExpr;</code></td>
1883
- <td><b>Relation Alias:</b> Defines a local alias for a relation expression.<br><i>e.g.</i> <code>swap = { . y x, . x y };</code></td>
1875
+ <td><b>Relation Alias:</b> Defines a local alias for a relation expression.<br><i>e.g.</i> <code>swap = { .y x, .x y };</code></td>
1884
1876
  </tr>
1885
1877
  <tr>
1886
1878
  <td><code>name[P1, ..., Pn] = filter;</code></td>
@@ -1889,7 +1881,7 @@ const htmlContent = `<!DOCTYPE html>
1889
1881
  pattern template.<br>
1890
1882
  <i>e.g.</i><br>
1891
1883
  <code>bit[] = &lt; {} 0, {} 1 &gt;;</code> or<br>
1892
- <code>list[X] = &lt; {} nil, ... &gt; = Y;</code>
1884
+ <code>list[X] = &lt; {} nil, { X car, Y cdr } cons &gt; = Y;</code>
1893
1885
  </td>
1894
1886
  </tr>
1895
1887
  </tbody>
@@ -1948,8 +1940,8 @@ const htmlContent = `<!DOCTYPE html>
1948
1940
  <div class="help-section">
1949
1941
  <h4>REPL Commands</h4>
1950
1942
  <table class="help-table">
1951
- <tr><td><code>:engine [wasm|pkir|js]</code></td><td>Display or switch evaluation engine (<code>wasm</code>, <code>pkir</code>, or <code>js</code>)</td></tr>
1952
- <tr><td><code>:load &lt;file&gt;</code></td><td>Load a <code>.k</code> source or <code>.klib</code> library into current state</td></tr>
1943
+ <tr><td><code>:engine [wasm|pkir|js]</code></td><td>Display or switch evaluation engine (<code>wasm</code>, <code>pkir</code>, or <code>js</code>; shortcuts: <code>:wasm</code>, <code>:pkir</code>, <code>:js</code>)</td></tr>
1944
+ <tr><td><code>:load [--no-alias] &lt;file&gt;</code></td><td>Load a <code>.k</code> source or <code>.klib</code> library into current state (use <code>--no-alias</code> to import by hash only)</td></tr>
1953
1945
  <tr>
1954
1946
  <td><code>:pattern &lt;name&gt;</code></td>
1955
1947
  <td>
@@ -1975,23 +1967,41 @@ const htmlContent = `<!DOCTYPE html>
1975
1967
  <tr><td><code>:rels</code></td><td>List all relation aliases</td></tr>
1976
1968
  <tr><td><code>:limit [num|none]</code></td><td>Display or set maximum characters for value output</td></tr>
1977
1969
  <tr><td><code>:max-pat-length [num|none]</code></td><td>Display or set max inline pattern length in <code>:rel</code> (default <code>45</code>, alias <code>:maxPatLength</code>)</td></tr>
1978
- <tr><td><code>:codecs</code></td><td>List all loaded format codecs</td></tr>
1979
- <tr><td><code>:codec load &lt;file.mjs&gt;</code></td><td>Load a codec from file (or load through Files)</td></tr>
1970
+ <tr><td><code>:codecs</code></td><td>List all loaded format codecs (alias <code>:codec list</code>)</td></tr>
1971
+ <tr><td><code>:codec load &lt;file.mjs&gt;</code></td><td>Load a codec from VFS (or via <b>Files</b>)</td></tr>
1980
1972
  <tr><td><code>:codec unload &lt;file.mjs&gt;</code></td><td>Unload a loaded codec</td></tr>
1981
1973
  <tr><td><code>:input &lt;codec.mjs&gt; [text]</code></td><td>Parse input using specified codec (opens dialog if text omitted)</td></tr>
1982
1974
  <tr><td><code>:klib &lt;file&gt;</code></td><td>Export current state as a <code>.klib</code> binary file</td></tr>
1975
+ <tr><td><code>:ko &lt;file&gt; &lt;expr&gt;</code></td><td>Export executable <code>.ko</code> object using <code>&lt;expr&gt;</code> as main</td></tr>
1983
1976
  <tr><td><code>:reset</code></td><td>Clear state and reset to initial environment</td></tr>
1984
1977
  <tr><td><code>:help</code></td><td>Show command reference</td></tr>
1985
1978
  </table>
1986
1979
  </div>
1987
1980
 
1981
+ <div class="help-section">
1982
+ <h4>Libraries &amp; Examples (VFS)</h4>
1983
+ <p style="margin-bottom: 8px; color: var(--text-muted); line-height: 1.45;">
1984
+ Libraries and examples are bundled in the Virtual File System and can be loaded with <code>:load &lt;file&gt;</code> or from the toolbar. Leading <code># --lib ...</code> lines are ordinary comments; load prerequisites in dependency order before dependents.
1985
+ </p>
1986
+ <table class="help-table">
1987
+ <tr><td><code>core.k</code></td><td>Standalone bit, Unicode string, and self-hosted pattern schemas (<code>bit[]</code>, <code>bits[]</code>, <code>list[X]</code>, <code>string[]</code>, <code>pattern[]</code>)</td></tr>
1988
+ <tr><td><code>lib/generic.k</code></td><td>Algebraic types, binary tries, and string/bit codecs (<code>bool[]</code>, <code>order[]</code>, <code>opt[V]</code>, <code>btrie[V]</code>); load <code>core.k</code> first</td></tr>
1989
+ <tr><td><code>lib/integer.k</code></td><td>Self-contained signed arbitrary-precision integers (<code>int[]</code>, <code>plus</code>, <code>minus</code>, Karatsuba <code>times</code>, <code>divmod</code>, <code>div</code>, <code>mod</code>, <code>gcd</code>, <code>lcm</code>)</td></tr>
1990
+ <tr><td><code>lib/ieee.k</code></td><td>Binary64 float types, predicates, negation, and conversions (<code>float64[]</code>); load <code>core.k</code> first</td></tr>
1991
+ <tr><td><code>lib/djson.k</code></td><td>RFC 8259 JSON parser (<code>parse_json</code>) and <code>djson[]</code> operations; load <code>core.k</code>, <code>lib/generic.k</code>, <code>lib/ieee.k</code> first</td></tr>
1992
+ <tr><td><code>Examples/nat.k</code></td><td>Small Peano natural-number arithmetic example (<code>nat[]</code>, <code>add</code>, <code>mult</code>)</td></tr>
1993
+ <tr><td><code>Examples/poly.k</code></td><td>Polymorphic list operations indexed by <code>int[]</code>; load <code>lib/integer.k</code> first</td></tr>
1994
+ <tr><td><code>Examples/ieee-arithmetics.k</code></td><td>Binary64 arithmetic returning <code>{result, flags}</code>; load <code>core.k</code> and <code>lib/ieee.k</code> first</td></tr>
1995
+ </table>
1996
+ </div>
1997
+
1988
1998
  <div class="help-section">
1989
1999
  <h4>Expressions &amp; Snippets</h4>
1990
- <p style="margin-bottom: 8px; color: var(--text-muted);">Any raw K expression entered at the prompt is compiled and evaluated on top of the current state using WebAssembly.</p>
2000
+ <p style="margin-bottom: 8px; color: var(--text-muted);">Any raw k expression entered at the prompt is compiled and evaluated on top of the current state (default engine: WebAssembly; switch via <code>:engine</code>). A line ending with <code>;</code> closes a definition block; end a line with <code>\</code> to continue.</p>
1991
2001
  <ul>
1992
- <li><code>{} | ok</code> &mdash; Constant relation producing variant <code>ok</code> with empty document payload <code>{}</code></li>
1993
- <li><code>not = &lt; / true | false, / false | true &gt;;</code> &mdash; Polymorphic negation via branch projections and ordered choice</li>
1994
- <li><code>{} | true not</code> &mdash; Compose constant relation <code>{} | true</code> with <code>not</code> (evaluates to <code>{} | false</code>)</li>
2002
+ <li><code>{} |ok</code> &mdash; Constant relation producing variant <code>ok</code> with empty document payload <code>{}</code></li>
2003
+ <li><code>not = &lt; /true |false, /false |true &gt;;</code> &mdash; Polymorphic negation via branch projections and ordered choice</li>
2004
+ <li><code>{} |true not</code> &mdash; Compose constant relation <code>{} |true</code> with <code>not</code> (evaluates to <code>{} |false</code>)</li>
1995
2005
  <li><code>bool? = ?&lt; {} true, {} false &gt;;</code> &mdash; Define a boolean pattern filter relation</li>
1996
2006
  <li>
1997
2007
  <code>bit[] = &lt; {} 0, {} 1 &gt;;</code>
@@ -1999,11 +2009,11 @@ const htmlContent = `<!DOCTYPE html>
1999
2009
  </li>
2000
2010
  <li>
2001
2011
  <code>? list[bool[]]</code>
2002
- &mdash; Instantiated pattern filter matching booleans
2012
+ &mdash; Instantiated pattern filter matching a list of booleans (requires <code>list[X]</code> and <code>bool[]</code> in scope)
2003
2013
  </li>
2004
- <li><code>not = bool? ?X &lt; / true | false, {} | true &gt; ?X;</code> &mdash; Filtered boolean negation: guarded by <code>bool?</code>, defaulting to <code>{} | true</code></li>
2005
- <li><code>swap = { . y x, . x y };</code> &mdash; Define a product field-swapping relation</li>
2006
- <li><code>{ {} | ok x, {} | nil y } swap</code> &mdash; Construct a product and pass it through <code>swap</code></li>
2014
+ <li><code>not = bool? ?X &lt; /true |false, {} |true &gt; ?X;</code> &mdash; Filtered boolean negation: guarded by <code>bool?</code>, defaulting to <code>{} |true</code></li>
2015
+ <li><code>swap = { .y x, .x y };</code> &mdash; Define a product field-swapping relation</li>
2016
+ <li><code>{ {} |ok x, {} |nil y } swap</code> &mdash; Construct a product and pass it through <code>swap</code></li>
2007
2017
  </ul>
2008
2018
  </div>
2009
2019
 
@@ -224,11 +224,7 @@ function pkirLaneName() {
224
224
  console.log("==> Initializing IEEE types and arithmetic");
225
225
  const state = createState();
226
226
  for (const name of [
227
- "lib/bit.k",
228
- "lib/bits.k",
229
- "lib/list.k",
230
- "lib/btrie.k",
231
- "lib/string.k",
227
+ "core.k",
232
228
  "lib/ieee.k",
233
229
  "Examples/ieee-arithmetics.k"
234
230
  ]) {
@@ -57,7 +57,7 @@ function printHelp() {
57
57
  console.log(`Usage: node scripts/perf-int.mjs [options]
58
58
 
59
59
  Big Integer Arithmetic Performance Benchmark Harness.
60
- Benchmarks plus, minus, times, and squaring scale on arithmetics.k
60
+ Benchmarks plus, minus, times, and squaring scale on lib/integer.k
61
61
  across Native JS, kVM interpreter, LLVM, Wasm, and PKIR backends.
62
62
 
63
63
  Options:
@@ -202,9 +202,9 @@ function pkirLaneName() {
202
202
  return "PKIR (Wasm persistent)";
203
203
  }
204
204
 
205
- console.log("==> Initializing state and loading @fraczak/k/lib/arithmetics.k");
205
+ console.log("==> Initializing state and loading @fraczak/k/lib/integer.k");
206
206
  const state = createState();
207
- for (const relPath of ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"]) {
207
+ for (const relPath of ["core.k", "lib/integer.k"]) {
208
208
  await evaluateInput(`:load ${fileURLToPath(import.meta.resolve(`@fraczak/k/${relPath}`))}`, state);
209
209
  }
210
210
 
@@ -221,7 +221,7 @@ const relations = {};
221
221
  for (const op of ops) {
222
222
  const name = benchNames[op];
223
223
  relations[op] = prepareRelation(state, name, {
224
- sourceLabel: `@fraczak/k/lib/arithmetics.k#${name}`
224
+ sourceLabel: `@fraczak/k/lib/integer.k#${name}`
225
225
  });
226
226
  }
227
227
  codes.load(state.codes);
@@ -263,7 +263,7 @@ if (runLLVM) {
263
263
  inputPattern: tc.inputPattern,
264
264
  cacheDir,
265
265
  sourceLabel:
266
- `@fraczak/k/Examples/arithmetics.k#${relation.relationName}`,
266
+ `@fraczak/k/lib/integer.k#${relation.relationName}`,
267
267
  usePKIR: false
268
268
  });
269
269
  }
@@ -283,7 +283,7 @@ if (runLLVMPKIR) {
283
283
  inputPattern: tc.inputPattern,
284
284
  cacheDir,
285
285
  sourceLabel:
286
- `@fraczak/k/Examples/arithmetics.k#${relation.relationName}`,
286
+ `@fraczak/k/lib/integer.k#${relation.relationName}`,
287
287
  usePKIR: true
288
288
  });
289
289
  }
@@ -444,7 +444,7 @@ function printBenchmarkDescription() {
444
444
  if (runPKIR) lanes.push(pkirLaneName());
445
445
 
446
446
  console.log("==> Benchmark description");
447
- console.log(" source: @fraczak/k/Examples/arithmetics.k");
447
+ console.log(" source: @fraczak/k/lib/integer.k");
448
448
  console.log(` benchmark relations: ${Object.values(benchNames).join(", ")}`);
449
449
  console.log(` operations: ${ops.join(", ")}`);
450
450
  console.log(` decimal inputs: ${inputTexts.join(", ")}`);
@@ -732,7 +732,7 @@ if (runPKIR && testSuite.some(tc => tc.pkirConformance !== "ok")) process.exitCo
732
732
 
733
733
  // =======================================================================
734
734
  // Squaring Scale & Memory Profiling Benchmark
735
- // Expressions: s = {()x,()y}times; and s = {()x,()y}karatsuba;
735
+ // Expression: s = {()x,()y}times;
736
736
  // =======================================================================
737
737
 
738
738
  function countBitsValue(val) {
@@ -772,13 +772,7 @@ const squaringInputText = process.env.SQUARING_INPUT || "987654321";
772
772
  const squaringStepTimeoutMs = parsePositiveIntEnv("SQUARING_STEP_TIMEOUT_MS", 60000);
773
773
 
774
774
  console.log("\n=================== SQUARING SCALE & MEMORY BENCHMARK ===================");
775
- console.log(`Algorithms: times vs karatsuba (${squaringSteps} successive squarings doubling bit length)`);
776
-
777
- const stateKara = createState();
778
- for (const relPath of ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"]) {
779
- await evaluateInput(`:load ${fileURLToPath(import.meta.resolve(`@fraczak/k/${relPath}`))}`, stateKara);
780
- }
781
- codes.load(stateKara.codes);
775
+ console.log(`Algorithm: times (Karatsuba, ${squaringSteps} successive squarings doubling bit length)`);
782
776
 
783
777
  const sInitialVal = intValue(squaringInputText);
784
778
  const { inputWire: sInitWire, inputPattern: sInputPattern } = wireInput(sInitialVal);
@@ -787,20 +781,11 @@ const squaringAlgos = [
787
781
  {
788
782
  id: "times",
789
783
  name: "times",
790
- title: "Long Multiplication (times)",
784
+ title: "Karatsuba Multiplication (times)",
791
785
  expr: "s = {()x,()y}times;",
792
- sourceLabel: "@fraczak/k/lib/arithmetics.k#s",
786
+ sourceLabel: "@fraczak/k/lib/integer.k#s",
793
787
  state: state,
794
788
  relName: "s"
795
- },
796
- {
797
- id: "karatsuba",
798
- name: "karatsuba",
799
- title: "Karatsuba Multiplication (karatsuba)",
800
- expr: "s = {()x,()y}karatsuba;",
801
- sourceLabel: "@fraczak/k/lib/arithmetics.k#s",
802
- state: stateKara,
803
- relName: "s"
804
789
  }
805
790
  ];
806
791
 
@@ -1049,7 +1034,7 @@ for (let step = 1; step <= squaringSteps; step++) {
1049
1034
  const sep130 = "=".repeat(130);
1050
1035
  const line130 = "-".repeat(130);
1051
1036
 
1052
- if (squaringLanes.length === 1 && (squaringLanes[0].id === "llvm" || squaringLanes[0].id === "llvm-pkir")) {
1037
+ if (squaringAlgos.length === 2 && squaringLanes.length === 1 && (squaringLanes[0].id === "llvm" || squaringLanes[0].id === "llvm-pkir")) {
1053
1038
  const laneId = squaringLanes[0].id;
1054
1039
  const laneName = squaringLanes[0].name;
1055
1040
  // LLVM Only side-by-side comparison table
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * Multiplication Algorithm & Multi-Backend Performance Harness
4
+ * Multiplication Performance Harness
5
5
  *
6
- * Compares multiplication algorithms ('times' vs 'karatsuba')
6
+ * Benchmarks lib/integer.k multiplication ('times', Karatsuba)
7
7
  * across available execution backends:
8
8
  * - LLVM (native binary via Clang/LLVM)
9
9
  * - WebAssembly (persistent runner via Wasm)
@@ -65,8 +65,8 @@ function hasFlag(flag) {
65
65
  function printHelp() {
66
66
  console.log(`Usage: node scripts/perf-multiplication.mjs [options]
67
67
 
68
- Multiplication Algorithm & Multi-Backend Performance Harness.
69
- Compares multiplication algorithms ('times' vs 'karatsuba') across
68
+ Multiplication Performance Harness.
69
+ Benchmarks lib/integer.k multiplication ('times', Karatsuba) across
70
70
  available execution backends (LLVM, Wasm, PKIR, kVM, JS).
71
71
 
72
72
  Options:
@@ -80,7 +80,7 @@ Options:
80
80
  (default: llvm,llvm-pkir,wasm,pkir,kvm,js)
81
81
  --algos <csv>
82
82
  Comma-separated list of multiplication algorithms to test:
83
- times, karatsuba. (default: times,karatsuba)
83
+ times. (default: times)
84
84
  --steps <n>
85
85
  Number of squaring steps in squaring mode. (default: 8)
86
86
  --input <int>
@@ -123,7 +123,7 @@ const backendsArg = getArg(
123
123
  );
124
124
  const selectedBackends = backendsArg
125
125
  .split(",").map(b => b.trim().toLowerCase()).filter(Boolean);
126
- const algosArg = getArg("--algos", "times,karatsuba");
126
+ const algosArg = getArg("--algos", "times");
127
127
  const selectedAlgos = algosArg
128
128
  .split(",").map(a => a.trim().toLowerCase()).filter(Boolean);
129
129
 
@@ -232,9 +232,8 @@ console.log("-".repeat(72) + "\n");
232
232
 
233
233
  // 1. Map algorithms to their source files
234
234
  const arithLibChain = [
235
- fileURLToPath(import.meta.resolve("../lib/bit.k")),
236
- fileURLToPath(import.meta.resolve("../lib/bits.k")),
237
- fileURLToPath(import.meta.resolve("../lib/arithmetics.k"))
235
+ fileURLToPath(import.meta.resolve("../core.k")),
236
+ fileURLToPath(import.meta.resolve("../lib/integer.k"))
238
237
  ];
239
238
 
240
239
  const cacheDir = makeCacheDir("k-mult-perf-");
@@ -193,22 +193,19 @@ function pkirLaneName() {
193
193
  }
194
194
 
195
195
 
196
- console.log("==> Loading @fraczak/k/lib/{bit,bits,arithmetics,list}.k as libraries");
197
- let depLib = null;
198
- for (const relPath of ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k", "lib/list.k"]) {
199
- const filePath = fileURLToPath(import.meta.resolve(`@fraczak/k/${relPath}`));
200
- depLib = loadLibrary(compileLibrary(fs.readFileSync(filePath, "utf8"), {
201
- source: filePath,
202
- libraries: depLib ? [depLib] : []
203
- }));
204
- }
196
+ console.log("==> Loading @fraczak/k/lib/integer.k as library");
197
+ const integerPath = fileURLToPath(import.meta.resolve("@fraczak/k/lib/integer.k"));
198
+ const depLib = loadLibrary(compileLibrary(fs.readFileSync(integerPath, "utf8"), {
199
+ source: integerPath
200
+ }));
205
201
 
206
202
  console.log("==> Compiling @fraczak/k/Examples/poly.k with library dependencies");
207
203
  const polyPath = fileURLToPath(import.meta.resolve("@fraczak/k/Examples/poly.k"));
208
204
  const polySource = fs.readFileSync(polyPath, "utf8");
209
205
  const polyLib = loadLibrary(compileLibrary(polySource, {
210
206
  source: polyPath,
211
- libraries: [depLib]
207
+ libraries: [depLib],
208
+ use: ["int[] nat int pos? neg? zero? gt? inc dec"]
212
209
  }));
213
210
 
214
211
  const state = {
@@ -55,7 +55,7 @@ const columnGroups = [
55
55
  },
56
56
  {
57
57
  title: "int",
58
- source: "Examples/arithmetics.k",
58
+ source: "lib/integer.k",
59
59
  columns: [
60
60
  { key: "int.factorial", label: "factorial" },
61
61
  { key: "int.gcd.90d", label: "gcd" },
@@ -48,9 +48,12 @@ const tests = [
48
48
  ["tests/test-djson-methods.mjs"]
49
49
  ],
50
50
  ["tests/test-lib.mjs", node, ["tests/test-lib.mjs"]],
51
+ ["tests/test-generic.mjs", node, ["tests/test-generic.mjs"]],
52
+ ["tests/test-integer.mjs", node, ["tests/test-integer.mjs"]],
53
+ ["tests/test-ieee.mjs", node, ["tests/test-ieee.mjs"]],
54
+ ["tests/test-djson.mjs", node, ["tests/test-djson.mjs"]],
51
55
  ["tests/test-library-isolation.mjs", node, ["tests/test-library-isolation.mjs"]],
52
56
  ["tests/test-parse-json.mjs", node, ["tests/test-parse-json.mjs"]],
53
- ["tests/test-ieee-text.mjs", node, ["tests/test-ieee-text.mjs"]],
54
57
  ["tests/test-deep-wire-value.mjs", node, ["tests/test-deep-wire-value.mjs"]],
55
58
  ["tests/test-k-object.mjs", node, ["tests/test-k-object.mjs"]],
56
59
  ["tests/test-kir.mjs", node, ["tests/test-kir.mjs"]],
@@ -62,7 +65,6 @@ const tests = [
62
65
  ["tests/test-kvm.mjs", node, ["tests/test-kvm.mjs"]],
63
66
  ["tests/test-kvm-polymorphic.mjs", node, ["tests/test-kvm-polymorphic.mjs"]],
64
67
  ["tests/test-arithmetics.mjs", node, ["tests/test-arithmetics.mjs"]],
65
- ["tests/test-karatsuba.mjs", node, ["tests/test-karatsuba.mjs"]],
66
68
  ["tests/test-poly.mjs", node, ["tests/test-poly.mjs"]],
67
69
  ["tests/test-polymorphic-tdd.mjs", node, ["tests/test-polymorphic-tdd.mjs"]],
68
70
  ["tests/test-access-table.mjs", node, ["tests/test-access-table.mjs"]],
@@ -45,18 +45,12 @@ try {
45
45
  assert.equal(run("k-print", [], hello).toString().trim(), '"ok"');
46
46
 
47
47
  const integer = run("k-int", ["--parse"], "42\n");
48
- const bitKlib = path.join(scratch, "bit.klib");
49
- const bitsKlib = path.join(scratch, "bits.klib");
50
- const arithKlib = path.join(scratch, "arithmetics.klib");
51
- run("k-compile", [path.join(packageDir, "lib/bit.k"), bitKlib]);
52
- run("k-compile", ["--lib", bitKlib, path.join(packageDir, "lib/bits.k"), bitsKlib]);
48
+ const integerKlib = path.join(scratch, "integer.klib");
53
49
  run("k-compile", [
54
- "--lib", bitsKlib,
55
- "--use", "trim inv_loop inv cmp inc_bits dec_bits plus_bits minus_bits mul_bits",
56
- path.join(packageDir, "lib/arithmetics.k"),
57
- arithKlib
50
+ path.join(packageDir, "lib/integer.k"),
51
+ integerKlib
58
52
  ]);
59
- const incremented = run("k", ["--lib", arithKlib,
53
+ const incremented = run("k", ["--lib", integerKlib,
60
54
  "--use", "inc", "inc"], integer);
61
55
  assert.equal(run("k-int", ["--print"], incremented).toString().trim(), "43");
62
56