@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
|
@@ -0,0 +1,239 @@
|
|
|
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 & rev_append
|
|
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("rev_append", Value.product({
|
|
106
|
+
xs: textToStringValue("ab"),
|
|
107
|
+
acc: textToStringValue("cd")
|
|
108
|
+
}))
|
|
109
|
+
),
|
|
110
|
+
"bacd"
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
// 3. bits[]: zero_bits?, trim_bits, inc_bits
|
|
114
|
+
assert.ok(runRel("zero_bits?", bitsFromStr("0")));
|
|
115
|
+
assert.equal(runRel("zero_bits?", bitsFromStr("1")), undefined);
|
|
116
|
+
assert.equal(bitsToStr(runRel("trim_bits", bitsFromStr("000"))), "0");
|
|
117
|
+
assert.equal(bitsToStr(runRel("trim_bits", bitsFromStr("00101"))), "101");
|
|
118
|
+
|
|
119
|
+
const expectedBits = ["0", "1", "10", "11", "100", "101", "110", "111", "1000"];
|
|
120
|
+
for (let i = 0; i < expectedBits.length - 1; i++) {
|
|
121
|
+
const next = runRel("inc_bits", bitsFromStr(expectedBits[i]));
|
|
122
|
+
assert.equal(bitsToStr(next), expectedBits[i + 1]);
|
|
123
|
+
}
|
|
124
|
+
assert.equal(bitsToStr(runRel("inc_bits", bitsFromStr("11111111"))), "100000000");
|
|
125
|
+
|
|
126
|
+
// 4. btrie[V]: empty, set, get, del pruning, entries_raw, max_key, bfs_values
|
|
127
|
+
let trie = runRel("btrie_empty", Value.product({}));
|
|
128
|
+
assert.equal(trie.tag, "nil");
|
|
129
|
+
assert.equal(
|
|
130
|
+
runRel("btrie_get", Value.product({ key: bitsFromStr("0"), trie })),
|
|
131
|
+
undefined
|
|
132
|
+
);
|
|
133
|
+
|
|
134
|
+
for (let i = 0; i < 5; i++) {
|
|
135
|
+
trie = runRel("btrie_set", Value.product({
|
|
136
|
+
key: parseIntVal(String(i)).value,
|
|
137
|
+
val: parseIntVal(String((i + 1) * 10)),
|
|
138
|
+
trie
|
|
139
|
+
}));
|
|
140
|
+
}
|
|
141
|
+
for (let i = 0; i < 5; i++) {
|
|
142
|
+
const got = runRel("btrie_get", Value.product({
|
|
143
|
+
key: parseIntVal(String(i)).value,
|
|
144
|
+
trie
|
|
145
|
+
}));
|
|
146
|
+
assert.deepEqual(got.toJSON(), parseIntVal(String((i + 1) * 10)).toJSON());
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Breadth-first order yields numeric index order [10, 20, 30, 40, 50] (not trie pre-order 0,1,2,4,3)
|
|
150
|
+
assert.deepEqual(
|
|
151
|
+
listToArray(runRel("btrie_bfs_values", trie)).map((v) => v.toJSON()),
|
|
152
|
+
[10, 20, 30, 40, 50].map((n) => parseIntVal(String(n)).toJSON())
|
|
153
|
+
);
|
|
154
|
+
|
|
155
|
+
// Deleting index 1 keeps canonical pruning, preserves sparse numeric order [10, 30, 40, 50],
|
|
156
|
+
// and max_key remains index 4 so subsequent insert computes 5.
|
|
157
|
+
const pruned = runRel("btrie_del", Value.product({
|
|
158
|
+
key: parseIntVal("1").value,
|
|
159
|
+
trie
|
|
160
|
+
}));
|
|
161
|
+
assert.equal(
|
|
162
|
+
runRel("btrie_get", Value.product({ key: parseIntVal("1").value, trie: pruned })),
|
|
163
|
+
undefined
|
|
164
|
+
);
|
|
165
|
+
assert.deepEqual(
|
|
166
|
+
listToArray(runRel("btrie_bfs_values", pruned)).map((v) => v.toJSON()),
|
|
167
|
+
[10, 30, 40, 50].map((n) => parseIntVal(String(n)).toJSON())
|
|
168
|
+
);
|
|
169
|
+
const maxOpt = runRel("btrie_max_key", pruned);
|
|
170
|
+
assert.equal(maxOpt.tag, "val");
|
|
171
|
+
assert.equal(bitsToStr(maxOpt.value), "100");
|
|
172
|
+
|
|
173
|
+
// Deleting every inserted key must collapse btrie back to exact |nil
|
|
174
|
+
let cleared = trie;
|
|
175
|
+
for (let i = 0; i < 5; i++) {
|
|
176
|
+
cleared = runRel("btrie_del", Value.product({
|
|
177
|
+
key: parseIntVal(String(i)).value,
|
|
178
|
+
trie: cleared
|
|
179
|
+
}));
|
|
180
|
+
}
|
|
181
|
+
assert.equal(cleared.tag, "nil");
|
|
182
|
+
assert.equal(runRel("btrie_max_key", cleared).tag, "nil");
|
|
183
|
+
|
|
184
|
+
// 5. unicode[] / string[]: eq_char? across all 6 variants & string_to_bits <-> bits_to_string bijection
|
|
185
|
+
const singleChar = (ch) => textToStringValue(ch).value.product.car;
|
|
186
|
+
const sampleChars = [
|
|
187
|
+
"a", // ascii
|
|
188
|
+
"é", // plane0
|
|
189
|
+
"語", // bmp_common h80_CF
|
|
190
|
+
"\u0905", // bmp_common h08_0F
|
|
191
|
+
"\u1234", // bmp_common h10_7F
|
|
192
|
+
"\uD123", // bmp_common hD0_D7
|
|
193
|
+
"\uF912", // bmp_common hF9
|
|
194
|
+
"\uFB12", // bmp_common hFA_FB
|
|
195
|
+
"\uFD12", // bmp_common hFC_FD
|
|
196
|
+
"\uFF12", // bmp_common hFE_FF
|
|
197
|
+
"\uE123", // bmp_private_use hE0_EF
|
|
198
|
+
"\uF123", // bmp_private_use hF0_F7
|
|
199
|
+
"\uF812", // bmp_private_use hF8
|
|
200
|
+
"😀", // supplementary_plane1
|
|
201
|
+
"\u{31234}", // supplementary_planes2_16 p02_03
|
|
202
|
+
"\u{51234}", // supplementary_planes2_16 p04_07
|
|
203
|
+
"\u{91234}", // supplementary_planes2_16 p08_0F
|
|
204
|
+
"\u{101234}" // supplementary_planes2_16 p10
|
|
205
|
+
];
|
|
206
|
+
|
|
207
|
+
for (let i = 0; i < sampleChars.length; i++) {
|
|
208
|
+
const c = singleChar(sampleChars[i]);
|
|
209
|
+
assert.ok(runRel("eq_char?", Value.product({ x: c, y: c })), `eq_char? failed on ${sampleChars[i]}`);
|
|
210
|
+
const other = singleChar(sampleChars[(i + 1) % sampleChars.length]);
|
|
211
|
+
assert.equal(
|
|
212
|
+
runRel("eq_char?", Value.product({ x: c, y: other })),
|
|
213
|
+
undefined,
|
|
214
|
+
`eq_char? falsely matched distinct chars`
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const mixedStrings = ["", "hello", ...sampleChars, sampleChars.join("")];
|
|
219
|
+
const wasmStrToBits = await instantiateWasmArtifact(
|
|
220
|
+
await compileWasmArtifact(genericLib.relAlias.string_to_bits, { libraries: [genericLib] })
|
|
221
|
+
);
|
|
222
|
+
for (const text of mixedStrings) {
|
|
223
|
+
const sVal = textToStringValue(text);
|
|
224
|
+
const encodedJs = runRel("string_to_bits", sVal);
|
|
225
|
+
const encodedWasm = wasmStrToBits.executeValue(sVal);
|
|
226
|
+
assert.equal(
|
|
227
|
+
bitsToStr(encodedJs),
|
|
228
|
+
stringToBitPath(text).join(""),
|
|
229
|
+
`string_to_bits bit path mismatch for ${JSON.stringify(text)}`
|
|
230
|
+
);
|
|
231
|
+
assert.equal(bitsToStr(encodedWasm), bitsToStr(encodedJs), "Wasm mismatch on string_to_bits");
|
|
232
|
+
assert.equal(
|
|
233
|
+
stringValueToText(runRel("bits_to_string", encodedJs)),
|
|
234
|
+
text,
|
|
235
|
+
`bits_to_string round-trip failed for ${JSON.stringify(text)}`
|
|
236
|
+
);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
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");
|
|
@@ -0,0 +1,264 @@
|
|
|
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 { Value } from "../Value.mjs";
|
|
9
|
+
import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
|
|
10
|
+
import { parse as parseIntVal, print as printIntVal } from "../codecs/int.mjs";
|
|
11
|
+
import { withCompiledLibrary } from "./helpers/cli.mjs";
|
|
12
|
+
|
|
13
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
14
|
+
const integerSource = fs.readFileSync(path.join(root, "lib/integer.k"), "utf8");
|
|
15
|
+
|
|
16
|
+
// Self-contained module: lib/integer.k compiles standalone and converges completely.
|
|
17
|
+
const intLib = loadLibrary(compileLibrary(integerSource, {
|
|
18
|
+
source: "lib/integer.k"
|
|
19
|
+
}));
|
|
20
|
+
|
|
21
|
+
for (const [hash, rel] of Object.entries(intLib.rels)) {
|
|
22
|
+
assert.equal(
|
|
23
|
+
rel.typeDerivation?.status,
|
|
24
|
+
"converged",
|
|
25
|
+
`lib/integer.k relation ${hash} did not converge: ${JSON.stringify(rel.typeDerivation)}`
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Karatsuba is implemented directly inside `times`; no separate `karatsuba` export.
|
|
30
|
+
assert.equal(intLib.relAlias.karatsuba, undefined, "lib/integer.k must expose `times`, not `karatsuba`");
|
|
31
|
+
|
|
32
|
+
const compileRel = (name) => {
|
|
33
|
+
const alias = intLib.relAlias[name];
|
|
34
|
+
assert.ok(alias, `missing exported relation '${name}' in lib/integer.k`);
|
|
35
|
+
return k.compile(alias, { libraries: [intLib] });
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const compiled = {
|
|
39
|
+
zero: compileRel("0"),
|
|
40
|
+
one: compileRel("1"),
|
|
41
|
+
nat: compileRel("nat"),
|
|
42
|
+
int: compileRel("int"),
|
|
43
|
+
isZero: compileRel("zero?"),
|
|
44
|
+
isPos: compileRel("pos?"),
|
|
45
|
+
isNeg: compileRel("neg?"),
|
|
46
|
+
abs: compileRel("abs"),
|
|
47
|
+
negate: compileRel("negate"),
|
|
48
|
+
inc: compileRel("inc"),
|
|
49
|
+
dec: compileRel("dec"),
|
|
50
|
+
cmp: compileRel("cmp"),
|
|
51
|
+
lt: compileRel("lt?"),
|
|
52
|
+
le: compileRel("le?"),
|
|
53
|
+
eq: compileRel("eq?"),
|
|
54
|
+
gt: compileRel("gt?"),
|
|
55
|
+
ge: compileRel("ge?"),
|
|
56
|
+
plus: compileRel("plus"),
|
|
57
|
+
minus: compileRel("minus"),
|
|
58
|
+
times: compileRel("times"),
|
|
59
|
+
divmod: compileRel("divmod"),
|
|
60
|
+
div: compileRel("div"),
|
|
61
|
+
mod: compileRel("mod"),
|
|
62
|
+
gcd: compileRel("gcd"),
|
|
63
|
+
lcm: compileRel("lcm")
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
function bitsFromStr(str) {
|
|
67
|
+
let v = Value.variant("_", Value.product({}));
|
|
68
|
+
for (let i = str.length - 1; i >= 0; i--) {
|
|
69
|
+
v = Value.variant(str[i], v);
|
|
70
|
+
}
|
|
71
|
+
return v;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const iVal = (n) => parseIntVal(String(n));
|
|
75
|
+
const toBig = (v) => BigInt(printIntVal(v));
|
|
76
|
+
const pair = (x, y) => Value.product({ x: iVal(x), y: iVal(y) });
|
|
77
|
+
|
|
78
|
+
function jsGcd(a, b) {
|
|
79
|
+
a = a < 0n ? -a : a;
|
|
80
|
+
b = b < 0n ? -b : b;
|
|
81
|
+
while (b !== 0n) {
|
|
82
|
+
[a, b] = [b, a % b];
|
|
83
|
+
}
|
|
84
|
+
return a;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function jsLcm(a, b) {
|
|
88
|
+
if (a === 0n || b === 0n) return 0n;
|
|
89
|
+
const aa = a < 0n ? -a : a;
|
|
90
|
+
const bb = b < 0n ? -b : b;
|
|
91
|
+
return (aa / jsGcd(aa, bb)) * bb;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// 1. Constants & normalization
|
|
95
|
+
assert.equal(toBig(compiled.zero(Value.product({}))), 0n);
|
|
96
|
+
assert.equal(toBig(compiled.one(Value.product({}))), 1n);
|
|
97
|
+
assert.equal(toBig(compiled.nat(bitsFromStr("000101"))), 5n);
|
|
98
|
+
assert.equal(toBig(compiled.nat(bitsFromStr("000"))), 0n);
|
|
99
|
+
assert.deepEqual(
|
|
100
|
+
compiled.int(Value.variant("-", bitsFromStr("000"))).toJSON(),
|
|
101
|
+
iVal(0n).toJSON(),
|
|
102
|
+
"int normalizer must canonicalize -0 to +0"
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
// 2. Predicates & unary relations
|
|
106
|
+
const unaryCases = [
|
|
107
|
+
0n,
|
|
108
|
+
1n,
|
|
109
|
+
-1n,
|
|
110
|
+
2n,
|
|
111
|
+
-2n,
|
|
112
|
+
255n,
|
|
113
|
+
-256n,
|
|
114
|
+
(1n << 64n) - 1n,
|
|
115
|
+
1n << 64n,
|
|
116
|
+
-(1n << 64n),
|
|
117
|
+
-((1n << 64n) - 1n)
|
|
118
|
+
];
|
|
119
|
+
|
|
120
|
+
for (const x of unaryCases) {
|
|
121
|
+
const vx = iVal(x);
|
|
122
|
+
assert.equal(Boolean(compiled.isZero(vx)), x === 0n, `zero?(${x})`);
|
|
123
|
+
assert.equal(Boolean(compiled.isPos(vx)), x > 0n, `pos?(${x})`);
|
|
124
|
+
assert.equal(Boolean(compiled.isNeg(vx)), x < 0n, `neg?(${x})`);
|
|
125
|
+
assert.equal(toBig(compiled.abs(vx)), x < 0n ? -x : x, `abs(${x})`);
|
|
126
|
+
assert.equal(toBig(compiled.negate(vx)), -x, `negate(${x})`);
|
|
127
|
+
assert.equal(toBig(compiled.inc(vx)), x + 1n, `inc(${x})`);
|
|
128
|
+
assert.equal(toBig(compiled.dec(vx)), x - 1n, `dec(${x})`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// 3. Ordering & binary arithmetic vs BigInt oracle (small, cross-sign, and large multi-limb)
|
|
132
|
+
const operands = [
|
|
133
|
+
0n,
|
|
134
|
+
1n,
|
|
135
|
+
-1n,
|
|
136
|
+
2n,
|
|
137
|
+
-2n,
|
|
138
|
+
3n,
|
|
139
|
+
-3n,
|
|
140
|
+
6n,
|
|
141
|
+
-7n,
|
|
142
|
+
42n,
|
|
143
|
+
-99n,
|
|
144
|
+
12345678901234567890n,
|
|
145
|
+
-98765432109876543210n,
|
|
146
|
+
(1n << 80n) - 3n,
|
|
147
|
+
-((1n << 95n) + 12345n),
|
|
148
|
+
(1n << 160n) + 999999999999999n
|
|
149
|
+
];
|
|
150
|
+
|
|
151
|
+
for (const x of operands) {
|
|
152
|
+
for (const y of operands) {
|
|
153
|
+
const inp = pair(x, y);
|
|
154
|
+
const expectedOrd = x < y ? "lt" : x > y ? "gt" : "eq";
|
|
155
|
+
assert.equal(compiled.cmp(inp).tag, expectedOrd, `cmp(${x}, ${y})`);
|
|
156
|
+
assert.equal(Boolean(compiled.lt(inp)), x < y, `lt?(${x}, ${y})`);
|
|
157
|
+
assert.equal(Boolean(compiled.le(inp)), x <= y, `le?(${x}, ${y})`);
|
|
158
|
+
assert.equal(Boolean(compiled.eq(inp)), x === y, `eq?(${x}, ${y})`);
|
|
159
|
+
assert.equal(Boolean(compiled.gt(inp)), x > y, `gt?(${x}, ${y})`);
|
|
160
|
+
assert.equal(Boolean(compiled.ge(inp)), x >= y, `ge?(${x}, ${y})`);
|
|
161
|
+
|
|
162
|
+
assert.equal(toBig(compiled.plus(inp)), x + y, `plus(${x}, ${y})`);
|
|
163
|
+
assert.equal(toBig(compiled.minus(inp)), x - y, `minus(${x}, ${y})`);
|
|
164
|
+
assert.equal(toBig(compiled.times(inp)), x * y, `times(${x}, ${y})`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Multi-limb Karatsuba squaring & asymmetric products (256-bit)
|
|
169
|
+
const bigA = (1n << 255n) - 19n;
|
|
170
|
+
const bigB = (1n << 220n) + 0xdeadbeefcafebaben;
|
|
171
|
+
assert.equal(toBig(compiled.times(pair(bigA, bigA))), bigA * bigA);
|
|
172
|
+
assert.equal(toBig(compiled.times(pair(bigA, -bigB))), bigA * -bigB);
|
|
173
|
+
assert.equal(toBig(compiled.times(pair(-bigA, bigB))), -bigA * bigB);
|
|
174
|
+
|
|
175
|
+
// 4. Fast binary division (truncating semantics), remainder, gcd, lcm
|
|
176
|
+
const divCases = [
|
|
177
|
+
[0n, 3n],
|
|
178
|
+
[0n, -3n],
|
|
179
|
+
[7n, 3n],
|
|
180
|
+
[-7n, 3n],
|
|
181
|
+
[7n, -3n],
|
|
182
|
+
[-7n, -3n],
|
|
183
|
+
[6n, -3n],
|
|
184
|
+
[-6n, 3n],
|
|
185
|
+
[3n, 7n],
|
|
186
|
+
[-3n, 7n],
|
|
187
|
+
[98765432109876543210987654321n, 123456789012345n],
|
|
188
|
+
[-98765432109876543210987654321n, 123456789012345n],
|
|
189
|
+
[(1n << 256n) + 123456789n, (1n << 100n) + 999999999999n],
|
|
190
|
+
[-((1n << 256n) + 123456789n), -((1n << 100n) + 999999999999n)]
|
|
191
|
+
];
|
|
192
|
+
|
|
193
|
+
for (const [x, y] of divCases) {
|
|
194
|
+
const inp = pair(x, y);
|
|
195
|
+
const dm = compiled.divmod(inp);
|
|
196
|
+
const q = toBig(dm.product.q);
|
|
197
|
+
const r = toBig(dm.product.r);
|
|
198
|
+
assert.equal(q, x / y, `divmod.q(${x}, ${y})`);
|
|
199
|
+
assert.equal(r, x % y, `divmod.r(${x}, ${y})`);
|
|
200
|
+
assert.equal(q * y + r, x, `divmod identity(${x}, ${y})`);
|
|
201
|
+
assert.equal(toBig(compiled.div(inp)), x / y, `div(${x}, ${y})`);
|
|
202
|
+
assert.equal(toBig(compiled.mod(inp)), x % y, `mod(${x}, ${y})`);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
for (const x of [0n, 7n, -7n]) {
|
|
206
|
+
assert.equal(compiled.divmod(pair(x, 0n)), undefined, `divmod(${x}, 0) must fail`);
|
|
207
|
+
assert.equal(compiled.div(pair(x, 0n)), undefined, `div(${x}, 0) must fail`);
|
|
208
|
+
assert.equal(compiled.mod(pair(x, 0n)), undefined, `mod(${x}, 0) must fail`);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const gcdCases = [
|
|
212
|
+
[0n, 0n],
|
|
213
|
+
[0n, -18n],
|
|
214
|
+
[-18n, 0n],
|
|
215
|
+
[-48n, 18n],
|
|
216
|
+
[48n, -18n],
|
|
217
|
+
[-12n, -18n],
|
|
218
|
+
[6n << 80n, -9n << 80n],
|
|
219
|
+
[104729n * 999983n, 999983n * 1299709n]
|
|
220
|
+
];
|
|
221
|
+
|
|
222
|
+
for (const [x, y] of gcdCases) {
|
|
223
|
+
const inp = pair(x, y);
|
|
224
|
+
assert.equal(toBig(compiled.gcd(inp)), jsGcd(x, y), `gcd(${x}, ${y})`);
|
|
225
|
+
assert.equal(toBig(compiled.lcm(inp)), jsLcm(x, y), `lcm(${x}, ${y})`);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// 5. Wasm & CLI chaining parity
|
|
229
|
+
const wasmInc = await instantiateWasmArtifact(
|
|
230
|
+
await compileWasmArtifact(intLib.relAlias.inc, { libraries: [intLib] })
|
|
231
|
+
);
|
|
232
|
+
assert.equal(toBig(wasmInc.executeValue(iVal(-1n))), 0n);
|
|
233
|
+
assert.equal(toBig(wasmInc.executeValue(iVal((1n << 64n) - 1n))), 1n << 64n);
|
|
234
|
+
|
|
235
|
+
const wasmSquare = await instantiateWasmArtifact(
|
|
236
|
+
await compileWasmArtifact(`{ () x, () y } ${intLib.relAlias.times}`, { libraries: [intLib] })
|
|
237
|
+
);
|
|
238
|
+
const sqInput = (1n << 140n) - 12345n;
|
|
239
|
+
assert.equal(toBig(wasmSquare.executeValue(iVal(sqInput))), sqInput * sqInput);
|
|
240
|
+
|
|
241
|
+
withCompiledLibrary(["lib/integer.k"], (library) => {
|
|
242
|
+
const parseCli = spawnSync(process.execPath, ["codecs/int.mjs", "--parse"], {
|
|
243
|
+
cwd: root,
|
|
244
|
+
input: "98765432109876543210\n"
|
|
245
|
+
});
|
|
246
|
+
assert.equal(parseCli.status, 0, parseCli.stderr?.toString());
|
|
247
|
+
const runCli = spawnSync(
|
|
248
|
+
process.execPath,
|
|
249
|
+
["k.mjs", "--lib", library, "--use", "times", "{ () x, () y } times"],
|
|
250
|
+
{ cwd: root, input: parseCli.stdout, maxBuffer: 8 * 1024 * 1024 }
|
|
251
|
+
);
|
|
252
|
+
assert.equal(runCli.status, 0, runCli.stderr?.toString());
|
|
253
|
+
const printCli = spawnSync(process.execPath, ["codecs/int.mjs", "--print"], {
|
|
254
|
+
cwd: root,
|
|
255
|
+
input: runCli.stdout
|
|
256
|
+
});
|
|
257
|
+
assert.equal(printCli.status, 0, printCli.stderr?.toString());
|
|
258
|
+
assert.equal(
|
|
259
|
+
printCli.stdout.toString("utf8").trim(),
|
|
260
|
+
String(98765432109876543210n * 98765432109876543210n)
|
|
261
|
+
);
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
console.log("lib/integer.k specification tests passed");
|