@fraczak/k 8.9.0 → 9.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/DOCS/ARCHITECTURE.md +5 -4
- package/DOCS/DICTIONARY.md +2 -2
- package/DOCS/FILE_FORMATS.md +11 -9
- package/DOCS/KIR_V1.md +5 -1
- package/DOCS/KTVM_SPEC.md +902 -0
- package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
- package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
- package/DOCS/PROFILING_AND_TRACING.md +6 -4
- package/DOCS/README.md +3 -2
- package/DOCS/REPL.md +16 -12
- package/README.md +132 -2
- package/backend-api.mjs +31 -16
- package/backends/llvm/README.md +4 -5
- package/backends/llvm/bin/k-llvm-build.mjs +7 -19
- package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
- package/backends/llvm/bin/k-llvm.mjs +11 -33
- package/backends/llvm/src/cli.mjs +2 -12
- package/backends/llvm/src/executable.mjs +7 -95
- package/backends/llvm/src/kvm2llvm.mjs +1 -5
- package/backends/llvm/src/llvm.mjs +4 -111
- package/backends/llvm/tests/k-llvm-run.mjs +1 -6
- package/backends/llvm/tests/perf-support.mjs +3 -5
- package/backends/llvm/tests/test-llvm.mjs +0 -16
- package/backends/wasm/README.md +2 -3
- package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
- package/backends/wasm/bin/k-wasm.mjs +4 -6
- package/backends/wasm/src/cli.mjs +8 -24
- package/backends/wasm/src/wasm.mjs +10 -56
- package/browser/repl-browser.mjs +9 -8
- package/browser/shims/buffer.mjs +31 -2
- package/browser/shims/child_process.mjs +26 -0
- package/browser/shims/fs.mjs +3 -1
- package/conformance/run.mjs +17 -2
- package/harness/adapters/ktvm-llvm.mjs +118 -0
- package/harness/adapters/ktvm-wasm.mjs +104 -0
- package/harness/adapters/ktvm.mjs +133 -0
- package/harness/registry.mjs +9 -0
- package/ktvm/ast.mjs +218 -0
- package/ktvm/bit-deque.mjs +482 -0
- package/ktvm/fixtures/integer-streaming.k +477 -0
- package/ktvm/index.mjs +119 -0
- package/ktvm/llvm/index.mjs +202 -0
- package/ktvm/llvm/lower-c.mjs +1258 -0
- package/ktvm/llvm/runtime.h +3542 -0
- package/ktvm/llvm/test-llvm.mjs +476 -0
- package/ktvm/lower-kir.mjs +2221 -0
- package/ktvm/optimize/fuse-kernel.mjs +2111 -0
- package/ktvm/optimize/index.mjs +116 -0
- package/ktvm/optimize/mwtr.mjs +283 -0
- package/ktvm/optimize/simplify-procs.mjs +5250 -0
- package/ktvm/optimize/synthesize-tables.mjs +1105 -0
- package/ktvm/parser.mjs +1101 -0
- package/ktvm/printer.mjs +281 -0
- package/ktvm/schema.mjs +543 -0
- package/ktvm/specialize.mjs +538 -0
- package/ktvm/test-conformance.mjs +597 -0
- package/ktvm/test-ktvm.mjs +1376 -0
- package/ktvm/test-optimize.mjs +598 -0
- package/ktvm/validator.mjs +1280 -0
- package/ktvm/vm.mjs +2225 -0
- package/ktvm/wasm/index.mjs +331 -0
- package/ktvm/wasm/lower-wasm.mjs +1272 -0
- package/ktvm/wasm/runtime.wat +4413 -0
- package/ktvm/wasm/test-wasm.mjs +426 -0
- package/ktvm/wire.mjs +489 -0
- package/package.json +1 -9
- package/repl.mjs +101 -20
- package/scripts/build-repl-html.mjs +40 -18
- package/scripts/perf-bigint-compare.mjs +12 -16
- package/scripts/perf-ieee.mjs +9 -229
- package/scripts/perf-int.mjs +14 -272
- package/scripts/perf-multiplication.mjs +8 -54
- package/scripts/perf-poly.mjs +9 -263
- package/scripts/run-tests.mjs +5 -2
- package/scripts/test-package.mjs +15 -3
- package/tests/README.md +3 -3
- package/tests/test-repl-html.mjs +72 -15
- package/tests/test-repl.mjs +24 -17
- package/DOCS/POLYMORPHIC_IR.md +0 -86
- package/access-table.mjs +0 -343
- package/pkir.mjs +0 -772
- package/tests/test-access-table.mjs +0 -213
- package/tests/test-pkir.mjs +0 -530
|
@@ -0,0 +1,597 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Milestone 2 Conformance & Standard Library Parity Suite for `kTVM`.
|
|
3
|
+
*
|
|
4
|
+
* Tests `KIR-P -> kTVM` lowering and wire-to-wire execution against K's reference
|
|
5
|
+
* `k.compile` evaluator across:
|
|
6
|
+
* 1. `lib/generic.k` (booleans, order, opt, polymorphic `reverse`, `trim_bits`,
|
|
7
|
+
* `inc_bits`, `string_to_bits`/`bits_to_string`, polymorphic `btrie[V]`!)
|
|
8
|
+
* 2. `lib/integer.k` (`plus`, `minus`, `times` incl. Karatsuba, `div`, `mod`,
|
|
9
|
+
* `divmod`, `gcd`, `cmp`, `abs`, `negate`, `inc`, `dec`, partial predicates)
|
|
10
|
+
* 3. `lib/ieee.k` (constants, predicates, `negate_float64`, `ratio_to_float64`,
|
|
11
|
+
* `bits_to_float64`, subnormals, ±0, ±Inf, qNaN)
|
|
12
|
+
* 4. `lib/djson.k` (RFC 8259 `parse_json`, Unicode `get`/`set`/`del`/`keys`/
|
|
13
|
+
* `values`, sparse arrays `del_nth`/`push`, predicates across all Unicode planes!)
|
|
14
|
+
* 5. `ktvm/fixtures/integer-streaming.k` (`lsb_add`, `lsb_sub`,
|
|
15
|
+
* `lsb_mul`, `lsb_trim`)
|
|
16
|
+
* 6. Polymorphic `kTVM-P` AOT lowering (`lowerKIRToKTVMP`) + DSL/JSON round-trip
|
|
17
|
+
* 7. Randomized differential fuzzing (`k.compile` vs `kTVM` wire-to-wire)
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import assert from "node:assert/strict";
|
|
21
|
+
import fs from "node:fs";
|
|
22
|
+
import path from "node:path";
|
|
23
|
+
import { fileURLToPath } from "node:url";
|
|
24
|
+
|
|
25
|
+
import k from "../index.mjs";
|
|
26
|
+
import codes from "../codes.mjs";
|
|
27
|
+
import { Value } from "../Value.mjs";
|
|
28
|
+
import { compileLibrary, compileObjectBuffer, decodeObject, loadLibrary } from "../object.mjs";
|
|
29
|
+
import { encodeToWire, decodeWire } from "../codecs/runtime/prefix-codec.mjs";
|
|
30
|
+
import { parse as parseIntVal } from "../codecs/int.mjs";
|
|
31
|
+
import { decodeValueToNumber, encodeNumberToValue } from "../codecs/ieee.mjs";
|
|
32
|
+
import { fromJsonValue, toJsonValue } from "../codecs/djson.mjs";
|
|
33
|
+
import { stringValueToText, textToStringValue } from "../codecs/string-codec.mjs";
|
|
34
|
+
import { useSpecsFor } from "../tests/helpers/cli.mjs";
|
|
35
|
+
import { relationPatternPropertyList } from "../kir.mjs";
|
|
36
|
+
|
|
37
|
+
import {
|
|
38
|
+
KTVMSchemaError,
|
|
39
|
+
compileKIRToKTVM,
|
|
40
|
+
executeKTVMWire,
|
|
41
|
+
executeObjectWithKTVM,
|
|
42
|
+
lowerKIRToKTVMP,
|
|
43
|
+
moduleFromJSON,
|
|
44
|
+
moduleToJSON,
|
|
45
|
+
parseModule,
|
|
46
|
+
printModule,
|
|
47
|
+
validateModule
|
|
48
|
+
} from "./index.mjs";
|
|
49
|
+
|
|
50
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
51
|
+
const readSrc = (rel) => fs.readFileSync(path.join(root, rel), "utf8");
|
|
52
|
+
const UNIT = Value.product({});
|
|
53
|
+
|
|
54
|
+
function bitsFromStr(str) {
|
|
55
|
+
let v = Value.variant("_", UNIT);
|
|
56
|
+
for (let i = str.length - 1; i >= 0; i--) {
|
|
57
|
+
v = Value.variant(str[i], v);
|
|
58
|
+
}
|
|
59
|
+
return v;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function listFrom(items) {
|
|
63
|
+
let v = Value.variant("nil", UNIT);
|
|
64
|
+
for (let i = items.length - 1; i >= 0; i--) {
|
|
65
|
+
v = Value.variant("cons", Value.product({ car: items[i], cdr: v }));
|
|
66
|
+
}
|
|
67
|
+
return v;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function plainValue(v) {
|
|
71
|
+
return v === undefined ? undefined : JSON.parse(JSON.stringify(v.toJSON()));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Run a library relation via BOTH K's reference evaluator (`k.compile`) and
|
|
76
|
+
* `kTVM` end-to-end over `k-wire`, asserting identical results (including
|
|
77
|
+
* partial `undefined` <-> `FAILED` and eager `decodeWire` round-trip!).
|
|
78
|
+
*/
|
|
79
|
+
function assertParity(lib, relName, inputVal, { inputPattern = null, label = relName } = {}) {
|
|
80
|
+
const relHash = lib.relAlias[relName] || relName;
|
|
81
|
+
assert.ok(lib.rels[relHash], `missing relation '${relName}'`);
|
|
82
|
+
codes.load(lib.codes);
|
|
83
|
+
|
|
84
|
+
// 1. Reference K result
|
|
85
|
+
const expected = k.compile(relHash, { libraries: [lib] })(inputVal);
|
|
86
|
+
|
|
87
|
+
// 2. Encode input to enveloped k-wire
|
|
88
|
+
let pat = inputPattern;
|
|
89
|
+
if (!pat) {
|
|
90
|
+
const inferred = relationPatternPropertyList(lib.rels[relHash], 0);
|
|
91
|
+
// Only pass inferred pattern if it's fully closed; otherwise let encodeToWire derive exact value envelope
|
|
92
|
+
const isClosed = Array.isArray(inferred) && inferred.every(([kind]) =>
|
|
93
|
+
kind === "closed-product" || kind === "closed-union"
|
|
94
|
+
);
|
|
95
|
+
pat = isClosed ? inferred : undefined;
|
|
96
|
+
}
|
|
97
|
+
const inWire = pat ? encodeToWire(inputVal, pat) : encodeToWire(inputVal);
|
|
98
|
+
|
|
99
|
+
// 3. Execute on kTVM directly over k-wire
|
|
100
|
+
const res = executeObjectWithKTVM(lib, relHash, inWire);
|
|
101
|
+
|
|
102
|
+
if (expected === undefined) {
|
|
103
|
+
assert.equal(res.status, "FAILED", `${label}: expected FAILED (undefined), got OK`);
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
assert.equal(res.status, "OK", `${label}: expected OK, got ${res.status}`);
|
|
108
|
+
assert.deepEqual(
|
|
109
|
+
plainValue(res.value),
|
|
110
|
+
plainValue(expected),
|
|
111
|
+
`${label}: kTVM value mismatch`
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
// 4. Verify output wire decodes bit-identically with K's own eager `decodeWire`
|
|
115
|
+
const decodedByK = decodeWire(res.wire, { eager: true }).value;
|
|
116
|
+
assert.deepEqual(
|
|
117
|
+
plainValue(decodedByK),
|
|
118
|
+
plainValue(expected),
|
|
119
|
+
`${label}: kTVM output k-wire failed K decodeWire parity`
|
|
120
|
+
);
|
|
121
|
+
|
|
122
|
+
return res.value;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// --- Load Standard Libraries Once ---
|
|
126
|
+
|
|
127
|
+
const coreLib = loadLibrary(compileLibrary(readSrc("core.k"), { source: "core.k" }));
|
|
128
|
+
const genericLib = loadLibrary(compileLibrary(readSrc("lib/generic.k"), {
|
|
129
|
+
source: "lib/generic.k",
|
|
130
|
+
libraries: [coreLib],
|
|
131
|
+
use: useSpecsFor("lib/generic.k")
|
|
132
|
+
}));
|
|
133
|
+
const integerLib = loadLibrary(compileLibrary(readSrc("lib/integer.k"), {
|
|
134
|
+
source: "lib/integer.k",
|
|
135
|
+
libraries: [coreLib],
|
|
136
|
+
use: useSpecsFor("lib/integer.k")
|
|
137
|
+
}));
|
|
138
|
+
const ieeeLib = loadLibrary(compileLibrary(readSrc("lib/ieee.k"), {
|
|
139
|
+
source: "lib/ieee.k",
|
|
140
|
+
libraries: [coreLib],
|
|
141
|
+
use: useSpecsFor("lib/ieee.k")
|
|
142
|
+
}));
|
|
143
|
+
const djsonLib = loadLibrary(compileLibrary(readSrc("lib/djson.k"), {
|
|
144
|
+
source: "lib/djson.k",
|
|
145
|
+
libraries: [coreLib, genericLib, ieeeLib],
|
|
146
|
+
use: useSpecsFor("lib/djson.k")
|
|
147
|
+
}));
|
|
148
|
+
const streamingIntLib = loadLibrary(compileLibrary(readSrc("ktvm/fixtures/integer-streaming.k"), {
|
|
149
|
+
source: "ktvm/fixtures/integer-streaming.k",
|
|
150
|
+
libraries: [coreLib],
|
|
151
|
+
use: useSpecsFor("lib/integer.k")
|
|
152
|
+
}));
|
|
153
|
+
|
|
154
|
+
let passed = 0;
|
|
155
|
+
let failed = 0;
|
|
156
|
+
|
|
157
|
+
function test(name, fn) {
|
|
158
|
+
try {
|
|
159
|
+
fn();
|
|
160
|
+
passed++;
|
|
161
|
+
console.log(` PASS ${name}`);
|
|
162
|
+
} catch (err) {
|
|
163
|
+
failed++;
|
|
164
|
+
console.error(` FAIL ${name}`);
|
|
165
|
+
console.error(err);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ============================================================================
|
|
170
|
+
console.log("\n=== 1. lib/generic.k Parity ===");
|
|
171
|
+
// ============================================================================
|
|
172
|
+
|
|
173
|
+
test("lib/generic.k: bool/order/opt predicates (both OK and partial FAILED)", () => {
|
|
174
|
+
const boolPat = [["closed-union", [["false", 1], ["true", 1]]], ["closed-product", []]];
|
|
175
|
+
assertParity(genericLib, "true?", Value.variant("true", UNIT), { inputPattern: boolPat });
|
|
176
|
+
assertParity(genericLib, "true?", Value.variant("false", UNIT), { inputPattern: boolPat });
|
|
177
|
+
assertParity(genericLib, "false?", Value.variant("false", UNIT), { inputPattern: boolPat });
|
|
178
|
+
assertParity(genericLib, "false?", Value.variant("true", UNIT), { inputPattern: boolPat });
|
|
179
|
+
|
|
180
|
+
const ordPat = [["closed-union", [["eq", 1], ["gt", 1], ["lt", 1]]], ["closed-product", []]];
|
|
181
|
+
assertParity(genericLib, "lt?", Value.variant("lt", UNIT), { inputPattern: ordPat });
|
|
182
|
+
assertParity(genericLib, "eq?", Value.variant("eq", UNIT), { inputPattern: ordPat });
|
|
183
|
+
assertParity(genericLib, "gt?", Value.variant("gt", UNIT), { inputPattern: ordPat });
|
|
184
|
+
assertParity(genericLib, "lt?", Value.variant("gt", UNIT), { inputPattern: ordPat });
|
|
185
|
+
|
|
186
|
+
const optPat = [["closed-union", [["nil", 1], ["val", 1]]], ["closed-product", []]];
|
|
187
|
+
assertParity(genericLib, "nil?", Value.variant("nil", UNIT), { inputPattern: optPat });
|
|
188
|
+
assertParity(genericLib, "nil?", Value.variant("val", UNIT), { inputPattern: optPat });
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
test("lib/generic.k: polymorphic reverse on string, int list, and opaque product list", () => {
|
|
192
|
+
// String (list[unicode[]])
|
|
193
|
+
const strPat = relationPatternPropertyList(genericLib.rels[genericLib.relAlias.string_to_bits], 0);
|
|
194
|
+
assertParity(genericLib, "reverse", textToStringValue("hello 🌍!"), { inputPattern: strPat });
|
|
195
|
+
assertParity(genericLib, "reverse", textToStringValue(""), { inputPattern: strPat });
|
|
196
|
+
|
|
197
|
+
// List of opaque products { a: int[], b: bits[] }
|
|
198
|
+
const intPat = relationPatternPropertyList(integerLib.rels[integerLib.relAlias.negate], 0);
|
|
199
|
+
const bitsPat = relationPatternPropertyList(genericLib.rels[genericLib.relAlias.trim_bits], 0);
|
|
200
|
+
const listIntPat = [
|
|
201
|
+
["closed-union", [["cons", 1], ["nil", 2]]],
|
|
202
|
+
["closed-product", [["car", 3], ["cdr", 0]]],
|
|
203
|
+
["closed-product", []],
|
|
204
|
+
...intPat.map(([k, e]) => [k, e.map(([l, t]) => [l, t + 3])])
|
|
205
|
+
];
|
|
206
|
+
assertParity(
|
|
207
|
+
genericLib,
|
|
208
|
+
"reverse",
|
|
209
|
+
listFrom([parseIntVal("1"), parseIntVal("-42"), parseIntVal("0"), parseIntVal("999")]),
|
|
210
|
+
{ inputPattern: listIntPat }
|
|
211
|
+
);
|
|
212
|
+
|
|
213
|
+
// trim_bits, inc_bits, rev_bits, string_to_bits <-> bits_to_string
|
|
214
|
+
for (const b of ["", "000", "00101", "11111111"]) {
|
|
215
|
+
assertParity(genericLib, "trim_bits", bitsFromStr(b), { inputPattern: bitsPat });
|
|
216
|
+
assertParity(genericLib, "inc_bits", bitsFromStr(b), { inputPattern: bitsPat });
|
|
217
|
+
assertParity(genericLib, "rev_bits", bitsFromStr(b), { inputPattern: bitsPat });
|
|
218
|
+
}
|
|
219
|
+
const sBits = assertParity(genericLib, "string_to_bits", textToStringValue("kTVM 🚀"), { inputPattern: strPat });
|
|
220
|
+
const roundStr = assertParity(genericLib, "bits_to_string", sBits, { inputPattern: bitsPat });
|
|
221
|
+
assert.equal(stringValueToText(roundStr), "kTVM 🚀");
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
test("lib/generic.k: polymorphic btrie[int[]] set, get, del, entries_raw, bfs_values", () => {
|
|
225
|
+
// Build closed btrie[int[]] schema
|
|
226
|
+
const intPat = relationPatternPropertyList(integerLib.rels[integerLib.relAlias.negate], 0);
|
|
227
|
+
const bitsPat = relationPatternPropertyList(genericLib.rels[genericLib.relAlias.trim_bits], 0);
|
|
228
|
+
// btrie[V] = < {} nil, { btrie[V] 0, btrie[V] 1, opt[V] val } trie >
|
|
229
|
+
// opt[V] = < {} nil, V val >
|
|
230
|
+
const intBase = 4;
|
|
231
|
+
const btriePat = [
|
|
232
|
+
["closed-union", [["nil", 2], ["trie", 1]]],
|
|
233
|
+
["closed-product", [["0", 0], ["1", 0], ["val", 3]]],
|
|
234
|
+
["closed-product", []],
|
|
235
|
+
["closed-union", [["nil", 2], ["val", intBase]]],
|
|
236
|
+
...intPat.map(([k, e]) => [k, e.map(([l, t]) => [l, t + intBase])])
|
|
237
|
+
];
|
|
238
|
+
|
|
239
|
+
// Product helpers for btrie_set({key, trie, val}) and btrie_get({key, trie})
|
|
240
|
+
const makeProdPat = (fields) => {
|
|
241
|
+
const nodes = [["closed-product", []]];
|
|
242
|
+
for (const [label, sub] of fields.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
|
|
243
|
+
const base = nodes.length;
|
|
244
|
+
for (const [k, e] of sub) nodes.push([k, e.map(([l, t]) => [l, t + base])]);
|
|
245
|
+
nodes[0][1].push([label, base]);
|
|
246
|
+
}
|
|
247
|
+
return nodes;
|
|
248
|
+
};
|
|
249
|
+
const setPat = makeProdPat([["key", bitsPat], ["trie", btriePat], ["val", intPat]]);
|
|
250
|
+
const getPat = makeProdPat([["key", bitsPat], ["trie", btriePat]]);
|
|
251
|
+
|
|
252
|
+
let trie = Value.variant("nil", UNIT);
|
|
253
|
+
assertParity(genericLib, "btrie_get", Value.product({ key: bitsFromStr("0"), trie }), { inputPattern: getPat });
|
|
254
|
+
|
|
255
|
+
for (let i = 0; i < 6; i++) {
|
|
256
|
+
trie = assertParity(
|
|
257
|
+
genericLib,
|
|
258
|
+
"btrie_set",
|
|
259
|
+
Value.product({ key: parseIntVal(String(i)).value, val: parseIntVal(String((i + 1) * 10)), trie }),
|
|
260
|
+
{ inputPattern: setPat, label: `btrie_set(${i})` }
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
for (let i = 0; i < 6; i++) {
|
|
264
|
+
assertParity(
|
|
265
|
+
genericLib,
|
|
266
|
+
"btrie_get",
|
|
267
|
+
Value.product({ key: parseIntVal(String(i)).value, trie }),
|
|
268
|
+
{ inputPattern: getPat, label: `btrie_get(${i})` }
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
assertParity(genericLib, "btrie_bfs_values", trie, { inputPattern: btriePat });
|
|
272
|
+
assertParity(genericLib, "btrie_entries_raw", trie, { inputPattern: btriePat });
|
|
273
|
+
|
|
274
|
+
trie = assertParity(
|
|
275
|
+
genericLib,
|
|
276
|
+
"btrie_del",
|
|
277
|
+
Value.product({ key: parseIntVal("3").value, trie }),
|
|
278
|
+
{ inputPattern: getPat }
|
|
279
|
+
);
|
|
280
|
+
assertParity(
|
|
281
|
+
genericLib,
|
|
282
|
+
"btrie_get",
|
|
283
|
+
Value.product({ key: parseIntVal("3").value, trie }),
|
|
284
|
+
{ inputPattern: getPat }
|
|
285
|
+
);
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
// ============================================================================
|
|
289
|
+
console.log("\n=== 2. lib/integer.k Parity ===");
|
|
290
|
+
// ============================================================================
|
|
291
|
+
|
|
292
|
+
test("lib/integer.k: plus, minus, times (incl. Karatsuba), div, mod, divmod, gcd, cmp, unary & predicates", () => {
|
|
293
|
+
const pairs = [
|
|
294
|
+
["0", "0"],
|
|
295
|
+
["0", "1"],
|
|
296
|
+
["-1", "1"],
|
|
297
|
+
["123", "456"],
|
|
298
|
+
["-123", "456"],
|
|
299
|
+
["1000", "-999"],
|
|
300
|
+
["-9999", "-1"],
|
|
301
|
+
["65535", "65537"],
|
|
302
|
+
["123456789", "987654321"]
|
|
303
|
+
];
|
|
304
|
+
|
|
305
|
+
for (const [a, b] of pairs) {
|
|
306
|
+
const arg = Value.product({ x: parseIntVal(a), y: parseIntVal(b) });
|
|
307
|
+
assertParity(integerLib, "plus", arg, { label: `plus(${a},${b})` });
|
|
308
|
+
assertParity(integerLib, "minus", arg, { label: `minus(${a},${b})` });
|
|
309
|
+
assertParity(integerLib, "times", arg, { label: `times(${a},${b})` });
|
|
310
|
+
assertParity(integerLib, "cmp", arg, { label: `cmp(${a},${b})` });
|
|
311
|
+
assertParity(integerLib, "eq?", arg, { label: `eq?(${a},${b})` });
|
|
312
|
+
assertParity(integerLib, "gt?", arg, { label: `gt?(${a},${b})` });
|
|
313
|
+
assertParity(integerLib, "lt?", arg, { label: `lt?(${a},${b})` });
|
|
314
|
+
if (b !== "0") {
|
|
315
|
+
assertParity(integerLib, "div", arg, { label: `div(${a},${b})` });
|
|
316
|
+
assertParity(integerLib, "mod", arg, { label: `mod(${a},${b})` });
|
|
317
|
+
assertParity(integerLib, "divmod", arg, { label: `divmod(${a},${b})` });
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
for (const [a, b] of [["48", "18"], ["1071", "462"], ["17", "13"], ["0", "25"]]) {
|
|
322
|
+
assertParity(integerLib, "gcd", Value.product({ x: parseIntVal(a), y: parseIntVal(b) }), {
|
|
323
|
+
label: `gcd(${a},${b})`
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
for (const x of ["-42", "-1", "0", "1", "42"]) {
|
|
328
|
+
const v = parseIntVal(x);
|
|
329
|
+
assertParity(integerLib, "inc", v, { label: `inc(${x})` });
|
|
330
|
+
assertParity(integerLib, "dec", v, { label: `dec(${x})` });
|
|
331
|
+
assertParity(integerLib, "abs", v, { label: `abs(${x})` });
|
|
332
|
+
assertParity(integerLib, "negate", v, { label: `negate(${x})` });
|
|
333
|
+
assertParity(integerLib, "pos?", v, { label: `pos?(${x})` });
|
|
334
|
+
assertParity(integerLib, "neg?", v, { label: `neg?(${x})` });
|
|
335
|
+
assertParity(integerLib, "zero?", v, { label: `zero?(${x})` });
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// Large 96-bit Karatsuba multiplication parity!
|
|
339
|
+
const bigX = parseIntVal("79228162514264337593543950335");
|
|
340
|
+
const bigY = parseIntVal("12345678901234567890123456789");
|
|
341
|
+
assertParity(integerLib, "times", Value.product({ x: bigX, y: bigY }), { label: "times(96b Karatsuba)" });
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
// ============================================================================
|
|
345
|
+
console.log("\n=== 3. lib/ieee.k Parity ===");
|
|
346
|
+
// ============================================================================
|
|
347
|
+
|
|
348
|
+
test("lib/ieee.k: constants, predicates, negate_float64, ratio_to_float64 (incl. subnormals/NaN/Inf)", () => {
|
|
349
|
+
for (const c of ["pos_zero", "neg_zero", "pos_inf", "neg_inf", "qnan"]) {
|
|
350
|
+
assertParity(ieeeLib, c, UNIT, { inputPattern: [["closed-product", []]], label: c });
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const samples = [0, -0, 1, -1, 3.141592653589793, 5e-324, Number.MAX_VALUE, Infinity, -Infinity, NaN];
|
|
354
|
+
for (const n of samples) {
|
|
355
|
+
const v = encodeNumberToValue(n);
|
|
356
|
+
assertParity(ieeeLib, "zero_float64?", v, { label: `zero_float64?(${n})` });
|
|
357
|
+
assertParity(ieeeLib, "finite_float64?", v, { label: `finite_float64?(${n})` });
|
|
358
|
+
assertParity(ieeeLib, "inf_float64?", v, { label: `inf_float64?(${n})` });
|
|
359
|
+
assertParity(ieeeLib, "nan_float64?", v, { label: `nan_float64?(${n})` });
|
|
360
|
+
const neg = assertParity(ieeeLib, "negate_float64", v, { label: `negate_float64(${n})` });
|
|
361
|
+
if (!Number.isNaN(n)) {
|
|
362
|
+
assert.ok(Object.is(decodeValueToNumber(neg), -n));
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// bits_to_float64: integer magnitudes & IEEE round-to-nearest ties-to-even
|
|
367
|
+
for (const [n, expected] of [
|
|
368
|
+
[0n, 0],
|
|
369
|
+
[1n, 1],
|
|
370
|
+
[42n, 42],
|
|
371
|
+
[1n << 53n, 9007199254740992],
|
|
372
|
+
[(1n << 53n) + 1n, 9007199254740992],
|
|
373
|
+
[(1n << 53n) + 3n, 9007199254740996]
|
|
374
|
+
]) {
|
|
375
|
+
const f = assertParity(ieeeLib, "bits_to_float64", parseIntVal(String(n)).value, {
|
|
376
|
+
label: `bits_to_float64(${n})`
|
|
377
|
+
});
|
|
378
|
+
assert.ok(Object.is(decodeValueToNumber(f), expected));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Exact rational-to-float64 rounding (ties-to-even, subnormal, normal, zero, zero-denom FAILED)
|
|
382
|
+
const makeRatio = (sign, num, den) => Value.product({
|
|
383
|
+
sign: Value.variant(sign, UNIT),
|
|
384
|
+
num: parseIntVal(String(num)).value,
|
|
385
|
+
den: parseIntVal(String(den)).value
|
|
386
|
+
});
|
|
387
|
+
for (const [sign, num, den, expectedNum] of [
|
|
388
|
+
["+", 0n, 1n, 0],
|
|
389
|
+
["-", 0n, 1n, -0],
|
|
390
|
+
["+", 1n, 2n, 0.5],
|
|
391
|
+
["-", 5n, 8n, -0.625],
|
|
392
|
+
["+", 1n, 10n, 0.1],
|
|
393
|
+
["+", (1n << 53n) + 1n, 2n, 4503599627370496],
|
|
394
|
+
["+", 1n, 1n << 50n, 2 ** -50]
|
|
395
|
+
]) {
|
|
396
|
+
const f = assertParity(ieeeLib, "ratio_to_float64", makeRatio(sign, num, den), {
|
|
397
|
+
label: `ratio(${sign}${num}/${den})`
|
|
398
|
+
});
|
|
399
|
+
assert.ok(Object.is(decodeValueToNumber(f), expectedNum));
|
|
400
|
+
}
|
|
401
|
+
assertParity(ieeeLib, "ratio_to_float64", makeRatio("+", 1n, 0n), {
|
|
402
|
+
label: "ratio(+1/0) -> FAILED"
|
|
403
|
+
});
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
// ============================================================================
|
|
407
|
+
console.log("\n=== 4. lib/djson.k Parity (Unicode Objects, Arrays & Full JSON Parser) ===");
|
|
408
|
+
// ============================================================================
|
|
409
|
+
|
|
410
|
+
test("lib/djson.k: predicates, Unicode get/set/del/keys/values, sparse arrays & push", () => {
|
|
411
|
+
codes.load(djsonLib.codes);
|
|
412
|
+
const djsonPat = relationPatternPropertyList(djsonLib.rels[djsonLib.relAlias.parse_json], 1);
|
|
413
|
+
|
|
414
|
+
for (const [pred, val] of [
|
|
415
|
+
["null?", null],
|
|
416
|
+
["null?", 0],
|
|
417
|
+
["bool?", true],
|
|
418
|
+
["number?", 42.5],
|
|
419
|
+
["string?", "hello"],
|
|
420
|
+
["list?", [1, 2]],
|
|
421
|
+
["object?", { a: 1 }],
|
|
422
|
+
["object?", []]
|
|
423
|
+
]) {
|
|
424
|
+
assertParity(djsonLib, pred, fromJsonValue(val), { inputPattern: djsonPat, label: `${pred}(${JSON.stringify(val)})` });
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const objDoc = { "": 0, "a": 1, "é": 2, "語": 3, "\uE123": 4, "😀": 5, "\u{21234}": 6 };
|
|
428
|
+
let objVal = fromJsonValue(objDoc);
|
|
429
|
+
|
|
430
|
+
for (const key of Object.keys(objDoc)) {
|
|
431
|
+
const got = assertParity(
|
|
432
|
+
djsonLib,
|
|
433
|
+
"get",
|
|
434
|
+
Value.product({ key: textToStringValue(key), json: objVal }),
|
|
435
|
+
{ label: `djson.get(${JSON.stringify(key)})` }
|
|
436
|
+
);
|
|
437
|
+
assert.equal(toJsonValue(got), objDoc[key]);
|
|
438
|
+
}
|
|
439
|
+
assertParity(djsonLib, "get", Value.product({ key: textToStringValue("missing"), json: objVal }), {
|
|
440
|
+
label: "djson.get(missing)"
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
assertParity(djsonLib, "keys", objVal, { inputPattern: djsonPat });
|
|
444
|
+
assertParity(djsonLib, "values", objVal, { inputPattern: djsonPat });
|
|
445
|
+
|
|
446
|
+
objVal = assertParity(
|
|
447
|
+
djsonLib,
|
|
448
|
+
"set",
|
|
449
|
+
Value.product({ key: textToStringValue("🔑"), val: fromJsonValue("ok"), json: objVal }),
|
|
450
|
+
{ label: "djson.set" }
|
|
451
|
+
);
|
|
452
|
+
objVal = assertParity(
|
|
453
|
+
djsonLib,
|
|
454
|
+
"del",
|
|
455
|
+
Value.product({ key: textToStringValue("😀"), json: objVal }),
|
|
456
|
+
{ label: "djson.del" }
|
|
457
|
+
);
|
|
458
|
+
|
|
459
|
+
// Sparse array del_nth + push
|
|
460
|
+
const arr = fromJsonValue([10, 20, 30, 40, 50]);
|
|
461
|
+
const sparse = assertParity(
|
|
462
|
+
djsonLib,
|
|
463
|
+
"del_nth",
|
|
464
|
+
Value.product({ index: parseIntVal("1").value, json: arr }),
|
|
465
|
+
{ label: "djson.del_nth" }
|
|
466
|
+
);
|
|
467
|
+
const pushed = assertParity(
|
|
468
|
+
djsonLib,
|
|
469
|
+
"push",
|
|
470
|
+
Value.product({ val: fromJsonValue(99), json: sparse }),
|
|
471
|
+
{ label: "djson.push" }
|
|
472
|
+
);
|
|
473
|
+
assert.deepEqual(toJsonValue(pushed), [10, 30, 40, 50, 99]);
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
test("lib/djson.k: full RFC 8259 parse_json parity on objects, arrays, escapes, numbers & invalid JSON", () => {
|
|
477
|
+
const jsonInputs = [
|
|
478
|
+
"null",
|
|
479
|
+
"true",
|
|
480
|
+
"false",
|
|
481
|
+
"0",
|
|
482
|
+
"-42.5",
|
|
483
|
+
"\"hello\\n\\u0041\"",
|
|
484
|
+
"[1, true, null, \"x\"]",
|
|
485
|
+
"{\"a\": 1, \"b\": [2, 3], \"c\": {\"ok\": true}}",
|
|
486
|
+
"{ invalid json" // partial failure -> FAILED!
|
|
487
|
+
];
|
|
488
|
+
for (const txt of jsonInputs) {
|
|
489
|
+
assertParity(djsonLib, "parse_json", textToStringValue(txt), { label: `parse_json(${txt})` });
|
|
490
|
+
}
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
// ============================================================================
|
|
494
|
+
console.log("\n=== 5. integer-streaming.k & Polymorphic kTVM-P AOT Round-Trip ===");
|
|
495
|
+
// ============================================================================
|
|
496
|
+
|
|
497
|
+
test("ktvm/fixtures/integer-streaming.k: lsb_add, lsb_sub, lsb_mul, lsb_trim parity", () => {
|
|
498
|
+
for (const [a, b] of [["0", "0"], ["7", "1"], ["255", "1"], ["12345", "67890"], ["99999", "12345"]]) {
|
|
499
|
+
const arg = Value.product({ x: parseIntVal(a).value, y: parseIntVal(b).value });
|
|
500
|
+
assertParity(streamingIntLib, "lsb_add", arg, { label: `stream.lsb_add(${a},${b})` });
|
|
501
|
+
assertParity(streamingIntLib, "lsb_mul", arg, { label: `stream.lsb_mul(${a},${b})` });
|
|
502
|
+
}
|
|
503
|
+
assertParity(streamingIntLib, "lsb_sub", Value.product({ x: parseIntVal("1000").value, y: parseIntVal("1").value }));
|
|
504
|
+
assertParity(streamingIntLib, "lsb_trim", bitsFromStr("01010000"));
|
|
505
|
+
assertParity(streamingIntLib, "lsb_trim", bitsFromStr("00000"));
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
test("Polymorphic lowerKIRToKTVMP produces valid .ktvmp DSL + JSON artifact round-trip", () => {
|
|
509
|
+
const script = `
|
|
510
|
+
list[X] = < {} nil, { X car, L cdr } cons > = L;
|
|
511
|
+
reverse = ?list[X] { () xs, {} |nil acc } _reverse ?list[X];
|
|
512
|
+
_reverse = ?{ list[X] xs, list[X] acc } <
|
|
513
|
+
{ .xs /nil _, .acc acc } .acc,
|
|
514
|
+
{ .xs /cons .cdr xs, { .xs /cons .car car, .acc cdr } |cons acc } _reverse
|
|
515
|
+
>;
|
|
516
|
+
reverse
|
|
517
|
+
`;
|
|
518
|
+
const obj = decodeObject(compileObjectBuffer(script));
|
|
519
|
+
const polyMod = lowerKIRToKTVMP(obj);
|
|
520
|
+
assert.equal(polyMod.layer, "poly");
|
|
521
|
+
assert.equal(validateModule(polyMod).ok, true);
|
|
522
|
+
|
|
523
|
+
// Lossless DSL print -> re-parse and JSON round-trip!
|
|
524
|
+
const text1 = printModule(polyMod);
|
|
525
|
+
const reparsed = parseModule(text1);
|
|
526
|
+
assert.equal(printModule(reparsed), text1);
|
|
527
|
+
assert.equal(printModule(moduleFromJSON(JSON.parse(JSON.stringify(moduleToJSON(polyMod))))), text1);
|
|
528
|
+
|
|
529
|
+
// Also test printing/re-parsing a compiled concrete mono module from lib/integer.k!
|
|
530
|
+
codes.load(integerLib.codes);
|
|
531
|
+
const compiledAdd = compileKIRToKTVM(
|
|
532
|
+
integerLib,
|
|
533
|
+
"plus",
|
|
534
|
+
relationPatternPropertyList(integerLib.rels[integerLib.relAlias.plus], 0)
|
|
535
|
+
);
|
|
536
|
+
const monoText = printModule(compiledAdd.module);
|
|
537
|
+
assert.equal(printModule(parseModule(monoText)), monoText);
|
|
538
|
+
});
|
|
539
|
+
|
|
540
|
+
// ============================================================================
|
|
541
|
+
console.log("\n=== 6. Edge-Case Filters, Partiality & Randomized Differential Fuzzing ===");
|
|
542
|
+
// ============================================================================
|
|
543
|
+
|
|
544
|
+
test("Runtime filters (?P), code guards (?T[]), overlapping backtracking unions & SchemaError boundaries", () => {
|
|
545
|
+
// Overlapping backtracking union: branch 0 checks /a /0, branch 1 falls back to /a ()
|
|
546
|
+
const backtrackProg = `
|
|
547
|
+
< /a /0 |hit, /a |fallback, /b |other >
|
|
548
|
+
`;
|
|
549
|
+
const btObj = decodeObject(compileObjectBuffer(backtrackProg));
|
|
550
|
+
const inPat = [
|
|
551
|
+
["closed-union", [["a", 1], ["b", 2]]],
|
|
552
|
+
["closed-union", [["0", 2], ["1", 2]]],
|
|
553
|
+
["closed-product", []]
|
|
554
|
+
];
|
|
555
|
+
for (const val of [
|
|
556
|
+
Value.variant("a", Value.variant("0", UNIT)),
|
|
557
|
+
Value.variant("a", Value.variant("1", UNIT)),
|
|
558
|
+
Value.variant("b", UNIT)
|
|
559
|
+
]) {
|
|
560
|
+
const exp = k.compile(backtrackProg)(val);
|
|
561
|
+
const res = executeObjectWithKTVM(btObj, btObj.main, encodeToWire(val, inPat));
|
|
562
|
+
assert.equal(res.status, "OK");
|
|
563
|
+
assert.deepEqual(plainValue(res.value), plainValue(exp));
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// Closed boundary mismatch raises KTVMSchemaError!
|
|
567
|
+
const boolCheckObj = decodeObject(compileObjectBuffer("?< {} true, {} false >"));
|
|
568
|
+
const badEnv = [["closed-union", [["other", 1]]], ["closed-product", []]];
|
|
569
|
+
assert.throws(
|
|
570
|
+
() => executeObjectWithKTVM(boolCheckObj, boolCheckObj.main, encodeToWire(Value.variant("other", UNIT), badEnv)),
|
|
571
|
+
KTVMSchemaError
|
|
572
|
+
);
|
|
573
|
+
});
|
|
574
|
+
|
|
575
|
+
test("Randomized differential fuzzing (50 random integer/list ops: k.compile vs kTVM wire-to-wire)", () => {
|
|
576
|
+
let seed = 0x5eed1234;
|
|
577
|
+
const rand = () => {
|
|
578
|
+
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
|
|
579
|
+
return seed;
|
|
580
|
+
};
|
|
581
|
+
const randInt = (maxAbs) => {
|
|
582
|
+
const mag = rand() % (maxAbs + 1);
|
|
583
|
+
return (rand() & 1) ? -mag : mag;
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
for (let i = 0; i < 50; i++) {
|
|
587
|
+
const a = randInt(5000);
|
|
588
|
+
const b = randInt(5000);
|
|
589
|
+
const arg = Value.product({ x: parseIntVal(String(a)), y: parseIntVal(String(b)) });
|
|
590
|
+
const op = ["plus", "minus", "times", "cmp", "gt?"][i % 5];
|
|
591
|
+
assertParity(integerLib, op, arg, { label: `fuzz[${i}]:${op}(${a},${b})` });
|
|
592
|
+
}
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
// --- Summary ---
|
|
596
|
+
console.log(`\nConformance & Stdlib Parity Results: ${passed} passed, ${failed} failed.`);
|
|
597
|
+
if (failed > 0) process.exit(1);
|