@fraczak/k 8.6.1 → 8.7.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 +22 -0
- package/DOCS/CODECS.md +20 -14
- package/DOCS/FILE_FORMATS.md +79 -12
- package/DOCS/GETTING_STARTED.md +17 -8
- package/DOCS/PATTERNS.md +17 -0
- package/DOCS/REPL.md +13 -7
- package/Examples/arithmetics.k +81 -468
- package/Examples/ieee-arithmetics.k +37 -33
- package/Examples/poly.k +107 -104
- package/README.md +19 -11
- package/backend-api.mjs +3 -1
- package/backends/llvm/README.md +1 -1
- package/backends/llvm/bin/k-llvm-build.mjs +5 -5
- package/backends/llvm/bin/k-llvm-compile.mjs +4 -4
- package/backends/llvm/bin/k-llvm.mjs +6 -6
- package/backends/llvm/src/cli.mjs +17 -12
- package/backends/llvm/tests/integration.sh +4 -1
- package/backends/wasm/README.md +3 -3
- package/backends/wasm/bin/k-wasm-compile.mjs +4 -4
- package/backends/wasm/bin/k-wasm.mjs +4 -4
- package/backends/wasm/src/cli.mjs +12 -10
- package/backends/wasm/src/wasm.mjs +6 -2
- package/backends/wasm/tests/integration.sh +8 -3
- package/browser/shims/fs.mjs +19 -3
- package/canonical-pattern.mjs +217 -57
- package/core.k +2 -1
- package/harness/suites/poly.mjs +14 -30
- package/k.mjs +17 -13
- package/kvm.mjs +13 -9
- package/lib/arithmetics.k +287 -0
- package/lib/bit.k +68 -0
- package/lib/bits.k +221 -0
- package/lib/btrie.k +187 -0
- package/lib/djson.k +326 -0
- package/lib/ieee.k +709 -0
- package/lib/list.k +49 -0
- package/lib/string.k +588 -0
- package/named-patterns.mjs +2 -2
- package/object.mjs +51 -9
- package/objects/README.md +10 -3
- package/objects/compile.mjs +10 -8
- package/package.json +1 -1
- package/repl.mjs +28 -6
- package/scripts/benchmark-idempotency.mjs +22 -15
- package/scripts/benchmark.mjs +29 -10
- package/scripts/build-repl-html.mjs +41 -13
- package/scripts/perf-ieee.mjs +9 -1
- package/scripts/perf-int.mjs +10 -17
- package/scripts/perf-multiplication.mjs +9 -15
- package/scripts/perf-poly.mjs +16 -32
- package/scripts/run-tests.mjs +2 -2
- package/scripts/test-package.mjs +8 -2
- package/tests/helpers/cli.mjs +11 -3
- package/tests/integration.sh +9 -4
- package/tests/test-arithmetics.mjs +4 -2
- package/tests/test-djson-methods.mjs +16 -12
- package/tests/test-ieee-arithmetic.mjs +11 -3
- package/tests/test-ieee-text.mjs +15 -4
- package/tests/test-k-object.mjs +11 -3
- package/tests/test-karatsuba.mjs +1 -1
- package/tests/test-kvm-polymorphic.mjs +54 -34
- package/tests/test-lib.mjs +115 -0
- package/tests/test-named-patterns.mjs +12 -3
- package/tests/test-parse-json.mjs +33 -13
- package/tests/test-poly.mjs +10 -4
- package/tests/test-repl-html.mjs +18 -7
- package/tests/test-repl.mjs +50 -35
- package/Examples/djson.k +0 -894
- package/Examples/ieee.k +0 -969
- package/Examples/karatsuba-mult.k +0 -227
- package/Examples/list.k +0 -10
package/scripts/perf-poly.mjs
CHANGED
|
@@ -193,48 +193,32 @@ function pkirLaneName() {
|
|
|
193
193
|
}
|
|
194
194
|
|
|
195
195
|
|
|
196
|
-
console.log("==> Loading @fraczak/k/
|
|
197
|
-
|
|
198
|
-
const
|
|
199
|
-
const
|
|
196
|
+
console.log("==> Loading @fraczak/k/lib/{bit,bits,arithmetics,list}.k as libraries");
|
|
197
|
+
let depLib = null;
|
|
198
|
+
for (const relPath of ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k", "lib/list.k"]) {
|
|
199
|
+
const filePath = fileURLToPath(import.meta.resolve(`@fraczak/k/${relPath}`));
|
|
200
|
+
depLib = loadLibrary(compileLibrary(fs.readFileSync(filePath, "utf8"), {
|
|
201
|
+
source: filePath,
|
|
202
|
+
libraries: depLib ? [depLib] : []
|
|
203
|
+
}));
|
|
204
|
+
}
|
|
200
205
|
|
|
201
|
-
console.log("==> Compiling @fraczak/k/Examples/poly.k with
|
|
206
|
+
console.log("==> Compiling @fraczak/k/Examples/poly.k with library dependencies");
|
|
202
207
|
const polyPath = fileURLToPath(import.meta.resolve("@fraczak/k/Examples/poly.k"));
|
|
203
208
|
const polySource = fs.readFileSync(polyPath, "utf8");
|
|
204
|
-
|
|
205
|
-
function buildExportPreamble(exports, libraries) {
|
|
206
|
-
const aliasMap = {};
|
|
207
|
-
for (const lib of libraries) {
|
|
208
|
-
for (const [name, hash] of Object.entries(lib.relAlias || {})) {
|
|
209
|
-
if (name !== "__main__") aliasMap[name] = hash;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
const lines = [];
|
|
213
|
-
for (const spec of exports) {
|
|
214
|
-
const [libName, localName] = spec.includes(":") ? spec.split(":", 2) : [spec, spec];
|
|
215
|
-
const hash = aliasMap[libName];
|
|
216
|
-
if (!hash) throw new Error(`--export: '${libName}' not found in loaded libraries`);
|
|
217
|
-
const body = hash.startsWith("@") ? hash.slice(1) : hash;
|
|
218
|
-
lines.push(`${localName} = @${body};`);
|
|
219
|
-
}
|
|
220
|
-
return lines.join("\n") + "\n";
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
const neededExports = ["0", "int", "inc", "dec", "nat", "zero_int?", "neg?", "GT"];
|
|
224
|
-
const exportPreamble = buildExportPreamble(neededExports, [arithmeticsLib]);
|
|
225
|
-
const polyLib = loadLibrary(compileLibrary(exportPreamble + polySource, {
|
|
209
|
+
const polyLib = loadLibrary(compileLibrary(polySource, {
|
|
226
210
|
source: polyPath,
|
|
227
|
-
libraries: [
|
|
211
|
+
libraries: [depLib]
|
|
228
212
|
}));
|
|
229
213
|
|
|
230
214
|
const state = {
|
|
231
|
-
codes: { ...
|
|
232
|
-
rels: { ...
|
|
215
|
+
codes: { ...depLib.codes, ...polyLib.codes },
|
|
216
|
+
rels: { ...depLib.rels, ...polyLib.rels },
|
|
233
217
|
typeAliases: {},
|
|
234
218
|
relAliases: { ...polyLib.relAlias },
|
|
235
|
-
meta: { ...
|
|
219
|
+
meta: { ...depLib.meta, ...polyLib.meta }
|
|
236
220
|
};
|
|
237
|
-
for (const [hash, entry] of Object.entries(
|
|
221
|
+
for (const [hash, entry] of Object.entries(depLib.meta)) {
|
|
238
222
|
if (entry.type === "code") {
|
|
239
223
|
for (const origin of entry.origins || []) {
|
|
240
224
|
if (origin.name) state.typeAliases[origin.name] = hash;
|
package/scripts/run-tests.mjs
CHANGED
|
@@ -43,11 +43,11 @@ const tests = [
|
|
|
43
43
|
["tests/test-hash-normalization.mjs", node, ["tests/test-hash-normalization.mjs"]],
|
|
44
44
|
["tests/test-structural-values.mjs", node, ["tests/test-structural-values.mjs"]],
|
|
45
45
|
["tests/test-codecs.mjs", node, ["tests/test-codecs.mjs"]],
|
|
46
|
-
[
|
|
47
|
-
"tests/test-djson-methods.mjs",
|
|
46
|
+
["tests/test-djson-methods.mjs",
|
|
48
47
|
node,
|
|
49
48
|
["tests/test-djson-methods.mjs"]
|
|
50
49
|
],
|
|
50
|
+
["tests/test-lib.mjs", node, ["tests/test-lib.mjs"]],
|
|
51
51
|
["tests/test-parse-json.mjs", node, ["tests/test-parse-json.mjs"]],
|
|
52
52
|
["tests/test-ieee-text.mjs", node, ["tests/test-ieee-text.mjs"]],
|
|
53
53
|
["tests/test-deep-wire-value.mjs", node, ["tests/test-deep-wire-value.mjs"]],
|
package/scripts/test-package.mjs
CHANGED
|
@@ -45,8 +45,14 @@ try {
|
|
|
45
45
|
assert.equal(run("k-print", [], hello).toString().trim(), '"ok"');
|
|
46
46
|
|
|
47
47
|
const integer = run("k-int", ["--parse"], "42\n");
|
|
48
|
-
const
|
|
49
|
-
|
|
48
|
+
const bitKlib = path.join(scratch, "bit.klib");
|
|
49
|
+
const bitsKlib = path.join(scratch, "bits.klib");
|
|
50
|
+
const arithKlib = path.join(scratch, "arithmetics.klib");
|
|
51
|
+
run("k-compile", [path.join(packageDir, "lib/bit.k"), bitKlib]);
|
|
52
|
+
run("k-compile", ["--lib", bitKlib, path.join(packageDir, "lib/bits.k"), bitsKlib]);
|
|
53
|
+
run("k-compile", ["--lib", bitsKlib, path.join(packageDir, "lib/arithmetics.k"), arithKlib]);
|
|
54
|
+
const incremented = run("k", ["--lib", arithKlib,
|
|
55
|
+
"--use", "inc", "inc"], integer);
|
|
50
56
|
assert.equal(run("k-int", ["--print"], incremented).toString().trim(), "43");
|
|
51
57
|
|
|
52
58
|
const object = path.join(scratch, "ok.ko");
|
package/tests/helpers/cli.mjs
CHANGED
|
@@ -25,9 +25,17 @@ export function succeeds(result, label) {
|
|
|
25
25
|
|
|
26
26
|
export function withCompiledLibrary(source, test) {
|
|
27
27
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "k-library-test-"));
|
|
28
|
-
const
|
|
28
|
+
const sources = Array.isArray(source) ? source : [source];
|
|
29
|
+
let library = null;
|
|
29
30
|
try {
|
|
30
|
-
|
|
31
|
+
for (let i = 0; i < sources.length; i++) {
|
|
32
|
+
const nextLibrary = path.join(dir, `library-${i}.klib`);
|
|
33
|
+
const args = ["objects/compile.mjs"];
|
|
34
|
+
if (library) args.push("--lib", library);
|
|
35
|
+
args.push(sources[i], nextLibrary);
|
|
36
|
+
succeeds(node(args), `compile ${sources[i]}`);
|
|
37
|
+
library = nextLibrary;
|
|
38
|
+
}
|
|
31
39
|
test(library);
|
|
32
40
|
} finally {
|
|
33
41
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
@@ -36,7 +44,7 @@ export function withCompiledLibrary(source, test) {
|
|
|
36
44
|
|
|
37
45
|
export function runLibrary(library, aliases, source, input = "0") {
|
|
38
46
|
return node(["k.mjs", "--lib", library,
|
|
39
|
-
...aliases.flatMap((alias) => ["--
|
|
47
|
+
...aliases.flatMap((alias) => ["--use", alias]), source],
|
|
40
48
|
encodeToWire(parse(input)));
|
|
41
49
|
}
|
|
42
50
|
|
package/tests/integration.sh
CHANGED
|
@@ -33,10 +33,10 @@ grep -q '"__main__"' "$TMP_DIR/stdin.kvm"
|
|
|
33
33
|
grep -q '"layer": "KVM-P"' "$TMP_DIR/poly-object.kvm"
|
|
34
34
|
grep -q '"isPolymorphic": true' "$TMP_DIR/poly-object.kvm"
|
|
35
35
|
./objects/compile.mjs 'id = ();' "$TMP_DIR/export.klib"
|
|
36
|
-
./objects/compile.mjs --lib "$TMP_DIR/export.klib" --
|
|
36
|
+
./objects/compile.mjs --lib "$TMP_DIR/export.klib" --use id:alias 'alias' "$TMP_DIR/export.ko"
|
|
37
37
|
./objects/decompile.mjs "$TMP_DIR/export.ko" | grep -q '^----- main -----$'
|
|
38
|
-
node ./codecs/unit.mjs --parse | ./k.mjs --lib "$TMP_DIR/export.klib" --
|
|
39
|
-
node ./codecs/unit.mjs --parse | ./kvm.mjs --lib "$TMP_DIR/export.klib" --
|
|
38
|
+
node ./codecs/unit.mjs --parse | ./k.mjs --lib "$TMP_DIR/export.klib" --use id:alias 'alias' | node ./codecs/unit.mjs --print | grep -qx '{}'
|
|
39
|
+
node ./codecs/unit.mjs --parse | ./kvm.mjs --lib "$TMP_DIR/export.klib" --use id:alias 'alias' | node ./codecs/unit.mjs --print | grep -qx '{}'
|
|
40
40
|
node ./codecs/unit.mjs --parse | ./k.mjs "$TMP_DIR/export.ko" | node ./codecs/unit.mjs --print | grep -qx '{}'
|
|
41
41
|
node ./codecs/unit.mjs --parse | ./kvm.mjs "$TMP_DIR/export.ko" | node ./codecs/unit.mjs --print | grep -qx '{}'
|
|
42
42
|
if ./k.mjs --lib "$TMP_DIR/export.klib" --lib "$TMP_DIR/export.klib" '()' > "$TMP_DIR/two-lib.out" 2> "$TMP_DIR/two-lib.err"; then
|
|
@@ -81,7 +81,12 @@ 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
|
|
84
|
+
./objects/compile.mjs lib/bit.k "$TMP_DIR/bit.klib"
|
|
85
|
+
./objects/compile.mjs --lib "$TMP_DIR/bit.klib" lib/bits.k "$TMP_DIR/bits.klib"
|
|
86
|
+
./objects/compile.mjs --lib "$TMP_DIR/bits.klib" lib/list.k "$TMP_DIR/list.klib"
|
|
87
|
+
./objects/compile.mjs --lib "$TMP_DIR/list.klib" lib/btrie.k "$TMP_DIR/btrie.klib"
|
|
88
|
+
./objects/compile.mjs --lib "$TMP_DIR/btrie.klib" lib/string.k "$TMP_DIR/string.klib"
|
|
89
|
+
./objects/compile.mjs --lib "$TMP_DIR/string.klib" lib/ieee.k "$TMP_DIR/ieee-types.klib"
|
|
85
90
|
./objects/compile.mjs --lib "$TMP_DIR/ieee-types.klib" Examples/ieee-arithmetics.k "$TMP_DIR/ieee.klib"
|
|
86
91
|
MUL=`./objects/extract-aliases.mjs "$TMP_DIR/ieee.klib" | grep '^mul = @' | sed 's/^mul = \(@[^;]*\);.*$/\1/'`
|
|
87
92
|
DIV=`./objects/extract-aliases.mjs "$TMP_DIR/ieee.klib" | grep '^div = @' | sed 's/^div = \(@[^;]*\);.*$/\1/'`
|
|
@@ -3,7 +3,7 @@ import { withCompiledLibrary, runLibrary, integer, succeeds } from "./helpers/cl
|
|
|
3
3
|
|
|
4
4
|
const large = "11111112222223333334444444555555666666777777788888899999900000011111122222233333344444455555";
|
|
5
5
|
|
|
6
|
-
withCompiledLibrary("Examples/arithmetics.k", (library) => {
|
|
6
|
+
withCompiledLibrary(["lib/bit.k", "lib/bits.k", "lib/arithmetics.k", "Examples/arithmetics.k"], (library) => {
|
|
7
7
|
const run = (aliases, source, input) => runLibrary(library, aliases, source, input);
|
|
8
8
|
const n = BigInt(large);
|
|
9
9
|
for (const [op, expected] of [
|
|
@@ -48,7 +48,9 @@ withCompiledLibrary("Examples/arithmetics.k", (library) => {
|
|
|
48
48
|
[["mod", "int", "10:ten", "3:three"], "{ten x, three y} mod int", "1"],
|
|
49
49
|
[["gcd", "int", "12:twelve", "8:eight"], "{twelve x, eight y} gcd int", "4"],
|
|
50
50
|
[["gcd", "int", "4:four", "_:zero_b"], "{four x, zero_b y} gcd int", "4"],
|
|
51
|
-
[["lcm", "int", "4:four", "6:six"], "{four x, six y} lcm int", "12"]
|
|
51
|
+
[["lcm", "int", "4:four", "6:six"], "{four x, six y} lcm int", "12"],
|
|
52
|
+
[["factorial", "int", "5:five"], "five int factorial", "120"],
|
|
53
|
+
[["fib", "int", "10:ten"], "ten int fib", "89"]
|
|
52
54
|
]) assert.equal(integer(run(aliases, source), source), expected, source);
|
|
53
55
|
});
|
|
54
56
|
|
|
@@ -7,18 +7,22 @@ import { fromJsonValue, toJsonValue } from "../codecs/djson.mjs";
|
|
|
7
7
|
import { textToStringValue, stringValueToText } from "../codecs/runtime/unicode-string.mjs";
|
|
8
8
|
import { parse as parseInt } from "../codecs/int.mjs";
|
|
9
9
|
|
|
10
|
-
const source = readFileSync(new URL("../
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
|
|
10
|
+
const source = readFileSync(new URL("../lib/djson.k", import.meta.url), "utf8");
|
|
11
|
+
let ieee = null;
|
|
12
|
+
for (const file of [
|
|
13
|
+
"lib/bit.k",
|
|
14
|
+
"lib/bits.k",
|
|
15
|
+
"lib/list.k",
|
|
16
|
+
"lib/btrie.k",
|
|
17
|
+
"lib/string.k",
|
|
18
|
+
"lib/ieee.k"
|
|
19
|
+
]) {
|
|
20
|
+
ieee = loadLibrary(compileLibrary(readFileSync(new URL(`../${file}`, import.meta.url), "utf8"), {
|
|
21
|
+
source: file,
|
|
22
|
+
libraries: ieee ? [ieee] : []
|
|
23
|
+
}));
|
|
24
|
+
}
|
|
25
|
+
const library = loadLibrary(compileLibrary(source, { libraries: [ieee] }));
|
|
22
26
|
const run = (op, value) => k.compile(library.relAlias[op], { libraries: [library] })(value);
|
|
23
27
|
|
|
24
28
|
function method(op, json, { key, index, val } = {}) {
|
|
@@ -7,9 +7,17 @@ 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
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
for (const file of [
|
|
11
|
+
"lib/bit.k",
|
|
12
|
+
"lib/bits.k",
|
|
13
|
+
"lib/list.k",
|
|
14
|
+
"lib/btrie.k",
|
|
15
|
+
"lib/string.k",
|
|
16
|
+
"lib/ieee.k",
|
|
17
|
+
"Examples/ieee-arithmetics.k"
|
|
18
|
+
]) {
|
|
19
|
+
await evaluateInput(`:load ${file}`, state);
|
|
20
|
+
}
|
|
13
21
|
|
|
14
22
|
for (const name of ["add", "sub", "mul", "div"]) {
|
|
15
23
|
assert.ok(state.relAliases[name], `Expected public IEEE relation '${name}'`);
|
package/tests/test-ieee-text.mjs
CHANGED
|
@@ -6,10 +6,21 @@ import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/s
|
|
|
6
6
|
import { encodeNumberToValue, decodeValueToNumber } from "../codecs/ieee.mjs";
|
|
7
7
|
import { textToStringValue, stringValueToText } from "../codecs/runtime/unicode-string.mjs";
|
|
8
8
|
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
const ieeeSources = [
|
|
10
|
+
"lib/bit.k",
|
|
11
|
+
"lib/bits.k",
|
|
12
|
+
"lib/list.k",
|
|
13
|
+
"lib/btrie.k",
|
|
14
|
+
"lib/string.k",
|
|
15
|
+
"lib/ieee.k"
|
|
16
|
+
];
|
|
17
|
+
let ieee = null;
|
|
18
|
+
for (const file of ieeeSources) {
|
|
19
|
+
ieee = loadLibrary(compileLibrary(readFileSync(new URL(`../${file}`, import.meta.url), "utf8"), {
|
|
20
|
+
source: file,
|
|
21
|
+
libraries: ieee ? [ieee] : []
|
|
22
|
+
}));
|
|
23
|
+
}
|
|
13
24
|
assert.equal(ieee.relAlias.add, undefined, "Text conversion must not load IEEE arithmetic");
|
|
14
25
|
const parser = await instantiateWasmArtifact(await compileWasmArtifact(ieee.relAlias.parseFloat64, { libraries: [ieee] }));
|
|
15
26
|
const printer = await instantiateWasmArtifact(await compileWasmArtifact(ieee.relAlias.printFloat64, { libraries: [ieee] }));
|
package/tests/test-k-object.mjs
CHANGED
|
@@ -101,13 +101,21 @@ const recursiveNatPattern = new RegExp(
|
|
|
101
101
|
assert.equal(natRoundTripSource, natDecompiledSource);
|
|
102
102
|
assert.match(natDecompiledSource, recursiveNatPattern);
|
|
103
103
|
|
|
104
|
+
const bitLib = loadLibrary(decodeObject(compileLibraryBuffer(
|
|
105
|
+
fs.readFileSync("lib/bit.k", "utf8"),
|
|
106
|
+
{ source: "lib/bit.k" }
|
|
107
|
+
)));
|
|
108
|
+
const bitsLib = loadLibrary(decodeObject(compileLibraryBuffer(
|
|
109
|
+
fs.readFileSync("lib/bits.k", "utf8"),
|
|
110
|
+
{ source: "lib/bits.k", libraries: [bitLib] }
|
|
111
|
+
)));
|
|
104
112
|
const arithmeticsLibraryBuffer = compileLibraryBuffer(
|
|
105
|
-
fs.readFileSync("
|
|
106
|
-
{ source: "
|
|
113
|
+
fs.readFileSync("lib/arithmetics.k", "utf8"),
|
|
114
|
+
{ source: "lib/arithmetics.k", libraries: [bitsLib] }
|
|
107
115
|
);
|
|
108
116
|
const arithmeticsDecompiledSource = decompileObjectBuffer(arithmeticsLibraryBuffer);
|
|
109
117
|
const arithmeticsRoundTripSource = decompileObjectBuffer(
|
|
110
|
-
compileLibraryBuffer(arithmeticsDecompiledSource, { source: "
|
|
118
|
+
compileLibraryBuffer(arithmeticsDecompiledSource, { source: "lib/arithmetics.decompiled.k" })
|
|
111
119
|
);
|
|
112
120
|
assert.equal(arithmeticsRoundTripSource, arithmeticsDecompiledSource);
|
|
113
121
|
|
package/tests/test-karatsuba.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { withCompiledLibrary, runLibrary, integer } from "./helpers/cli.mjs";
|
|
|
3
3
|
|
|
4
4
|
const large = "11111112222223333334444444555555666666777777788888899999900000011111122222233333344444455555";
|
|
5
5
|
|
|
6
|
-
withCompiledLibrary("
|
|
6
|
+
withCompiledLibrary(["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"], (library) => {
|
|
7
7
|
const multiply = (source, input) =>
|
|
8
8
|
integer(runLibrary(library, ["karatsuba"], source, input), source);
|
|
9
9
|
|
|
@@ -223,7 +223,7 @@ console.log("==> Starting Polymorphic kVM & Specialization Tests");
|
|
|
223
223
|
// Test 7: CLI Compilation to Polymorphic .kvm without --input-pattern
|
|
224
224
|
{
|
|
225
225
|
const compileScript = path.join(__dirname, "../objects/compile.mjs");
|
|
226
|
-
const res = spawnSync(process.execPath, [compileScript, "--format", "kvm", "Examples/
|
|
226
|
+
const res = spawnSync(process.execPath, [compileScript, "--format", "kvm", "Examples/nat.k"], {
|
|
227
227
|
cwd: path.join(__dirname, ".."),
|
|
228
228
|
encoding: "utf8"
|
|
229
229
|
});
|
|
@@ -236,41 +236,61 @@ console.log("==> Starting Polymorphic kVM & Specialization Tests");
|
|
|
236
236
|
console.log("Test 7 (CLI Compilation to Polymorphic .kvm): Passed");
|
|
237
237
|
}
|
|
238
238
|
|
|
239
|
-
// Test 8: CLI Compilation with --lib and explicit --
|
|
239
|
+
// Test 8: CLI Compilation with --lib and explicit --use (no auto-export)
|
|
240
240
|
{
|
|
241
241
|
const compileScript = path.join(__dirname, "../objects/compile.mjs");
|
|
242
|
-
|
|
243
|
-
const
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
242
|
+
const os = await import("node:os");
|
|
243
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-kvm-poly-"));
|
|
244
|
+
try {
|
|
245
|
+
let prevLib = null;
|
|
246
|
+
for (const [idx, src] of ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"].entries()) {
|
|
247
|
+
const nextLib = path.join(tmpDir, `step-${idx}.klib`);
|
|
248
|
+
const stepRes = spawnSync(process.execPath, [
|
|
249
|
+
compileScript,
|
|
250
|
+
...(prevLib ? ["--lib", prevLib] : []),
|
|
251
|
+
src,
|
|
252
|
+
nextLib
|
|
253
|
+
], {
|
|
254
|
+
cwd: path.join(__dirname, ".."),
|
|
255
|
+
encoding: "utf8"
|
|
256
|
+
});
|
|
257
|
+
assert.equal(stepRes.status, 0, `CLI lib step failed: ${stepRes.stderr}`);
|
|
258
|
+
prevLib = nextLib;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Fails without explicit --use
|
|
262
|
+
const failRes = spawnSync(process.execPath, [
|
|
263
|
+
compileScript,
|
|
264
|
+
"--lib", prevLib,
|
|
265
|
+
"{succ int x,int y}+"
|
|
266
|
+
], {
|
|
267
|
+
cwd: path.join(__dirname, ".."),
|
|
268
|
+
encoding: "utf8"
|
|
269
|
+
});
|
|
270
|
+
assert.notEqual(failRes.status, 0, "Should fail without explicit --use");
|
|
271
|
+
|
|
272
|
+
// Succeeds with explicit --use
|
|
273
|
+
const successRes = spawnSync(process.execPath, [
|
|
274
|
+
compileScript,
|
|
275
|
+
"--lib", prevLib,
|
|
276
|
+
"--use", "plus:+ succ int",
|
|
277
|
+
"--format", "kvm",
|
|
278
|
+
"{succ int x,int y}+"
|
|
279
|
+
], {
|
|
280
|
+
cwd: path.join(__dirname, ".."),
|
|
281
|
+
encoding: "utf8",
|
|
282
|
+
maxBuffer: 10 * 1024 * 1024
|
|
283
|
+
});
|
|
284
|
+
assert.equal(successRes.status, 0, `CLI compile with --use failed: ${successRes.stderr}`);
|
|
285
|
+
const kvm = JSON.parse(successRes.stdout);
|
|
286
|
+
assert.equal(kvm.format, "k-vm");
|
|
287
|
+
assert.equal(kvm.layer, "KVM-P");
|
|
288
|
+
assert.equal(kvm.isPolymorphic, true);
|
|
289
|
+
assert.ok(kvm.functions["__main__"]);
|
|
290
|
+
console.log("Test 8 (CLI Compilation with --lib and explicit --use): Passed");
|
|
291
|
+
} finally {
|
|
292
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
293
|
+
}
|
|
274
294
|
}
|
|
275
295
|
|
|
276
296
|
console.log("==> All Polymorphic kVM Tests Passed Successfully!");
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import k from "../index.mjs";
|
|
4
|
+
import { Value } from "../Value.mjs";
|
|
5
|
+
import { compileLibrary, loadLibrary } from "../object.mjs";
|
|
6
|
+
import { fromJsonValue, toJsonValue } from "../codecs/djson.mjs";
|
|
7
|
+
import { textToStringValue, stringValueToText } from "../codecs/runtime/unicode-string.mjs";
|
|
8
|
+
import { encodeNumberToValue, decodeValueToNumber } from "../codecs/ieee.mjs";
|
|
9
|
+
import { parse as parseInt, parseIntStr, print as printInt } from "../codecs/int.mjs";
|
|
10
|
+
|
|
11
|
+
const libFiles = [
|
|
12
|
+
"lib/bit.k",
|
|
13
|
+
"lib/bits.k",
|
|
14
|
+
"lib/arithmetics.k",
|
|
15
|
+
"lib/list.k",
|
|
16
|
+
"lib/btrie.k",
|
|
17
|
+
"lib/string.k",
|
|
18
|
+
"lib/ieee.k",
|
|
19
|
+
"lib/djson.k"
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
const libs = [];
|
|
23
|
+
for (const file of libFiles) {
|
|
24
|
+
const source = readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
|
|
25
|
+
const compiled = loadLibrary(
|
|
26
|
+
compileLibrary(source, { source: file, libraries: libs })
|
|
27
|
+
);
|
|
28
|
+
libs.push(compiled);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const arithLib = libs[2];
|
|
32
|
+
const ieeeLib = libs[6];
|
|
33
|
+
const djsonLib = libs[7];
|
|
34
|
+
|
|
35
|
+
const runArith = (op, value) =>
|
|
36
|
+
k.compile(arithLib.relAlias[op], { libraries: [arithLib] })(value);
|
|
37
|
+
const runIeee = (op, value) =>
|
|
38
|
+
k.compile(ieeeLib.relAlias[op], { libraries: [ieeeLib] })(value);
|
|
39
|
+
const runDjson = (op, value) =>
|
|
40
|
+
k.compile(djsonLib.relAlias[op], { libraries: [djsonLib] })(value);
|
|
41
|
+
|
|
42
|
+
// Verify lib/arithmetics.k integer operations.
|
|
43
|
+
assert.equal(
|
|
44
|
+
printInt(runArith("plus", Value.product({ x: parseIntStr("19"), y: parseIntStr("23") }))),
|
|
45
|
+
"42"
|
|
46
|
+
);
|
|
47
|
+
assert.equal(
|
|
48
|
+
printInt(runArith("times", Value.product({ x: parseIntStr("-6"), y: parseIntStr("7") }))),
|
|
49
|
+
"-42"
|
|
50
|
+
);
|
|
51
|
+
assert.equal(
|
|
52
|
+
printInt(runArith("karatsuba", Value.product({ x: parseIntStr("123456"), y: parseIntStr("-654321") }))),
|
|
53
|
+
String(123456n * -654321n)
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
// Verify lib/ieee.k text parsing, natural conversion, and exact decimal printing.
|
|
57
|
+
for (const num of [0, -0, 1, -1, 3.141592653589793, 1e-10, 1e20, Infinity, -Infinity, NaN]) {
|
|
58
|
+
const val = encodeNumberToValue(num);
|
|
59
|
+
const text = stringValueToText(runIeee("printFloat64", val));
|
|
60
|
+
const parsed = decodeValueToNumber(runIeee("parseFloat64", textToStringValue(text)));
|
|
61
|
+
if (Number.isNaN(num)) {
|
|
62
|
+
assert.ok(Number.isNaN(parsed));
|
|
63
|
+
} else {
|
|
64
|
+
assert.ok(Object.is(parsed, num), `round-trip ${num} via ${text}`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
for (const n of [0, 1, 2, 10, 42, 1024, 65535]) {
|
|
69
|
+
const f = decodeValueToNumber(runIeee("natToFloat64", parseInt(String(n)).value));
|
|
70
|
+
assert.equal(f, n);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Verify lib/djson.k methods and RFC 8259 JSON parser.
|
|
74
|
+
function method(op, json, { key, index, val } = {}) {
|
|
75
|
+
const fields = { json: fromJsonValue(json) };
|
|
76
|
+
if (key !== undefined) fields.key = textToStringValue(key);
|
|
77
|
+
if (index !== undefined) fields.index = parseInt(String(index)).value;
|
|
78
|
+
if (val !== undefined) fields.val = fromJsonValue(val);
|
|
79
|
+
return runDjson(op, Value.product(fields));
|
|
80
|
+
}
|
|
81
|
+
const result = (...args) => toJsonValue(method(...args));
|
|
82
|
+
|
|
83
|
+
const doc = { name: "Alice", age: 30, tags: ["developer", "k"] };
|
|
84
|
+
assert.equal(result("get", doc, { key: "name" }), "Alice");
|
|
85
|
+
assert.equal(result("get", doc, { key: "age" }), 30);
|
|
86
|
+
assert.ok(method("has?", doc, { key: "name" }));
|
|
87
|
+
assert.equal(method("has?", doc, { key: "missing" }), undefined);
|
|
88
|
+
|
|
89
|
+
const withCity = result("set", doc, { key: "city", val: "Paris" });
|
|
90
|
+
assert.deepEqual(withCity, { ...doc, city: "Paris" });
|
|
91
|
+
const withoutAge = result("del", withCity, { key: "age" });
|
|
92
|
+
assert.deepEqual(withoutAge, { name: "Alice", tags: doc.tags, city: "Paris" });
|
|
93
|
+
|
|
94
|
+
const arr = [10, 20, 30];
|
|
95
|
+
for (const [index, expected] of arr.entries()) {
|
|
96
|
+
assert.equal(result("nth", arr, { index }), expected);
|
|
97
|
+
}
|
|
98
|
+
assert.ok(method("has_index?", arr, { index: 1 }));
|
|
99
|
+
assert.equal(method("has_index?", arr, { index: 99 }), undefined);
|
|
100
|
+
assert.deepEqual(result("set_nth", arr, { index: 1, val: 99 }), [10, 99, 30]);
|
|
101
|
+
assert.equal(toJsonValue(runDjson("length", fromJsonValue(arr))), 3);
|
|
102
|
+
assert.equal(toJsonValue(runDjson("length", fromJsonValue(doc))), 3);
|
|
103
|
+
assert.equal(toJsonValue(runDjson("length", fromJsonValue("hello"))), 5);
|
|
104
|
+
assert.deepEqual(result("push", arr, { val: 40 }), [10, 20, 30, 40]);
|
|
105
|
+
assert.deepEqual(new Set(toJsonValue(runDjson("keys", fromJsonValue(doc)))), new Set(["name", "age", "tags"]));
|
|
106
|
+
|
|
107
|
+
const sampleJson = JSON.stringify({
|
|
108
|
+
nullVal: null,
|
|
109
|
+
bools: [true, false],
|
|
110
|
+
nums: [0, -0, 42, -12.5, 1e5],
|
|
111
|
+
str: "hello\n\t\"world\"\\/\u0041\uD83D\uDE00",
|
|
112
|
+
empty: [{}, []]
|
|
113
|
+
});
|
|
114
|
+
const parsedJson = toJsonValue(runDjson("parseJson", textToStringValue(sampleJson)));
|
|
115
|
+
assert.deepEqual(parsedJson, JSON.parse(sampleJson));
|
|
@@ -3,7 +3,7 @@ import k from "../index.mjs";
|
|
|
3
3
|
import { Value } from "../Value.mjs";
|
|
4
4
|
import { compileLibrary, extractAliasesFromObject } from "../object.mjs";
|
|
5
5
|
import { validateObjectPayload } from "../objects/validate.mjs";
|
|
6
|
-
import {
|
|
6
|
+
import { buildUsePreamble, resolvePatternCanonicalInfo } from "../canonical-pattern.mjs";
|
|
7
7
|
|
|
8
8
|
const BIT = "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg";
|
|
9
9
|
const LIST = "@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe";
|
|
@@ -111,9 +111,11 @@ const aliases = extractAliasesFromObject(library);
|
|
|
111
111
|
for (const expected of [/bit\[\] = @Mjusy/, /list\[X\] = @JagVex/, /pair\[A, B\] = @KqTB/]) {
|
|
112
112
|
assert.match(aliases, expected);
|
|
113
113
|
}
|
|
114
|
-
const preamble =
|
|
114
|
+
const preamble = buildUsePreamble(["bit", "list:my_list"], [library]);
|
|
115
115
|
assert.match(preamble, /bit\[\] = @Mjusy/);
|
|
116
116
|
assert.match(preamble, /my_list\[X\] = @JagVex/);
|
|
117
|
+
const usePreamble = buildUsePreamble(["bit list:my_list"], [library]);
|
|
118
|
+
assert.equal(usePreamble, preamble);
|
|
117
119
|
|
|
118
120
|
{
|
|
119
121
|
const out = evaluate(`
|
|
@@ -130,7 +132,14 @@ assert.equal(evaluate(`
|
|
|
130
132
|
my_list[T] = ${LIST}[T];
|
|
131
133
|
{{}|0 car, {}|nil cdr}|cons ?my_list[my_bit[]]
|
|
132
134
|
`, { libraries: [library] }).tag, "cons");
|
|
133
|
-
|
|
135
|
+
// Unexported pattern templates from a library do not leak into scope:
|
|
136
|
+
assert.throws(
|
|
137
|
+
() => evaluate("is_bit = ?bit[]; ()", { libraries: [library] }),
|
|
138
|
+
/Unknown pattern template 'bit\[\]'/
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
const preambleBoth = buildUsePreamble(["bit", "list"], [library]);
|
|
142
|
+
assert.equal(evaluate(preambleBoth + `
|
|
134
143
|
is_bit = ?bit[];
|
|
135
144
|
is_pair = ?${PAIR}[bit[],bit[]];
|
|
136
145
|
is_pair_list = ?list[${PAIR}[bit[],bit[]]];
|
|
@@ -11,11 +11,22 @@ import { textToStringValue } from "../codecs/runtime/unicode-string.mjs";
|
|
|
11
11
|
import { parse as utf8 } from "../codecs/utf8.mjs";
|
|
12
12
|
import { encodeToWire, decodeWire } from "../codecs/runtime/codec-sdk.mjs";
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
14
|
+
let ieee = null;
|
|
15
|
+
for (const file of [
|
|
16
|
+
"lib/bit.k",
|
|
17
|
+
"lib/bits.k",
|
|
18
|
+
"lib/list.k",
|
|
19
|
+
"lib/btrie.k",
|
|
20
|
+
"lib/string.k",
|
|
21
|
+
"lib/ieee.k"
|
|
22
|
+
]) {
|
|
23
|
+
ieee = loadLibrary(compileLibrary(readFileSync(new URL(`../${file}`, import.meta.url), "utf8"), {
|
|
24
|
+
source: file,
|
|
25
|
+
libraries: ieee ? [ieee] : []
|
|
26
|
+
}));
|
|
27
|
+
}
|
|
28
|
+
const library = loadLibrary(compileLibrary(readFileSync(new URL("../lib/djson.k", import.meta.url), "utf8"), {
|
|
29
|
+
source: "lib/djson.k",
|
|
19
30
|
libraries: [ieee]
|
|
20
31
|
}));
|
|
21
32
|
const wasm = await instantiateWasmArtifact(await compileWasmArtifact(library.relAlias.parseJson, { libraries: [library] }));
|
|
@@ -72,19 +83,28 @@ for (const text of ["1e309", "-1.8e308"]) assert.equal(fast(text), undefined, te
|
|
|
72
83
|
const text = '{"answer":42,"ok":true}';
|
|
73
84
|
const scratch = mkdtempSync(path.join(os.tmpdir(), "k-json-test-"));
|
|
74
85
|
try {
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
86
|
+
const chain = [
|
|
87
|
+
"lib/bit.k",
|
|
88
|
+
"lib/bits.k",
|
|
89
|
+
"lib/list.k",
|
|
90
|
+
"lib/btrie.k",
|
|
91
|
+
"lib/string.k",
|
|
92
|
+
"lib/ieee.k",
|
|
93
|
+
"lib/djson.k"
|
|
94
|
+
];
|
|
95
|
+
let prev = null;
|
|
96
|
+
for (let i = 0; i < chain.length; i++) {
|
|
97
|
+
const out = path.join(scratch, `step-${i}.klib`);
|
|
98
|
+
const args = ["objects/compile.mjs", ...(prev ? ["--lib", prev] : []), chain[i], out];
|
|
99
|
+
const built = spawnSync(process.execPath, args, {
|
|
82
100
|
cwd: new URL("..", import.meta.url)
|
|
83
101
|
});
|
|
84
102
|
assert.ifError(built.error);
|
|
85
103
|
assert.equal(built.status, 0, built.stderr.toString());
|
|
104
|
+
prev = out;
|
|
86
105
|
}
|
|
87
|
-
const
|
|
106
|
+
const artifact = prev;
|
|
107
|
+
const cli = spawnSync(process.execPath, ["k.mjs", "--lib", artifact, "--use", "parseJson", "parseJson"], {
|
|
88
108
|
cwd: new URL("..", import.meta.url), input: encodeToWire(utf8(text))
|
|
89
109
|
});
|
|
90
110
|
assert.ifError(cli.error);
|