@fraczak/k 8.6.1 → 8.7.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 (75) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/DOCS/CODECS.md +20 -14
  3. package/DOCS/FILE_FORMATS.md +53 -12
  4. package/DOCS/GETTING_STARTED.md +15 -8
  5. package/DOCS/PATTERNS.md +10 -0
  6. package/DOCS/REPL.md +12 -7
  7. package/Examples/arithmetics.k +81 -468
  8. package/Examples/ieee-arithmetics.k +37 -33
  9. package/Examples/poly.k +107 -104
  10. package/README.md +19 -11
  11. package/backend-api.mjs +3 -1
  12. package/backends/llvm/README.md +1 -1
  13. package/backends/llvm/bin/k-llvm-build.mjs +5 -5
  14. package/backends/llvm/bin/k-llvm-compile.mjs +4 -4
  15. package/backends/llvm/bin/k-llvm.mjs +6 -6
  16. package/backends/llvm/src/cli.mjs +17 -15
  17. package/backends/llvm/tests/integration.sh +6 -1
  18. package/backends/wasm/README.md +3 -3
  19. package/backends/wasm/bin/k-wasm-compile.mjs +4 -4
  20. package/backends/wasm/bin/k-wasm.mjs +4 -4
  21. package/backends/wasm/src/cli.mjs +12 -10
  22. package/backends/wasm/src/wasm.mjs +4 -4
  23. package/backends/wasm/tests/integration.sh +24 -4
  24. package/browser/shims/fs.mjs +19 -3
  25. package/canonical-pattern.mjs +214 -57
  26. package/compiler.mjs +26 -0
  27. package/core.k +2 -1
  28. package/harness/suites/poly.mjs +14 -30
  29. package/index.mjs +67 -2
  30. package/k.mjs +14 -18
  31. package/kir.mjs +3 -1
  32. package/kvm.mjs +11 -11
  33. package/lib/arithmetics.k +286 -0
  34. package/lib/bit.k +68 -0
  35. package/lib/bits.k +227 -0
  36. package/lib/btrie.k +187 -0
  37. package/lib/djson.k +327 -0
  38. package/lib/ieee.k +709 -0
  39. package/lib/list.k +49 -0
  40. package/lib/string.k +588 -0
  41. package/named-patterns.mjs +2 -14
  42. package/object.mjs +32 -7
  43. package/objects/README.md +9 -3
  44. package/objects/compile.mjs +11 -14
  45. package/package.json +1 -1
  46. package/repl.mjs +24 -5
  47. package/scripts/benchmark-idempotency.mjs +22 -15
  48. package/scripts/benchmark.mjs +29 -10
  49. package/scripts/build-repl-html.mjs +41 -13
  50. package/scripts/perf-ieee.mjs +9 -1
  51. package/scripts/perf-int.mjs +10 -17
  52. package/scripts/perf-multiplication.mjs +9 -15
  53. package/scripts/perf-poly.mjs +16 -32
  54. package/scripts/run-tests.mjs +3 -2
  55. package/scripts/test-package.mjs +13 -2
  56. package/tests/helpers/cli.mjs +19 -3
  57. package/tests/integration.sh +25 -5
  58. package/tests/test-arithmetics.mjs +4 -2
  59. package/tests/test-djson-methods.mjs +21 -12
  60. package/tests/test-ieee-arithmetic.mjs +11 -3
  61. package/tests/test-ieee-text.mjs +19 -4
  62. package/tests/test-k-object.mjs +15 -4
  63. package/tests/test-karatsuba.mjs +1 -1
  64. package/tests/test-kvm-polymorphic.mjs +58 -34
  65. package/tests/test-lib.mjs +117 -0
  66. package/tests/test-library-isolation.mjs +381 -0
  67. package/tests/test-named-patterns.mjs +21 -3
  68. package/tests/test-parse-json.mjs +44 -14
  69. package/tests/test-poly.mjs +10 -4
  70. package/tests/test-repl-html.mjs +18 -7
  71. package/tests/test-repl.mjs +50 -35
  72. package/Examples/djson.k +0 -894
  73. package/Examples/ieee.k +0 -969
  74. package/Examples/karatsuba-mult.k +0 -227
  75. package/Examples/list.k +0 -10
