@fraczak/k 8.5.0 → 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 +35 -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/llvm/src/kvm2llvm.mjs +5 -4
- package/backends/llvm/src/llvm.mjs +2 -1
- package/backends/llvm/tests/integration.sh +7 -0
- package/backends/llvm/tests/test-llvm.mjs +20 -0
- package/backends/wasm/src/kvm2wasm.mjs +64 -18
- package/backends/wasm/tests/integration.sh +7 -1
- package/backends/wasm/tests/test-wasm.mjs +86 -2
- 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 +21 -8
- package/tests/test-repl.mjs +105 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fraczak/k",
|
|
3
|
-
"version": "8.
|
|
3
|
+
"version": "8.6.0",
|
|
4
4
|
"description": "k — a language for content-addressable schemas and data transformations over algebraic data types (products and tagged unions); includes runtime, contract derivation, REPL, and codec toolchain",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
package/repl.mjs
CHANGED
|
@@ -63,6 +63,7 @@ const COMMAND_NAMES = [
|
|
|
63
63
|
"help", "rel", "pattern", "pat", "patterns", "pats",
|
|
64
64
|
"codecs", "rels", "codec", "input", "reset", "klib", "ko", "load",
|
|
65
65
|
"engine", "wasm", "pkir", "js", "limit",
|
|
66
|
+
"max-pat-length", "maxPatLength",
|
|
66
67
|
"quit", "exit"
|
|
67
68
|
];
|
|
68
69
|
const CODEC_COMMAND_NAMES = ["load", "unload", "list"];
|
|
@@ -110,7 +111,8 @@ function createState(options = {}) {
|
|
|
110
111
|
lastMain: null,
|
|
111
112
|
lastTiming: null,
|
|
112
113
|
showTiming: true,
|
|
113
|
-
printLimit: options.printLimit ?? Infinity
|
|
114
|
+
printLimit: options.printLimit ?? Infinity,
|
|
115
|
+
maxPatLength: options.maxPatLength ?? 30
|
|
114
116
|
};
|
|
115
117
|
}
|
|
116
118
|
|
|
@@ -732,6 +734,7 @@ function canonicalNames(state) {
|
|
|
732
734
|
return [...new Set([
|
|
733
735
|
...Object.keys(state.codes),
|
|
734
736
|
...Object.keys(state.rels),
|
|
737
|
+
...Object.keys(state.patterns || {}),
|
|
735
738
|
...Object.values(state.typeAliases),
|
|
736
739
|
...Object.values(state.relAliases),
|
|
737
740
|
...Object.values(state.patternAliases || {})
|
|
@@ -1061,16 +1064,23 @@ function completeCommandArgument(line, state) {
|
|
|
1061
1064
|
|
|
1062
1065
|
if (command === "pattern" || command === "pat") {
|
|
1063
1066
|
const trimmed = arg.trimStart();
|
|
1067
|
+
const qMatch = trimmed.match(/^(\?\s*)(.*)$/);
|
|
1068
|
+
const qPrefix = qMatch ? qMatch[1] : "";
|
|
1069
|
+
const target = qMatch ? qMatch[2] : trimmed;
|
|
1064
1070
|
const leadingWhitespace = arg.length - trimmed.length;
|
|
1065
|
-
const prefix = line.slice(0, argStart + leadingWhitespace);
|
|
1071
|
+
const prefix = line.slice(0, argStart + leadingWhitespace) + qPrefix;
|
|
1066
1072
|
const names = Object.keys(state.patterns || {}).sort();
|
|
1067
1073
|
const matches = names
|
|
1068
|
-
.filter((name) => name.startsWith(
|
|
1074
|
+
.filter((name) => name.startsWith(target))
|
|
1069
1075
|
.map((name) => `${prefix}${name}`);
|
|
1070
|
-
if (
|
|
1076
|
+
if (target.startsWith("@")) {
|
|
1071
1077
|
for (const [name, p] of Object.entries(state.patterns || {})) {
|
|
1072
1078
|
const hash = resolvePatternCanonicalName(state, name, p);
|
|
1073
|
-
if (
|
|
1079
|
+
if (
|
|
1080
|
+
hash &&
|
|
1081
|
+
hash.startsWith(target) &&
|
|
1082
|
+
!matches.includes(`${prefix}${hash}`)
|
|
1083
|
+
) {
|
|
1074
1084
|
matches.push(`${prefix}${hash}`);
|
|
1075
1085
|
}
|
|
1076
1086
|
}
|
|
@@ -1572,13 +1582,21 @@ async function evaluateCommand(line, state) {
|
|
|
1572
1582
|
"Use :rel <name> to show a relation definition"
|
|
1573
1583
|
);
|
|
1574
1584
|
}
|
|
1585
|
+
restoreCodes(state);
|
|
1575
1586
|
const { hash, rel } = resolveRel(state, arg);
|
|
1576
1587
|
if (!rel) throw new Error(`Unknown relation '${arg}'`);
|
|
1577
1588
|
const prettyRelStr = prettyRelation(
|
|
1578
1589
|
rel,
|
|
1579
1590
|
displayAliases(state),
|
|
1580
|
-
state.relAliases
|
|
1591
|
+
state.relAliases,
|
|
1592
|
+
{
|
|
1593
|
+
libraries: [stateLibrary(state)],
|
|
1594
|
+
patterns: state.patterns,
|
|
1595
|
+
registerPatterns: state.patterns,
|
|
1596
|
+
maxPatLength: state.maxPatLength
|
|
1597
|
+
}
|
|
1581
1598
|
);
|
|
1599
|
+
state.codes = codes.dump();
|
|
1582
1600
|
return [`${arg} = ${prettyRelStr}; -- ${hash}`];
|
|
1583
1601
|
}
|
|
1584
1602
|
case "rels":
|
|
@@ -1588,8 +1606,15 @@ async function evaluateCommand(line, state) {
|
|
|
1588
1606
|
if (!arg) {
|
|
1589
1607
|
throw new Error(`${usagePrefix}pattern requires a pattern name`);
|
|
1590
1608
|
}
|
|
1609
|
+
restoreCodes(state);
|
|
1591
1610
|
const rawName = arg.trim();
|
|
1592
|
-
let patternName = rawName
|
|
1611
|
+
let patternName = rawName
|
|
1612
|
+
.replace(/^\?\s*/, "")
|
|
1613
|
+
.replace(/\[.*\]$/, "")
|
|
1614
|
+
.trim();
|
|
1615
|
+
if (!patternName) {
|
|
1616
|
+
throw new Error(`${usagePrefix}pattern requires a pattern name`);
|
|
1617
|
+
}
|
|
1593
1618
|
let pat = null;
|
|
1594
1619
|
if (patternName.startsWith("@")) {
|
|
1595
1620
|
pat = state.patterns?.[patternName];
|
|
@@ -1681,12 +1706,37 @@ async function evaluateCommand(line, state) {
|
|
|
1681
1706
|
state.printLimit = n;
|
|
1682
1707
|
return [`output limit set to ${n}`];
|
|
1683
1708
|
}
|
|
1709
|
+
case "maxPatLength":
|
|
1710
|
+
case "max-pat-length": {
|
|
1711
|
+
const mode = (arg || "").trim().toLowerCase();
|
|
1712
|
+
if (!mode) {
|
|
1713
|
+
const current = Number.isFinite(state.maxPatLength)
|
|
1714
|
+
? state.maxPatLength
|
|
1715
|
+
: "none";
|
|
1716
|
+
return [`Current max pattern length: ${current}`];
|
|
1717
|
+
}
|
|
1718
|
+
if (mode === "none" || mode === "infinity" || mode === "off") {
|
|
1719
|
+
state.maxPatLength = Infinity;
|
|
1720
|
+
return ["max pattern length disabled"];
|
|
1721
|
+
}
|
|
1722
|
+
const n = parseInt(mode, 10);
|
|
1723
|
+
if (Number.isNaN(n) || n < 0) {
|
|
1724
|
+
throw new Error(
|
|
1725
|
+
`Invalid max pattern length '${arg.trim()}'. ` +
|
|
1726
|
+
`Usage: :${command} [num|none]`
|
|
1727
|
+
);
|
|
1728
|
+
}
|
|
1729
|
+
state.maxPatLength = n;
|
|
1730
|
+
return [`max pattern length set to ${n}`];
|
|
1731
|
+
}
|
|
1684
1732
|
case "reset": {
|
|
1685
1733
|
const currentEngine = state.engine;
|
|
1686
1734
|
const currentLimit = state.printLimit;
|
|
1735
|
+
const currentMaxPatLength = state.maxPatLength;
|
|
1687
1736
|
const fresh = createState({
|
|
1688
1737
|
engine: currentEngine,
|
|
1689
|
-
printLimit: currentLimit
|
|
1738
|
+
printLimit: currentLimit,
|
|
1739
|
+
maxPatLength: currentMaxPatLength
|
|
1690
1740
|
});
|
|
1691
1741
|
Object.assign(state, fresh);
|
|
1692
1742
|
return ["reset"];
|
|
@@ -1725,6 +1775,7 @@ function helpText() {
|
|
|
1725
1775
|
":pattern name show named pattern definition (alias :pat)",
|
|
1726
1776
|
":patterns list pattern aliases (alias :pats)",
|
|
1727
1777
|
":limit [num|none] set maximum characters for value output",
|
|
1778
|
+
":max-pat-length [n|none] max inline pattern length in :rel (default 30)",
|
|
1728
1779
|
":codec load file load a codec module from file",
|
|
1729
1780
|
":codec unload name unload a registered codec",
|
|
1730
1781
|
":codec list list loaded codecs (or simply :codecs)",
|
|
@@ -1762,6 +1813,8 @@ function cliUsage() {
|
|
|
1762
1813
|
console.log(" --wasm Shortcut for --engine=wasm.");
|
|
1763
1814
|
console.log(" --js Shortcut for --engine=js.");
|
|
1764
1815
|
console.log(" --limit=<num> Set maximum characters for output.");
|
|
1816
|
+
console.log(" --max-pat-length=<num> Set max inline pattern length in :rel");
|
|
1817
|
+
console.log(" (default: 30).");
|
|
1765
1818
|
console.log(" -h, --help Show this help.");
|
|
1766
1819
|
}
|
|
1767
1820
|
|
|
@@ -1858,6 +1911,7 @@ if (isMainEntrypoint()) {
|
|
|
1858
1911
|
const args = argv.slice(2);
|
|
1859
1912
|
let engine = "wasm";
|
|
1860
1913
|
let printLimit = Infinity;
|
|
1914
|
+
let maxPatLength = 30;
|
|
1861
1915
|
for (let i = 0; i < args.length; i++) {
|
|
1862
1916
|
const arg = args[i];
|
|
1863
1917
|
if (arg === "-h" || arg === "--help") {
|
|
@@ -1905,13 +1959,41 @@ if (isMainEntrypoint()) {
|
|
|
1905
1959
|
exit(1);
|
|
1906
1960
|
}
|
|
1907
1961
|
printLimit = val;
|
|
1962
|
+
} else if (
|
|
1963
|
+
arg.startsWith("--max-pat-length=") ||
|
|
1964
|
+
arg.startsWith("--maxPatLength=")
|
|
1965
|
+
) {
|
|
1966
|
+
const raw = arg.slice(arg.indexOf("=") + 1).trim().toLowerCase();
|
|
1967
|
+
if (raw === "none" || raw === "infinity" || raw === "off") {
|
|
1968
|
+
maxPatLength = Infinity;
|
|
1969
|
+
} else {
|
|
1970
|
+
const val = parseInt(raw, 10);
|
|
1971
|
+
if (Number.isNaN(val) || val < 0) {
|
|
1972
|
+
console.error(`Invalid max pattern length '${raw}'.`);
|
|
1973
|
+
exit(1);
|
|
1974
|
+
}
|
|
1975
|
+
maxPatLength = val;
|
|
1976
|
+
}
|
|
1977
|
+
} else if (arg === "--max-pat-length" || arg === "--maxPatLength") {
|
|
1978
|
+
i++;
|
|
1979
|
+
const raw = (args[i] || "").trim().toLowerCase();
|
|
1980
|
+
if (raw === "none" || raw === "infinity" || raw === "off") {
|
|
1981
|
+
maxPatLength = Infinity;
|
|
1982
|
+
} else {
|
|
1983
|
+
const val = parseInt(raw, 10);
|
|
1984
|
+
if (Number.isNaN(val) || val < 0) {
|
|
1985
|
+
console.error(`Invalid max pattern length '${args[i]}'.`);
|
|
1986
|
+
exit(1);
|
|
1987
|
+
}
|
|
1988
|
+
maxPatLength = val;
|
|
1989
|
+
}
|
|
1908
1990
|
} else {
|
|
1909
1991
|
console.error(`Unknown option '${arg}'.`);
|
|
1910
1992
|
cliUsage();
|
|
1911
1993
|
exit(1);
|
|
1912
1994
|
}
|
|
1913
1995
|
}
|
|
1914
|
-
startRepl({ engine, printLimit });
|
|
1996
|
+
startRepl({ engine, printLimit, maxPatLength });
|
|
1915
1997
|
}
|
|
1916
1998
|
|
|
1917
1999
|
export {
|
|
@@ -3,14 +3,15 @@
|
|
|
3
3
|
import { spawnSync } from "node:child_process";
|
|
4
4
|
import { mkdtempSync, rmSync, statSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
|
-
import { join } from "node:path";
|
|
6
|
+
import { join, resolve } from "node:path";
|
|
7
7
|
import { performance } from "node:perf_hooks";
|
|
8
8
|
|
|
9
9
|
const DEFAULT_EXAMPLES = [
|
|
10
10
|
"Examples/nat.k",
|
|
11
11
|
"Examples/list.k",
|
|
12
12
|
"Examples/arithmetics.k",
|
|
13
|
-
"Examples/ieee.k"
|
|
13
|
+
"Examples/ieee.k",
|
|
14
|
+
"Examples/ieee-arithmetics.k"
|
|
14
15
|
];
|
|
15
16
|
|
|
16
17
|
function printHelp() {
|
|
@@ -24,7 +25,8 @@ Arguments:
|
|
|
24
25
|
example.k ...
|
|
25
26
|
One or more .k source files to benchmark.
|
|
26
27
|
(default: Examples/nat.k Examples/list.k
|
|
27
|
-
Examples/arithmetics.k Examples/ieee.k
|
|
28
|
+
Examples/arithmetics.k Examples/ieee.k
|
|
29
|
+
Examples/ieee-arithmetics.k)
|
|
28
30
|
|
|
29
31
|
Options:
|
|
30
32
|
-h, --help
|
|
@@ -52,7 +54,7 @@ function run(args) {
|
|
|
52
54
|
});
|
|
53
55
|
if (result.error) throw result.error;
|
|
54
56
|
if (result.status !== 0) {
|
|
55
|
-
throw new Error(`${args.join(" ")} failed\n${result.stderr || result.stdout}`);
|
|
57
|
+
throw new Error(`${args.join(" ")} failed (${result.status ?? result.signal})\n${result.stderr || result.stdout}`);
|
|
56
58
|
}
|
|
57
59
|
}
|
|
58
60
|
|
|
@@ -81,8 +83,21 @@ for (const example of benchmarkExamples) {
|
|
|
81
83
|
for (let i = 0; i < iterations; i++) {
|
|
82
84
|
const out = mkdtempSync(join(tmpdir(), `k-idempotency-bench-${example.replaceAll("/", "_")}-`));
|
|
83
85
|
try {
|
|
86
|
+
const isIEEE = resolve(example) === resolve("Examples/ieee.k");
|
|
87
|
+
const isArithmetic = resolve(example) === resolve("Examples/ieee-arithmetics.k");
|
|
88
|
+
let dependency;
|
|
89
|
+
if (isIEEE || isArithmetic) {
|
|
90
|
+
dependency = join(out, "core.klib");
|
|
91
|
+
run(["objects/compile.mjs", "core.k", dependency]);
|
|
92
|
+
}
|
|
93
|
+
if (isArithmetic) {
|
|
94
|
+
const ieee = join(out, "ieee.klib");
|
|
95
|
+
run(["objects/compile.mjs", "--lib", dependency, "Examples/ieee.k", ieee]);
|
|
96
|
+
dependency = ieee;
|
|
97
|
+
}
|
|
98
|
+
const library = dependency ? ["--lib", dependency] : [];
|
|
84
99
|
const t0 = performance.now();
|
|
85
|
-
run(["objects/compile.mjs", example, join(out, "1.klib")]);
|
|
100
|
+
run(["objects/compile.mjs", ...library, example, join(out, "1.klib")]);
|
|
86
101
|
run(["objects/decompile.mjs", join(out, "1.klib"), join(out, "1.k")]);
|
|
87
102
|
run(["objects/compile.mjs", join(out, "1.k"), join(out, "2.klib")]);
|
|
88
103
|
run(["objects/decompile.mjs", join(out, "2.klib"), join(out, "2.k")]);
|
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(), {});
|