@fraczak/k 8.7.0 → 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 (73) hide show
  1. package/CHANGELOG.md +40 -8
  2. package/DOCS/CODECS.md +42 -40
  3. package/DOCS/FILE_FORMATS.md +41 -64
  4. package/DOCS/GETTING_STARTED.md +10 -17
  5. package/DOCS/PATTERNS.md +3 -10
  6. package/DOCS/REPL.md +5 -9
  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 +7 -11
  12. package/backends/llvm/tests/integration.sh +2 -4
  13. package/backends/wasm/src/wasm.mjs +2 -6
  14. package/backends/wasm/tests/integration.sh +17 -7
  15. package/browser/shims/fs.mjs +2 -6
  16. package/canonical-pattern.mjs +9 -32
  17. package/compiler.mjs +36 -0
  18. package/harness/suites/poly.mjs +9 -11
  19. package/index.mjs +140 -6
  20. package/k.mjs +4 -12
  21. package/kir.mjs +3 -1
  22. package/kvm.mjs +4 -8
  23. package/lib/djson.k +981 -294
  24. package/lib/generic.k +701 -0
  25. package/lib/ieee.k +662 -638
  26. package/lib/integer.k +542 -0
  27. package/named-patterns.mjs +0 -12
  28. package/object.mjs +22 -32
  29. package/objects/README.md +6 -7
  30. package/objects/compile.mjs +5 -10
  31. package/package.json +1 -1
  32. package/repl.mjs +4 -7
  33. package/scripts/benchmark-idempotency.mjs +16 -17
  34. package/scripts/benchmark.mjs +39 -29
  35. package/scripts/build-repl-html.mjs +45 -35
  36. package/scripts/perf-ieee.mjs +1 -5
  37. package/scripts/perf-int.mjs +12 -27
  38. package/scripts/perf-multiplication.mjs +8 -9
  39. package/scripts/perf-poly.mjs +7 -10
  40. package/scripts/render-benchmark.mjs +1 -1
  41. package/scripts/run-tests.mjs +5 -2
  42. package/scripts/test-package.mjs +6 -7
  43. package/tests/README.md +4 -5
  44. package/tests/helpers/cli.mjs +31 -0
  45. package/tests/integration.sh +17 -7
  46. package/tests/test-arithmetics.mjs +23 -16
  47. package/tests/test-djson-methods.mjs +19 -22
  48. package/tests/test-djson.mjs +273 -0
  49. package/tests/test-generic.mjs +239 -0
  50. package/tests/test-ieee-arithmetic.mjs +1 -5
  51. package/tests/test-ieee.mjs +153 -0
  52. package/tests/test-integer.mjs +264 -0
  53. package/tests/test-k-object.mjs +11 -14
  54. package/tests/test-kvm-polymorphic.mjs +7 -4
  55. package/tests/test-lib.mjs +62 -50
  56. package/tests/test-library-isolation.mjs +704 -0
  57. package/tests/test-named-patterns.mjs +13 -4
  58. package/tests/test-parse-json.mjs +20 -19
  59. package/tests/test-poly.mjs +21 -16
  60. package/tests/test-repl-html.mjs +39 -44
  61. package/tests/test-repl.mjs +46 -59
  62. package/DOCS/book-combined.md +0 -3786
  63. package/DOCS/dependency-graph.md +0 -144
  64. package/Examples/arithmetics.k +0 -108
  65. package/Examples/esc.k +0 -9
  66. package/lib/arithmetics.k +0 -287
  67. package/lib/bit.k +0 -68
  68. package/lib/bits.k +0 -221
  69. package/lib/btrie.k +0 -187
  70. package/lib/list.k +0 -49
  71. package/lib/string.k +0 -588
  72. package/tests/test-ieee-text.mjs +0 -70
  73. package/tests/test-karatsuba.mjs +0 -25
@@ -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,8 +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"]],
55
+ ["tests/test-library-isolation.mjs", node, ["tests/test-library-isolation.mjs"]],
51
56
  ["tests/test-parse-json.mjs", node, ["tests/test-parse-json.mjs"]],
52
- ["tests/test-ieee-text.mjs", node, ["tests/test-ieee-text.mjs"]],
53
57
  ["tests/test-deep-wire-value.mjs", node, ["tests/test-deep-wire-value.mjs"]],
54
58
  ["tests/test-k-object.mjs", node, ["tests/test-k-object.mjs"]],
55
59
  ["tests/test-kir.mjs", node, ["tests/test-kir.mjs"]],
