@fraczak/k 8.7.1 → 8.9.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 +28 -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/codecs/djson.mjs +2 -3
- package/codecs/int.mjs +66 -14
- package/compiler.mjs +22 -12
- package/harness/suites/poly.mjs +9 -11
- package/index.mjs +119 -50
- package/lib/djson.k +976 -288
- package/lib/generic.k +686 -0
- package/lib/ieee.k +658 -639
- package/lib/integer.k +536 -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-bigint-compare.mjs +279 -0
- 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 +16 -25
- package/tests/test-djson.mjs +272 -0
- package/tests/test-generic.mjs +237 -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/tests/test-structural-values.mjs +1 -1
- 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
|
@@ -0,0 +1,272 @@
|
|
|
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(filterName, fromJsonValue(jsonVal)), `${filterName} failed for ${JSON.stringify(jsonVal)}`);
|
|
81
|
+
}
|
|
82
|
+
assert.equal(runRel("null?", fromJsonValue(0)), undefined);
|
|
83
|
+
assert.equal(runRel("object?", fromJsonValue([])), undefined);
|
|
84
|
+
|
|
85
|
+
// 4. Container methods: Unicode object keys, array order >=5, push after del_nth
|
|
86
|
+
{
|
|
87
|
+
const objDoc = {
|
|
88
|
+
"": 0,
|
|
89
|
+
"a": 1,
|
|
90
|
+
"é": 2,
|
|
91
|
+
"語": 3,
|
|
92
|
+
"\uE123": 4,
|
|
93
|
+
"😀": 5,
|
|
94
|
+
"\u{21234}": 6
|
|
95
|
+
};
|
|
96
|
+
let objVal = fromJsonValue(objDoc);
|
|
97
|
+
for (const [key, expected] of Object.entries(objDoc)) {
|
|
98
|
+
const got = runRel("get", Value.product({ key: textToStringValue(key), json: objVal }));
|
|
99
|
+
assert.equal(toJsonValue(got), expected, `get failed for key ${JSON.stringify(key)}`);
|
|
100
|
+
}
|
|
101
|
+
assert.equal(
|
|
102
|
+
runRel("get", Value.product({ key: textToStringValue("missing"), json: objVal })),
|
|
103
|
+
undefined
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
// `keys`, `keys_raw`, `values` work across all Unicode planes
|
|
107
|
+
const ks = toJsonValue(runRel("keys", objVal));
|
|
108
|
+
const vs = toJsonValue(runRel("values", objVal));
|
|
109
|
+
assert.equal(ks.length, Object.keys(objDoc).length);
|
|
110
|
+
assert.deepEqual(new Set(ks), new Set(Object.keys(objDoc)));
|
|
111
|
+
const byKey = Object.fromEntries(ks.map((kStr, i) => [kStr, vs[i]]));
|
|
112
|
+
assert.deepEqual(byKey, objDoc);
|
|
113
|
+
|
|
114
|
+
const rawKeys = [];
|
|
115
|
+
let cursor = runRel("keys_raw", objVal);
|
|
116
|
+
while (cursor.tag === "cons") {
|
|
117
|
+
rawKeys.push(stringValueToText(cursor.value.product.car));
|
|
118
|
+
cursor = cursor.value.product.cdr;
|
|
119
|
+
}
|
|
120
|
+
assert.equal(cursor.tag, "nil");
|
|
121
|
+
assert.deepEqual(rawKeys, ks);
|
|
122
|
+
|
|
123
|
+
objVal = runRel("set", Value.product({
|
|
124
|
+
key: textToStringValue("🔑"),
|
|
125
|
+
val: fromJsonValue("ok"),
|
|
126
|
+
json: objVal
|
|
127
|
+
}));
|
|
128
|
+
assert.equal(
|
|
129
|
+
toJsonValue(runRel("get", Value.product({ key: textToStringValue("🔑"), json: objVal }))),
|
|
130
|
+
"ok"
|
|
131
|
+
);
|
|
132
|
+
objVal = runRel("del", Value.product({ key: textToStringValue("😀"), json: objVal }));
|
|
133
|
+
assert.equal(
|
|
134
|
+
runRel("get", Value.product({ key: textToStringValue("😀"), json: objVal })),
|
|
135
|
+
undefined
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
// Array `values` respects numerical index order even >= 5 elements
|
|
139
|
+
const arr5 = fromJsonValue([10, 20, 30, 40, 50]);
|
|
140
|
+
assert.deepEqual(toJsonValue(runRel("values", arr5)), [10, 20, 30, 40, 50]);
|
|
141
|
+
|
|
142
|
+
// `del_nth` followed by `push` appends at max_index + 1 instead of overwriting index 4 (`50`)
|
|
143
|
+
const sparse = runRel("del_nth", Value.product({
|
|
144
|
+
index: parseIntVal("1").value,
|
|
145
|
+
json: arr5
|
|
146
|
+
}));
|
|
147
|
+
assert.equal(
|
|
148
|
+
runRel("nth", Value.product({ index: parseIntVal("1").value, json: sparse })),
|
|
149
|
+
undefined
|
|
150
|
+
);
|
|
151
|
+
const pushed = runRel("push", Value.product({
|
|
152
|
+
val: fromJsonValue(99),
|
|
153
|
+
json: sparse
|
|
154
|
+
}));
|
|
155
|
+
assert.deepEqual(toJsonValue(pushed), [10, 30, 40, 50, 99]);
|
|
156
|
+
assert.deepEqual(
|
|
157
|
+
toJsonValue(runRel("push", Value.product({ val: fromJsonValue(7), json: fromJsonValue([]) }))),
|
|
158
|
+
[7]
|
|
159
|
+
);
|
|
160
|
+
|
|
161
|
+
const updated = runRel("set_nth", Value.product({
|
|
162
|
+
index: parseIntVal("2").value,
|
|
163
|
+
val: fromJsonValue(300),
|
|
164
|
+
json: arr5
|
|
165
|
+
}));
|
|
166
|
+
assert.deepEqual(toJsonValue(updated), [10, 20, 300, 40, 50]);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// 5. RFC 8259 JSON parser (`parse_json`) across Wasm, JS, and CLI
|
|
170
|
+
const wasmParse = await instantiateWasmArtifact(
|
|
171
|
+
await compileWasmArtifact(djsonLib.relAlias.parse_json, { libraries: [djsonLib] })
|
|
172
|
+
);
|
|
173
|
+
|
|
174
|
+
const validJsonSamples = [
|
|
175
|
+
"null",
|
|
176
|
+
" \t\n\r true \n",
|
|
177
|
+
"false",
|
|
178
|
+
"0",
|
|
179
|
+
"-0",
|
|
180
|
+
"42",
|
|
181
|
+
"-42",
|
|
182
|
+
"0.1",
|
|
183
|
+
"1e22",
|
|
184
|
+
"1e23",
|
|
185
|
+
"9007199254740992",
|
|
186
|
+
"9007199254740993",
|
|
187
|
+
"9007199254740995",
|
|
188
|
+
"5e-324",
|
|
189
|
+
"1.7976931348623157e+308",
|
|
190
|
+
"1e-400",
|
|
191
|
+
"-1e-400",
|
|
192
|
+
"0.000000000000000000001e20",
|
|
193
|
+
'""',
|
|
194
|
+
'"hello\\n\\t\\"\\\\\\/\\b\\f\\r"',
|
|
195
|
+
'"\\u00e9\\u8a9e\\ue123"',
|
|
196
|
+
'"\\uD83D\\uDE00\\uD844\\uDE34"',
|
|
197
|
+
'{"":0,"a":1,"é":2,"😀":3,"\u{21234}":4,"nested":[true,false,null,{}]}'
|
|
198
|
+
];
|
|
199
|
+
|
|
200
|
+
for (const sample of validJsonSamples) {
|
|
201
|
+
const input = textToStringValue(sample);
|
|
202
|
+
const actual = toJsonValue(wasmParse.executeValue(input));
|
|
203
|
+
const expected = JSON.parse(sample);
|
|
204
|
+
assert.deepEqual(actual, expected, `parse_json mismatch on ${sample}`);
|
|
205
|
+
if (sample === "-0" || sample === "-1e-400") {
|
|
206
|
+
assert.ok(Object.is(actual, -0), `expected negative zero for ${sample}`);
|
|
207
|
+
} else if (sample === "0" || sample === "1e-400") {
|
|
208
|
+
assert.ok(Object.is(actual, 0), `expected positive zero for ${sample}`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// JS execution parity on representative subset
|
|
213
|
+
for (const sample of ["null", "true", "-0", "0.1", "9007199254740993", '{"😀":"ok"}']) {
|
|
214
|
+
assert.deepEqual(
|
|
215
|
+
toJsonValue(runRel("parse_json", textToStringValue(sample))),
|
|
216
|
+
JSON.parse(sample)
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const invalidJsonSamples = [
|
|
221
|
+
"",
|
|
222
|
+
" ",
|
|
223
|
+
"undefined",
|
|
224
|
+
"NaN",
|
|
225
|
+
"Infinity",
|
|
226
|
+
"-Infinity",
|
|
227
|
+
"1e309",
|
|
228
|
+
"-1e309",
|
|
229
|
+
"1e1000",
|
|
230
|
+
"+1",
|
|
231
|
+
".5",
|
|
232
|
+
"1.",
|
|
233
|
+
"01",
|
|
234
|
+
"-01",
|
|
235
|
+
"1e",
|
|
236
|
+
"1e+",
|
|
237
|
+
"[1,]",
|
|
238
|
+
'{"a":1,}',
|
|
239
|
+
'"\\x"',
|
|
240
|
+
'"\\uD800"',
|
|
241
|
+
'"\\uDC00"',
|
|
242
|
+
'"\\uD800abc"',
|
|
243
|
+
'"line\nbreak"',
|
|
244
|
+
"1 2",
|
|
245
|
+
"{}[]"
|
|
246
|
+
];
|
|
247
|
+
|
|
248
|
+
for (const bad of invalidJsonSamples) {
|
|
249
|
+
assert.equal(runRel("parse_json", textToStringValue(bad)), undefined, `expected failure for ${bad}`);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
withCompiledLibrary(["core.k", "lib/generic.k", "lib/ieee.k", "lib/djson.k"], (library) => {
|
|
253
|
+
const utf8Cli = spawnSync(process.execPath, ["codecs/utf8.mjs", "--parse"], {
|
|
254
|
+
cwd: root,
|
|
255
|
+
input: '{"é":[1,"😀"]}\n'
|
|
256
|
+
});
|
|
257
|
+
assert.equal(utf8Cli.status, 0, utf8Cli.stderr?.toString());
|
|
258
|
+
const kCli = spawnSync(
|
|
259
|
+
process.execPath,
|
|
260
|
+
["k.mjs", "--lib", library, "--use", "parse_json", "parse_json"],
|
|
261
|
+
{ cwd: root, input: utf8Cli.stdout, maxBuffer: 8 * 1024 * 1024 }
|
|
262
|
+
);
|
|
263
|
+
assert.equal(kCli.status, 0, kCli.stderr?.toString());
|
|
264
|
+
const djsonCli = spawnSync(process.execPath, ["codecs/djson.mjs", "--print"], {
|
|
265
|
+
cwd: root,
|
|
266
|
+
input: kCli.stdout
|
|
267
|
+
});
|
|
268
|
+
assert.equal(djsonCli.status, 0, djsonCli.stderr?.toString());
|
|
269
|
+
assert.deepEqual(JSON.parse(djsonCli.stdout.toString("utf8")), { "é": [1, "😀"] });
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
console.log("lib/djson.k specification tests passed");
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import k from "../index.mjs";
|
|
6
|
+
import { compileLibrary, loadLibrary } from "../object.mjs";
|
|
7
|
+
import { Value } from "../Value.mjs";
|
|
8
|
+
import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
|
|
9
|
+
import { parse as parseIntVal } from "../codecs/int.mjs";
|
|
10
|
+
import { stringValueToText, textToStringValue } from "../codecs/string-codec.mjs";
|
|
11
|
+
import { stringToBitPath } from "../codecs/djson.mjs";
|
|
12
|
+
import { useSpecsFor } from "./helpers/cli.mjs";
|
|
13
|
+
|
|
14
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
15
|
+
const coreSource = fs.readFileSync(path.join(root, "core.k"), "utf8");
|
|
16
|
+
const genericPath = path.join(root, "lib/generic.k");
|
|
17
|
+
const genericSource = fs.readFileSync(genericPath, "utf8");
|
|
18
|
+
|
|
19
|
+
const coreLib = loadLibrary(compileLibrary(coreSource, { source: "core.k" }));
|
|
20
|
+
const genericLib = loadLibrary(compileLibrary(genericSource, {
|
|
21
|
+
source: "lib/generic.k",
|
|
22
|
+
libraries: [coreLib],
|
|
23
|
+
use: useSpecsFor("lib/generic.k")
|
|
24
|
+
}));
|
|
25
|
+
|
|
26
|
+
for (const [hash, rel] of Object.entries(genericLib.rels)) {
|
|
27
|
+
assert.equal(
|
|
28
|
+
rel.typeDerivation?.status,
|
|
29
|
+
"converged",
|
|
30
|
+
`lib/generic.k relation ${hash} did not converge: ${JSON.stringify(rel.typeDerivation)}`
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const runRel = (name, input) => {
|
|
35
|
+
const alias = genericLib.relAlias[name];
|
|
36
|
+
assert.ok(alias, `missing exported relation '${name}' in lib/generic.k`);
|
|
37
|
+
return k.compile(alias, { libraries: [genericLib] })(input);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function bitsFromStr(str) {
|
|
41
|
+
let v = Value.variant("_", Value.product({}));
|
|
42
|
+
for (let i = str.length - 1; i >= 0; i--) {
|
|
43
|
+
v = Value.variant(str[i], v);
|
|
44
|
+
}
|
|
45
|
+
return v;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function bitsToStr(v) {
|
|
49
|
+
let out = "";
|
|
50
|
+
let cur = v;
|
|
51
|
+
while (cur?.type === "<>" && cur.tag !== "_") {
|
|
52
|
+
out += cur.tag;
|
|
53
|
+
cur = cur.value;
|
|
54
|
+
}
|
|
55
|
+
assert.equal(cur?.tag, "_", "expected canonical bits leaf '_'");
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function listFrom(items) {
|
|
60
|
+
let v = Value.variant("nil", Value.product({}));
|
|
61
|
+
for (let i = items.length - 1; i >= 0; i--) {
|
|
62
|
+
v = Value.variant("cons", Value.product({ car: items[i], cdr: v }));
|
|
63
|
+
}
|
|
64
|
+
return v;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function listToArray(v) {
|
|
68
|
+
const out = [];
|
|
69
|
+
let cur = v;
|
|
70
|
+
while (cur?.type === "<>" && cur.tag === "cons") {
|
|
71
|
+
out.push(cur.value.product.car);
|
|
72
|
+
cur = cur.value.product.cdr;
|
|
73
|
+
}
|
|
74
|
+
assert.equal(cur?.tag, "nil", "expected proper list ending in nil");
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// 1. bool[], order[], opt[] filters and pattern existence
|
|
79
|
+
for (const pat of ["bool", "order", "opt", "btrie"]) {
|
|
80
|
+
assert.ok(genericLib.patternAlias[pat], `missing exported pattern '${pat}' in lib/generic.k`);
|
|
81
|
+
}
|
|
82
|
+
assert.equal(runRel("true?", Value.variant("true", Value.product({}))).tag, "true");
|
|
83
|
+
assert.equal(runRel("true?", Value.variant("false", Value.product({}))), undefined);
|
|
84
|
+
assert.equal(runRel("false?", Value.variant("false", Value.product({}))).tag, "false");
|
|
85
|
+
assert.equal(runRel("false?", Value.variant("true", Value.product({}))), undefined);
|
|
86
|
+
|
|
87
|
+
assert.equal(runRel("lt?", Value.variant("lt", Value.product({}))).tag, "lt");
|
|
88
|
+
assert.equal(runRel("eq?", Value.variant("eq", Value.product({}))).tag, "eq");
|
|
89
|
+
assert.equal(runRel("gt?", Value.variant("gt", Value.product({}))).tag, "gt");
|
|
90
|
+
assert.equal(runRel("lt?", Value.variant("gt", Value.product({}))), undefined);
|
|
91
|
+
|
|
92
|
+
assert.equal(runRel("nil?", Value.variant("nil", Value.product({}))).tag, "nil");
|
|
93
|
+
assert.equal(runRel("nil?", Value.variant("val", Value.product({}))), undefined);
|
|
94
|
+
|
|
95
|
+
// 2. list[X]: reverse
|
|
96
|
+
assert.deepEqual(listToArray(runRel("reverse", listFrom([]))).length, 0);
|
|
97
|
+
assert.deepEqual(
|
|
98
|
+
listToArray(runRel("reverse", textToStringValue("abc"))).map((ch) =>
|
|
99
|
+
stringValueToText(listFrom([ch]))
|
|
100
|
+
),
|
|
101
|
+
["c", "b", "a"]
|
|
102
|
+
);
|
|
103
|
+
assert.equal(
|
|
104
|
+
stringValueToText(
|
|
105
|
+
runRel("_reverse", Value.product({
|
|
106
|
+
xs: textToStringValue("ab"),
|
|
107
|
+
acc: textToStringValue("cd")
|
|
108
|
+
}))
|
|
109
|
+
),
|
|
110
|
+
"bacd"
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
// 3. bits[]: trim_bits, inc_bits
|
|
114
|
+
assert.equal(bitsToStr(runRel("trim_bits", bitsFromStr("000"))), "");
|
|
115
|
+
assert.equal(bitsToStr(runRel("trim_bits", bitsFromStr("00101"))), "101");
|
|
116
|
+
|
|
117
|
+
const expectedBits = ["", "1", "10", "11", "100", "101", "110", "111", "1000"];
|
|
118
|
+
for (let i = 0; i < expectedBits.length - 1; i++) {
|
|
119
|
+
const next = runRel("inc_bits", bitsFromStr(expectedBits[i]));
|
|
120
|
+
assert.equal(bitsToStr(next), expectedBits[i + 1]);
|
|
121
|
+
}
|
|
122
|
+
assert.equal(bitsToStr(runRel("inc_bits", bitsFromStr("11111111"))), "100000000");
|
|
123
|
+
|
|
124
|
+
// 4. btrie[V]: empty, set, get, del pruning, entries_raw, max_key, bfs_values
|
|
125
|
+
let trie = runRel("btrie_empty", Value.product({}));
|
|
126
|
+
assert.equal(trie.tag, "nil");
|
|
127
|
+
assert.equal(
|
|
128
|
+
runRel("btrie_get", Value.product({ key: bitsFromStr("0"), trie })),
|
|
129
|
+
undefined
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
for (let i = 0; i < 5; i++) {
|
|
133
|
+
trie = runRel("btrie_set", Value.product({
|
|
134
|
+
key: parseIntVal(String(i)).value,
|
|
135
|
+
val: parseIntVal(String((i + 1) * 10)),
|
|
136
|
+
trie
|
|
137
|
+
}));
|
|
138
|
+
}
|
|
139
|
+
for (let i = 0; i < 5; i++) {
|
|
140
|
+
const got = runRel("btrie_get", Value.product({
|
|
141
|
+
key: parseIntVal(String(i)).value,
|
|
142
|
+
trie
|
|
143
|
+
}));
|
|
144
|
+
assert.deepEqual(got.toJSON(), parseIntVal(String((i + 1) * 10)).toJSON());
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Breadth-first order yields numeric index order [10, 20, 30, 40, 50] (not trie pre-order 0,1,2,4,3)
|
|
148
|
+
assert.deepEqual(
|
|
149
|
+
listToArray(runRel("btrie_bfs_values", trie)).map((v) => v.toJSON()),
|
|
150
|
+
[10, 20, 30, 40, 50].map((n) => parseIntVal(String(n)).toJSON())
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
// Deleting index 1 keeps canonical pruning, preserves sparse numeric order [10, 30, 40, 50],
|
|
154
|
+
// and max_key remains index 4 so subsequent insert computes 5.
|
|
155
|
+
const pruned = runRel("btrie_del", Value.product({
|
|
156
|
+
key: parseIntVal("1").value,
|
|
157
|
+
trie
|
|
158
|
+
}));
|
|
159
|
+
assert.equal(
|
|
160
|
+
runRel("btrie_get", Value.product({ key: parseIntVal("1").value, trie: pruned })),
|
|
161
|
+
undefined
|
|
162
|
+
);
|
|
163
|
+
assert.deepEqual(
|
|
164
|
+
listToArray(runRel("btrie_bfs_values", pruned)).map((v) => v.toJSON()),
|
|
165
|
+
[10, 30, 40, 50].map((n) => parseIntVal(String(n)).toJSON())
|
|
166
|
+
);
|
|
167
|
+
const maxOpt = runRel("btrie_max_key", pruned);
|
|
168
|
+
assert.equal(maxOpt.tag, "val");
|
|
169
|
+
assert.equal(bitsToStr(maxOpt.value), "100");
|
|
170
|
+
|
|
171
|
+
// Deleting every inserted key must collapse btrie back to exact |nil
|
|
172
|
+
let cleared = trie;
|
|
173
|
+
for (let i = 0; i < 5; i++) {
|
|
174
|
+
cleared = runRel("btrie_del", Value.product({
|
|
175
|
+
key: parseIntVal(String(i)).value,
|
|
176
|
+
trie: cleared
|
|
177
|
+
}));
|
|
178
|
+
}
|
|
179
|
+
assert.equal(cleared.tag, "nil");
|
|
180
|
+
assert.equal(runRel("btrie_max_key", cleared).tag, "nil");
|
|
181
|
+
|
|
182
|
+
// 5. unicode[] / string[]: eq_char? across all 6 variants & string_to_bits <-> bits_to_string bijection
|
|
183
|
+
const singleChar = (ch) => textToStringValue(ch).value.product.car;
|
|
184
|
+
const sampleChars = [
|
|
185
|
+
"a", // ascii
|
|
186
|
+
"é", // plane0
|
|
187
|
+
"語", // bmp_common h80_CF
|
|
188
|
+
"\u0905", // bmp_common h08_0F
|
|
189
|
+
"\u1234", // bmp_common h10_7F
|
|
190
|
+
"\uD123", // bmp_common hD0_D7
|
|
191
|
+
"\uF912", // bmp_common hF9
|
|
192
|
+
"\uFB12", // bmp_common hFA_FB
|
|
193
|
+
"\uFD12", // bmp_common hFC_FD
|
|
194
|
+
"\uFF12", // bmp_common hFE_FF
|
|
195
|
+
"\uE123", // bmp_private_use hE0_EF
|
|
196
|
+
"\uF123", // bmp_private_use hF0_F7
|
|
197
|
+
"\uF812", // bmp_private_use hF8
|
|
198
|
+
"😀", // supplementary_plane1
|
|
199
|
+
"\u{31234}", // supplementary_planes2_16 p02_03
|
|
200
|
+
"\u{51234}", // supplementary_planes2_16 p04_07
|
|
201
|
+
"\u{91234}", // supplementary_planes2_16 p08_0F
|
|
202
|
+
"\u{101234}" // supplementary_planes2_16 p10
|
|
203
|
+
];
|
|
204
|
+
|
|
205
|
+
for (let i = 0; i < sampleChars.length; i++) {
|
|
206
|
+
const c = singleChar(sampleChars[i]);
|
|
207
|
+
assert.ok(runRel("eq_char?", Value.product({ x: c, y: c })), `eq_char? failed on ${sampleChars[i]}`);
|
|
208
|
+
const other = singleChar(sampleChars[(i + 1) % sampleChars.length]);
|
|
209
|
+
assert.equal(
|
|
210
|
+
runRel("eq_char?", Value.product({ x: c, y: other })),
|
|
211
|
+
undefined,
|
|
212
|
+
`eq_char? falsely matched distinct chars`
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const mixedStrings = ["", "hello", ...sampleChars, sampleChars.join("")];
|
|
217
|
+
const wasmStrToBits = await instantiateWasmArtifact(
|
|
218
|
+
await compileWasmArtifact(genericLib.relAlias.string_to_bits, { libraries: [genericLib] })
|
|
219
|
+
);
|
|
220
|
+
for (const text of mixedStrings) {
|
|
221
|
+
const sVal = textToStringValue(text);
|
|
222
|
+
const encodedJs = runRel("string_to_bits", sVal);
|
|
223
|
+
const encodedWasm = wasmStrToBits.executeValue(sVal);
|
|
224
|
+
assert.equal(
|
|
225
|
+
bitsToStr(encodedJs),
|
|
226
|
+
stringToBitPath(text).join(""),
|
|
227
|
+
`string_to_bits bit path mismatch for ${JSON.stringify(text)}`
|
|
228
|
+
);
|
|
229
|
+
assert.equal(bitsToStr(encodedWasm), bitsToStr(encodedJs), "Wasm mismatch on string_to_bits");
|
|
230
|
+
assert.equal(
|
|
231
|
+
stringValueToText(runRel("bits_to_string", encodedJs)),
|
|
232
|
+
text,
|
|
233
|
+
`bits_to_string round-trip failed for ${JSON.stringify(text)}`
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
console.log("lib/generic.k specification tests passed");
|
|
@@ -8,11 +8,7 @@ import { closedPatternToCodeHash, valueForCode } from "../repl-codecs.mjs";
|
|
|
8
8
|
|
|
9
9
|
const state = createState({ engine: "js" });
|
|
10
10
|
for (const file of [
|
|
11
|
-
"
|
|
12
|
-
"lib/bits.k",
|
|
13
|
-
"lib/list.k",
|
|
14
|
-
"lib/btrie.k",
|
|
15
|
-
"lib/string.k",
|
|
11
|
+
"core.k",
|
|
16
12
|
"lib/ieee.k",
|
|
17
13
|
"Examples/ieee-arithmetics.k"
|
|
18
14
|
]) {
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import k from "../index.mjs";
|
|
6
|
+
import { compileLibrary, loadLibrary } from "../object.mjs";
|
|
7
|
+
import { Value } from "../Value.mjs";
|
|
8
|
+
import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
|
|
9
|
+
import { decodeValueToNumber, encodeNumberToValue } from "../codecs/ieee.mjs";
|
|
10
|
+
import { parseIntStr } from "../codecs/int.mjs";
|
|
11
|
+
import { withCompiledLibrary, useSpecsFor } from "./helpers/cli.mjs";
|
|
12
|
+
|
|
13
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
14
|
+
const coreSource = fs.readFileSync(path.join(root, "core.k"), "utf8");
|
|
15
|
+
const ieeeSource = fs.readFileSync(path.join(root, "lib/ieee.k"), "utf8");
|
|
16
|
+
|
|
17
|
+
const coreLib = loadLibrary(compileLibrary(coreSource, { source: "core.k" }));
|
|
18
|
+
const ieeeLib = loadLibrary(compileLibrary(ieeeSource, {
|
|
19
|
+
source: "lib/ieee.k",
|
|
20
|
+
libraries: [coreLib],
|
|
21
|
+
use: useSpecsFor("lib/ieee.k")
|
|
22
|
+
}));
|
|
23
|
+
|
|
24
|
+
for (const [hash, rel] of Object.entries(ieeeLib.rels)) {
|
|
25
|
+
assert.equal(
|
|
26
|
+
rel.typeDerivation?.status,
|
|
27
|
+
"converged",
|
|
28
|
+
`lib/ieee.k relation ${hash} did not converge: ${JSON.stringify(rel.typeDerivation)}`
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
for (const forbidden of ["parseFloat64", "printFloat64", "parse_float64", "print_float64"]) {
|
|
33
|
+
assert.equal(ieeeLib.relAlias[forbidden], undefined, `lib/ieee.k must not define ${forbidden}`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
for (const pat of ["sign", "exp11", "frac52", "float64"]) {
|
|
37
|
+
assert.ok(ieeeLib.patternAlias[pat], `missing exported pattern '${pat}' in lib/ieee.k`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const runRel = (name, input) => {
|
|
41
|
+
const alias = ieeeLib.relAlias[name];
|
|
42
|
+
assert.ok(alias, `missing exported relation '${name}' in lib/ieee.k`);
|
|
43
|
+
return k.compile(alias, { libraries: [ieeeLib] })(input);
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
// 1. Constants & classification predicates
|
|
47
|
+
const pz = runRel("pos_zero", Value.product({}));
|
|
48
|
+
const nz = runRel("neg_zero", Value.product({}));
|
|
49
|
+
const pi = runRel("pos_inf", Value.product({}));
|
|
50
|
+
const ni = runRel("neg_inf", Value.product({}));
|
|
51
|
+
const qn = runRel("qnan", Value.product({}));
|
|
52
|
+
|
|
53
|
+
assert.ok(Object.is(decodeValueToNumber(pz), 0));
|
|
54
|
+
assert.ok(Object.is(decodeValueToNumber(nz), -0));
|
|
55
|
+
assert.equal(decodeValueToNumber(pi), Infinity);
|
|
56
|
+
assert.equal(decodeValueToNumber(ni), -Infinity);
|
|
57
|
+
assert.ok(Number.isNaN(decodeValueToNumber(qn)));
|
|
58
|
+
|
|
59
|
+
for (const [label, v, z, fin, inf, nan] of [
|
|
60
|
+
["+0", pz, true, true, false, false],
|
|
61
|
+
["-0", nz, true, true, false, false],
|
|
62
|
+
["1", encodeNumberToValue(1), false, true, false, false],
|
|
63
|
+
["5e-324", encodeNumberToValue(5e-324), false, true, false, false],
|
|
64
|
+
["MAX_VALUE", encodeNumberToValue(Number.MAX_VALUE), false, true, false, false],
|
|
65
|
+
["+Inf", pi, false, false, true, false],
|
|
66
|
+
["-Inf", ni, false, false, true, false],
|
|
67
|
+
["qNaN", qn, false, false, false, true]
|
|
68
|
+
]) {
|
|
69
|
+
assert.equal(Boolean(runRel("zero_float64?", v)), z, `zero_float64?(${label})`);
|
|
70
|
+
assert.equal(Boolean(runRel("finite_float64?", v)), fin, `finite_float64?(${label})`);
|
|
71
|
+
assert.equal(Boolean(runRel("inf_float64?", v)), inf, `inf_float64?(${label})`);
|
|
72
|
+
assert.equal(Boolean(runRel("nan_float64?", v)), nan, `nan_float64?(${label})`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
assert.ok(runRel("zero_exponent?", runRel("exp0", Value.product({}))));
|
|
76
|
+
assert.equal(runRel("all_ones_exponent?", runRel("exp0", Value.product({}))), undefined);
|
|
77
|
+
assert.ok(runRel("all_ones_exponent?", pi.product.exponent));
|
|
78
|
+
assert.equal(runRel("zero_exponent?", pi.product.exponent), undefined);
|
|
79
|
+
|
|
80
|
+
// 2. Sign negation
|
|
81
|
+
assert.ok(Object.is(decodeValueToNumber(runRel("negate_float64", pz)), -0));
|
|
82
|
+
assert.ok(Object.is(decodeValueToNumber(runRel("negate_float64", nz)), 0));
|
|
83
|
+
assert.equal(decodeValueToNumber(runRel("negate_float64", pi)), -Infinity);
|
|
84
|
+
assert.equal(decodeValueToNumber(runRel("negate_float64", ni)), Infinity);
|
|
85
|
+
assert.equal(decodeValueToNumber(runRel("negate_float64", encodeNumberToValue(3.25))), -3.25);
|
|
86
|
+
|
|
87
|
+
// 3. bits_to_float64: integer magnitudes & IEEE round-to-nearest ties-to-even
|
|
88
|
+
const bitsCases = [
|
|
89
|
+
[0n, 0],
|
|
90
|
+
[1n, 1],
|
|
91
|
+
[42n, 42],
|
|
92
|
+
[1n << 53n, 9007199254740992],
|
|
93
|
+
[(1n << 53n) + 1n, 9007199254740992], // tie -> even
|
|
94
|
+
[(1n << 53n) + 2n, 9007199254740994],
|
|
95
|
+
[(1n << 53n) + 3n, 9007199254740996], // tie -> even
|
|
96
|
+
[(1n << 1024n) - (1n << 971n), Number.MAX_VALUE],
|
|
97
|
+
[(1n << 1024n) - (1n << 970n), Infinity],
|
|
98
|
+
[1n << 1024n, Infinity]
|
|
99
|
+
];
|
|
100
|
+
|
|
101
|
+
for (const [n, expected] of bitsCases) {
|
|
102
|
+
const actual = decodeValueToNumber(runRel("bits_to_float64", parseIntStr(String(n)).value));
|
|
103
|
+
assert.ok(Object.is(actual, expected), `bits_to_float64(${n}) => ${actual}, expected ${expected}`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// 4. ratio_to_float64: exact fractions, ties-to-even, subnormals, underflow, overflow
|
|
107
|
+
const ratio = (sign, num, den) =>
|
|
108
|
+
Value.product({
|
|
109
|
+
sign: Value.variant(sign, Value.product({})),
|
|
110
|
+
num: parseIntStr(String(num)).value,
|
|
111
|
+
den: parseIntStr(String(den)).value
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
const ratioCases = [
|
|
115
|
+
["+", 0n, 1n, 0],
|
|
116
|
+
["-", 0n, 1n, -0],
|
|
117
|
+
["+", 1n, 2n, 0.5],
|
|
118
|
+
["-", 5n, 8n, -0.625],
|
|
119
|
+
["+", 1n, 10n, 0.1],
|
|
120
|
+
["-", 1n, 3n, -1 / 3],
|
|
121
|
+
["+", (1n << 53n) + 1n, 2n, 4503599627370496],
|
|
122
|
+
["+", (1n << 53n) + 3n, 2n, 4503599627370498],
|
|
123
|
+
["+", 1n, 1n << 1022n, 2 ** -1022], // smallest normal
|
|
124
|
+
["+", 1n, 1n << 1074n, 5e-324], // smallest subnormal
|
|
125
|
+
["+", 1n, 1n << 1075n, 0], // tie at half min-subnormal -> +0 (even)
|
|
126
|
+
["+", 3n, 1n << 1076n, 5e-324], // 0.75 * 2^-1074 -> 5e-324
|
|
127
|
+
["+", 3n, 1n << 1075n, 1e-323], // 1.5 * 2^-1074 -> 2 * 2^-1074 (tie to even)
|
|
128
|
+
["-", 1n, 1n << 1100n, -0], // underflow preserves sign
|
|
129
|
+
["+", 1n << 1024n, 1n, Infinity], // overflow -> +Inf
|
|
130
|
+
["-", 1n << 1024n, 1n, -Infinity] // overflow -> -Inf
|
|
131
|
+
];
|
|
132
|
+
|
|
133
|
+
for (const [sign, num, den, expected] of ratioCases) {
|
|
134
|
+
const actual = decodeValueToNumber(runRel("ratio_to_float64", ratio(sign, num, den)));
|
|
135
|
+
assert.ok(
|
|
136
|
+
Object.is(actual, expected),
|
|
137
|
+
`ratio_to_float64(${sign}${num}/${den}) => ${actual}, expected ${expected}`
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
assert.equal(runRel("ratio_to_float64", ratio("+", 1n, 0n)), undefined, "zero denominator must fail");
|
|
141
|
+
|
|
142
|
+
// 5. Wasm parity & CLI compilation
|
|
143
|
+
const wasmNegate = await instantiateWasmArtifact(
|
|
144
|
+
await compileWasmArtifact(ieeeLib.relAlias.negate_float64, { libraries: [ieeeLib] })
|
|
145
|
+
);
|
|
146
|
+
assert.ok(Object.is(decodeValueToNumber(wasmNegate.executeValue(pz)), -0));
|
|
147
|
+
assert.equal(decodeValueToNumber(wasmNegate.executeValue(encodeNumberToValue(2.5))), -2.5);
|
|
148
|
+
|
|
149
|
+
withCompiledLibrary(["core.k", "lib/ieee.k"], (library) => {
|
|
150
|
+
assert.ok(fs.existsSync(library));
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
console.log("lib/ieee.k specification tests passed");
|