@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.
- package/CHANGELOG.md +17 -0
- package/DOCS/CODECS.md +42 -40
- package/DOCS/FILE_FORMATS.md +28 -25
- package/DOCS/GETTING_STARTED.md +10 -15
- package/DOCS/PATTERNS.md +3 -3
- package/DOCS/REPL.md +3 -6
- package/Examples/ieee-arithmetics.k +14 -29
- package/Examples/poly.k +18 -29
- package/README.md +14 -18
- package/backend-api.mjs +1 -3
- package/backends/llvm/src/cli.mjs +1 -2
- package/backends/llvm/tests/integration.sh +2 -6
- package/backends/wasm/tests/integration.sh +5 -10
- package/browser/shims/fs.mjs +2 -6
- package/canonical-pattern.mjs +9 -29
- package/compiler.mjs +22 -12
- package/harness/suites/poly.mjs +9 -11
- package/index.mjs +119 -50
- package/lib/djson.k +981 -295
- package/lib/generic.k +701 -0
- package/lib/ieee.k +662 -638
- package/lib/integer.k +542 -0
- package/object.mjs +19 -12
- package/objects/README.md +6 -6
- package/package.json +1 -1
- package/scripts/benchmark-idempotency.mjs +16 -17
- package/scripts/benchmark.mjs +39 -29
- package/scripts/build-repl-html.mjs +45 -35
- package/scripts/perf-ieee.mjs +1 -5
- package/scripts/perf-int.mjs +12 -27
- package/scripts/perf-multiplication.mjs +8 -9
- package/scripts/perf-poly.mjs +7 -10
- package/scripts/render-benchmark.mjs +1 -1
- package/scripts/run-tests.mjs +4 -2
- package/scripts/test-package.mjs +4 -10
- package/tests/README.md +4 -5
- package/tests/helpers/cli.mjs +30 -7
- package/tests/integration.sh +5 -10
- package/tests/test-arithmetics.mjs +23 -16
- package/tests/test-djson-methods.mjs +17 -25
- package/tests/test-djson.mjs +273 -0
- package/tests/test-generic.mjs +239 -0
- package/tests/test-ieee-arithmetic.mjs +1 -5
- package/tests/test-ieee.mjs +153 -0
- package/tests/test-integer.mjs +264 -0
- package/tests/test-k-object.mjs +12 -18
- package/tests/test-kvm-polymorphic.mjs +6 -7
- package/tests/test-lib.mjs +62 -52
- package/tests/test-library-isolation.mjs +349 -26
- package/tests/test-parse-json.mjs +15 -24
- package/tests/test-poly.mjs +21 -16
- package/tests/test-repl-html.mjs +39 -44
- package/tests/test-repl.mjs +46 -59
- package/DOCS/book-combined.md +0 -3786
- package/DOCS/dependency-graph.md +0 -144
- package/Examples/arithmetics.k +0 -108
- package/Examples/esc.k +0 -9
- package/lib/arithmetics.k +0 -286
- package/lib/bit.k +0 -68
- package/lib/bits.k +0 -227
- package/lib/btrie.k +0 -187
- package/lib/list.k +0 -49
- package/lib/string.k +0 -588
- package/tests/test-ieee-text.mjs +0 -74
- package/tests/test-karatsuba.mjs +0 -25
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 |
|
|
47
|
-
| JSON text parsing | `test-parse-json.mjs`: grammar, Unicode escapes, binary64
|
|
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
|
|
59
|
-
|
|
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
|
|
package/tests/helpers/cli.mjs
CHANGED
|
@@ -6,10 +6,37 @@ 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";
|
|
10
9
|
|
|
11
10
|
const root = fileURLToPath(new URL("../../", import.meta.url));
|
|
12
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
|
+
|
|
13
40
|
export function node(args, input) {
|
|
14
41
|
const result = spawnSync(process.execPath, args, {
|
|
15
42
|
cwd: root, input, maxBuffer: 64 * 1024 * 1024
|
|
@@ -33,12 +60,8 @@ export function withCompiledLibrary(source, test) {
|
|
|
33
60
|
const nextLibrary = path.join(dir, `library-${i}.klib`);
|
|
34
61
|
const args = ["objects/compile.mjs"];
|
|
35
62
|
if (library) args.push("--lib", library);
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
const raw = fs.readFileSync(filePath, "utf8");
|
|
39
|
-
for (const u of parseHeaderUses(raw)) {
|
|
40
|
-
args.push("--use", u.use);
|
|
41
|
-
}
|
|
63
|
+
for (const u of useSpecsFor(sources[i])) {
|
|
64
|
+
args.push("--use", u);
|
|
42
65
|
}
|
|
43
66
|
args.push(sources[i], nextLibrary);
|
|
44
67
|
succeeds(node(args), `compile ${sources[i]}`);
|
package/tests/integration.sh
CHANGED
|
@@ -85,10 +85,9 @@ compile_step() {
|
|
|
85
85
|
local prev="$1"
|
|
86
86
|
local src="$2"
|
|
87
87
|
local out="$3"
|
|
88
|
+
local use_spec="$4"
|
|
88
89
|
local uses=()
|
|
89
|
-
|
|
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)
|
|
90
|
+
[ -n "$use_spec" ] && uses=(--use "$use_spec")
|
|
92
91
|
if [ -n "$prev" ]; then
|
|
93
92
|
./objects/compile.mjs --lib "$prev" "${uses[@]}" "$src" "$out"
|
|
94
93
|
else
|
|
@@ -96,13 +95,9 @@ compile_step() {
|
|
|
96
95
|
fi
|
|
97
96
|
}
|
|
98
97
|
|
|
99
|
-
compile_step ""
|
|
100
|
-
compile_step "$TMP_DIR/
|
|
101
|
-
compile_step "$TMP_DIR/
|
|
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"
|
|
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?"
|
|
106
101
|
MUL=`./objects/extract-aliases.mjs "$TMP_DIR/ieee.klib" | grep '^mul = @' | sed 's/^mul = \(@[^;]*\);.*$/\1/'`
|
|
107
102
|
DIV=`./objects/extract-aliases.mjs "$TMP_DIR/ieee.klib" | grep '^div = @' | sed 's/^div = \(@[^;]*\);.*$/\1/'`
|
|
108
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
|
-
|
|
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", "
|
|
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 = ["
|
|
32
|
+
const aliases = ["divmod"];
|
|
24
33
|
for (const [projection, expected] of [
|
|
25
|
-
[".
|
|
34
|
+
[".q", a / b], [".r", a % b]
|
|
26
35
|
]) {
|
|
27
|
-
const source = `{() x, divisor
|
|
36
|
+
const source = `{() x, ${kPosInt(divisor)} y} divmod ${projection}`;
|
|
28
37
|
assert.equal(integer(run(aliases, source, x), source), String(expected),
|
|
29
|
-
`
|
|
38
|
+
`divmod(${x}, ${divisor}) ${projection}`);
|
|
30
39
|
}
|
|
31
40
|
}
|
|
32
41
|
|
|
33
42
|
for (const [aliases, source] of [
|
|
34
|
-
[["
|
|
35
|
-
[["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
|
-
[["
|
|
40
|
-
[["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"
|
|
49
|
-
[["gcd"
|
|
50
|
-
[["gcd"
|
|
51
|
-
[["lcm"
|
|
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,31 +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 {
|
|
6
|
+
import { useSpecsFor } from "./helpers/cli.mjs";
|
|
7
7
|
import { fromJsonValue, toJsonValue } from "../codecs/djson.mjs";
|
|
8
8
|
import { textToStringValue, stringValueToText } from "../codecs/runtime/unicode-string.mjs";
|
|
9
9
|
import { parse as parseInt } from "../codecs/int.mjs";
|
|
10
10
|
|
|
11
11
|
const source = readFileSync(new URL("../lib/djson.k", import.meta.url), "utf8");
|
|
12
|
-
let
|
|
12
|
+
let prev = null;
|
|
13
13
|
for (const file of [
|
|
14
|
-
"
|
|
15
|
-
"lib/
|
|
16
|
-
"lib/list.k",
|
|
17
|
-
"lib/btrie.k",
|
|
18
|
-
"lib/string.k",
|
|
14
|
+
"core.k",
|
|
15
|
+
"lib/generic.k",
|
|
19
16
|
"lib/ieee.k"
|
|
20
17
|
]) {
|
|
21
18
|
const fileSource = readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
|
|
22
|
-
const uses =
|
|
23
|
-
|
|
19
|
+
const uses = useSpecsFor(file);
|
|
20
|
+
prev = loadLibrary(compileLibrary(fileSource, {
|
|
24
21
|
source: file,
|
|
25
|
-
libraries:
|
|
22
|
+
libraries: prev ? [prev] : [],
|
|
26
23
|
use: uses
|
|
27
24
|
}));
|
|
28
25
|
}
|
|
29
|
-
const
|
|
30
|
-
const library = loadLibrary(compileLibrary(source, { libraries: [ieee], use: djsonUses }));
|
|
26
|
+
const library = loadLibrary(compileLibrary(source, { source: "lib/djson.k", libraries: [prev], use: useSpecsFor("lib/djson.k") }));
|
|
31
27
|
const run = (op, value) => k.compile(library.relAlias[op], { libraries: [library] })(value);
|
|
32
28
|
|
|
33
29
|
function method(op, json, { key, index, val } = {}) {
|
|
@@ -44,8 +40,8 @@ const doc = { name: "Alice", age: 30, tags: ["developer", "k"] };
|
|
|
44
40
|
for (const key of ["name", "age"]) {
|
|
45
41
|
assert.equal(result("get", doc, { key }), doc[key], key);
|
|
46
42
|
}
|
|
47
|
-
assert.ok(method("
|
|
48
|
-
assert.equal(method("
|
|
43
|
+
assert.ok(method("has_key?", doc, { key: "name" }));
|
|
44
|
+
assert.equal(method("has_key?", doc, { key: "missing" }), undefined);
|
|
49
45
|
const withCity = result("set", doc, { key: "city", val: "Paris" });
|
|
50
46
|
assert.deepEqual(withCity, { ...doc, city: "Paris" });
|
|
51
47
|
const withoutAge = result("del", withCity, { key: "age" });
|
|
@@ -56,15 +52,15 @@ const list = [10, 20, 30];
|
|
|
56
52
|
for (const [index, expected] of list.entries()) {
|
|
57
53
|
assert.equal(result("nth", list, { index }), expected, `index ${index}`);
|
|
58
54
|
}
|
|
59
|
-
assert.ok(method("
|
|
60
|
-
assert.equal(method("
|
|
55
|
+
assert.ok(method("has_nth?", list, { index: 1 }));
|
|
56
|
+
assert.equal(method("has_nth?", list, { index: 99 }), undefined);
|
|
61
57
|
const updated = method("set_nth", list, { index: 1, val: 99 });
|
|
62
58
|
assert.deepEqual(toJsonValue(updated), [10, 99, 30]);
|
|
63
59
|
const deleted = run("del_nth", Value.product({
|
|
64
60
|
json: updated, index: parseInt("1").value
|
|
65
61
|
}));
|
|
66
62
|
assert.deepEqual(toJsonValue(deleted), [10, 30]);
|
|
67
|
-
assert.equal(run("
|
|
63
|
+
assert.equal(run("has_nth?", Value.product({
|
|
68
64
|
json: deleted, index: parseInt("1").value
|
|
69
65
|
})), undefined);
|
|
70
66
|
assert.deepEqual(result("push", list, { val: 40 }), [10, 20, 30, 40]);
|
|
@@ -83,18 +79,14 @@ assert.deepEqual(keys, ["a", "b", "c"]);
|
|
|
83
79
|
assert.deepEqual(toJsonValue(run("values", record)), [1, 2, 3]);
|
|
84
80
|
assert.deepEqual(toJsonValue(run("values", fromJsonValue([100, 200]))), [100, 200]);
|
|
85
81
|
|
|
86
|
-
for (const [value, expected] of [
|
|
87
|
-
[{ x: 1, y: 2, z: 3, w: 4 }, 4], [["a", "b", "c"], 3], ["hello", 5]
|
|
88
|
-
]) assert.equal(toJsonValue(run("length", fromJsonValue(value))), expected);
|
|
89
|
-
|
|
90
82
|
for (const [type, value] of [
|
|
91
83
|
["object", { a: 1 }], ["list", [1, 2]], ["string", "hi"],
|
|
92
84
|
["number", 3.14], ["bool", true], ["null", null]
|
|
93
85
|
]) {
|
|
94
86
|
const input = fromJsonValue(value);
|
|
95
|
-
assert.
|
|
96
|
-
assert.ok(run(
|
|
87
|
+
assert.ok(run(`${type}?`, input), type);
|
|
88
|
+
assert.ok(run("json?", input), `json? ${type}`);
|
|
97
89
|
}
|
|
98
|
-
assert.equal(run("
|
|
99
|
-
assert.equal(run("
|
|
90
|
+
assert.equal(run("object?", fromJsonValue([1, 2])), undefined);
|
|
91
|
+
assert.equal(run("list?", fromJsonValue({ a: 1 })), undefined);
|
|
100
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");
|