@fraczak/k 8.5.1 → 8.6.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 +20 -0
- package/DOCS/CODECS.md +54 -0
- package/DOCS/REPL.md +1 -0
- package/Examples/djson.k +443 -328
- package/Examples/ieee-arithmetics.k +7183 -0
- package/Examples/ieee.k +895 -7374
- package/Examples/poly.k +1 -1
- package/README.md +3 -2
- package/backends/wasm/tests/integration.sh +2 -1
- package/browser/shims/fs.mjs +1 -0
- package/canonical-pattern.mjs +231 -2
- package/object.mjs +18 -9
- package/package.json +1 -1
- package/repl.mjs +91 -9
- package/scripts/benchmark-idempotency.mjs +20 -5
- package/scripts/benchmark.mjs +42 -10
- package/scripts/build-repl-html.mjs +4 -0
- package/scripts/perf-ieee.mjs +9 -16
- package/scripts/render-benchmark.mjs +1 -1
- package/scripts/run-tests.mjs +2 -0
- package/tests/README.md +2 -0
- package/tests/integration.sh +2 -1
- package/tests/test-djson-methods.mjs +11 -1
- package/tests/test-ieee-arithmetic.mjs +3 -1
- package/tests/test-ieee-text.mjs +59 -0
- package/tests/test-k-object.mjs +9 -0
- package/tests/test-parse-json.mjs +96 -0
- package/tests/test-repl-html.mjs +1 -0
- package/tests/test-repl.mjs +105 -2
package/scripts/benchmark.mjs
CHANGED
|
@@ -27,7 +27,10 @@ import {
|
|
|
27
27
|
} from "../backend-api.mjs";
|
|
28
28
|
import { parse as parseIntValue } from "../codecs/int.mjs";
|
|
29
29
|
import { parse as parseFloatValue } from "../codecs/ieee.mjs";
|
|
30
|
+
import { composePattern, edgeSubpattern } from "../Value.mjs";
|
|
30
31
|
import {
|
|
32
|
+
compileLibrary,
|
|
33
|
+
loadLibrary,
|
|
31
34
|
compileObjectBuffer as compileBackendObjectBuffer,
|
|
32
35
|
decodeObject as decodeBackendObject
|
|
33
36
|
} from "../object.mjs";
|
|
@@ -45,7 +48,9 @@ const scriptPath = fileURLToPath(import.meta.url);
|
|
|
45
48
|
const root = path.resolve(path.dirname(scriptPath), "..");
|
|
46
49
|
const kRoot = root;
|
|
47
50
|
const llvmRoot = path.join(root, "backends/llvm");
|
|
48
|
-
const resultsPath =
|
|
51
|
+
const resultsPath = process.env.K_BENCHMARK_RESULT_PATH
|
|
52
|
+
? path.resolve(process.env.K_BENCHMARK_RESULT_PATH)
|
|
53
|
+
: path.join(root, "benchmark-results.json");
|
|
49
54
|
|
|
50
55
|
const bigA = "1234567890".repeat(22);
|
|
51
56
|
const bigB = "9876543210".repeat(22);
|
|
@@ -146,11 +151,23 @@ function sha256() {
|
|
|
146
151
|
}
|
|
147
152
|
|
|
148
153
|
function suiteSourcePath(suite) {
|
|
149
|
-
return path.join(kRoot, suite
|
|
154
|
+
return path.join(kRoot, sourceNameForSuite(suite));
|
|
150
155
|
}
|
|
151
156
|
|
|
152
157
|
function sourceNameForSuite(suite) {
|
|
153
|
-
return suite === "ieee" ? "Examples/ieee.k" : "Examples/arithmetics.k";
|
|
158
|
+
return suite === "ieee" ? "Examples/ieee-arithmetics.k" : "Examples/arithmetics.k";
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
let ieeeDependencies;
|
|
162
|
+
function dependenciesForSuite(suite) {
|
|
163
|
+
if (suite !== "ieee") return [];
|
|
164
|
+
if (!ieeeDependencies) {
|
|
165
|
+
const core = loadLibrary(compileLibrary(fs.readFileSync(path.join(kRoot, "core.k"), "utf8")));
|
|
166
|
+
ieeeDependencies = [loadLibrary(compileLibrary(fs.readFileSync(path.join(kRoot, "Examples/ieee.k"), "utf8"), {
|
|
167
|
+
libraries: [core]
|
|
168
|
+
}))];
|
|
169
|
+
}
|
|
170
|
+
return ieeeDependencies;
|
|
154
171
|
}
|
|
155
172
|
|
|
156
173
|
function stripTrailingUnitMain(source) {
|
|
@@ -174,7 +191,7 @@ function canonicalPattern(propertyList) {
|
|
|
174
191
|
}
|
|
175
192
|
|
|
176
193
|
function wireInput(inputVal, relDef) {
|
|
177
|
-
const inputPattern = relationPattern(relDef, 0);
|
|
194
|
+
const inputPattern = inputVal.pattern || relationPattern(relDef, 0);
|
|
178
195
|
const inputWire = encodeToWire(inputVal, inputPattern);
|
|
179
196
|
return { inputPattern, inputWire };
|
|
180
197
|
}
|
|
@@ -182,7 +199,8 @@ function wireInput(inputVal, relDef) {
|
|
|
182
199
|
function backendObjectForCase(testCase) {
|
|
183
200
|
const source = sourceForCase(testCase);
|
|
184
201
|
return decodeBackendObject(compileBackendObjectBuffer(source, {
|
|
185
|
-
source: `${sourceNameForSuite(testCase.suite)}#${testCase.rel}
|
|
202
|
+
source: `${sourceNameForSuite(testCase.suite)}#${testCase.rel}`,
|
|
203
|
+
libraries: dependenciesForSuite(testCase.suite)
|
|
186
204
|
}));
|
|
187
205
|
}
|
|
188
206
|
|
|
@@ -454,33 +472,47 @@ async function prepareBackendRunner(job, relation, inputVal, state) {
|
|
|
454
472
|
|
|
455
473
|
async function prepareState(suite) {
|
|
456
474
|
const state = createState();
|
|
475
|
+
if (suite === "ieee") {
|
|
476
|
+
await evaluateInput(`:load ${path.join(kRoot, "core.k")}`, state);
|
|
477
|
+
await evaluateInput(`:load ${path.join(kRoot, "Examples/ieee.k")}`, state);
|
|
478
|
+
}
|
|
457
479
|
await evaluateInput(`:load ${suiteSourcePath(suite)}`, state);
|
|
458
480
|
return state;
|
|
459
481
|
}
|
|
460
482
|
|
|
461
483
|
function ieeeInput(testCase, state) {
|
|
462
|
-
return
|
|
484
|
+
return typedProduct({
|
|
463
485
|
x: parseFloatValue(testCase.input.x),
|
|
464
486
|
y: parseFloatValue(testCase.input.y)
|
|
465
487
|
});
|
|
466
488
|
}
|
|
467
489
|
|
|
490
|
+
function typedProduct(fields) {
|
|
491
|
+
return Value.product(fields, composePattern("closed-product",
|
|
492
|
+
Object.entries(fields).map(([label, value]) => [label, value.pattern])));
|
|
493
|
+
}
|
|
494
|
+
|
|
468
495
|
function arithmeticInput(testCase) {
|
|
469
496
|
const { shape } = testCase.input;
|
|
470
497
|
if (shape === "int") {
|
|
471
498
|
return parseIntValue(testCase.input.x);
|
|
472
499
|
}
|
|
473
500
|
if (shape === "int-pair") {
|
|
474
|
-
return
|
|
501
|
+
return typedProduct({
|
|
475
502
|
x: parseIntValue(testCase.input.x),
|
|
476
503
|
y: parseIntValue(testCase.input.y)
|
|
477
504
|
});
|
|
478
505
|
}
|
|
479
506
|
if (shape === "bits-pair") {
|
|
507
|
+
const x = parseIntValue(testCase.input.x);
|
|
508
|
+
const y = parseIntValue(testCase.input.y);
|
|
480
509
|
return Value.product({
|
|
481
|
-
x:
|
|
482
|
-
y:
|
|
483
|
-
}
|
|
510
|
+
x: x.value,
|
|
511
|
+
y: y.value
|
|
512
|
+
}, composePattern("closed-product", [
|
|
513
|
+
["x", edgeSubpattern(x.pattern, x.tag)],
|
|
514
|
+
["y", edgeSubpattern(y.pattern, y.tag)]
|
|
515
|
+
]));
|
|
484
516
|
}
|
|
485
517
|
throw new Error(`Unknown arithmetic input shape '${shape}'`);
|
|
486
518
|
}
|
|
@@ -82,6 +82,7 @@ if (fs.existsSync(coreKPath)) {
|
|
|
82
82
|
const verifiedExamples = [
|
|
83
83
|
"arithmetics.k",
|
|
84
84
|
"ieee.k",
|
|
85
|
+
"ieee-arithmetics.k",
|
|
85
86
|
"poly.k",
|
|
86
87
|
"karatsuba-mult.k",
|
|
87
88
|
"djson.k"
|
|
@@ -1691,6 +1692,7 @@ const htmlContent = `<!DOCTYPE html>
|
|
|
1691
1692
|
<option value="core.k">core.k</option>
|
|
1692
1693
|
<option value="arithmetics.k">arithmetics.k</option>
|
|
1693
1694
|
<option value="ieee.k">ieee.k</option>
|
|
1695
|
+
<option value="ieee-arithmetics.k">ieee-arithmetics.k</option>
|
|
1694
1696
|
<option value="poly.k">poly.k</option>
|
|
1695
1697
|
<option value="karatsuba-mult.k">karatsuba-mult.k</option>
|
|
1696
1698
|
<option value="djson.k">djson.k</option>
|
|
@@ -1936,6 +1938,8 @@ const htmlContent = `<!DOCTYPE html>
|
|
|
1936
1938
|
</tr>
|
|
1937
1939
|
<tr><td><code>:rel <name></code></td><td>Display definition of relation <code><name></code></td></tr>
|
|
1938
1940
|
<tr><td><code>:rels</code></td><td>List all relation aliases</td></tr>
|
|
1941
|
+
<tr><td><code>:limit [num|none]</code></td><td>Display or set maximum characters for value output</td></tr>
|
|
1942
|
+
<tr><td><code>:max-pat-length [num|none]</code></td><td>Display or set max inline pattern length in <code>:rel</code> (default <code>30</code>, alias <code>:maxPatLength</code>)</td></tr>
|
|
1939
1943
|
<tr><td><code>:codecs</code></td><td>List all loaded format codecs</td></tr>
|
|
1940
1944
|
<tr><td><code>:codec load <file.mjs></code></td><td>Load a codec from file (or load through Files)</td></tr>
|
|
1941
1945
|
<tr><td><code>:codec unload <file.mjs></code></td><td>Unload a loaded codec</td></tr>
|
package/scripts/perf-ieee.mjs
CHANGED
|
@@ -53,7 +53,7 @@ function printHelp() {
|
|
|
53
53
|
console.log(`Usage: node scripts/perf-ieee.mjs [options]
|
|
54
54
|
|
|
55
55
|
IEEE 754 Floating-Point Arithmetic Benchmark Harness.
|
|
56
|
-
Benchmarks add, sub, mul, and div on Examples/ieee.k across
|
|
56
|
+
Benchmarks add, sub, mul, and div on Examples/ieee-arithmetics.k across
|
|
57
57
|
Native JS, kVM interpreter, LLVM, Wasm, and PKIR backends.
|
|
58
58
|
|
|
59
59
|
Options:
|
|
@@ -221,10 +221,11 @@ function pkirLaneName() {
|
|
|
221
221
|
return "PKIR (Wasm persistent)";
|
|
222
222
|
}
|
|
223
223
|
|
|
224
|
-
console.log("==> Initializing
|
|
224
|
+
console.log("==> Initializing IEEE types and arithmetic");
|
|
225
225
|
const state = createState();
|
|
226
|
-
const
|
|
227
|
-
await evaluateInput(`:load ${
|
|
226
|
+
for (const name of ["core.k", "Examples/ieee.k", "Examples/ieee-arithmetics.k"]) {
|
|
227
|
+
await evaluateInput(`:load ${fileURLToPath(import.meta.resolve(`@fraczak/k/${name}`))}`, state);
|
|
228
|
+
}
|
|
228
229
|
|
|
229
230
|
function generatePerfK(values) {
|
|
230
231
|
const lines = [];
|
|
@@ -253,17 +254,9 @@ function generatePerfK(values) {
|
|
|
253
254
|
const perfKSource = generatePerfK(values);
|
|
254
255
|
await evaluateInput(perfKSource, state);
|
|
255
256
|
|
|
256
|
-
const ieeeRaw = fs.readFileSync(ieeePath, "utf8");
|
|
257
|
-
// Exclude trailing unassigned expression and comment block to ensure
|
|
258
|
-
// clean parse.
|
|
259
|
-
const endIdx = ieeeRaw.indexOf("\n()\n");
|
|
260
|
-
const ieeeBase = endIdx !== -1 ? ieeeRaw.slice(0, endIdx) : ieeeRaw;
|
|
261
|
-
const fullSource = `${ieeeBase}\n${perfKSource}\nperf_ieee`;
|
|
262
|
-
|
|
263
257
|
console.log("==> Preparing relation perf_ieee");
|
|
264
258
|
const relation = prepareRelation(state, "perf_ieee", {
|
|
265
|
-
|
|
266
|
-
sourceLabel: "@fraczak/k/Examples/ieee.k#perf_ieee"
|
|
259
|
+
sourceLabel: "@fraczak/k/Examples/ieee-arithmetics.k#perf_ieee"
|
|
267
260
|
});
|
|
268
261
|
codes.load(state.codes);
|
|
269
262
|
|
|
@@ -296,7 +289,7 @@ if (runLLVM) {
|
|
|
296
289
|
relHash: relation.relHash,
|
|
297
290
|
inputPattern,
|
|
298
291
|
cacheDir,
|
|
299
|
-
sourceLabel: "@fraczak/k/Examples/ieee.k#perf_ieee",
|
|
292
|
+
sourceLabel: "@fraczak/k/Examples/ieee-arithmetics.k#perf_ieee",
|
|
300
293
|
runtimeMode: llvmRuntimeMode,
|
|
301
294
|
clangOpt: opt,
|
|
302
295
|
usePKIR: false
|
|
@@ -327,7 +320,7 @@ if (runLLVMPKIR) {
|
|
|
327
320
|
relHash: relation.relHash,
|
|
328
321
|
inputPattern,
|
|
329
322
|
cacheDir,
|
|
330
|
-
sourceLabel: "@fraczak/k/Examples/ieee.k#perf_ieee",
|
|
323
|
+
sourceLabel: "@fraczak/k/Examples/ieee-arithmetics.k#perf_ieee",
|
|
331
324
|
runtimeMode: llvmRuntimeMode,
|
|
332
325
|
clangOpt: opt,
|
|
333
326
|
usePKIR: true
|
|
@@ -446,7 +439,7 @@ function printBenchmarkDescription() {
|
|
|
446
439
|
if (runPKIR) lanes.push(pkirLaneName());
|
|
447
440
|
|
|
448
441
|
console.log("==> Benchmark description");
|
|
449
|
-
console.log(" source: @fraczak/k/Examples/ieee.k#perf_ieee (single program)");
|
|
442
|
+
console.log(" source: @fraczak/k/Examples/ieee-arithmetics.k#perf_ieee (single program)");
|
|
450
443
|
console.log(` operations: ${ops.join(", ")}`);
|
|
451
444
|
console.log(` values: ${values.join(", ")}`);
|
|
452
445
|
console.log(` evaluation: 1 program call evaluating all ${totalOps} operations`);
|
package/scripts/run-tests.mjs
CHANGED
|
@@ -48,6 +48,8 @@ const tests = [
|
|
|
48
48
|
node,
|
|
49
49
|
["tests/test-djson-methods.mjs"]
|
|
50
50
|
],
|
|
51
|
+
["tests/test-parse-json.mjs", node, ["tests/test-parse-json.mjs"]],
|
|
52
|
+
["tests/test-ieee-text.mjs", node, ["tests/test-ieee-text.mjs"]],
|
|
51
53
|
["tests/test-deep-wire-value.mjs", node, ["tests/test-deep-wire-value.mjs"]],
|
|
52
54
|
["tests/test-k-object.mjs", node, ["tests/test-k-object.mjs"]],
|
|
53
55
|
["tests/test-kir.mjs", node, ["tests/test-kir.mjs"]],
|
package/tests/README.md
CHANGED
|
@@ -44,6 +44,8 @@ cases; shared helpers live outside the discovered directory.
|
|
|
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
46
|
| Libraries | Arithmetic, IEEE, list, Karatsuba, and dynamic JSON suites |
|
|
47
|
+
| JSON text parsing | `test-parse-json.mjs`: grammar, Unicode escapes, binary64 boundaries, Wasm, and CLI |
|
|
48
|
+
| IEEE text conversion | `test-ieee-text.mjs`: parsing, exact printing, special values, and binary64 round-trips |
|
|
47
49
|
|
|
48
50
|
`test-hash-fuzz.mjs` uses a deterministic generator to check renaming and
|
|
49
51
|
definition-order invariance; it is not a general cryptographic collision test.
|
package/tests/integration.sh
CHANGED
|
@@ -81,7 +81,8 @@ if ./kvm.mjs -k Examples/nat.k > "$TMP_DIR/dash-k-kvm.out" 2> "$TMP_DIR/dash-k-k
|
|
|
81
81
|
fi
|
|
82
82
|
grep -q -- '-k is no longer supported' "$TMP_DIR/dash-k-kvm.err"
|
|
83
83
|
echo
|
|
84
|
-
./objects/compile.mjs Examples/ieee.k "$TMP_DIR/ieee.klib"
|
|
84
|
+
./objects/compile.mjs --lib core.k Examples/ieee.k "$TMP_DIR/ieee-types.klib"
|
|
85
|
+
./objects/compile.mjs --lib "$TMP_DIR/ieee-types.klib" Examples/ieee-arithmetics.k "$TMP_DIR/ieee.klib"
|
|
85
86
|
MUL=`./objects/extract-aliases.mjs "$TMP_DIR/ieee.klib" | grep '^mul = @' | sed 's/^mul = \(@[^;]*\);.*$/\1/'`
|
|
86
87
|
DIV=`./objects/extract-aliases.mjs "$TMP_DIR/ieee.klib" | grep '^div = @' | sed 's/^div = \(@[^;]*\);.*$/\1/'`
|
|
87
88
|
ARG=0.12
|
|
@@ -8,7 +8,17 @@ import { textToStringValue, stringValueToText } from "../codecs/runtime/unicode-
|
|
|
8
8
|
import { parse as parseInt } from "../codecs/int.mjs";
|
|
9
9
|
|
|
10
10
|
const source = readFileSync(new URL("../Examples/djson.k", import.meta.url), "utf8");
|
|
11
|
-
const
|
|
11
|
+
const core = loadLibrary(compileLibrary(readFileSync(new URL("../core.k", import.meta.url), "utf8")));
|
|
12
|
+
const ieee = loadLibrary(compileLibrary(readFileSync(new URL("../Examples/ieee.k", import.meta.url), "utf8"), {
|
|
13
|
+
libraries: [core]
|
|
14
|
+
}));
|
|
15
|
+
// Resolve dependencies by hash even when the provider's friendly aliases are absent.
|
|
16
|
+
const canonicalTypes = {
|
|
17
|
+
...ieee,
|
|
18
|
+
patternAlias: {},
|
|
19
|
+
patterns: Object.fromEntries(Object.entries(ieee.patterns).filter(([name]) => name.startsWith("@")))
|
|
20
|
+
};
|
|
21
|
+
const library = loadLibrary(compileLibrary(source, { libraries: [canonicalTypes] }));
|
|
12
22
|
const run = (op, value) => k.compile(library.relAlias[op], { libraries: [library] })(value);
|
|
13
23
|
|
|
14
24
|
function method(op, json, { key, index, val } = {}) {
|
|
@@ -7,7 +7,9 @@ import { parse as parseFloat64, print as printFloat64 } from "../codecs/ieee.mjs
|
|
|
7
7
|
import { closedPatternToCodeHash, valueForCode } from "../repl-codecs.mjs";
|
|
8
8
|
|
|
9
9
|
const state = createState({ engine: "js" });
|
|
10
|
+
await evaluateInput(":load core.k", state);
|
|
10
11
|
await evaluateInput(":load Examples/ieee.k", state);
|
|
12
|
+
await evaluateInput(":load Examples/ieee-arithmetics.k", state);
|
|
11
13
|
|
|
12
14
|
for (const name of ["add", "sub", "mul", "div"]) {
|
|
13
15
|
assert.ok(state.relAliases[name], `Expected public IEEE relation '${name}'`);
|
|
@@ -59,7 +61,7 @@ async function assertOperation({ op, x, y, result, flags = null, projection = fa
|
|
|
59
61
|
}
|
|
60
62
|
|
|
61
63
|
const cases = [
|
|
62
|
-
// Keep this as a
|
|
64
|
+
// Keep this as a smoke matrix over the separate arithmetic library.
|
|
63
65
|
{ op: "add", x: "0.5", y: "0.25", result: "0.75", flags: "none", projection: true },
|
|
64
66
|
{ op: "add", x: "Infinity", y: "-Infinity", result: "NaN", flags: "invalid" },
|
|
65
67
|
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import k from "../index.mjs";
|
|
4
|
+
import { compileLibrary, loadLibrary } from "../object.mjs";
|
|
5
|
+
import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
|
|
6
|
+
import { encodeNumberToValue, decodeValueToNumber } from "../codecs/ieee.mjs";
|
|
7
|
+
import { textToStringValue, stringValueToText } from "../codecs/runtime/unicode-string.mjs";
|
|
8
|
+
|
|
9
|
+
const core = loadLibrary(compileLibrary(readFileSync(new URL("../core.k", import.meta.url), "utf8")));
|
|
10
|
+
const ieee = loadLibrary(compileLibrary(readFileSync(new URL("../Examples/ieee.k", import.meta.url), "utf8"), {
|
|
11
|
+
libraries: [core]
|
|
12
|
+
}));
|
|
13
|
+
assert.equal(ieee.relAlias.add, undefined, "Text conversion must not load IEEE arithmetic");
|
|
14
|
+
const parser = await instantiateWasmArtifact(await compileWasmArtifact(ieee.relAlias.parseFloat64, { libraries: [ieee] }));
|
|
15
|
+
const printer = await instantiateWasmArtifact(await compileWasmArtifact(ieee.relAlias.printFloat64, { libraries: [ieee] }));
|
|
16
|
+
const parse = text => parser.executeValue(textToStringValue(text));
|
|
17
|
+
const print = number => stringValueToText(printer.executeValue(encodeNumberToValue(number)));
|
|
18
|
+
const js = (name, value) => k.compile(ieee.relAlias[name], { libraries: [ieee] })(value);
|
|
19
|
+
|
|
20
|
+
for (const [text, number] of [
|
|
21
|
+
[" +12.5\n", 12.5], ["-0", -0], ["0.1", 0.1], ["1e309", Infinity],
|
|
22
|
+
["-1e999999999", -Infinity], ["+Infinity", Infinity], ["-Infinity", -Infinity]
|
|
23
|
+
]) {
|
|
24
|
+
assert.equal(decodeValueToNumber(parse(text)), number, text);
|
|
25
|
+
}
|
|
26
|
+
assert.ok(Number.isNaN(decodeValueToNumber(parse("NaN"))));
|
|
27
|
+
for (const text of ["", " ", ".1", "1.", "01", "1e", "1e+", "Infinityx", "NaNx", "1 2", "--1", "+-1", "-+1"]) {
|
|
28
|
+
assert.equal(parse(text), undefined, text);
|
|
29
|
+
}
|
|
30
|
+
for (const [number, text] of [
|
|
31
|
+
[0, "0"], [-0, "-0"], [1.5, "1.5"], [-12.5, "-12.5"],
|
|
32
|
+
[Infinity, "Infinity"], [-Infinity, "-Infinity"], [NaN, "NaN"],
|
|
33
|
+
[0.1, "0.1000000000000000055511151231257827021181583404541015625"]
|
|
34
|
+
]) assert.equal(print(number), text);
|
|
35
|
+
|
|
36
|
+
// Round-trip representative extremes and deterministic binary64 bit patterns.
|
|
37
|
+
const numbers = [
|
|
38
|
+
Number.MIN_VALUE, -Number.MIN_VALUE, 2.2250738585072014e-308,
|
|
39
|
+
Number.MAX_VALUE, -Number.MAX_VALUE, 1 / 3, 9007199254740992,
|
|
40
|
+
1e-100, 1e100, 1e20, -0
|
|
41
|
+
];
|
|
42
|
+
const view = new DataView(new ArrayBuffer(8));
|
|
43
|
+
let bits = 0x123456789abcdefn;
|
|
44
|
+
for (let i = 0; i < 16; i++) {
|
|
45
|
+
bits = BigInt.asUintN(64, bits * 6364136223846793005n + 1442695040888963407n);
|
|
46
|
+
view.setBigUint64(0, bits);
|
|
47
|
+
const value = view.getFloat64(0);
|
|
48
|
+
if (Number.isFinite(value)) numbers.push(value);
|
|
49
|
+
}
|
|
50
|
+
for (const number of numbers) {
|
|
51
|
+
const text = print(number);
|
|
52
|
+
assert.equal(Number(text), number, `Native round-trip: ${number}`);
|
|
53
|
+
assert.equal(decodeValueToNumber(parse(text)), number, `k round-trip: ${number}`);
|
|
54
|
+
}
|
|
55
|
+
for (const [text, number] of [["1.5", 1.5], ["-0", -0], ["Infinity", Infinity]]) {
|
|
56
|
+
assert.equal(decodeValueToNumber(js("parseFloat64", textToStringValue(text))), number);
|
|
57
|
+
assert.equal(stringValueToText(js("printFloat64", encodeNumberToValue(number))), text);
|
|
58
|
+
}
|
|
59
|
+
console.log("IEEE text: parsing, exact printing, special values and binary64 round-trips passed");
|
package/tests/test-k-object.mjs
CHANGED
|
@@ -9,6 +9,7 @@ import { patternToPropertyList } from "../codecs/runtime/pattern-json.mjs";
|
|
|
9
9
|
import {
|
|
10
10
|
compileObjectBuffer,
|
|
11
11
|
compileLibraryBuffer,
|
|
12
|
+
loadLibrary,
|
|
12
13
|
decodeObject,
|
|
13
14
|
objectToFunction,
|
|
14
15
|
runConvergedObject,
|
|
@@ -110,6 +111,14 @@ const arithmeticsRoundTripSource = decompileObjectBuffer(
|
|
|
110
111
|
);
|
|
111
112
|
assert.equal(arithmeticsRoundTripSource, arithmeticsDecompiledSource);
|
|
112
113
|
|
|
114
|
+
// Imported relations have canonical keys without local aliases. They still
|
|
115
|
+
// need legal definition names when the complete library is decompiled.
|
|
116
|
+
const imported = loadLibrary(decodeObject(compileLibraryBuffer("leaf = {} |leaf;")));
|
|
117
|
+
const derived = compileLibraryBuffer(`wrap = ${imported.relAlias.leaf} |wrapped;`, { libraries: [imported] });
|
|
118
|
+
const importedSource = decompileObjectBuffer(derived);
|
|
119
|
+
const importedRoundTrip = decompileObjectBuffer(compileLibraryBuffer(importedSource));
|
|
120
|
+
assert.equal(importedRoundTrip, importedSource);
|
|
121
|
+
|
|
113
122
|
assert.throws(() => k.compile("@A = (); @A"), /Parse error/);
|
|
114
123
|
assert.throws(() => k.compile("$ @A = {}; $@A"), /Lexical error/);
|
|
115
124
|
assert.deepEqual(k.compile("7jfi = ?X0; 7jfi")(Value.product({})).toJSON(), {});
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { readFileSync, mkdtempSync, rmSync } from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
import k from "../index.mjs";
|
|
7
|
+
import { compileLibrary, loadLibrary } from "../object.mjs";
|
|
8
|
+
import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
|
|
9
|
+
import { fromJsonValue } from "../codecs/djson.mjs";
|
|
10
|
+
import { textToStringValue } from "../codecs/runtime/unicode-string.mjs";
|
|
11
|
+
import { parse as utf8 } from "../codecs/utf8.mjs";
|
|
12
|
+
import { encodeToWire, decodeWire } from "../codecs/runtime/codec-sdk.mjs";
|
|
13
|
+
|
|
14
|
+
const core = loadLibrary(compileLibrary(readFileSync(new URL("../core.k", import.meta.url), "utf8")));
|
|
15
|
+
const ieee = loadLibrary(compileLibrary(readFileSync(new URL("../Examples/ieee.k", import.meta.url), "utf8"), {
|
|
16
|
+
libraries: [core]
|
|
17
|
+
}));
|
|
18
|
+
const library = loadLibrary(compileLibrary(readFileSync(new URL("../Examples/djson.k", import.meta.url), "utf8"), {
|
|
19
|
+
libraries: [ieee]
|
|
20
|
+
}));
|
|
21
|
+
const wasm = await instantiateWasmArtifact(await compileWasmArtifact(library.relAlias.parseJson, { libraries: [library] }));
|
|
22
|
+
const fast = text => wasm.executeValue(textToStringValue(text));
|
|
23
|
+
const parse = k.compile(library.relAlias.parseJson, { libraries: [library] });
|
|
24
|
+
const payload = value => JSON.parse(JSON.stringify(value));
|
|
25
|
+
function check(text, evaluate = text => parse(textToStringValue(text))) {
|
|
26
|
+
const actual = evaluate(text);
|
|
27
|
+
assert.ok(actual, text);
|
|
28
|
+
assert.deepEqual(payload(actual), payload(fromJsonValue(JSON.parse(text))), text);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
for (const text of [
|
|
32
|
+
" \t\r\n null \t", "true", "false", '""', "[ \t ]", "{ \r\n }",
|
|
33
|
+
'[[],{},null,true,false,[1,-2,3.14]]',
|
|
34
|
+
'{"a":1,"a":{"new":"type"},"":0,"__proto__":{"safe":true},"emoji😀":[1,2]}',
|
|
35
|
+
String.raw`"\"\\\/\b\f\n\r\t"`,
|
|
36
|
+
String.raw`"\uD834\uDD1E\uFAbC"`,
|
|
37
|
+
"0", "-0", "-42", "0.1", "1.25", "12E-2", "1e+20",
|
|
38
|
+
"0e999999999999999999", "-0.00e-999999999999999999", "-1e-999999999999999999"
|
|
39
|
+
]) check(text);
|
|
40
|
+
|
|
41
|
+
// Exercise every Unicode encoding partition, including surrogate pairs.
|
|
42
|
+
const scalars = [
|
|
43
|
+
0, 0x1f, 0x7f, 0x80, 0x7ff, 0x800, 0xfff, 0x1000, 0x7fff,
|
|
44
|
+
0x8000, 0xcfff, 0xd000, 0xd7ff, 0xe000, 0xefff, 0xf000, 0xf7ff,
|
|
45
|
+
0xf800, 0xf8ff, 0xf900, 0xf9ff, 0xfa00, 0xfbff, 0xfc00, 0xfdff,
|
|
46
|
+
0xfe00, 0xffff, 0x10000, 0x1ffff, 0x20000, 0x3ffff, 0x40000,
|
|
47
|
+
0x7ffff, 0x80000, 0xfffff, 0x100000, 0x10ffff
|
|
48
|
+
];
|
|
49
|
+
for (const scalar of scalars) {
|
|
50
|
+
const text = JSON.stringify(String.fromCodePoint(scalar));
|
|
51
|
+
check(text);
|
|
52
|
+
check(text.replace(/[\u007f-\uffff]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`));
|
|
53
|
+
}
|
|
54
|
+
for (const text of [
|
|
55
|
+
"", " ", "nil", "True", "+1", "01", "-01", ".1", "1.", "1e", "1e+", "--1", "0x10",
|
|
56
|
+
"NaN", "Infinity", "1e999999999999999999", "[1,]", "[,1]", "[1 2]", "[",
|
|
57
|
+
'{"x":1,}', "{x:1}", '{"x" 1}', "{", "null true", '"x"x', '"unterminated',
|
|
58
|
+
String.raw`"\x20"`, String.raw`"\u123"`, String.raw`"\uZZZZ"`,
|
|
59
|
+
String.raw`"\uD800"`, String.raw`"\uDC00"`, String.raw`"\uD800\u0041"`,
|
|
60
|
+
String.raw`"\uDC00\uD800"`, '"line\nfeed"', "\u00a0null"
|
|
61
|
+
]) assert.equal(parse(textToStringValue(text)), undefined, JSON.stringify(text));
|
|
62
|
+
|
|
63
|
+
// Use compiled Wasm for the expensive exact-rational boundary cases.
|
|
64
|
+
for (const text of [
|
|
65
|
+
"9007199254740993", "9007199254740995", "1.9999999999999999", "9.9999999999999999",
|
|
66
|
+
"1.00000000000000011102230246251565404236316680908203125",
|
|
67
|
+
"1.00000000000000011102230246251565404236316680908203126",
|
|
68
|
+
"5e-324", "2e-324", "2.2250738585072014e-308", "1.7976931348623157e308"
|
|
69
|
+
]) check(text, fast);
|
|
70
|
+
for (const text of ["1e309", "-1.8e308"]) assert.equal(fast(text), undefined, text);
|
|
71
|
+
|
|
72
|
+
const text = '{"answer":42,"ok":true}';
|
|
73
|
+
const scratch = mkdtempSync(path.join(os.tmpdir(), "k-json-test-"));
|
|
74
|
+
try {
|
|
75
|
+
const artifact = path.join(scratch, "djson.klib");
|
|
76
|
+
const ieeeArtifact = path.join(scratch, "ieee.klib");
|
|
77
|
+
for (const args of [
|
|
78
|
+
["--lib", "core.k", "Examples/ieee.k", ieeeArtifact],
|
|
79
|
+
["--lib", ieeeArtifact, "Examples/djson.k", artifact]
|
|
80
|
+
]) {
|
|
81
|
+
const built = spawnSync(process.execPath, ["objects/compile.mjs", ...args], {
|
|
82
|
+
cwd: new URL("..", import.meta.url)
|
|
83
|
+
});
|
|
84
|
+
assert.ifError(built.error);
|
|
85
|
+
assert.equal(built.status, 0, built.stderr.toString());
|
|
86
|
+
}
|
|
87
|
+
const cli = spawnSync(process.execPath, ["k.mjs", "--lib", artifact, "--export", "parseJson", "parseJson"], {
|
|
88
|
+
cwd: new URL("..", import.meta.url), input: encodeToWire(utf8(text))
|
|
89
|
+
});
|
|
90
|
+
assert.ifError(cli.error);
|
|
91
|
+
assert.equal(cli.status, 0, cli.stderr.toString());
|
|
92
|
+
assert.deepEqual(payload(decodeWire(cli.stdout).value), payload(fromJsonValue(JSON.parse(text))));
|
|
93
|
+
} finally {
|
|
94
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
95
|
+
}
|
|
96
|
+
console.log("JSON text parser: grammar, Unicode, binary64 rounding, Wasm and CLI passed");
|
package/tests/test-repl-html.mjs
CHANGED
package/tests/test-repl.mjs
CHANGED
|
@@ -26,11 +26,19 @@ const state = createState();
|
|
|
26
26
|
|
|
27
27
|
let output = await evaluateInput("zero = {} | zero;", state);
|
|
28
28
|
output = await evaluateInput(":rel zero", state);
|
|
29
|
-
assert.
|
|
29
|
+
assert.equal(
|
|
30
|
+
output[0],
|
|
31
|
+
"zero = ?(...) {} |zero ?<{} zero, ...>; " +
|
|
32
|
+
"-- @ZdauiYp7DqPGmHkUiG8yuWz4ZbEgvxZyNkBAmJ4ENhAX"
|
|
33
|
+
);
|
|
30
34
|
|
|
31
35
|
output = await evaluateInput("succ = | succ;", state);
|
|
32
36
|
output = await evaluateInput(":rel succ", state);
|
|
33
|
-
assert.
|
|
37
|
+
assert.equal(
|
|
38
|
+
output[0],
|
|
39
|
+
"succ = ?X0 |succ ?<X0 succ, ...>; " +
|
|
40
|
+
"-- @SwjzXdcxv8ZbpCkF4cXGtgKkqPTfYqGGP5erQE7DCCsj"
|
|
41
|
+
);
|
|
34
42
|
|
|
35
43
|
output = await evaluateInput(":rels", state);
|
|
36
44
|
assert.match(output[0], /^zero = @/m);
|
|
@@ -400,6 +408,7 @@ output = await evaluateInput("test utf8", utf8AutoState);
|
|
|
400
408
|
assert.match(output[0], /utf8\.mjs: test utf8/);
|
|
401
409
|
|
|
402
410
|
const ieeeAutoState = createState();
|
|
411
|
+
await evaluateInput(":load core.k", ieeeAutoState);
|
|
403
412
|
await evaluateInput(":load Examples/ieee.k", ieeeAutoState);
|
|
404
413
|
output = await evaluateInput(":codec load ./codecs/ieee.mjs", ieeeAutoState);
|
|
405
414
|
assert.match(output[0], /^loaded codec ieee\.mjs/);
|
|
@@ -625,6 +634,8 @@ assert.equal(output[0], "Current output limit: none");
|
|
|
625
634
|
|
|
626
635
|
// Verify Examples/djson.k (json?, get, nth, set, del)
|
|
627
636
|
const djsonKState = createState({ engine: "wasm" });
|
|
637
|
+
await evaluateInput(":load core.k", djsonKState);
|
|
638
|
+
await evaluateInput(":load Examples/ieee.k", djsonKState);
|
|
628
639
|
output = await evaluateInput(":load Examples/djson.k", djsonKState);
|
|
629
640
|
assert.equal(output[0], "loaded Examples/djson.k");
|
|
630
641
|
await evaluateInput(":codec load codecs/djson.mjs", djsonKState);
|
|
@@ -969,6 +980,98 @@ assert(
|
|
|
969
980
|
)
|
|
970
981
|
);
|
|
971
982
|
|
|
983
|
+
// Verify :rel prints canonical pattern names for input and output patterns
|
|
984
|
+
output = await evaluateInput(":rel car", polyExplicitState);
|
|
985
|
+
assert.equal(
|
|
986
|
+
output[0],
|
|
987
|
+
"car = ?@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[X0] " +
|
|
988
|
+
"/cons .car ?X0; " +
|
|
989
|
+
"-- @zjRvxpKqktzNfR3VYSqq4bF9XLQTnCp4MpP82JLmysaP"
|
|
990
|
+
);
|
|
991
|
+
output = await evaluateInput(":rel reverse", polyExplicitState);
|
|
992
|
+
assert.equal(
|
|
993
|
+
output[0],
|
|
994
|
+
"reverse = ?@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[X0] " +
|
|
995
|
+
"{() xs, nil acc} _reverse " +
|
|
996
|
+
"?@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[X0]; " +
|
|
997
|
+
"-- @JbJ2aQugNct2GGeCJ65zKjN55Bf5YPyGHzsikTCjx82w"
|
|
998
|
+
);
|
|
999
|
+
output = await evaluateInput(":rel nil?", polyExplicitState);
|
|
1000
|
+
assert.equal(
|
|
1001
|
+
output[0],
|
|
1002
|
+
"nil? = ?@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[(...)] " +
|
|
1003
|
+
"/nil nil " +
|
|
1004
|
+
"?@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[(...)]; " +
|
|
1005
|
+
"-- @YHZEettEijtfW68ekdSKKiZRfiiEkqJjLDb9NNcJnwcg"
|
|
1006
|
+
);
|
|
1007
|
+
output = await evaluateInput(":rel parseJson", djsonKState);
|
|
1008
|
+
assert.equal(
|
|
1009
|
+
output[0],
|
|
1010
|
+
"parseJson = " +
|
|
1011
|
+
"?@Pt3MwQwzUPxQKu58zXR3qUBHWTzfycx5bSZGzcK6EZQK[] " +
|
|
1012
|
+
"json_value {.rest ws /nil end, .value value} .value " +
|
|
1013
|
+
"?@P5C7TQKTSPnFUkYkYzTudJamxAQ3T3fHbvZNqwWMfAA2[]; " +
|
|
1014
|
+
"-- @tWaZchv9AbbWxSHVk8nBpz8jVnjswiwDNhpFZeFwg6Pt"
|
|
1015
|
+
);
|
|
1016
|
+
const shortThresholdState = createState();
|
|
1017
|
+
output = await evaluateInput(":max-pat-length", shortThresholdState);
|
|
1018
|
+
assert.equal(output[0], "Current max pattern length: 30");
|
|
1019
|
+
output = await evaluateInput(":maxPatLength 10", shortThresholdState);
|
|
1020
|
+
assert.equal(output[0], "max pattern length set to 10");
|
|
1021
|
+
output = await evaluateInput(":max-pat-length", shortThresholdState);
|
|
1022
|
+
assert.equal(output[0], "Current max pattern length: 10");
|
|
1023
|
+
await evaluateInput("zero = {} | zero;", shortThresholdState);
|
|
1024
|
+
output = await evaluateInput(":rel zero", shortThresholdState);
|
|
1025
|
+
assert.equal(
|
|
1026
|
+
output[0],
|
|
1027
|
+
"zero = ?(...) {} |zero " +
|
|
1028
|
+
"?@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM[]; " +
|
|
1029
|
+
"-- @ZdauiYp7DqPGmHkUiG8yuWz4ZbEgvxZyNkBAmJ4ENhAX"
|
|
1030
|
+
);
|
|
1031
|
+
output = await evaluateInput(
|
|
1032
|
+
":pat @92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM",
|
|
1033
|
+
shortThresholdState
|
|
1034
|
+
);
|
|
1035
|
+
assert.equal(
|
|
1036
|
+
output[0],
|
|
1037
|
+
"@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM[] = <{} zero, ...>;"
|
|
1038
|
+
);
|
|
1039
|
+
output = await evaluateInput(
|
|
1040
|
+
":pat ?@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM",
|
|
1041
|
+
shortThresholdState
|
|
1042
|
+
);
|
|
1043
|
+
assert.equal(
|
|
1044
|
+
output[0],
|
|
1045
|
+
"@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM[] = <{} zero, ...>;"
|
|
1046
|
+
);
|
|
1047
|
+
output = await evaluateInput(
|
|
1048
|
+
":pat ?@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM[]",
|
|
1049
|
+
shortThresholdState
|
|
1050
|
+
);
|
|
1051
|
+
assert.equal(
|
|
1052
|
+
output[0],
|
|
1053
|
+
"@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM[] = <{} zero, ...>;"
|
|
1054
|
+
);
|
|
1055
|
+
completions = completeInput(":pat ?@92TY", shortThresholdState)[0];
|
|
1056
|
+
assert(
|
|
1057
|
+
completions.includes(
|
|
1058
|
+
":pat ?@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM"
|
|
1059
|
+
)
|
|
1060
|
+
);
|
|
1061
|
+
output = await evaluateInput(":max-pat-length none", shortThresholdState);
|
|
1062
|
+
assert.equal(output[0], "max pattern length disabled");
|
|
1063
|
+
output = await evaluateInput(":maxPatLength", shortThresholdState);
|
|
1064
|
+
assert.equal(output[0], "Current max pattern length: none");
|
|
1065
|
+
output = await evaluateInput(":rel zero", shortThresholdState);
|
|
1066
|
+
assert.equal(
|
|
1067
|
+
output[0],
|
|
1068
|
+
"zero = ?(...) {} |zero ?<{} zero, ...>; " +
|
|
1069
|
+
"-- @ZdauiYp7DqPGmHkUiG8yuWz4ZbEgvxZyNkBAmJ4ENhAX"
|
|
1070
|
+
);
|
|
1071
|
+
completions = completeInput(":max", shortThresholdState)[0];
|
|
1072
|
+
assert(completions.includes(":max-pat-length"));
|
|
1073
|
+
assert(completions.includes(":maxPatLength"));
|
|
1074
|
+
|
|
972
1075
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
973
1076
|
fs.rmSync(symlinkPath, { force: true });
|
|
974
1077
|
console.log("OK");
|