@fraczak/k 8.7.1 → 8.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/DOCS/CODECS.md +42 -40
- package/DOCS/FILE_FORMATS.md +28 -25
- package/DOCS/GETTING_STARTED.md +10 -15
- package/DOCS/PATTERNS.md +3 -3
- package/DOCS/REPL.md +3 -6
- package/Examples/ieee-arithmetics.k +14 -29
- package/Examples/poly.k +18 -29
- package/README.md +14 -18
- package/backend-api.mjs +1 -3
- package/backends/llvm/src/cli.mjs +1 -2
- package/backends/llvm/tests/integration.sh +2 -6
- package/backends/wasm/tests/integration.sh +5 -10
- package/browser/shims/fs.mjs +2 -6
- package/canonical-pattern.mjs +9 -29
- package/codecs/djson.mjs +2 -3
- package/codecs/int.mjs +66 -14
- package/compiler.mjs +22 -12
- package/harness/suites/poly.mjs +9 -11
- package/index.mjs +119 -50
- package/lib/djson.k +976 -288
- package/lib/generic.k +686 -0
- package/lib/ieee.k +658 -639
- package/lib/integer.k +536 -0
- package/object.mjs +19 -12
- package/objects/README.md +6 -6
- package/package.json +1 -1
- package/scripts/benchmark-idempotency.mjs +16 -17
- package/scripts/benchmark.mjs +39 -29
- package/scripts/build-repl-html.mjs +45 -35
- package/scripts/perf-bigint-compare.mjs +279 -0
- package/scripts/perf-ieee.mjs +1 -5
- package/scripts/perf-int.mjs +12 -27
- package/scripts/perf-multiplication.mjs +8 -9
- package/scripts/perf-poly.mjs +7 -10
- package/scripts/render-benchmark.mjs +1 -1
- package/scripts/run-tests.mjs +4 -2
- package/scripts/test-package.mjs +4 -10
- package/tests/README.md +4 -5
- package/tests/helpers/cli.mjs +30 -7
- package/tests/integration.sh +5 -10
- package/tests/test-arithmetics.mjs +23 -16
- package/tests/test-djson-methods.mjs +16 -25
- package/tests/test-djson.mjs +272 -0
- package/tests/test-generic.mjs +237 -0
- package/tests/test-ieee-arithmetic.mjs +1 -5
- package/tests/test-ieee.mjs +153 -0
- package/tests/test-integer.mjs +264 -0
- package/tests/test-k-object.mjs +12 -18
- package/tests/test-kvm-polymorphic.mjs +6 -7
- package/tests/test-lib.mjs +62 -52
- package/tests/test-library-isolation.mjs +349 -26
- package/tests/test-parse-json.mjs +15 -24
- package/tests/test-poly.mjs +21 -16
- package/tests/test-repl-html.mjs +39 -44
- package/tests/test-repl.mjs +46 -59
- package/tests/test-structural-values.mjs +1 -1
- package/DOCS/book-combined.md +0 -3786
- package/DOCS/dependency-graph.md +0 -144
- package/Examples/arithmetics.k +0 -108
- package/Examples/esc.k +0 -9
- package/lib/arithmetics.k +0 -286
- package/lib/bit.k +0 -68
- package/lib/bits.k +0 -227
- package/lib/btrie.k +0 -187
- package/lib/list.k +0 -49
- package/lib/string.k +0 -588
- package/tests/test-ieee-text.mjs +0 -74
- package/tests/test-karatsuba.mjs +0 -25
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
import { spawnSync } from "node:child_process";
|
|
4
|
-
import { mkdtempSync, rmSync, statSync } from "node:fs";
|
|
4
|
+
import { readFileSync, mkdtempSync, rmSync, statSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
6
|
import { join, resolve } from "node:path";
|
|
7
7
|
import { performance } from "node:perf_hooks";
|
|
8
|
+
import { useSpecsFor } from "../tests/helpers/cli.mjs";
|
|
8
9
|
|
|
9
10
|
const DEFAULT_EXAMPLES = [
|
|
10
11
|
"Examples/nat.k",
|
|
11
|
-
"lib/
|
|
12
|
-
"lib/
|
|
12
|
+
"lib/generic.k",
|
|
13
|
+
"lib/integer.k",
|
|
13
14
|
"lib/ieee.k",
|
|
14
15
|
"Examples/ieee-arithmetics.k"
|
|
15
16
|
];
|
|
@@ -24,8 +25,8 @@ for K source files through the .klib object format.
|
|
|
24
25
|
Arguments:
|
|
25
26
|
example.k ...
|
|
26
27
|
One or more .k source files to benchmark.
|
|
27
|
-
(default: Examples/nat.k lib/
|
|
28
|
-
lib/
|
|
28
|
+
(default: Examples/nat.k lib/generic.k
|
|
29
|
+
lib/integer.k lib/ieee.k
|
|
29
30
|
Examples/ieee-arithmetics.k)
|
|
30
31
|
|
|
31
32
|
Options:
|
|
@@ -84,25 +85,23 @@ for (const example of benchmarkExamples) {
|
|
|
84
85
|
const out = mkdtempSync(join(tmpdir(), `k-idempotency-bench-${example.replaceAll("/", "_")}-`));
|
|
85
86
|
try {
|
|
86
87
|
const depsByTarget = new Map([
|
|
87
|
-
[resolve("lib/
|
|
88
|
-
[resolve("lib/
|
|
89
|
-
[resolve("Examples/
|
|
90
|
-
[resolve("lib/
|
|
91
|
-
[resolve("
|
|
92
|
-
[resolve("
|
|
93
|
-
[resolve("lib/string.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k"]],
|
|
94
|
-
[resolve("lib/ieee.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k"]],
|
|
95
|
-
[resolve("lib/djson.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k", "lib/ieee.k"]],
|
|
96
|
-
[resolve("Examples/ieee-arithmetics.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k", "lib/ieee.k"]]
|
|
88
|
+
[resolve("lib/generic.k"), ["core.k"]],
|
|
89
|
+
[resolve("lib/integer.k"), []],
|
|
90
|
+
[resolve("Examples/poly.k"), ["lib/integer.k"]],
|
|
91
|
+
[resolve("lib/ieee.k"), ["core.k"]],
|
|
92
|
+
[resolve("lib/djson.k"), ["core.k", "lib/generic.k", "lib/ieee.k"]],
|
|
93
|
+
[resolve("Examples/ieee-arithmetics.k"), ["core.k", "lib/ieee.k"]]
|
|
97
94
|
]);
|
|
95
|
+
const useArgsFor = (filePath) =>
|
|
96
|
+
useSpecsFor(filePath).flatMap((u) => ["--use", u]);
|
|
98
97
|
const deps = depsByTarget.get(resolve(example)) || [];
|
|
99
98
|
let dependency;
|
|
100
99
|
for (const [idx, dep] of deps.entries()) {
|
|
101
100
|
const nextDep = join(out, `dep-${idx}.klib`);
|
|
102
|
-
run(["objects/compile.mjs", ...(dependency ? ["--lib", dependency] : []), dep, nextDep]);
|
|
101
|
+
run(["objects/compile.mjs", ...(dependency ? ["--lib", dependency, ...useArgsFor(dep)] : []), dep, nextDep]);
|
|
103
102
|
dependency = nextDep;
|
|
104
103
|
}
|
|
105
|
-
const library = dependency ? ["--lib", dependency] : [];
|
|
104
|
+
const library = dependency ? ["--lib", dependency, ...useArgsFor(example)] : [];
|
|
106
105
|
const t0 = performance.now();
|
|
107
106
|
run(["objects/compile.mjs", ...library, example, join(out, "1.klib")]);
|
|
108
107
|
run(["objects/decompile.mjs", join(out, "1.klib"), join(out, "1.k")]);
|
package/scripts/benchmark.mjs
CHANGED
|
@@ -64,7 +64,7 @@ const cases = [
|
|
|
64
64
|
{ name: "ieee.mul", suite: "ieee", rel: "mul", input: { x: "-2", y: "4" } },
|
|
65
65
|
{ name: "ieee.div", suite: "ieee", rel: "div", input: { x: "1", y: "2" } },
|
|
66
66
|
{ name: "int.times.220d", suite: "arithmetics", rel: "times", input: { shape: "int-pair", x: bigA, y: bigB } },
|
|
67
|
-
{ name: "int.gcd.90d", suite: "arithmetics", rel: "gcd", input: { shape: "
|
|
67
|
+
{ name: "int.gcd.90d", suite: "arithmetics", rel: "gcd", input: { shape: "int-pair", x: gcdA, y: gcdB } },
|
|
68
68
|
{ name: "int.factorial.101", suite: "arithmetics", rel: "factorial", input: { shape: "int", x: "101" } },
|
|
69
69
|
{ name: "int.factorial.242", suite: "arithmetics", rel: "factorial", input: { shape: "int", x: "242" } },
|
|
70
70
|
{ name: "int.factorial.1174", suite: "arithmetics", rel: "factorial", input: { shape: "int", x: "1174" } }
|
|
@@ -150,41 +150,48 @@ function sha256() {
|
|
|
150
150
|
return crypto.createHash("sha256");
|
|
151
151
|
}
|
|
152
152
|
|
|
153
|
+
const ARITHMETIC_FACTORIAL_SOURCE = `
|
|
154
|
+
_factorial = ?{ int[] n, int[] acc } <
|
|
155
|
+
{ .n zero? _n, .acc acc } .acc,
|
|
156
|
+
{ .n pos? dec n, { .n x, .acc y } times acc } _factorial
|
|
157
|
+
> ?int[];
|
|
158
|
+
factorial = ?int[] { () n, 1 acc } _factorial ?int[];
|
|
159
|
+
`;
|
|
160
|
+
|
|
153
161
|
function suiteSourcePath(suite) {
|
|
154
162
|
return path.join(kRoot, sourceNameForSuite(suite));
|
|
155
163
|
}
|
|
156
164
|
|
|
157
165
|
function sourceNameForSuite(suite) {
|
|
158
|
-
return suite === "ieee" ? "Examples/ieee-arithmetics.k" : "
|
|
166
|
+
return suite === "ieee" ? "Examples/ieee-arithmetics.k" : "lib/integer.k";
|
|
159
167
|
}
|
|
160
168
|
|
|
161
169
|
let ieeeDependencies;
|
|
162
|
-
|
|
170
|
+
const EXPLICIT_USES = {
|
|
171
|
+
"lib/ieee.k": ["bit[] bits[]"]
|
|
172
|
+
};
|
|
173
|
+
function compileDepChain(files) {
|
|
174
|
+
let prev = null;
|
|
175
|
+
for (const f of files) {
|
|
176
|
+
const src = fs.readFileSync(path.join(kRoot, f), "utf8");
|
|
177
|
+
const use = EXPLICIT_USES[f] || [];
|
|
178
|
+
prev = loadLibrary(compileLibrary(src, {
|
|
179
|
+
source: f,
|
|
180
|
+
libraries: prev ? [prev] : [],
|
|
181
|
+
use
|
|
182
|
+
}));
|
|
183
|
+
}
|
|
184
|
+
return [prev];
|
|
185
|
+
}
|
|
186
|
+
|
|
163
187
|
function dependenciesForSuite(suite) {
|
|
164
188
|
if (suite === "ieee") {
|
|
165
189
|
if (!ieeeDependencies) {
|
|
166
|
-
|
|
167
|
-
for (const f of ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k", "lib/ieee.k"]) {
|
|
168
|
-
prev = loadLibrary(compileLibrary(fs.readFileSync(path.join(kRoot, f), "utf8"), {
|
|
169
|
-
source: f,
|
|
170
|
-
libraries: prev ? [prev] : []
|
|
171
|
-
}));
|
|
172
|
-
}
|
|
173
|
-
ieeeDependencies = [prev];
|
|
190
|
+
ieeeDependencies = compileDepChain(["core.k", "lib/ieee.k"]);
|
|
174
191
|
}
|
|
175
192
|
return ieeeDependencies;
|
|
176
193
|
}
|
|
177
|
-
|
|
178
|
-
let prev = null;
|
|
179
|
-
for (const f of ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"]) {
|
|
180
|
-
prev = loadLibrary(compileLibrary(fs.readFileSync(path.join(kRoot, f), "utf8"), {
|
|
181
|
-
source: f,
|
|
182
|
-
libraries: prev ? [prev] : []
|
|
183
|
-
}));
|
|
184
|
-
}
|
|
185
|
-
arithDependencies = [prev];
|
|
186
|
-
}
|
|
187
|
-
return arithDependencies;
|
|
194
|
+
return [];
|
|
188
195
|
}
|
|
189
196
|
|
|
190
197
|
function stripTrailingUnitMain(source) {
|
|
@@ -194,7 +201,8 @@ function stripTrailingUnitMain(source) {
|
|
|
194
201
|
function sourceForCase(testCase) {
|
|
195
202
|
const sourcePath = suiteSourcePath(testCase.suite);
|
|
196
203
|
const source = stripTrailingUnitMain(fs.readFileSync(sourcePath, "utf8"));
|
|
197
|
-
|
|
204
|
+
const extra = testCase.rel === "factorial" ? ARITHMETIC_FACTORIAL_SOURCE : "";
|
|
205
|
+
return `${source}${extra}\n${testCase.rel}\n`;
|
|
198
206
|
}
|
|
199
207
|
|
|
200
208
|
function relationPattern(relDef, index) {
|
|
@@ -489,13 +497,15 @@ async function prepareBackendRunner(job, relation, inputVal, state) {
|
|
|
489
497
|
|
|
490
498
|
async function prepareState(suite) {
|
|
491
499
|
const state = createState();
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
await evaluateInput(`:load ${
|
|
500
|
+
if (suite === "ieee") {
|
|
501
|
+
for (const dep of ["core.k", "lib/ieee.k"]) {
|
|
502
|
+
await evaluateInput(`:load ${path.join(kRoot, dep)}`, state);
|
|
503
|
+
}
|
|
504
|
+
await evaluateInput(`:load ${suiteSourcePath(suite)}`, state);
|
|
505
|
+
return state;
|
|
497
506
|
}
|
|
498
|
-
await evaluateInput(`:load ${
|
|
507
|
+
await evaluateInput(`:load ${path.join(kRoot, "lib/integer.k")}`, state);
|
|
508
|
+
await evaluateInput(ARITHMETIC_FACTORIAL_SOURCE, state);
|
|
499
509
|
return state;
|
|
500
510
|
}
|
|
501
511
|
|
|
@@ -14,7 +14,7 @@ function printHelp() {
|
|
|
14
14
|
console.log(`Usage: node scripts/build-repl-html.mjs [options]
|
|
15
15
|
|
|
16
16
|
Builds the standalone, self-contained K web REPL (repl.html).
|
|
17
|
-
Bundles browser shims, virtual file system (core.k, Examples, Wasm),
|
|
17
|
+
Bundles browser shims, virtual file system (core.k, lib, Examples, Wasm),
|
|
18
18
|
and UI components into a single zero-dependency HTML file.
|
|
19
19
|
|
|
20
20
|
Options:
|
|
@@ -80,12 +80,8 @@ if (fs.existsSync(coreKPath)) {
|
|
|
80
80
|
|
|
81
81
|
// Add verified lib/ k-code files
|
|
82
82
|
const verifiedLibs = [
|
|
83
|
-
"
|
|
84
|
-
"
|
|
85
|
-
"arithmetics.k",
|
|
86
|
-
"list.k",
|
|
87
|
-
"btrie.k",
|
|
88
|
-
"string.k",
|
|
83
|
+
"generic.k",
|
|
84
|
+
"integer.k",
|
|
89
85
|
"ieee.k",
|
|
90
86
|
"djson.k"
|
|
91
87
|
];
|
|
@@ -101,9 +97,9 @@ for (const filename of verifiedLibs) {
|
|
|
101
97
|
|
|
102
98
|
// Add verified Examples/ k-code files
|
|
103
99
|
const verifiedExamples = [
|
|
104
|
-
"
|
|
105
|
-
"
|
|
106
|
-
"
|
|
100
|
+
"nat.k",
|
|
101
|
+
"poly.k",
|
|
102
|
+
"ieee-arithmetics.k"
|
|
107
103
|
];
|
|
108
104
|
const examplesDir = path.join(projectRoot, "Examples");
|
|
109
105
|
for (const filename of verifiedExamples) {
|
|
@@ -1709,28 +1705,24 @@ const htmlContent = `<!DOCTYPE html>
|
|
|
1709
1705
|
<select id="example-select" title="Choose an example or expression">
|
|
1710
1706
|
<option value="">-- Example / Expression --</option>
|
|
1711
1707
|
<optgroup label="Standard Libraries (lib/)">
|
|
1712
|
-
<option value="
|
|
1713
|
-
<option value="lib/
|
|
1714
|
-
<option value="lib/
|
|
1715
|
-
<option value="lib/list.k">lib/list.k</option>
|
|
1716
|
-
<option value="lib/btrie.k">lib/btrie.k</option>
|
|
1717
|
-
<option value="lib/string.k">lib/string.k</option>
|
|
1708
|
+
<option value="core.k">core.k</option>
|
|
1709
|
+
<option value="lib/generic.k">lib/generic.k</option>
|
|
1710
|
+
<option value="lib/integer.k">lib/integer.k</option>
|
|
1718
1711
|
<option value="lib/ieee.k">lib/ieee.k</option>
|
|
1719
1712
|
<option value="lib/djson.k">lib/djson.k</option>
|
|
1720
1713
|
</optgroup>
|
|
1721
1714
|
<optgroup label="Examples">
|
|
1722
|
-
<option value="core.k">core.k</option>
|
|
1723
1715
|
<option value="Examples/nat.k">Examples/nat.k</option>
|
|
1724
|
-
<option value="Examples/arithmetics.k">Examples/arithmetics.k</option>
|
|
1725
1716
|
<option value="Examples/poly.k">Examples/poly.k</option>
|
|
1726
1717
|
<option value="Examples/ieee-arithmetics.k">Examples/ieee-arithmetics.k</option>
|
|
1727
1718
|
</optgroup>
|
|
1728
1719
|
<optgroup label="Quick Expressions">
|
|
1729
1720
|
<option value="expr:{} | ok">{} | ok</option>
|
|
1730
1721
|
<option value="expr:not = < / true | false, / false | true >; {} | true not">not (boolean relation)</option>
|
|
1731
|
-
<option value="expr:
|
|
1732
|
-
<option value="expr:
|
|
1733
|
-
<option value="expr:{
|
|
1722
|
+
<option value="expr:0 succ">0 succ (nat)</option>
|
|
1723
|
+
<option value="expr:1 inc">1 inc (int)</option>
|
|
1724
|
+
<option value="expr:{{}|_|0|1|0|1 nat x, {}|_|1|0|1 nat y} plus">{10 x, 5 y} plus (int)</option>
|
|
1725
|
+
<option value="expr:{{}|_|0|1|0|1 nat x, {}|_|1|0|1 nat y} times">{10 x, 5 y} times (Karatsuba)</option>
|
|
1734
1726
|
<option value="expr::rels">:rels (list relations)</option>
|
|
1735
1727
|
<option value="expr::engine">:engine (show engine)</option>
|
|
1736
1728
|
<option value="expr::engine wasm">:engine wasm</option>
|
|
@@ -1880,7 +1872,7 @@ const htmlContent = `<!DOCTYPE html>
|
|
|
1880
1872
|
<tbody>
|
|
1881
1873
|
<tr>
|
|
1882
1874
|
<td><code>name = relExpr;</code></td>
|
|
1883
|
-
<td><b>Relation Alias:</b> Defines a local alias for a relation expression.<br><i>e.g.</i> <code>swap = { .
|
|
1875
|
+
<td><b>Relation Alias:</b> Defines a local alias for a relation expression.<br><i>e.g.</i> <code>swap = { .y x, .x y };</code></td>
|
|
1884
1876
|
</tr>
|
|
1885
1877
|
<tr>
|
|
1886
1878
|
<td><code>name[P1, ..., Pn] = filter;</code></td>
|
|
@@ -1889,7 +1881,7 @@ const htmlContent = `<!DOCTYPE html>
|
|
|
1889
1881
|
pattern template.<br>
|
|
1890
1882
|
<i>e.g.</i><br>
|
|
1891
1883
|
<code>bit[] = < {} 0, {} 1 >;</code> or<br>
|
|
1892
|
-
<code>list[X] = < {} nil,
|
|
1884
|
+
<code>list[X] = < {} nil, { X car, Y cdr } cons > = Y;</code>
|
|
1893
1885
|
</td>
|
|
1894
1886
|
</tr>
|
|
1895
1887
|
</tbody>
|
|
@@ -1948,8 +1940,8 @@ const htmlContent = `<!DOCTYPE html>
|
|
|
1948
1940
|
<div class="help-section">
|
|
1949
1941
|
<h4>REPL Commands</h4>
|
|
1950
1942
|
<table class="help-table">
|
|
1951
|
-
<tr><td><code>:engine [wasm|pkir|js]</code></td><td>Display or switch evaluation engine (<code>wasm</code>, <code>pkir</code>, or <code>js</code>)</td></tr>
|
|
1952
|
-
<tr><td><code>:load <file></code></td><td>Load a <code>.k</code> source or <code>.klib</code> library into current state</td></tr>
|
|
1943
|
+
<tr><td><code>:engine [wasm|pkir|js]</code></td><td>Display or switch evaluation engine (<code>wasm</code>, <code>pkir</code>, or <code>js</code>; shortcuts: <code>:wasm</code>, <code>:pkir</code>, <code>:js</code>)</td></tr>
|
|
1944
|
+
<tr><td><code>:load [--no-alias] <file></code></td><td>Load a <code>.k</code> source or <code>.klib</code> library into current state (use <code>--no-alias</code> to import by hash only)</td></tr>
|
|
1953
1945
|
<tr>
|
|
1954
1946
|
<td><code>:pattern <name></code></td>
|
|
1955
1947
|
<td>
|
|
@@ -1975,23 +1967,41 @@ const htmlContent = `<!DOCTYPE html>
|
|
|
1975
1967
|
<tr><td><code>:rels</code></td><td>List all relation aliases</td></tr>
|
|
1976
1968
|
<tr><td><code>:limit [num|none]</code></td><td>Display or set maximum characters for value output</td></tr>
|
|
1977
1969
|
<tr><td><code>:max-pat-length [num|none]</code></td><td>Display or set max inline pattern length in <code>:rel</code> (default <code>45</code>, alias <code>:maxPatLength</code>)</td></tr>
|
|
1978
|
-
<tr><td><code>:codecs</code></td><td>List all loaded format codecs</td></tr>
|
|
1979
|
-
<tr><td><code>:codec load <file.mjs></code></td><td>Load a codec from
|
|
1970
|
+
<tr><td><code>:codecs</code></td><td>List all loaded format codecs (alias <code>:codec list</code>)</td></tr>
|
|
1971
|
+
<tr><td><code>:codec load <file.mjs></code></td><td>Load a codec from VFS (or via <b>Files</b>)</td></tr>
|
|
1980
1972
|
<tr><td><code>:codec unload <file.mjs></code></td><td>Unload a loaded codec</td></tr>
|
|
1981
1973
|
<tr><td><code>:input <codec.mjs> [text]</code></td><td>Parse input using specified codec (opens dialog if text omitted)</td></tr>
|
|
1982
1974
|
<tr><td><code>:klib <file></code></td><td>Export current state as a <code>.klib</code> binary file</td></tr>
|
|
1975
|
+
<tr><td><code>:ko <file> <expr></code></td><td>Export executable <code>.ko</code> object using <code><expr></code> as main</td></tr>
|
|
1983
1976
|
<tr><td><code>:reset</code></td><td>Clear state and reset to initial environment</td></tr>
|
|
1984
1977
|
<tr><td><code>:help</code></td><td>Show command reference</td></tr>
|
|
1985
1978
|
</table>
|
|
1986
1979
|
</div>
|
|
1987
1980
|
|
|
1981
|
+
<div class="help-section">
|
|
1982
|
+
<h4>Libraries & Examples (VFS)</h4>
|
|
1983
|
+
<p style="margin-bottom: 8px; color: var(--text-muted); line-height: 1.45;">
|
|
1984
|
+
Libraries and examples are bundled in the Virtual File System and can be loaded with <code>:load <file></code> or from the toolbar. Leading <code># --lib ...</code> lines are ordinary comments; load prerequisites in dependency order before dependents.
|
|
1985
|
+
</p>
|
|
1986
|
+
<table class="help-table">
|
|
1987
|
+
<tr><td><code>core.k</code></td><td>Standalone bit, Unicode string, and self-hosted pattern schemas (<code>bit[]</code>, <code>bits[]</code>, <code>list[X]</code>, <code>string[]</code>, <code>pattern[]</code>)</td></tr>
|
|
1988
|
+
<tr><td><code>lib/generic.k</code></td><td>Algebraic types, binary tries, and string/bit codecs (<code>bool[]</code>, <code>order[]</code>, <code>opt[V]</code>, <code>btrie[V]</code>); load <code>core.k</code> first</td></tr>
|
|
1989
|
+
<tr><td><code>lib/integer.k</code></td><td>Self-contained signed arbitrary-precision integers (<code>int[]</code>, <code>plus</code>, <code>minus</code>, Karatsuba <code>times</code>, <code>divmod</code>, <code>div</code>, <code>mod</code>, <code>gcd</code>, <code>lcm</code>)</td></tr>
|
|
1990
|
+
<tr><td><code>lib/ieee.k</code></td><td>Binary64 float types, predicates, negation, and conversions (<code>float64[]</code>); load <code>core.k</code> first</td></tr>
|
|
1991
|
+
<tr><td><code>lib/djson.k</code></td><td>RFC 8259 JSON parser (<code>parse_json</code>) and <code>djson[]</code> operations; load <code>core.k</code>, <code>lib/generic.k</code>, <code>lib/ieee.k</code> first</td></tr>
|
|
1992
|
+
<tr><td><code>Examples/nat.k</code></td><td>Small Peano natural-number arithmetic example (<code>nat[]</code>, <code>add</code>, <code>mult</code>)</td></tr>
|
|
1993
|
+
<tr><td><code>Examples/poly.k</code></td><td>Polymorphic list operations indexed by <code>int[]</code>; load <code>lib/integer.k</code> first</td></tr>
|
|
1994
|
+
<tr><td><code>Examples/ieee-arithmetics.k</code></td><td>Binary64 arithmetic returning <code>{result, flags}</code>; load <code>core.k</code> and <code>lib/ieee.k</code> first</td></tr>
|
|
1995
|
+
</table>
|
|
1996
|
+
</div>
|
|
1997
|
+
|
|
1988
1998
|
<div class="help-section">
|
|
1989
1999
|
<h4>Expressions & Snippets</h4>
|
|
1990
|
-
<p style="margin-bottom: 8px; color: var(--text-muted);">Any raw
|
|
2000
|
+
<p style="margin-bottom: 8px; color: var(--text-muted);">Any raw k expression entered at the prompt is compiled and evaluated on top of the current state (default engine: WebAssembly; switch via <code>:engine</code>). A line ending with <code>;</code> closes a definition block; end a line with <code>\</code> to continue.</p>
|
|
1991
2001
|
<ul>
|
|
1992
|
-
<li><code>{} |
|
|
1993
|
-
<li><code>not = < /
|
|
1994
|
-
<li><code>{} |
|
|
2002
|
+
<li><code>{} |ok</code> — Constant relation producing variant <code>ok</code> with empty document payload <code>{}</code></li>
|
|
2003
|
+
<li><code>not = < /true |false, /false |true >;</code> — Polymorphic negation via branch projections and ordered choice</li>
|
|
2004
|
+
<li><code>{} |true not</code> — Compose constant relation <code>{} |true</code> with <code>not</code> (evaluates to <code>{} |false</code>)</li>
|
|
1995
2005
|
<li><code>bool? = ?< {} true, {} false >;</code> — Define a boolean pattern filter relation</li>
|
|
1996
2006
|
<li>
|
|
1997
2007
|
<code>bit[] = < {} 0, {} 1 >;</code>
|
|
@@ -1999,11 +2009,11 @@ const htmlContent = `<!DOCTYPE html>
|
|
|
1999
2009
|
</li>
|
|
2000
2010
|
<li>
|
|
2001
2011
|
<code>? list[bool[]]</code>
|
|
2002
|
-
— Instantiated pattern filter matching booleans
|
|
2012
|
+
— Instantiated pattern filter matching a list of booleans (requires <code>list[X]</code> and <code>bool[]</code> in scope)
|
|
2003
2013
|
</li>
|
|
2004
|
-
<li><code>not = bool? ?X < /
|
|
2005
|
-
<li><code>swap = { .
|
|
2006
|
-
<li><code>{ {} |
|
|
2014
|
+
<li><code>not = bool? ?X < /true |false, {} |true > ?X;</code> — Filtered boolean negation: guarded by <code>bool?</code>, defaulting to <code>{} |true</code></li>
|
|
2015
|
+
<li><code>swap = { .y x, .x y };</code> — Define a product field-swapping relation</li>
|
|
2016
|
+
<li><code>{ {} |ok x, {} |nil y } swap</code> — Construct a product and pass it through <code>swap</code></li>
|
|
2007
2017
|
</ul>
|
|
2008
2018
|
</div>
|
|
2009
2019
|
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* End-to-End Integer Squaring Benchmark: K vs JS BigInt
|
|
5
|
+
*
|
|
6
|
+
* Compares the full UTF-8 decimal string -> parse -> N squarings -> decimal print
|
|
7
|
+
* pipeline between JavaScript BigInt and K (lib/integer.k) across backends:
|
|
8
|
+
* llvm, llvm-pkir, wasm, pkir, kvm, js
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* node scripts/perf-bigint-compare.mjs [options]
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import fs from "node:fs";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
import { performance } from "node:perf_hooks";
|
|
17
|
+
import { fileURLToPath } from "node:url";
|
|
18
|
+
|
|
19
|
+
import k from "../index.mjs";
|
|
20
|
+
import {
|
|
21
|
+
codes,
|
|
22
|
+
createState,
|
|
23
|
+
decodeWire,
|
|
24
|
+
encodeToWire,
|
|
25
|
+
evaluateInput,
|
|
26
|
+
executeKVM
|
|
27
|
+
} from "../backend-api.mjs";
|
|
28
|
+
import { compileLibrary, loadLibrary } from "../object.mjs";
|
|
29
|
+
import { parse as parseIntVal, print as printIntVal } from "../codecs/int.mjs";
|
|
30
|
+
import { compileObjectToExecutable } from "../backends/llvm/src/executable.mjs";
|
|
31
|
+
import {
|
|
32
|
+
compileWasmArtifact,
|
|
33
|
+
instantiateWasmArtifact
|
|
34
|
+
} from "../backends/wasm/src/wasm.mjs";
|
|
35
|
+
import {
|
|
36
|
+
PersistentExecutable,
|
|
37
|
+
makeCacheDir,
|
|
38
|
+
prepareRelation
|
|
39
|
+
} from "../backends/llvm/tests/perf-support.mjs";
|
|
40
|
+
|
|
41
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
42
|
+
const args = process.argv.slice(2);
|
|
43
|
+
|
|
44
|
+
function getArg(flag, fallback) {
|
|
45
|
+
const idx = args.indexOf(flag);
|
|
46
|
+
return idx !== -1 && args[idx + 1] ? args[idx + 1] : fallback;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (args.includes("-h") || args.includes("--help")) {
|
|
50
|
+
console.log(`Usage: node scripts/perf-bigint-compare.mjs [options]
|
|
51
|
+
|
|
52
|
+
End-to-end decimal parse -> N squarings -> decimal print benchmark comparing
|
|
53
|
+
JS BigInt against K (lib/integer.k) across execution backends.
|
|
54
|
+
|
|
55
|
+
Options:
|
|
56
|
+
--input <decimal> Starting decimal integer (default: 987654321)
|
|
57
|
+
--steps <n> Number of consecutive squarings (default: 10)
|
|
58
|
+
--backends <csv> K backends: llvm,llvm-pkir,wasm,pkir,kvm,js
|
|
59
|
+
(default: llvm,wasm,pkir)
|
|
60
|
+
--iters <n> Measured iterations per K backend (default: 3)
|
|
61
|
+
-h, --help Show this help message and exit`);
|
|
62
|
+
process.exit(0);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const INPUT = getArg("--input", "987654321");
|
|
66
|
+
const STEPS = Number.parseInt(getArg("--steps", "10"), 10);
|
|
67
|
+
const ITERS = Number.parseInt(getArg("--iters", "3"), 10);
|
|
68
|
+
const BACKENDS = getArg("--backends", "llvm,wasm,pkir")
|
|
69
|
+
.split(",")
|
|
70
|
+
.map((b) => b.trim().toLowerCase())
|
|
71
|
+
.filter(Boolean);
|
|
72
|
+
|
|
73
|
+
function fmtMs(ms) {
|
|
74
|
+
if (ms < 0.01) return `${(ms * 1000).toFixed(2)} µs`;
|
|
75
|
+
if (ms < 1) return `${(ms * 1000).toFixed(0)} µs`;
|
|
76
|
+
if (ms < 100) return `${ms.toFixed(2)} ms`;
|
|
77
|
+
if (ms < 1000) return `${ms.toFixed(1)} ms`;
|
|
78
|
+
return `${(ms / 1000).toFixed(2)} s`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// 1. JS BigInt baseline
|
|
82
|
+
function benchBigInt(iters = 500) {
|
|
83
|
+
let expected;
|
|
84
|
+
for (let i = 0; i < 20; i++) {
|
|
85
|
+
let x = BigInt(INPUT);
|
|
86
|
+
for (let s = 0; s < STEPS; s++) x = x * x;
|
|
87
|
+
expected = x.toString(10);
|
|
88
|
+
}
|
|
89
|
+
let parseMs = 0;
|
|
90
|
+
let computeMs = 0;
|
|
91
|
+
let printMs = 0;
|
|
92
|
+
for (let i = 0; i < iters; i++) {
|
|
93
|
+
const t0 = performance.now();
|
|
94
|
+
let x = BigInt(INPUT);
|
|
95
|
+
const t1 = performance.now();
|
|
96
|
+
for (let s = 0; s < STEPS; s++) x = x * x;
|
|
97
|
+
const t2 = performance.now();
|
|
98
|
+
const out = x.toString(10);
|
|
99
|
+
const t3 = performance.now();
|
|
100
|
+
if (out.length !== expected.length) throw new Error("BigInt mismatch");
|
|
101
|
+
parseMs += t1 - t0;
|
|
102
|
+
computeMs += t2 - t1;
|
|
103
|
+
printMs += t3 - t2;
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
name: "JS BigInt",
|
|
107
|
+
parseMs: parseMs / iters,
|
|
108
|
+
computeMs: computeMs / iters,
|
|
109
|
+
printMs: printMs / iters,
|
|
110
|
+
totalMs: (parseMs + computeMs + printMs) / iters,
|
|
111
|
+
output: expected
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const bigRes = benchBigInt();
|
|
116
|
+
console.log(
|
|
117
|
+
`Input: "${INPUT}" | Squarings: ${STEPS} | Output: ${bigRes.output.length} decimal digits`
|
|
118
|
+
);
|
|
119
|
+
console.log(
|
|
120
|
+
`Result: ${bigRes.output.slice(0, 30)}...${bigRes.output.slice(-20)}\n`
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
// 2. Compile sqN in K (both library form for Wasm/JS and REPL state for LLVM/kVM)
|
|
124
|
+
const intSource = fs.readFileSync(path.join(root, "lib/integer.k"), "utf8");
|
|
125
|
+
const sqDefs = `\nsq = ?int[] { () x, () y } times ?int[];\nsqN = ${Array(STEPS).fill("sq").join(" ")};\n`;
|
|
126
|
+
const intLib = loadLibrary(
|
|
127
|
+
compileLibrary(intSource + sqDefs, { source: "lib/integer.k+sqN" })
|
|
128
|
+
);
|
|
129
|
+
const sqNAlias = intLib.relAlias.sqN;
|
|
130
|
+
const intPattern = parseIntVal("0").pattern;
|
|
131
|
+
|
|
132
|
+
const results = [bigRes];
|
|
133
|
+
|
|
134
|
+
async function benchInProcess(name, runFn, iters) {
|
|
135
|
+
// Warmup & conformance check
|
|
136
|
+
{
|
|
137
|
+
const val = parseIntVal(INPUT);
|
|
138
|
+
const outStr = printIntVal(runFn(val));
|
|
139
|
+
if (outStr !== bigRes.output) throw new Error(`${name}: output mismatch`);
|
|
140
|
+
}
|
|
141
|
+
let parseMs = 0;
|
|
142
|
+
let computeMs = 0;
|
|
143
|
+
let printMs = 0;
|
|
144
|
+
for (let i = 0; i < iters; i++) {
|
|
145
|
+
const t0 = performance.now();
|
|
146
|
+
const val = parseIntVal(INPUT);
|
|
147
|
+
const t1 = performance.now();
|
|
148
|
+
const outVal = runFn(val);
|
|
149
|
+
const t2 = performance.now();
|
|
150
|
+
const outStr = printIntVal(outVal);
|
|
151
|
+
const t3 = performance.now();
|
|
152
|
+
if (outStr !== bigRes.output) throw new Error(`${name}: output mismatch`);
|
|
153
|
+
parseMs += t1 - t0;
|
|
154
|
+
computeMs += t2 - t1;
|
|
155
|
+
printMs += t3 - t2;
|
|
156
|
+
}
|
|
157
|
+
return {
|
|
158
|
+
name,
|
|
159
|
+
parseMs: parseMs / iters,
|
|
160
|
+
computeMs: computeMs / iters,
|
|
161
|
+
printMs: printMs / iters,
|
|
162
|
+
totalMs: (parseMs + computeMs + printMs) / iters
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function benchWireServer(name, server, iters) {
|
|
167
|
+
// Warmup & conformance check
|
|
168
|
+
{
|
|
169
|
+
const val = parseIntVal(INPUT);
|
|
170
|
+
const wire = encodeToWire(val, val.pattern);
|
|
171
|
+
const outWire = await server.request(wire);
|
|
172
|
+
const outStr = printIntVal(decodeWire(outWire).value);
|
|
173
|
+
if (outStr !== bigRes.output) throw new Error(`${name}: output mismatch`);
|
|
174
|
+
}
|
|
175
|
+
let parseMs = 0;
|
|
176
|
+
let computeMs = 0;
|
|
177
|
+
let printMs = 0;
|
|
178
|
+
for (let i = 0; i < iters; i++) {
|
|
179
|
+
const t0 = performance.now();
|
|
180
|
+
const val = parseIntVal(INPUT);
|
|
181
|
+
const wire = encodeToWire(val, val.pattern);
|
|
182
|
+
const t1 = performance.now();
|
|
183
|
+
const outWire = await server.request(wire);
|
|
184
|
+
const t2 = performance.now();
|
|
185
|
+
const outStr = printIntVal(decodeWire(outWire).value);
|
|
186
|
+
const t3 = performance.now();
|
|
187
|
+
if (outStr !== bigRes.output) throw new Error(`${name}: output mismatch`);
|
|
188
|
+
parseMs += t1 - t0;
|
|
189
|
+
computeMs += t2 - t1;
|
|
190
|
+
printMs += t3 - t2;
|
|
191
|
+
}
|
|
192
|
+
return {
|
|
193
|
+
name,
|
|
194
|
+
parseMs: parseMs / iters,
|
|
195
|
+
computeMs: computeMs / iters,
|
|
196
|
+
printMs: printMs / iters,
|
|
197
|
+
totalMs: (parseMs + computeMs + printMs) / iters
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Prepare LLVM/kVM relation object if needed
|
|
202
|
+
let prepared = null;
|
|
203
|
+
let preparedState = null;
|
|
204
|
+
let cacheDir = null;
|
|
205
|
+
if (BACKENDS.some((b) => b === "llvm" || b === "llvm-pkir" || b === "kvm")) {
|
|
206
|
+
preparedState = createState();
|
|
207
|
+
await evaluateInput(`:load ${path.join(root, "lib/integer.k")}`, preparedState);
|
|
208
|
+
await evaluateInput("sq = ?int[] { () x, () y } times ?int[];", preparedState);
|
|
209
|
+
await evaluateInput(`sqN = ${Array(STEPS).fill("sq").join(" ")};`, preparedState);
|
|
210
|
+
codes.load(preparedState.codes);
|
|
211
|
+
prepared = prepareRelation(preparedState, "sqN", { sourceLabel: "lib/integer.k#sqN" });
|
|
212
|
+
cacheDir = makeCacheDir("k-bigint-cmp-");
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
for (const backend of BACKENDS) {
|
|
216
|
+
try {
|
|
217
|
+
if (backend === "llvm" || backend === "llvm-pkir") {
|
|
218
|
+
const usePKIR = backend === "llvm-pkir";
|
|
219
|
+
const label = usePKIR ? "K LLVM-PKIR (-O3)" : "K LLVM (-O3)";
|
|
220
|
+
const exe = path.join(cacheDir, `sqN_${backend.replace("-", "_")}`);
|
|
221
|
+
compileObjectToExecutable(prepared.object, exe, {
|
|
222
|
+
clangOpt: "-O3",
|
|
223
|
+
inputPattern: intPattern,
|
|
224
|
+
usePKIR
|
|
225
|
+
});
|
|
226
|
+
const srv = new PersistentExecutable(exe, {
|
|
227
|
+
env: { ...process.env, K_ARENA_CAPACITY_MB: "4096" }
|
|
228
|
+
});
|
|
229
|
+
try {
|
|
230
|
+
results.push(await benchWireServer(label, srv, ITERS));
|
|
231
|
+
} finally {
|
|
232
|
+
await srv.close();
|
|
233
|
+
}
|
|
234
|
+
} else if (backend === "wasm" || backend === "pkir") {
|
|
235
|
+
const usePKIR = backend === "pkir";
|
|
236
|
+
const label = usePKIR ? "K PKIR-Wasm" : "K Wasm";
|
|
237
|
+
const artifact = await compileWasmArtifact(sqNAlias, {
|
|
238
|
+
libraries: [intLib],
|
|
239
|
+
usePKIR
|
|
240
|
+
});
|
|
241
|
+
const inst = await instantiateWasmArtifact(artifact);
|
|
242
|
+
results.push(
|
|
243
|
+
await benchInProcess(label, (val) => inst.executeValue(val), ITERS)
|
|
244
|
+
);
|
|
245
|
+
} else if (backend === "kvm") {
|
|
246
|
+
const kvmContext = {
|
|
247
|
+
rels: preparedState.rels,
|
|
248
|
+
findCode: codes.find,
|
|
249
|
+
options: { envelopeFree: true }
|
|
250
|
+
};
|
|
251
|
+
results.push(
|
|
252
|
+
await benchInProcess(
|
|
253
|
+
"K kVM",
|
|
254
|
+
(val) => executeKVM(prepared.kvmFunc, val, kvmContext),
|
|
255
|
+
Math.min(ITERS, 2)
|
|
256
|
+
)
|
|
257
|
+
);
|
|
258
|
+
} else if (backend === "js") {
|
|
259
|
+
const fn = k.compile(sqNAlias, { libraries: [intLib] });
|
|
260
|
+
results.push(await benchInProcess("K JS", fn, Math.min(ITERS, 2)));
|
|
261
|
+
} else {
|
|
262
|
+
console.warn(`[WARN] Unknown backend: ${backend}`);
|
|
263
|
+
}
|
|
264
|
+
} catch (err) {
|
|
265
|
+
console.warn(`[SKIP] ${backend}: ${err.message}`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
console.log(
|
|
270
|
+
`| Engine | Parse | Compute (${STEPS}x sq) | Print | Total | vs BigInt (Compute) | vs BigInt (Total) |`
|
|
271
|
+
);
|
|
272
|
+
console.log("| --- | ---: | ---: | ---: | ---: | ---: | ---: |");
|
|
273
|
+
for (const r of results) {
|
|
274
|
+
const cRatio = `${(r.computeMs / bigRes.computeMs).toFixed(1)}x`;
|
|
275
|
+
const tRatio = `${(r.totalMs / bigRes.totalMs).toFixed(1)}x`;
|
|
276
|
+
console.log(
|
|
277
|
+
`| ${r.name} | ${fmtMs(r.parseMs)} | ${fmtMs(r.computeMs)} | ${fmtMs(r.printMs)} | ${fmtMs(r.totalMs)} | ${cRatio} | ${tRatio} |`
|
|
278
|
+
);
|
|
279
|
+
}
|
package/scripts/perf-ieee.mjs
CHANGED
|
@@ -224,11 +224,7 @@ function pkirLaneName() {
|
|
|
224
224
|
console.log("==> Initializing IEEE types and arithmetic");
|
|
225
225
|
const state = createState();
|
|
226
226
|
for (const name of [
|
|
227
|
-
"
|
|
228
|
-
"lib/bits.k",
|
|
229
|
-
"lib/list.k",
|
|
230
|
-
"lib/btrie.k",
|
|
231
|
-
"lib/string.k",
|
|
227
|
+
"core.k",
|
|
232
228
|
"lib/ieee.k",
|
|
233
229
|
"Examples/ieee-arithmetics.k"
|
|
234
230
|
]) {
|