@@ -61,7 +65,6 @@ const tests = [
61
65
  ["tests/test-kvm.mjs", node, ["tests/test-kvm.mjs"]],
62
66
  ["tests/test-kvm-polymorphic.mjs", node, ["tests/test-kvm-polymorphic.mjs"]],
63
67
  ["tests/test-arithmetics.mjs", node, ["tests/test-arithmetics.mjs"]],
64
- ["tests/test-karatsuba.mjs", node, ["tests/test-karatsuba.mjs"]],
65
68
  ["tests/test-poly.mjs", node, ["tests/test-poly.mjs"]],
66
69
  ["tests/test-polymorphic-tdd.mjs", node, ["tests/test-polymorphic-tdd.mjs"]],
67
70
  ["tests/test-access-table.mjs", node, ["tests/test-access-table.mjs"]],
@@ -45,13 +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]);
53
- run("k-compile", ["--lib", bitsKlib, path.join(packageDir, "lib/arithmetics.k"), arithKlib]);
54
- const incremented = run("k", ["--lib", arithKlib,
48
+ const integerKlib = path.join(scratch, "integer.klib");
49
+ run("k-compile", [
50
+ path.join(packageDir, "lib/integer.k"),
51
+ integerKlib
52
+ ]);
53
+ const incremented = run("k", ["--lib", integerKlib,
55
54
  "--use", "inc", "inc"], integer);
56
55
  assert.equal(run("k-int", ["--print"], incremented).toString().trim(), "43");
57
56
 
package/tests/README.md CHANGED
@@ -43,9 +43,8 @@ cases; shared helpers live outside the discovered directory.
43
43
  | Objects and portable export | `test-k-object.mjs`, `test-kir.mjs`, `test-validate-object.mjs` |
44
44
  | Interactive state and browser UI | `test-repl.mjs`, `test-repl-html.mjs`, `test-tree-view.mjs` |
45
45
  | Execution layers | `test-kvm.mjs`, `test-kvm-polymorphic.mjs`, `test-access-table.mjs`, `test-pkir.mjs` |
46
- | Libraries | Arithmetic, IEEE, list, Karatsuba, and dynamic JSON suites |
47
- | JSON text parsing | `test-parse-json.mjs`: grammar, Unicode escapes, binary64 boundaries, Wasm, and CLI |
48
- | IEEE text conversion | `test-ieee-text.mjs`: parsing, exact printing, special values, and binary64 round-trips |
46
+ | Libraries | `test-generic.mjs`, `test-integer.mjs`, `test-ieee.mjs`, `test-djson.mjs`, `test-lib.mjs`, and example suites (`test-arithmetics.mjs`, `test-poly.mjs`, `test-ieee-arithmetic.mjs`, `test-djson-methods.mjs`) |
47
+ | JSON text parsing | `test-parse-json.mjs`: RFC 8259 grammar, Unicode escapes, binary64 rounding, Wasm, and CLI |
49
48
 
50
49
  `test-hash-fuzz.mjs` uses a deterministic generator to check renaming and
51
50
  definition-order invariance; it is not a general cryptographic collision test.
@@ -55,8 +54,8 @@ expected values, and case descriptions reused by supported execution paths.
55
54
  A rendered payload alone can hide envelope differences, so keep pattern
56
55
  comparisons when checking structural correctness.
57
56
 
58
- Arithmetic and Karatsuba tests share CLI setup in `helpers/cli.mjs`. They still
59
- run the library through `k.mjs` and compare numerical results with BigInt;
57
+ Arithmetic tests share CLI setup in `helpers/cli.mjs`. They run
58
+ `lib/integer.k` through `k.mjs` and compare numerical results with BigInt;
60
59
  codec modules prepare and decode the wire values in process. The dedicated
61
60
  codec and shell suites cover the codec command-line boundary.
62
61
 
@@ -9,6 +9,34 @@ import { encodeToWire, decodeWire } from "../../codecs/runtime/prefix-codec.mjs"
9
9
 
10
10
  const root = fileURLToPath(new URL("../../", import.meta.url));
11
11
 
12
+ const LIBRARY_USE_SPECS = new Map([
13
+ ["core.k", []],
14
+ ["lib/integer.k", []],
15
+ ["lib/generic.k", [
16
+ "bit[] bits[] list[X] byte[] ascii[] bmp_hi_common[] bmp_hi_private_use[] plane0[] plane_02_10[] unicode[] string[]"
17
+ ]],
18
+ ["lib/ieee.k", ["bit[] bits[]"]],
19
+ ["lib/djson.k", [
20
+ "bit[] bits[] list[] byte[] ascii[] bmp_hi_common[] bmp_hi_private_use[] plane0[] plane_02_10[] unicode[] string[]",
21
+ "bool[] false? true? order[] lt? eq? gt? opt[] reverse trim_bits inc_bits btrie[] btrie_empty btrie_get btrie_set btrie_del btrie_entries_raw btrie_max_key btrie_bfs_values string_to_bits bits_to_string",
22
+ "sign[] float64[] pos_zero neg_zero finite_float64? ratio_to_float64"
23
+ ]],
24
+ ["Examples/poly.k", ["int[] nat int pos? neg? zero? gt? inc dec"]],
25
+ ["Examples/ieee-arithmetics.k", [
26
+ "bit[] sign[] exp11[] frac52[] float64[] all_ones_exponent? exp0 finite_float64? frac0 inf_float64? nan_float64? neg_inf neg_zero negate_float64 pos_inf pos_zero qnan zero_exponent? zero_float64?"
27
+ ]]
28
+ ]);
29
+
30
+ export function useSpecsFor(sourcePath) {
31
+ const normalized = String(sourcePath).replace(/\\/g, "/");
32
+ for (const [key, specs] of LIBRARY_USE_SPECS) {
33
+ if (normalized === key || normalized.endsWith(`/${key}`)) {
34
+ return specs;
35
+ }
36
+ }
37
+ return [];
38
+ }
39
+
12
40
  export function node(args, input) {
13
41
  const result = spawnSync(process.execPath, args, {
14
42
  cwd: root, input, maxBuffer: 64 * 1024 * 1024
@@ -32,6 +60,9 @@ export function withCompiledLibrary(source, test) {
32
60
  const nextLibrary = path.join(dir, `library-${i}.klib`);
33
61
  const args = ["objects/compile.mjs"];
34
62
  if (library) args.push("--lib", library);
63
+ for (const u of useSpecsFor(sources[i])) {
64
+ args.push("--use", u);
65
+ }
35
66
  args.push(sources[i], nextLibrary);
36
67
  succeeds(node(args), `compile ${sources[i]}`);
37
68
  library = nextLibrary;
@@ -81,13 +81,23 @@ 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/bit.k "$TMP_DIR/bit.klib"
85
- ./objects/compile.mjs --lib "$TMP_DIR/bit.klib" lib/bits.k "$TMP_DIR/bits.klib"
86
- ./objects/compile.mjs --lib "$TMP_DIR/bits.klib" lib/list.k "$TMP_DIR/list.klib"
87
- ./objects/compile.mjs --lib "$TMP_DIR/list.klib" lib/btrie.k "$TMP_DIR/btrie.klib"
88
- ./objects/compile.mjs --lib "$TMP_DIR/btrie.klib" lib/string.k "$TMP_DIR/string.klib"
89
- ./objects/compile.mjs --lib "$TMP_DIR/string.klib" lib/ieee.k "$TMP_DIR/ieee-types.klib"
90
- ./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 use_spec="$4"
89
+ local uses=()
90
+ [ -n "$use_spec" ] && uses=(--use "$use_spec")
91
+ if [ -n "$prev" ]; then
92
+ ./objects/compile.mjs --lib "$prev" "${uses[@]}" "$src" "$out"
93
+ else
94
+ ./objects/compile.mjs "${uses[@]}" "$src" "$out"
95
+ fi
96
+ }
97
+
98
+ compile_step "" core.k "$TMP_DIR/core.klib" ""
99
+ compile_step "$TMP_DIR/core.klib" lib/ieee.k "$TMP_DIR/ieee-types.klib" "bit[] bits[]"
100
+ compile_step "$TMP_DIR/ieee-types.klib" Examples/ieee-arithmetics.k "$TMP_DIR/ieee.klib" "bit[] sign[] exp11[] frac52[] float64[] all_ones_exponent? exp0 finite_float64? frac0 inf_float64? nan_float64? neg_inf neg_zero negate_float64 pos_inf pos_zero qnan zero_exponent? zero_float64?"
91
101
  MUL=`./objects/extract-aliases.mjs "$TMP_DIR/ieee.klib" | grep '^mul = @' | sed 's/^mul = \(@[^;]*\);.*$/\1/'`
92
102
  DIV=`./objects/extract-aliases.mjs "$TMP_DIR/ieee.klib" | grep '^div = @' | sed 's/^div = \(@[^;]*\);.*$/\1/'`
93
103
  ARG=0.12
@@ -3,7 +3,16 @@ import { withCompiledLibrary, runLibrary, integer, succeeds } from "./helpers/cl
3
3
 
4
4
  const large = "11111112222223333334444444555555666666777777788888899999900000011111122222233333344444455555";
5
5
 
6
- withCompiledLibrary(["lib/bit.k", "lib/bits.k", "lib/arithmetics.k", "Examples/arithmetics.k"], (library) => {
6
+ function kPosInt(value) {
7
+ const bits = BigInt(value).toString(2);
8
+ let expr = "{} |_";
9
+ for (let i = bits.length - 1; i >= 0; i--) {
10
+ expr += ` |${bits[i]}`;
11
+ }
12
+ return `${expr} |+`;
13
+ }
14
+
15
+ withCompiledLibrary(["lib/integer.k"], (library) => {
7
16
  const run = (aliases, source, input) => runLibrary(library, aliases, source, input);
8
17
  const n = BigInt(large);
9
18
  for (const [op, expected] of [
@@ -13,31 +22,31 @@ withCompiledLibrary(["lib/bit.k", "lib/bits.k", "lib/arithmetics.k", "Examples/a
13
22
  String(expected), op);
14
23
  }
15
24
 
16
- succeeds(run(["dec", "zero_int?"], "dec dec zero_int?", "2"),
25
+ succeeds(run(["dec", "zero?"], "dec dec zero?", "2"),
17
26
  "decrement normalization");
18
27
  for (const [x, divisor] of [
19
28
  ["0", "7"], ["3", "7"], ["4", "1"], ["10", "2"], ["12", "3"],
20
29
  ["11", "3"], ["12", "12"], ["100", "7"], ["-100", "7"], ["1000", "10"]
21
30
  ]) {
22
31
  const a = BigInt(x), b = BigInt(divisor);
23
- const aliases = ["div", "int", `${divisor}:divisor`];
32
+ const aliases = ["divmod"];
24
33
  for (const [projection, expected] of [
25
- [".div", a / b], [".rem int", (a < 0n ? -a : a) % b]
34
+ [".q", a / b], [".r", a % b]
26
35
  ]) {
27
- const source = `{() x, divisor int y} div ${projection}`;
36
+ const source = `{() x, ${kPosInt(divisor)} y} divmod ${projection}`;
28
37
  assert.equal(integer(run(aliases, source, x), source), String(expected),
29
- `div(${x}, ${divisor}) ${projection}`);
38
+ `divmod(${x}, ${divisor}) ${projection}`);
30
39
  }
31
40
  }
32
41
 
33
42
  for (const [aliases, source] of [
34
- [["EQ", "int", "2:two"], "{two x, two y} EQ .x int"],
35
- [["pos?", "int", "2:two"], "two int pos?"]
43
+ [["eq?"], `{${kPosInt(2)} x, ${kPosInt(2)} y} eq? .x`],
44
+ [["pos?"], `${kPosInt(2)} pos?`]
36
45
  ]) succeeds(run(aliases, source), source);
37
46
 
38
47
  for (const [aliases, source] of [
39
- [["EQ", "int", "2:two", "3:three"], "{two x, three y} EQ .x int"],
40
- [["pos?", "int", "0:zero"], "zero int pos?"]
48
+ [["eq?"], `{${kPosInt(2)} x, ${kPosInt(3)} y} eq? .x`],
49
+ [["pos?"], `${kPosInt(0)} pos?`]
41
50
  ]) {
42
51
  const result = run(aliases, source);
43
52
  assert.notEqual(result.status, 0, source);
@@ -45,12 +54,10 @@ withCompiledLibrary(["lib/bit.k", "lib/bits.k", "lib/arithmetics.k", "Examples/a
45
54
  }
46
55
 
47
56
  for (const [aliases, source, expected] of [
48
- [["mod", "int", "10:ten", "3:three"], "{ten x, three y} mod int", "1"],
49
- [["gcd", "int", "12:twelve", "8:eight"], "{twelve x, eight y} gcd int", "4"],
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"],
52
- [["factorial", "int", "5:five"], "five int factorial", "120"],
53
- [["fib", "int", "10:ten"], "ten int fib", "89"]
57
+ [["mod"], `{${kPosInt(10)} x, ${kPosInt(3)} y} mod`, "1"],
58
+ [["gcd"], `{${kPosInt(12)} x, ${kPosInt(8)} y} gcd`, "4"],
59
+ [["gcd"], `{${kPosInt(4)} x, ${kPosInt(0)} y} gcd`, "4"],
60
+ [["lcm"], `{${kPosInt(4)} x, ${kPosInt(6)} y} lcm`, "12"]
54
61
  ]) assert.equal(integer(run(aliases, source), source), expected, source);
55
62
  });
56
63
 
@@ -3,26 +3,27 @@ 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 { useSpecsFor } from "./helpers/cli.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
11
  const source = readFileSync(new URL("../lib/djson.k", import.meta.url), "utf8");
11
- let ieee = null;
12
+ let prev = null;
12
13
  for (const file of [
13
- "lib/bit.k",
14
- "lib/bits.k",
15
- "lib/list.k",
16
- "lib/btrie.k",
17
- "lib/string.k",
14
+ "core.k",
15
+ "lib/generic.k",
18
16
  "lib/ieee.k"
19
17
  ]) {
20
- ieee = loadLibrary(compileLibrary(readFileSync(new URL(`../${file}`, import.meta.url), "utf8"), {
18
+ const fileSource = readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
19
+ const uses = useSpecsFor(file);
20
+ prev = loadLibrary(compileLibrary(fileSource, {
21
21
  source: file,
22
- libraries: ieee ? [ieee] : []
22
+ libraries: prev ? [prev] : [],
23
+ use: uses
23
24
  }));
24
25
  }
25
- const library = loadLibrary(compileLibrary(source, { libraries: [ieee] }));
26
+ const library = loadLibrary(compileLibrary(source, { source: "lib/djson.k", libraries: [prev], use: useSpecsFor("lib/djson.k") }));
26
27
  const run = (op, value) => k.compile(library.relAlias[op], { libraries: [library] })(value);
27
28
 
28
29
  function method(op, json, { key, index, val } = {}) {
@@ -39,8 +40,8 @@ const doc = { name: "Alice", age: 30, tags: ["developer", "k"] };
39
40
  for (const key of ["name", "age"]) {
40
41
  assert.equal(result("get", doc, { key }), doc[key], key);
41
42
  }
42
- assert.ok(method("has?", doc, { key: "name" }));
43
- assert.equal(method("has?", doc, { key: "missing" }), undefined);
43
+ assert.ok(method("has_key?", doc, { key: "name" }));
44
+ assert.equal(method("has_key?", doc, { key: "missing" }), undefined);
44
45
  const withCity = result("set", doc, { key: "city", val: "Paris" });
45
46
  assert.deepEqual(withCity, { ...doc, city: "Paris" });
46
47
  const withoutAge = result("del", withCity, { key: "age" });
@@ -51,15 +52,15 @@ const list = [10, 20, 30];
51
52
  for (const [index, expected] of list.entries()) {
52
53
  assert.equal(result("nth", list, { index }), expected, `index ${index}`);
53
54
  }
54
- assert.ok(method("has_index?", list, { index: 1 }));
55
- assert.equal(method("has_index?", list, { index: 99 }), undefined);
55
+ assert.ok(method("has_nth?", list, { index: 1 }));
56
+ assert.equal(method("has_nth?", list, { index: 99 }), undefined);
56
57
  const updated = method("set_nth", list, { index: 1, val: 99 });
57
58
  assert.deepEqual(toJsonValue(updated), [10, 99, 30]);
58
59
  const deleted = run("del_nth", Value.product({
59
60
  json: updated, index: parseInt("1").value
60
61
  }));
61
62
  assert.deepEqual(toJsonValue(deleted), [10, 30]);
62
- assert.equal(run("has_index?", Value.product({
63
+ assert.equal(run("has_nth?", Value.product({
63
64
  json: deleted, index: parseInt("1").value
64
65
  })), undefined);
65
66
  assert.deepEqual(result("push", list, { val: 40 }), [10, 20, 30, 40]);
@@ -78,18 +79,14 @@ assert.deepEqual(keys, ["a", "b", "c"]);
78
79
  assert.deepEqual(toJsonValue(run("values", record)), [1, 2, 3]);
79
80
  assert.deepEqual(toJsonValue(run("values", fromJsonValue([100, 200]))), [100, 200]);
80
81
 
81
- for (const [value, expected] of [
82
- [{ x: 1, y: 2, z: 3, w: 4 }, 4], [["a", "b", "c"], 3], ["hello", 5]
83
- ]) assert.equal(toJsonValue(run("length", fromJsonValue(value))), expected);
84
-
85
82
  for (const [type, value] of [
86
83
  ["object", { a: 1 }], ["list", [1, 2]], ["string", "hi"],
87
84
  ["number", 3.14], ["bool", true], ["null", null]
88
85
  ]) {
89
86
  const input = fromJsonValue(value);
90
- assert.equal(run("type_of", input).tag, type);
91
- assert.ok(run(`is_${type}?`, input), type);
87
+ assert.ok(run(`${type}?`, input), type);
88
+ assert.ok(run("json?", input), `json? ${type}`);
92
89
  }
93
- assert.equal(run("is_object?", fromJsonValue([1, 2])), undefined);
94
- assert.equal(run("is_list?", fromJsonValue({ a: 1 })), undefined);
90
+ assert.equal(run("object?", fromJsonValue([1, 2])), undefined);
91
+ assert.equal(run("list?", fromJsonValue({ a: 1 })), undefined);
95
92
  console.log("dynamic JSON methods: ok");
@@ -0,0 +1,273 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ import { fileURLToPath } from "node:url";
6
+ import k from "../index.mjs";
7
+ import { compileLibrary, loadLibrary } from "../object.mjs";
8
+ import { createState, evaluateInput } from "../repl.mjs";
9
+ import { Value } from "../Value.mjs";
10
+ import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
11
+ import { fromJsonValue, toJsonValue } from "../codecs/djson.mjs";
12
+ import { parse as parseIntVal } from "../codecs/int.mjs";
13
+ import { stringValueToText, textToStringValue } from "../codecs/string-codec.mjs";
14
+ import { withCompiledLibrary, useSpecsFor } from "./helpers/cli.mjs";
15
+
16
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
17
+ const readSrc = (rel) => fs.readFileSync(path.join(root, rel), "utf8");
18
+
19
+ // 1. Dependency chain & convergence along core.k -> generic.k -> ieee.k -> djson.k
20
+ const coreSource = readSrc("core.k");
21
+ const genericSource = readSrc("lib/generic.k");
22
+ const ieeeSource = readSrc("lib/ieee.k");
23
+ const djsonSource = readSrc("lib/djson.k");
24
+
25
+ const coreLib = loadLibrary(compileLibrary(coreSource, { source: "core.k" }));
26
+ const genericLib = loadLibrary(compileLibrary(genericSource, {
27
+ source: "lib/generic.k",
28
+ libraries: [coreLib],
29
+ use: useSpecsFor("lib/generic.k")
30
+ }));
31
+ const ieeeLib = loadLibrary(compileLibrary(ieeeSource, {
32
+ source: "lib/ieee.k",
33
+ libraries: [coreLib],
34
+ use: useSpecsFor("lib/ieee.k")
35
+ }));
36
+ const djsonLib = loadLibrary(compileLibrary(djsonSource, {
37
+ source: "lib/djson.k",
38
+ libraries: [coreLib, genericLib, ieeeLib],
39
+ use: useSpecsFor("lib/djson.k")
40
+ }));
41
+
42
+ for (const [hash, rel] of Object.entries(djsonLib.rels)) {
43
+ assert.equal(
44
+ rel.typeDerivation?.status,
45
+ "converged",
46
+ `lib/djson.k relation ${hash} did not converge: ${JSON.stringify(rel.typeDerivation)}`
47
+ );
48
+ }
49
+
50
+ const runRel = (name, input) => {
51
+ const alias = djsonLib.relAlias[name];
52
+ assert.ok(alias, `missing exported relation '${name}' in lib/djson.k`);
53
+ return k.compile(alias, { libraries: [djsonLib] })(input);
54
+ };
55
+
56
+ // 2. REPL sequential :load contract
57
+ {
58
+ const state = createState();
59
+ for (const f of ["core.k", "lib/generic.k", "lib/ieee.k", "lib/djson.k"]) {
60
+ const out = await evaluateInput(`:load ${f}`, state);
61
+ assert.equal(out[0], `loaded ${f}`);
62
+ }
63
+ await evaluateInput(":codec codecs/utf8.mjs", state);
64
+ await evaluateInput(":codec codecs/djson.mjs", state);
65
+ await evaluateInput(':input utf8.mjs {"é":42,"😀":[true,null]}', state);
66
+ const res = await evaluateInput("parse_json", state);
67
+ assert.ok(!String(res[0]).startsWith("Error:"), `REPL parse_json failed: ${res}`);
68
+ assert.deepEqual(toJsonValue(state.value), { "é": 42, "😀": [true, null] });
69
+ }
70
+
71
+ // 3. Variant filters
72
+ for (const [filterName, jsonVal] of [
73
+ ["null?", null],
74
+ ["bool?", false],
75
+ ["number?", 3.5],
76
+ ["string?", "hi"],
77
+ ["list?", [1, 2]],
78
+ ["object?", { a: 1 }]
79
+ ]) {
80
+ assert.ok(runRel("json?", fromJsonValue(jsonVal)), `json? failed for ${JSON.stringify(jsonVal)}`);
81
+ assert.ok(runRel(filterName, fromJsonValue(jsonVal)), `${filterName} failed for ${JSON.stringify(jsonVal)}`);
82
+ }
83
+ assert.equal(runRel("null?", fromJsonValue(0)), undefined);
84
+ assert.equal(runRel("object?", fromJsonValue([])), undefined);
85
+
86
+ // 4. Container methods: Unicode object keys, array order >=5, push after del_nth
87
+ {
88
+ const objDoc = {
89
+ "": 0,
90
+ "a": 1,
91
+ "é": 2,
92
+ "語": 3,
93
+ "\uE123": 4,
94
+ "😀": 5,
95
+ "\u{21234}": 6
96
+ };
97
+ let objVal = fromJsonValue(objDoc);
98
+ for (const [key, expected] of Object.entries(objDoc)) {
99
+ const got = runRel("get", Value.product({ key: textToStringValue(key), json: objVal }));
100
+ assert.equal(toJsonValue(got), expected, `get failed for key ${JSON.stringify(key)}`);
101
+ }
102
+ assert.equal(
103
+ runRel("get", Value.product({ key: textToStringValue("missing"), json: objVal })),
104
+ undefined
105
+ );
106
+
107
+ // `keys`, `keys_raw`, `values` work across all Unicode planes
108
+ const ks = toJsonValue(runRel("keys", objVal));
109
+ const vs = toJsonValue(runRel("values", objVal));
110
+ assert.equal(ks.length, Object.keys(objDoc).length);
111
+ assert.deepEqual(new Set(ks), new Set(Object.keys(objDoc)));
112
+ const byKey = Object.fromEntries(ks.map((kStr, i) => [kStr, vs[i]]));
113
+ assert.deepEqual(byKey, objDoc);
114
+
115
+ const rawKeys = [];
116
+ let cursor = runRel("keys_raw", objVal);
117
+ while (cursor.tag === "cons") {
118
+ rawKeys.push(stringValueToText(cursor.value.product.car));
119
+ cursor = cursor.value.product.cdr;
120
+ }
121
+ assert.equal(cursor.tag, "nil");
122
+ assert.deepEqual(rawKeys, ks);
123
+
124
+ objVal = runRel("set", Value.product({
125
+ key: textToStringValue("🔑"),
126
+ val: fromJsonValue("ok"),
127
+ json: objVal
128
+ }));
129
+ assert.equal(
130
+ toJsonValue(runRel("get", Value.product({ key: textToStringValue("🔑"), json: objVal }))),
131
+ "ok"
132
+ );
133
+ objVal = runRel("del", Value.product({ key: textToStringValue("😀"), json: objVal }));
134
+ assert.equal(
135
+ runRel("get", Value.product({ key: textToStringValue("😀"), json: objVal })),
136
+ undefined
137
+ );
138
+
139
+ // Array `values` respects numerical index order even >= 5 elements
140
+ const arr5 = fromJsonValue([10, 20, 30, 40, 50]);
141
+ assert.deepEqual(toJsonValue(runRel("values", arr5)), [10, 20, 30, 40, 50]);
142
+
143
+ // `del_nth` followed by `push` appends at max_index + 1 instead of overwriting index 4 (`50`)
144
+ const sparse = runRel("del_nth", Value.product({
145
+ index: parseIntVal("1").value,
146
+ json: arr5
147
+ }));
148
+ assert.equal(
149
+ runRel("nth", Value.product({ index: parseIntVal("1").value, json: sparse })),
150
+ undefined
151
+ );
152
+ const pushed = runRel("push", Value.product({
153
+ val: fromJsonValue(99),
154
+ json: sparse
155
+ }));
156
+ assert.deepEqual(toJsonValue(pushed), [10, 30, 40, 50, 99]);
157
+ assert.deepEqual(
158
+ toJsonValue(runRel("push", Value.product({ val: fromJsonValue(7), json: fromJsonValue([]) }))),
159
+ [7]
160
+ );
161
+
162
+ const updated = runRel("set_nth", Value.product({
163
+ index: parseIntVal("2").value,
164
+ val: fromJsonValue(300),
165
+ json: arr5
166
+ }));
167
+ assert.deepEqual(toJsonValue(updated), [10, 20, 300, 40, 50]);
168
+ }
169
+
170
+ // 5. RFC 8259 JSON parser (`parse_json`) across Wasm, JS, and CLI
171
+ const wasmParse = await instantiateWasmArtifact(
172
+ await compileWasmArtifact(djsonLib.relAlias.parse_json, { libraries: [djsonLib] })
173
+ );
174
+
175
+ const validJsonSamples = [
176
+ "null",
177
+ " \t\n\r true \n",
178
+ "false",
179
+ "0",
180
+ "-0",
181
+ "42",
182
+ "-42",
183
+ "0.1",
184
+ "1e22",
185
+ "1e23",
186
+ "9007199254740992",
187
+ "9007199254740993",
188
+ "9007199254740995",
189
+ "5e-324",
190
+ "1.7976931348623157e+308",
191
+ "1e-400",
192
+ "-1e-400",
193
+ "0.000000000000000000001e20",
194
+ '""',
195
+ '"hello\\n\\t\\"\\\\\\/\\b\\f\\r"',
196
+ '"\\u00e9\\u8a9e\\ue123"',
197
+ '"\\uD83D\\uDE00\\uD844\\uDE34"',
198
+ '{"":0,"a":1,"é":2,"😀":3,"\u{21234}":4,"nested":[true,false,null,{}]}'
199
+ ];
200
+
201
+ for (const sample of validJsonSamples) {
202
+ const input = textToStringValue(sample);
203
+ const actual = toJsonValue(wasmParse.executeValue(input));
204
+ const expected = JSON.parse(sample);
205
+ assert.deepEqual(actual, expected, `parse_json mismatch on ${sample}`);
206
+ if (sample === "-0" || sample === "-1e-400") {
207
+ assert.ok(Object.is(actual, -0), `expected negative zero for ${sample}`);
208
+ } else if (sample === "0" || sample === "1e-400") {
209
+ assert.ok(Object.is(actual, 0), `expected positive zero for ${sample}`);
210
+ }
211
+ }
212
+
213
+ // JS execution parity on representative subset
214
+ for (const sample of ["null", "true", "-0", "0.1", "9007199254740993", '{"😀":"ok"}']) {
215
+ assert.deepEqual(
216
+ toJsonValue(runRel("parse_json", textToStringValue(sample))),
217
+ JSON.parse(sample)
218
+ );
219
+ }
220
+
221
+ const invalidJsonSamples = [
222
+ "",
223
+ " ",
224
+ "undefined",
225
+ "NaN",
226
+ "Infinity",
227
+ "-Infinity",
228
+ "1e309",
229
+ "-1e309",
230
+ "1e1000",
231
+ "+1",
232
+ ".5",
233
+ "1.",
234
+ "01",
235
+ "-01",
236
+ "1e",
237
+ "1e+",
238
+ "[1,]",
239
+ '{"a":1,}',
240
+ '"\\x"',
241
+ '"\\uD800"',
242
+ '"\\uDC00"',
243
+ '"\\uD800abc"',
244
+ '"line\nbreak"',
245
+ "1 2",
246
+ "{}[]"
247
+ ];
248
+
249
+ for (const bad of invalidJsonSamples) {
250
+ assert.equal(runRel("parse_json", textToStringValue(bad)), undefined, `expected failure for ${bad}`);
251
+ }
252
+
253
+ withCompiledLibrary(["core.k", "lib/generic.k", "lib/ieee.k", "lib/djson.k"], (library) => {
254
+ const utf8Cli = spawnSync(process.execPath, ["codecs/utf8.mjs", "--parse"], {
255
+ cwd: root,
256
+ input: '{"é":[1,"😀"]}\n'
257
+ });
258
+ assert.equal(utf8Cli.status, 0, utf8Cli.stderr?.toString());
259
+ const kCli = spawnSync(
260
+ process.execPath,
261
+ ["k.mjs", "--lib", library, "--use", "parse_json", "parse_json"],
262
+ { cwd: root, input: utf8Cli.stdout, maxBuffer: 8 * 1024 * 1024 }
263
+ );
264
+ assert.equal(kCli.status, 0, kCli.stderr?.toString());
265
+ const djsonCli = spawnSync(process.execPath, ["codecs/djson.mjs", "--print"], {
266
+ cwd: root,
267
+ input: kCli.stdout
268
+ });
269
+ assert.equal(djsonCli.status, 0, djsonCli.stderr?.toString());
270
+ assert.deepEqual(JSON.parse(djsonCli.stdout.toString("utf8")), { "é": [1, "😀"] });
271
+ });
272
+
273
+ console.log("lib/djson.k specification tests passed");