@@ -43,11 +43,12 @@ const tests = [
43
43
  ["tests/test-hash-normalization.mjs", node, ["tests/test-hash-normalization.mjs"]],
44
44
  ["tests/test-structural-values.mjs", node, ["tests/test-structural-values.mjs"]],
45
45
  ["tests/test-codecs.mjs", node, ["tests/test-codecs.mjs"]],
46
- [
47
- "tests/test-djson-methods.mjs",
46
+ ["tests/test-djson-methods.mjs",
48
47
  node,
49
48
  ["tests/test-djson-methods.mjs"]
50
49
  ],
50
+ ["tests/test-lib.mjs", node, ["tests/test-lib.mjs"]],
51
+ ["tests/test-library-isolation.mjs", node, ["tests/test-library-isolation.mjs"]],
51
52
  ["tests/test-parse-json.mjs", node, ["tests/test-parse-json.mjs"]],
52
53
  ["tests/test-ieee-text.mjs", node, ["tests/test-ieee-text.mjs"]],
53
54
  ["tests/test-deep-wire-value.mjs", node, ["tests/test-deep-wire-value.mjs"]],
@@ -45,8 +45,19 @@ 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 incremented = run("k", ["--lib", path.join(packageDir, "Examples/arithmetics.k"),
49
- "--export", "inc", "inc"], integer);
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]);
53
+ 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
58
+ ]);
59
+ const incremented = run("k", ["--lib", arithKlib,
60
+ "--use", "inc", "inc"], integer);
50
61
  assert.equal(run("k-int", ["--print"], incremented).toString().trim(), "43");
51
62
 
52
63
  const object = path.join(scratch, "ok.ko");
@@ -6,6 +6,7 @@ import { spawnSync } from "node:child_process";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { parse, print } from "../../codecs/int.mjs";
8
8
  import { encodeToWire, decodeWire } from "../../codecs/runtime/prefix-codec.mjs";
9
+ import { parseHeaderUses } from "../../canonical-pattern.mjs";
9
10
 
10
11
  const root = fileURLToPath(new URL("../../", import.meta.url));
11
12
 
@@ -25,9 +26,24 @@ export function succeeds(result, label) {
25
26
 
26
27
  export function withCompiledLibrary(source, test) {
27
28
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "k-library-test-"));
28
- const library = path.join(dir, "library.klib");
29
+ const sources = Array.isArray(source) ? source : [source];
30
+ let library = null;
29
31
  try {
30
- succeeds(node(["objects/compile.mjs", source, library]), `compile ${source}`);
32
+ for (let i = 0; i < sources.length; i++) {
33
+ const nextLibrary = path.join(dir, `library-${i}.klib`);
34
+ const args = ["objects/compile.mjs"];
35
+ if (library) args.push("--lib", library);
36
+ const filePath = path.isAbsolute(sources[i]) ? sources[i] : path.join(root, sources[i]);
37
+ if (fs.existsSync(filePath)) {
38
+ const raw = fs.readFileSync(filePath, "utf8");
39
+ for (const u of parseHeaderUses(raw)) {
40
+ args.push("--use", u.use);
41
+ }
42
+ }
43
+ args.push(sources[i], nextLibrary);
44
+ succeeds(node(args), `compile ${sources[i]}`);
45
+ library = nextLibrary;
46
+ }
31
47
  test(library);
32
48
  } finally {
33
49
  fs.rmSync(dir, { recursive: true, force: true });
@@ -36,7 +52,7 @@ export function withCompiledLibrary(source, test) {
36
52
 
37
53
  export function runLibrary(library, aliases, source, input = "0") {
38
54
  return node(["k.mjs", "--lib", library,
39
- ...aliases.flatMap((alias) => ["--export", alias]), source],
55
+ ...aliases.flatMap((alias) => ["--use", alias]), source],
40
56
  encodeToWire(parse(input)));
41
57
  }
42
58
 
@@ -33,10 +33,10 @@ grep -q '"__main__"' "$TMP_DIR/stdin.kvm"
33
33
  grep -q '"layer": "KVM-P"' "$TMP_DIR/poly-object.kvm"
34
34
  grep -q '"isPolymorphic": true' "$TMP_DIR/poly-object.kvm"
35
35
  ./objects/compile.mjs 'id = ();' "$TMP_DIR/export.klib"
36
- ./objects/compile.mjs --lib "$TMP_DIR/export.klib" --export id:alias 'alias' "$TMP_DIR/export.ko"
36
+ ./objects/compile.mjs --lib "$TMP_DIR/export.klib" --use id:alias 'alias' "$TMP_DIR/export.ko"
37
37
  ./objects/decompile.mjs "$TMP_DIR/export.ko" | grep -q '^----- main -----$'
38
- node ./codecs/unit.mjs --parse | ./k.mjs --lib "$TMP_DIR/export.klib" --export id:alias 'alias' | node ./codecs/unit.mjs --print | grep -qx '{}'
39
- node ./codecs/unit.mjs --parse | ./kvm.mjs --lib "$TMP_DIR/export.klib" --export id:alias 'alias' | node ./codecs/unit.mjs --print | grep -qx '{}'
38
+ node ./codecs/unit.mjs --parse | ./k.mjs --lib "$TMP_DIR/export.klib" --use id:alias 'alias' | node ./codecs/unit.mjs --print | grep -qx '{}'
39
+ node ./codecs/unit.mjs --parse | ./kvm.mjs --lib "$TMP_DIR/export.klib" --use id:alias 'alias' | node ./codecs/unit.mjs --print | grep -qx '{}'
40
40
  node ./codecs/unit.mjs --parse | ./k.mjs "$TMP_DIR/export.ko" | node ./codecs/unit.mjs --print | grep -qx '{}'
41
41
  node ./codecs/unit.mjs --parse | ./kvm.mjs "$TMP_DIR/export.ko" | node ./codecs/unit.mjs --print | grep -qx '{}'
42
42
  if ./k.mjs --lib "$TMP_DIR/export.klib" --lib "$TMP_DIR/export.klib" '()' > "$TMP_DIR/two-lib.out" 2> "$TMP_DIR/two-lib.err"; then
@@ -81,8 +81,28 @@ if ./kvm.mjs -k Examples/nat.k > "$TMP_DIR/dash-k-kvm.out" 2> "$TMP_DIR/dash-k-k
81
81
  fi
82
82
  grep -q -- '-k is no longer supported' "$TMP_DIR/dash-k-kvm.err"
83
83
  echo
84
- ./objects/compile.mjs --lib core.k Examples/ieee.k "$TMP_DIR/ieee-types.klib"
85
- ./objects/compile.mjs --lib "$TMP_DIR/ieee-types.klib" Examples/ieee-arithmetics.k "$TMP_DIR/ieee.klib"
84
+ compile_step() {
85
+ local prev="$1"
86
+ local src="$2"
87
+ local out="$3"
88
+ local uses=()
89
+ while IFS= read -r line; do
90
+ [ -n "$line" ] && uses+=(--use "$line")
91
+ done < <(node -e 'import("./canonical-pattern.mjs").then(m => { for (const u of m.parseHeaderUses(fs.readFileSync(process.argv[1],"utf8"))) console.log(u.use); })' "$src" 2>/dev/null || true)
92
+ if [ -n "$prev" ]; then
93
+ ./objects/compile.mjs --lib "$prev" "${uses[@]}" "$src" "$out"
94
+ else
95
+ ./objects/compile.mjs "${uses[@]}" "$src" "$out"
96
+ fi
97
+ }
98
+
99
+ compile_step "" lib/bit.k "$TMP_DIR/bit.klib"
100
+ compile_step "$TMP_DIR/bit.klib" lib/bits.k "$TMP_DIR/bits.klib"
101
+ compile_step "$TMP_DIR/bits.klib" lib/list.k "$TMP_DIR/list.klib"
102
+ compile_step "$TMP_DIR/list.klib" lib/btrie.k "$TMP_DIR/btrie.klib"
103
+ compile_step "$TMP_DIR/btrie.klib" lib/string.k "$TMP_DIR/string.klib"
104
+ compile_step "$TMP_DIR/string.klib" lib/ieee.k "$TMP_DIR/ieee-types.klib"
105
+ compile_step "$TMP_DIR/ieee-types.klib" Examples/ieee-arithmetics.k "$TMP_DIR/ieee.klib"
86
106
  MUL=`./objects/extract-aliases.mjs "$TMP_DIR/ieee.klib" | grep '^mul = @' | sed 's/^mul = \(@[^;]*\);.*$/\1/'`
87
107
  DIV=`./objects/extract-aliases.mjs "$TMP_DIR/ieee.klib" | grep '^div = @' | sed 's/^div = \(@[^;]*\);.*$/\1/'`
88
108
  ARG=0.12
@@ -3,7 +3,7 @@ import { withCompiledLibrary, runLibrary, integer, succeeds } from "./helpers/cl
3
3
 
4
4
  const large = "11111112222223333334444444555555666666777777788888899999900000011111122222233333344444455555";
5
5
 
6
- withCompiledLibrary("Examples/arithmetics.k", (library) => {
6
+ withCompiledLibrary(["lib/bit.k", "lib/bits.k", "lib/arithmetics.k", "Examples/arithmetics.k"], (library) => {
7
7
  const run = (aliases, source, input) => runLibrary(library, aliases, source, input);
8
8
  const n = BigInt(large);
9
9
  for (const [op, expected] of [
@@ -48,7 +48,9 @@ withCompiledLibrary("Examples/arithmetics.k", (library) => {
48
48
  [["mod", "int", "10:ten", "3:three"], "{ten x, three y} mod int", "1"],
49
49
  [["gcd", "int", "12:twelve", "8:eight"], "{twelve x, eight y} gcd int", "4"],
50
50
  [["gcd", "int", "4:four", "_:zero_b"], "{four x, zero_b y} gcd int", "4"],
51
- [["lcm", "int", "4:four", "6:six"], "{four x, six y} lcm int", "12"]
51
+ [["lcm", "int", "4:four", "6:six"], "{four x, six y} lcm int", "12"],
52
+ [["factorial", "int", "5:five"], "five int factorial", "120"],
53
+ [["fib", "int", "10:ten"], "ten int fib", "89"]
52
54
  ]) assert.equal(integer(run(aliases, source), source), expected, source);
53
55
  });
54
56
 
@@ -3,22 +3,31 @@ import { readFileSync } from "node:fs";
3
3
  import k from "../index.mjs";
4
4
  import { Value } from "../Value.mjs";
5
5
  import { compileLibrary, loadLibrary } from "../object.mjs";
6
+ import { parseHeaderUses } from "../canonical-pattern.mjs";
6
7
  import { fromJsonValue, toJsonValue } from "../codecs/djson.mjs";
7
8
  import { textToStringValue, stringValueToText } from "../codecs/runtime/unicode-string.mjs";
8
9
  import { parse as parseInt } from "../codecs/int.mjs";
9
10
 
10
- const source = readFileSync(new URL("../Examples/djson.k", import.meta.url), "utf8");
11
- const core = loadLibrary(compileLibrary(readFileSync(new URL("../core.k", import.meta.url), "utf8")));
12
- const ieee = loadLibrary(compileLibrary(readFileSync(new URL("../Examples/ieee.k", import.meta.url), "utf8"), {
13
- libraries: [core]
14
- }));
15
- // Resolve dependencies by hash even when the provider's friendly aliases are absent.
16
- const canonicalTypes = {
17
- ...ieee,
18
- patternAlias: {},
19
- patterns: Object.fromEntries(Object.entries(ieee.patterns).filter(([name]) => name.startsWith("@")))
20
- };
21
- const library = loadLibrary(compileLibrary(source, { libraries: [canonicalTypes] }));
11
+ const source = readFileSync(new URL("../lib/djson.k", import.meta.url), "utf8");
12
+ let ieee = null;
13
+ for (const file of [
14
+ "lib/bit.k",
15
+ "lib/bits.k",
16
+ "lib/list.k",
17
+ "lib/btrie.k",
18
+ "lib/string.k",
19
+ "lib/ieee.k"
20
+ ]) {
21
+ const fileSource = readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
22
+ const uses = parseHeaderUses(fileSource).map((u) => u.use);
23
+ ieee = loadLibrary(compileLibrary(fileSource, {
24
+ source: file,
25
+ libraries: ieee ? [ieee] : [],
26
+ use: uses
27
+ }));
28
+ }
29
+ const djsonUses = parseHeaderUses(source).map((u) => u.use);
30
+ const library = loadLibrary(compileLibrary(source, { libraries: [ieee], use: djsonUses }));
22
31
  const run = (op, value) => k.compile(library.relAlias[op], { libraries: [library] })(value);
23
32
 
24
33
  function method(op, json, { key, index, val } = {}) {
@@ -7,9 +7,17 @@ import { parse as parseFloat64, print as printFloat64 } from "../codecs/ieee.mjs
7
7
  import { closedPatternToCodeHash, valueForCode } from "../repl-codecs.mjs";
8
8
 
9
9
  const state = createState({ engine: "js" });
10
- await evaluateInput(":load core.k", state);
11
- await evaluateInput(":load Examples/ieee.k", state);
12
- await evaluateInput(":load Examples/ieee-arithmetics.k", state);
10
+ for (const file of [
11
+ "lib/bit.k",
12
+ "lib/bits.k",
13
+ "lib/list.k",
14
+ "lib/btrie.k",
15
+ "lib/string.k",
16
+ "lib/ieee.k",
17
+ "Examples/ieee-arithmetics.k"
18
+ ]) {
19
+ await evaluateInput(`:load ${file}`, state);
20
+ }
13
21
 
14
22
  for (const name of ["add", "sub", "mul", "div"]) {
15
23
  assert.ok(state.relAliases[name], `Expected public IEEE relation '${name}'`);
@@ -2,14 +2,29 @@ import assert from "node:assert/strict";
2
2
  import { readFileSync } from "node:fs";
3
3
  import k from "../index.mjs";
4
4
  import { compileLibrary, loadLibrary } from "../object.mjs";
5
+ import { parseHeaderUses } from "../canonical-pattern.mjs";
5
6
  import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
6
7
  import { encodeNumberToValue, decodeValueToNumber } from "../codecs/ieee.mjs";
7
8
  import { textToStringValue, stringValueToText } from "../codecs/runtime/unicode-string.mjs";
8
9
 
9
- const core = loadLibrary(compileLibrary(readFileSync(new URL("../core.k", import.meta.url), "utf8")));
10
- const ieee = loadLibrary(compileLibrary(readFileSync(new URL("../Examples/ieee.k", import.meta.url), "utf8"), {
11
- libraries: [core]
12
- }));
10
+ const ieeeSources = [
11
+ "lib/bit.k",
12
+ "lib/bits.k",
13
+ "lib/list.k",
14
+ "lib/btrie.k",
15
+ "lib/string.k",
16
+ "lib/ieee.k"
17
+ ];
18
+ let ieee = null;
19
+ for (const file of ieeeSources) {
20
+ const fileSource = readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
21
+ const uses = parseHeaderUses(fileSource).map((u) => u.use);
22
+ ieee = loadLibrary(compileLibrary(fileSource, {
23
+ source: file,
24
+ libraries: ieee ? [ieee] : [],
25
+ use: uses
26
+ }));
27
+ }
13
28
  assert.equal(ieee.relAlias.add, undefined, "Text conversion must not load IEEE arithmetic");
14
29
  const parser = await instantiateWasmArtifact(await compileWasmArtifact(ieee.relAlias.parseFloat64, { libraries: [ieee] }));
15
30
  const printer = await instantiateWasmArtifact(await compileWasmArtifact(ieee.relAlias.printFloat64, { libraries: [ieee] }));
@@ -14,7 +14,8 @@ import {
14
14
  objectToFunction,
15
15
  runConvergedObject,
16
16
  decompileObjectBuffer,
17
- extractAliasesFromObject
17
+ extractAliasesFromObject,
18
+ parseHeaderUses
18
19
  } from "../object.mjs";
19
20
 
20
21
  const value = parseValue("{a:{b:x,c:{}}}");
@@ -101,13 +102,23 @@ const recursiveNatPattern = new RegExp(
101
102
  assert.equal(natRoundTripSource, natDecompiledSource);
102
103
  assert.match(natDecompiledSource, recursiveNatPattern);
103
104
 
105
+ const bitLib = loadLibrary(decodeObject(compileLibraryBuffer(
106
+ fs.readFileSync("lib/bit.k", "utf8"),
107
+ { source: "lib/bit.k" }
108
+ )));
109
+ const bitsLib = loadLibrary(decodeObject(compileLibraryBuffer(
110
+ fs.readFileSync("lib/bits.k", "utf8"),
111
+ { source: "lib/bits.k", libraries: [bitLib] }
112
+ )));
113
+ const arithRaw = fs.readFileSync("lib/arithmetics.k", "utf8");
114
+ const arithUses = parseHeaderUses(arithRaw).map((u) => u.use);
104
115
  const arithmeticsLibraryBuffer = compileLibraryBuffer(
105
- fs.readFileSync("Examples/arithmetics.k", "utf8"),
106
- { source: "Examples/arithmetics.k" }
116
+ arithRaw,
117
+ { source: "lib/arithmetics.k", libraries: [bitsLib], use: arithUses }
107
118
  );
108
119
  const arithmeticsDecompiledSource = decompileObjectBuffer(arithmeticsLibraryBuffer);
109
120
  const arithmeticsRoundTripSource = decompileObjectBuffer(
110
- compileLibraryBuffer(arithmeticsDecompiledSource, { source: "Examples/arithmetics.decompiled.k" })
121
+ compileLibraryBuffer(arithmeticsDecompiledSource, { source: "lib/arithmetics.decompiled.k" })
111
122
  );
112
123
  assert.equal(arithmeticsRoundTripSource, arithmeticsDecompiledSource);
113
124
 
@@ -3,7 +3,7 @@ import { withCompiledLibrary, runLibrary, integer } from "./helpers/cli.mjs";
3
3
 
4
4
  const large = "11111112222223333334444444555555666666777777788888899999900000011111122222233333344444455555";
5
5
 
6
- withCompiledLibrary("Examples/karatsuba-mult.k", (library) => {
6
+ withCompiledLibrary(["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"], (library) => {
7
7
  const multiply = (source, input) =>
8
8
  integer(runLibrary(library, ["karatsuba"], source, input), source);
9
9
 
@@ -6,6 +6,7 @@ import {
6
6
  executeKVM
7
7
  } from "../kvm.mjs";
8
8
  import { compileObjectBuffer, decodeObject } from "../object.mjs";
9
+ import { parseHeaderUses } from "../canonical-pattern.mjs";
9
10
  import { objectToKIRP } from "../kir.mjs";
10
11
  import { fromObject, Value } from "../Value.mjs";
11
12
  import { lowerToWasm } from "../backends/wasm/src/kvm2wasm.mjs";
@@ -223,7 +224,7 @@ console.log("==> Starting Polymorphic kVM & Specialization Tests");
223
224
  // Test 7: CLI Compilation to Polymorphic .kvm without --input-pattern
224
225
  {
225
226
  const compileScript = path.join(__dirname, "../objects/compile.mjs");
226
- const res = spawnSync(process.execPath, [compileScript, "--format", "kvm", "Examples/arithmetics.k"], {
227
+ const res = spawnSync(process.execPath, [compileScript, "--format", "kvm", "Examples/nat.k"], {
227
228
  cwd: path.join(__dirname, ".."),
228
229
  encoding: "utf8"
229
230
  });
@@ -236,41 +237,64 @@ console.log("==> Starting Polymorphic kVM & Specialization Tests");
236
237
  console.log("Test 7 (CLI Compilation to Polymorphic .kvm): Passed");
237
238
  }
238
239
 
239
- // Test 8: CLI Compilation with --lib and explicit --export (no auto-export)
240
+ // Test 8: CLI Compilation with --lib and explicit --use (no auto-export)
240
241
  {
241
242
  const compileScript = path.join(__dirname, "../objects/compile.mjs");
242
- // Fails without explicit --export
243
- const failRes = spawnSync(process.execPath, [
244
- compileScript,
245
- "--lib", "Examples/arithmetics.k",
246
- "{succ int x,int y}+"
247
- ], {
248
- cwd: path.join(__dirname, ".."),
249
- encoding: "utf8"
250
- });
251
- assert.notEqual(failRes.status, 0, "Should fail without explicit --export");
252
-
253
- // Succeeds with explicit --export
254
- const successRes = spawnSync(process.execPath, [
255
- compileScript,
256
- "--lib", "Examples/arithmetics.k",
257
- "--export", "plus:+",
258
- "--export", "succ",
259
- "--export", "int",
260
- "--format", "kvm",
261
- "{succ int x,int y}+"
262
- ], {
263
- cwd: path.join(__dirname, ".."),
264
- encoding: "utf8",
265
- maxBuffer: 10 * 1024 * 1024
266
- });
267
- assert.equal(successRes.status, 0, `CLI compile with --export failed: ${successRes.stderr}`);
268
- const kvm = JSON.parse(successRes.stdout);
269
- assert.equal(kvm.format, "k-vm");
270
- assert.equal(kvm.layer, "KVM-P");
271
- assert.equal(kvm.isPolymorphic, true);
272
- assert.ok(kvm.functions["__main__"]);
273
- console.log("Test 8 (CLI Compilation with --lib and explicit --export): Passed");
243
+ const os = await import("node:os");
244
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-kvm-poly-"));
245
+ try {
246
+ let prevLib = null;
247
+ for (const [idx, src] of ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"].entries()) {
248
+ const nextLib = path.join(tmpDir, `step-${idx}.klib`);
249
+ const fileSource = fs.readFileSync(path.join(__dirname, "..", src), "utf8");
250
+ const uses = parseHeaderUses(fileSource).flatMap((u) => ["--use", u.use]);
251
+ const stepRes = spawnSync(process.execPath, [
252
+ compileScript,
253
+ ...(prevLib ? ["--lib", prevLib] : []),
254
+ ...uses,
255
+ src,
256
+ nextLib
257
+ ], {
258
+ cwd: path.join(__dirname, ".."),
259
+ encoding: "utf8"
260
+ });
261
+ assert.equal(stepRes.status, 0, `CLI lib step failed: ${stepRes.stderr}`);
262
+ prevLib = nextLib;
263
+ }
264
+
265
+ // Fails without explicit --use
266
+ const failRes = spawnSync(process.execPath, [
267
+ compileScript,
268
+ "--lib", prevLib,
269
+ "{succ int x,int y}+"
270
+ ], {
271
+ cwd: path.join(__dirname, ".."),
272
+ encoding: "utf8"
273
+ });
274
+ assert.notEqual(failRes.status, 0, "Should fail without explicit --use");
275
+
276
+ // Succeeds with explicit --use
277
+ const successRes = spawnSync(process.execPath, [
278
+ compileScript,
279
+ "--lib", prevLib,
280
+ "--use", "plus:+ succ int",
281
+ "--format", "kvm",
282
+ "{succ int x,int y}+"
283
+ ], {
284
+ cwd: path.join(__dirname, ".."),
285
+ encoding: "utf8",
286
+ maxBuffer: 10 * 1024 * 1024
287
+ });
288
+ assert.equal(successRes.status, 0, `CLI compile with --use failed: ${successRes.stderr}`);
289
+ const kvm = JSON.parse(successRes.stdout);
290
+ assert.equal(kvm.format, "k-vm");
291
+ assert.equal(kvm.layer, "KVM-P");
292
+ assert.equal(kvm.isPolymorphic, true);
293
+ assert.ok(kvm.functions["__main__"]);
294
+ console.log("Test 8 (CLI Compilation with --lib and explicit --use): Passed");
295
+ } finally {
296
+ fs.rmSync(tmpDir, { recursive: true, force: true });
297
+ }
274
298
  }
275
299
 
276
300
  console.log("==> All Polymorphic kVM Tests Passed Successfully!");
@@ -0,0 +1,117 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFileSync } from "node:fs";
3
+ import k from "../index.mjs";
4
+ import { Value } from "../Value.mjs";
5
+ import { compileLibrary, loadLibrary } from "../object.mjs";
6
+ import { parseHeaderUses } from "../canonical-pattern.mjs";
7
+ import { fromJsonValue, toJsonValue } from "../codecs/djson.mjs";
8
+ import { textToStringValue, stringValueToText } from "../codecs/runtime/unicode-string.mjs";
9
+ import { encodeNumberToValue, decodeValueToNumber } from "../codecs/ieee.mjs";
10
+ import { parse as parseInt, parseIntStr, print as printInt } from "../codecs/int.mjs";
11
+
12
+ const libFiles = [
13
+ "lib/bit.k",
14
+ "lib/bits.k",
15
+ "lib/list.k",
16
+ "lib/btrie.k",
17
+ "lib/string.k",
18
+ "lib/ieee.k",
19
+ "lib/djson.k",
20
+ "lib/arithmetics.k"
21
+ ];
22
+
23
+ const libs = [];
24
+ for (const file of libFiles) {
25
+ const source = readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
26
+ const uses = parseHeaderUses(source).map((u) => u.use);
27
+ const compiled = loadLibrary(
28
+ compileLibrary(source, { source: file, libraries: libs, use: uses })
29
+ );
30
+ libs.push(compiled);
31
+ }
32
+
33
+ const ieeeLib = libs[5];
34
+ const djsonLib = libs[6];
35
+ const arithLib = libs[7];
36
+
37
+ const runArith = (op, value) =>
38
+ k.compile(arithLib.relAlias[op], { libraries: [arithLib] })(value);
39
+ const runIeee = (op, value) =>
40
+ k.compile(ieeeLib.relAlias[op], { libraries: [ieeeLib] })(value);
41
+ const runDjson = (op, value) =>
42
+ k.compile(djsonLib.relAlias[op], { libraries: [djsonLib] })(value);
43
+
44
+ // Verify lib/arithmetics.k integer operations.
45
+ assert.equal(
46
+ printInt(runArith("plus", Value.product({ x: parseIntStr("19"), y: parseIntStr("23") }))),
47
+ "42"
48
+ );
49
+ assert.equal(
50
+ printInt(runArith("times", Value.product({ x: parseIntStr("-6"), y: parseIntStr("7") }))),
51
+ "-42"
52
+ );
53
+ assert.equal(
54
+ printInt(runArith("karatsuba", Value.product({ x: parseIntStr("123456"), y: parseIntStr("-654321") }))),
55
+ String(123456n * -654321n)
56
+ );
57
+
58
+ // Verify lib/ieee.k text parsing, natural conversion, and exact decimal printing.
59
+ for (const num of [0, -0, 1, -1, 3.141592653589793, 1e-10, 1e20, Infinity, -Infinity, NaN]) {
60
+ const val = encodeNumberToValue(num);
61
+ const text = stringValueToText(runIeee("printFloat64", val));
62
+ const parsed = decodeValueToNumber(runIeee("parseFloat64", textToStringValue(text)));
63
+ if (Number.isNaN(num)) {
64
+ assert.ok(Number.isNaN(parsed));
65
+ } else {
66
+ assert.ok(Object.is(parsed, num), `round-trip ${num} via ${text}`);
67
+ }
68
+ }
69
+
70
+ for (const n of [0, 1, 2, 10, 42, 1024, 65535]) {
71
+ const f = decodeValueToNumber(runIeee("natToFloat64", parseInt(String(n)).value));
72
+ assert.equal(f, n);
73
+ }
74
+
75
+ // Verify lib/djson.k methods and RFC 8259 JSON parser.
76
+ function method(op, json, { key, index, val } = {}) {
77
+ const fields = { json: fromJsonValue(json) };
78
+ if (key !== undefined) fields.key = textToStringValue(key);
79
+ if (index !== undefined) fields.index = parseInt(String(index)).value;
80
+ if (val !== undefined) fields.val = fromJsonValue(val);
81
+ return runDjson(op, Value.product(fields));
82
+ }
83
+ const result = (...args) => toJsonValue(method(...args));
84
+
85
+ const doc = { name: "Alice", age: 30, tags: ["developer", "k"] };
86
+ assert.equal(result("get", doc, { key: "name" }), "Alice");
87
+ assert.equal(result("get", doc, { key: "age" }), 30);
88
+ assert.ok(method("has?", doc, { key: "name" }));
89
+ assert.equal(method("has?", doc, { key: "missing" }), undefined);
90
+
91
+ const withCity = result("set", doc, { key: "city", val: "Paris" });
92
+ assert.deepEqual(withCity, { ...doc, city: "Paris" });
93
+ const withoutAge = result("del", withCity, { key: "age" });
94
+ assert.deepEqual(withoutAge, { name: "Alice", tags: doc.tags, city: "Paris" });
95
+
96
+ const arr = [10, 20, 30];
97
+ for (const [index, expected] of arr.entries()) {
98
+ assert.equal(result("nth", arr, { index }), expected);
99
+ }
100
+ assert.ok(method("has_index?", arr, { index: 1 }));
101
+ assert.equal(method("has_index?", arr, { index: 99 }), undefined);
102
+ assert.deepEqual(result("set_nth", arr, { index: 1, val: 99 }), [10, 99, 30]);
103
+ assert.equal(toJsonValue(runDjson("length", fromJsonValue(arr))), 3);
104
+ assert.equal(toJsonValue(runDjson("length", fromJsonValue(doc))), 3);
105
+ assert.equal(toJsonValue(runDjson("length", fromJsonValue("hello"))), 5);
106
+ assert.deepEqual(result("push", arr, { val: 40 }), [10, 20, 30, 40]);
107
+ assert.deepEqual(new Set(toJsonValue(runDjson("keys", fromJsonValue(doc)))), new Set(["name", "age", "tags"]));
108
+
109
+ const sampleJson = JSON.stringify({
110
+ nullVal: null,
111
+ bools: [true, false],
112
+ nums: [0, -0, 42, -12.5, 1e5],
113
+ str: "hello\n\t\"world\"\\/\u0041\uD83D\uDE00",
114
+ empty: [{}, []]
115
+ });
116
+ const parsedJson = toJsonValue(runDjson("parseJson", textToStringValue(sampleJson)));
117
+ assert.deepEqual(parsedJson, JSON.parse(sampleJson));