@fraczak/k 8.5.1 → 8.6.1

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.
@@ -82,6 +82,7 @@ if (fs.existsSync(coreKPath)) {
82
82
  const verifiedExamples = [
83
83
  "arithmetics.k",
84
84
  "ieee.k",
85
+ "ieee-arithmetics.k",
85
86
  "poly.k",
86
87
  "karatsuba-mult.k",
87
88
  "djson.k"
@@ -1691,6 +1692,7 @@ const htmlContent = `<!DOCTYPE html>
1691
1692
  <option value="core.k">core.k</option>
1692
1693
  <option value="arithmetics.k">arithmetics.k</option>
1693
1694
  <option value="ieee.k">ieee.k</option>
1695
+ <option value="ieee-arithmetics.k">ieee-arithmetics.k</option>
1694
1696
  <option value="poly.k">poly.k</option>
1695
1697
  <option value="karatsuba-mult.k">karatsuba-mult.k</option>
1696
1698
  <option value="djson.k">djson.k</option>
@@ -1934,8 +1936,17 @@ const htmlContent = `<!DOCTYPE html>
1934
1936
  (alias <code>:pats</code>)
1935
1937
  </td>
1936
1938
  </tr>
1939
+ <tr>
1940
+ <td><code>:all-patterns</code></td>
1941
+ <td>
1942
+ List canonical patterns keyed by hash with their aliases
1943
+ (alias <code>:all-pat</code>)
1944
+ </td>
1945
+ </tr>
1937
1946
  <tr><td><code>:rel &lt;name&gt;</code></td><td>Display definition of relation <code>&lt;name&gt;</code></td></tr>
1938
1947
  <tr><td><code>:rels</code></td><td>List all relation aliases</td></tr>
1948
+ <tr><td><code>:limit [num|none]</code></td><td>Display or set maximum characters for value output</td></tr>
1949
+ <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>
1939
1950
  <tr><td><code>:codecs</code></td><td>List all loaded format codecs</td></tr>
1940
1951
  <tr><td><code>:codec load &lt;file.mjs&gt;</code></td><td>Load a codec from file (or load through Files)</td></tr>
1941
1952
  <tr><td><code>:codec unload &lt;file.mjs&gt;</code></td><td>Unload a loaded codec</td></tr>
@@ -53,7 +53,7 @@ function printHelp() {
53
53
  console.log(`Usage: node scripts/perf-ieee.mjs [options]
54
54
 
55
55
  IEEE 754 Floating-Point Arithmetic Benchmark Harness.
56
- Benchmarks add, sub, mul, and div on Examples/ieee.k across
56
+ Benchmarks add, sub, mul, and div on Examples/ieee-arithmetics.k across
57
57
  Native JS, kVM interpreter, LLVM, Wasm, and PKIR backends.
58
58
 
59
59
  Options:
@@ -221,10 +221,11 @@ function pkirLaneName() {
221
221
  return "PKIR (Wasm persistent)";
222
222
  }
223
223
 
224
- console.log("==> Initializing state and loading @fraczak/k/Examples/ieee.k");
224
+ console.log("==> Initializing IEEE types and arithmetic");
225
225
  const state = createState();
226
- const ieeePath = fileURLToPath(import.meta.resolve("@fraczak/k/Examples/ieee.k"));
227
- await evaluateInput(`:load ${ieeePath}`, state);
226
+ for (const name of ["core.k", "Examples/ieee.k", "Examples/ieee-arithmetics.k"]) {
227
+ await evaluateInput(`:load ${fileURLToPath(import.meta.resolve(`@fraczak/k/${name}`))}`, state);
228
+ }
228
229
 
229
230
  function generatePerfK(values) {
230
231
  const lines = [];
@@ -253,17 +254,9 @@ function generatePerfK(values) {
253
254
  const perfKSource = generatePerfK(values);
254
255
  await evaluateInput(perfKSource, state);
255
256
 
256
- const ieeeRaw = fs.readFileSync(ieeePath, "utf8");
257
- // Exclude trailing unassigned expression and comment block to ensure
258
- // clean parse.
259
- const endIdx = ieeeRaw.indexOf("\n()\n");
260
- const ieeeBase = endIdx !== -1 ? ieeeRaw.slice(0, endIdx) : ieeeRaw;
261
- const fullSource = `${ieeeBase}\n${perfKSource}\nperf_ieee`;
262
-
263
257
  console.log("==> Preparing relation perf_ieee");
264
258
  const relation = prepareRelation(state, "perf_ieee", {
265
- source: fullSource,
266
- sourceLabel: "@fraczak/k/Examples/ieee.k#perf_ieee"
259
+ sourceLabel: "@fraczak/k/Examples/ieee-arithmetics.k#perf_ieee"
267
260
  });
268
261
  codes.load(state.codes);
269
262
 
@@ -296,7 +289,7 @@ if (runLLVM) {
296
289
  relHash: relation.relHash,
297
290
  inputPattern,
298
291
  cacheDir,
299
- sourceLabel: "@fraczak/k/Examples/ieee.k#perf_ieee",
292
+ sourceLabel: "@fraczak/k/Examples/ieee-arithmetics.k#perf_ieee",
300
293
  runtimeMode: llvmRuntimeMode,
301
294
  clangOpt: opt,
302
295
  usePKIR: false
@@ -327,7 +320,7 @@ if (runLLVMPKIR) {
327
320
  relHash: relation.relHash,
328
321
  inputPattern,
329
322
  cacheDir,
330
- sourceLabel: "@fraczak/k/Examples/ieee.k#perf_ieee",
323
+ sourceLabel: "@fraczak/k/Examples/ieee-arithmetics.k#perf_ieee",
331
324
  runtimeMode: llvmRuntimeMode,
332
325
  clangOpt: opt,
333
326
  usePKIR: true
@@ -446,7 +439,7 @@ function printBenchmarkDescription() {
446
439
  if (runPKIR) lanes.push(pkirLaneName());
447
440
 
448
441
  console.log("==> Benchmark description");
449
- console.log(" source: @fraczak/k/Examples/ieee.k#perf_ieee (single program)");
442
+ console.log(" source: @fraczak/k/Examples/ieee-arithmetics.k#perf_ieee (single program)");
450
443
  console.log(` operations: ${ops.join(", ")}`);
451
444
  console.log(` values: ${values.join(", ")}`);
452
445
  console.log(` evaluation: 1 program call evaluating all ${totalOps} operations`);
@@ -45,7 +45,7 @@ const rowOrder = [
45
45
  const columnGroups = [
46
46
  {
47
47
  title: "ieee",
48
- source: "Examples/ieee.k",
48
+ source: "Examples/ieee-arithmetics.k",
49
49
  columns: [
50
50
  { key: "ieee.add", label: "add" },
51
51
  { key: "ieee.div", label: "div" },
@@ -48,6 +48,8 @@ const tests = [
48
48
  node,
49
49
  ["tests/test-djson-methods.mjs"]
50
50
  ],
51
+ ["tests/test-parse-json.mjs", node, ["tests/test-parse-json.mjs"]],
52
+ ["tests/test-ieee-text.mjs", node, ["tests/test-ieee-text.mjs"]],
51
53
  ["tests/test-deep-wire-value.mjs", node, ["tests/test-deep-wire-value.mjs"]],
52
54
  ["tests/test-k-object.mjs", node, ["tests/test-k-object.mjs"]],
53
55
  ["tests/test-kir.mjs", node, ["tests/test-kir.mjs"]],
package/tests/README.md CHANGED
@@ -44,6 +44,8 @@ cases; shared helpers live outside the discovered directory.
44
44
  | Interactive state and browser UI | `test-repl.mjs`, `test-repl-html.mjs`, `test-tree-view.mjs` |
45
45
  | Execution layers | `test-kvm.mjs`, `test-kvm-polymorphic.mjs`, `test-access-table.mjs`, `test-pkir.mjs` |
46
46
  | Libraries | Arithmetic, IEEE, list, Karatsuba, and dynamic JSON suites |
47
+ | JSON text parsing | `test-parse-json.mjs`: grammar, Unicode escapes, binary64 boundaries, Wasm, and CLI |
48
+ | IEEE text conversion | `test-ieee-text.mjs`: parsing, exact printing, special values, and binary64 round-trips |
47
49
 
48
50
  `test-hash-fuzz.mjs` uses a deterministic generator to check renaming and
49
51
  definition-order invariance; it is not a general cryptographic collision test.
@@ -81,7 +81,8 @@ if ./kvm.mjs -k Examples/nat.k > "$TMP_DIR/dash-k-kvm.out" 2> "$TMP_DIR/dash-k-k
81
81
  fi
82
82
  grep -q -- '-k is no longer supported' "$TMP_DIR/dash-k-kvm.err"
83
83
  echo
84
- ./objects/compile.mjs Examples/ieee.k "$TMP_DIR/ieee.klib"
84
+ ./objects/compile.mjs --lib core.k Examples/ieee.k "$TMP_DIR/ieee-types.klib"
85
+ ./objects/compile.mjs --lib "$TMP_DIR/ieee-types.klib" Examples/ieee-arithmetics.k "$TMP_DIR/ieee.klib"
85
86
  MUL=`./objects/extract-aliases.mjs "$TMP_DIR/ieee.klib" | grep '^mul = @' | sed 's/^mul = \(@[^;]*\);.*$/\1/'`
86
87
  DIV=`./objects/extract-aliases.mjs "$TMP_DIR/ieee.klib" | grep '^div = @' | sed 's/^div = \(@[^;]*\);.*$/\1/'`
87
88
  ARG=0.12
@@ -8,7 +8,17 @@ import { textToStringValue, stringValueToText } from "../codecs/runtime/unicode-
8
8
  import { parse as parseInt } from "../codecs/int.mjs";
9
9
 
10
10
  const source = readFileSync(new URL("../Examples/djson.k", import.meta.url), "utf8");
11
- const library = loadLibrary(compileLibrary(source));
11
+ const core = loadLibrary(compileLibrary(readFileSync(new URL("../core.k", import.meta.url), "utf8")));
12
+ const ieee = loadLibrary(compileLibrary(readFileSync(new URL("../Examples/ieee.k", import.meta.url), "utf8"), {
13
+ libraries: [core]
14
+ }));
15
+ // Resolve dependencies by hash even when the provider's friendly aliases are absent.
16
+ const canonicalTypes = {
17
+ ...ieee,
18
+ patternAlias: {},
19
+ patterns: Object.fromEntries(Object.entries(ieee.patterns).filter(([name]) => name.startsWith("@")))
20
+ };
21
+ const library = loadLibrary(compileLibrary(source, { libraries: [canonicalTypes] }));
12
22
  const run = (op, value) => k.compile(library.relAlias[op], { libraries: [library] })(value);
13
23
 
14
24
  function method(op, json, { key, index, val } = {}) {
@@ -7,7 +7,9 @@ import { parse as parseFloat64, print as printFloat64 } from "../codecs/ieee.mjs
7
7
  import { closedPatternToCodeHash, valueForCode } from "../repl-codecs.mjs";
8
8
 
9
9
  const state = createState({ engine: "js" });
10
+ await evaluateInput(":load core.k", state);
10
11
  await evaluateInput(":load Examples/ieee.k", state);
12
+ await evaluateInput(":load Examples/ieee-arithmetics.k", state);
11
13
 
12
14
  for (const name of ["add", "sub", "mul", "div"]) {
13
15
  assert.ok(state.relAliases[name], `Expected public IEEE relation '${name}'`);
@@ -59,7 +61,7 @@ async function assertOperation({ op, x, y, result, flags = null, projection = fa
59
61
  }
60
62
 
61
63
  const cases = [
62
- // Keep this as a fast smoke matrix. Examples/ieee.k has detailed relation-level coverage.
64
+ // Keep this as a smoke matrix over the separate arithmetic library.
63
65
  { op: "add", x: "0.5", y: "0.25", result: "0.75", flags: "none", projection: true },
64
66
  { op: "add", x: "Infinity", y: "-Infinity", result: "NaN", flags: "invalid" },
65
67
 
@@ -0,0 +1,59 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFileSync } from "node:fs";
3
+ import k from "../index.mjs";
4
+ import { compileLibrary, loadLibrary } from "../object.mjs";
5
+ import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
6
+ import { encodeNumberToValue, decodeValueToNumber } from "../codecs/ieee.mjs";
7
+ import { textToStringValue, stringValueToText } from "../codecs/runtime/unicode-string.mjs";
8
+
9
+ const core = loadLibrary(compileLibrary(readFileSync(new URL("../core.k", import.meta.url), "utf8")));
10
+ const ieee = loadLibrary(compileLibrary(readFileSync(new URL("../Examples/ieee.k", import.meta.url), "utf8"), {
11
+ libraries: [core]
12
+ }));
13
+ assert.equal(ieee.relAlias.add, undefined, "Text conversion must not load IEEE arithmetic");
14
+ const parser = await instantiateWasmArtifact(await compileWasmArtifact(ieee.relAlias.parseFloat64, { libraries: [ieee] }));
15
+ const printer = await instantiateWasmArtifact(await compileWasmArtifact(ieee.relAlias.printFloat64, { libraries: [ieee] }));
16
+ const parse = text => parser.executeValue(textToStringValue(text));
17
+ const print = number => stringValueToText(printer.executeValue(encodeNumberToValue(number)));
18
+ const js = (name, value) => k.compile(ieee.relAlias[name], { libraries: [ieee] })(value);
19
+
20
+ for (const [text, number] of [
21
+ [" +12.5\n", 12.5], ["-0", -0], ["0.1", 0.1], ["1e309", Infinity],
22
+ ["-1e999999999", -Infinity], ["+Infinity", Infinity], ["-Infinity", -Infinity]
23
+ ]) {
24
+ assert.equal(decodeValueToNumber(parse(text)), number, text);
25
+ }
26
+ assert.ok(Number.isNaN(decodeValueToNumber(parse("NaN"))));
27
+ for (const text of ["", " ", ".1", "1.", "01", "1e", "1e+", "Infinityx", "NaNx", "1 2", "--1", "+-1", "-+1"]) {
28
+ assert.equal(parse(text), undefined, text);
29
+ }
30
+ for (const [number, text] of [
31
+ [0, "0"], [-0, "-0"], [1.5, "1.5"], [-12.5, "-12.5"],
32
+ [Infinity, "Infinity"], [-Infinity, "-Infinity"], [NaN, "NaN"],
33
+ [0.1, "0.1000000000000000055511151231257827021181583404541015625"]
34
+ ]) assert.equal(print(number), text);
35
+
36
+ // Round-trip representative extremes and deterministic binary64 bit patterns.
37
+ const numbers = [
38
+ Number.MIN_VALUE, -Number.MIN_VALUE, 2.2250738585072014e-308,
39
+ Number.MAX_VALUE, -Number.MAX_VALUE, 1 / 3, 9007199254740992,
40
+ 1e-100, 1e100, 1e20, -0
41
+ ];
42
+ const view = new DataView(new ArrayBuffer(8));
43
+ let bits = 0x123456789abcdefn;
44
+ for (let i = 0; i < 16; i++) {
45
+ bits = BigInt.asUintN(64, bits * 6364136223846793005n + 1442695040888963407n);
46
+ view.setBigUint64(0, bits);
47
+ const value = view.getFloat64(0);
48
+ if (Number.isFinite(value)) numbers.push(value);
49
+ }
50
+ for (const number of numbers) {
51
+ const text = print(number);
52
+ assert.equal(Number(text), number, `Native round-trip: ${number}`);
53
+ assert.equal(decodeValueToNumber(parse(text)), number, `k round-trip: ${number}`);
54
+ }
55
+ for (const [text, number] of [["1.5", 1.5], ["-0", -0], ["Infinity", Infinity]]) {
56
+ assert.equal(decodeValueToNumber(js("parseFloat64", textToStringValue(text))), number);
57
+ assert.equal(stringValueToText(js("printFloat64", encodeNumberToValue(number))), text);
58
+ }
59
+ console.log("IEEE text: parsing, exact printing, special values and binary64 round-trips passed");
@@ -9,6 +9,7 @@ import { patternToPropertyList } from "../codecs/runtime/pattern-json.mjs";
9
9
  import {
10
10
  compileObjectBuffer,
11
11
  compileLibraryBuffer,
12
+ loadLibrary,
12
13
  decodeObject,
13
14
  objectToFunction,
14
15
  runConvergedObject,
@@ -110,6 +111,14 @@ const arithmeticsRoundTripSource = decompileObjectBuffer(
110
111
  );
111
112
  assert.equal(arithmeticsRoundTripSource, arithmeticsDecompiledSource);
112
113
 
114
+ // Imported relations have canonical keys without local aliases. They still
115
+ // need legal definition names when the complete library is decompiled.
116
+ const imported = loadLibrary(decodeObject(compileLibraryBuffer("leaf = {} |leaf;")));
117
+ const derived = compileLibraryBuffer(`wrap = ${imported.relAlias.leaf} |wrapped;`, { libraries: [imported] });
118
+ const importedSource = decompileObjectBuffer(derived);
119
+ const importedRoundTrip = decompileObjectBuffer(compileLibraryBuffer(importedSource));
120
+ assert.equal(importedRoundTrip, importedSource);
121
+
113
122
  assert.throws(() => k.compile("@A = (); @A"), /Parse error/);
114
123
  assert.throws(() => k.compile("$ @A = {}; $@A"), /Lexical error/);
115
124
  assert.deepEqual(k.compile("7jfi = ?X0; 7jfi")(Value.product({})).toJSON(), {});
@@ -0,0 +1,96 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFileSync, mkdtempSync, rmSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ import k from "../index.mjs";
7
+ import { compileLibrary, loadLibrary } from "../object.mjs";
8
+ import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
9
+ import { fromJsonValue } from "../codecs/djson.mjs";
10
+ import { textToStringValue } from "../codecs/runtime/unicode-string.mjs";
11
+ import { parse as utf8 } from "../codecs/utf8.mjs";
12
+ import { encodeToWire, decodeWire } from "../codecs/runtime/codec-sdk.mjs";
13
+
14
+ const core = loadLibrary(compileLibrary(readFileSync(new URL("../core.k", import.meta.url), "utf8")));
15
+ const ieee = loadLibrary(compileLibrary(readFileSync(new URL("../Examples/ieee.k", import.meta.url), "utf8"), {
16
+ libraries: [core]
17
+ }));
18
+ const library = loadLibrary(compileLibrary(readFileSync(new URL("../Examples/djson.k", import.meta.url), "utf8"), {
19
+ libraries: [ieee]
20
+ }));
21
+ const wasm = await instantiateWasmArtifact(await compileWasmArtifact(library.relAlias.parseJson, { libraries: [library] }));
22
+ const fast = text => wasm.executeValue(textToStringValue(text));
23
+ const parse = k.compile(library.relAlias.parseJson, { libraries: [library] });
24
+ const payload = value => JSON.parse(JSON.stringify(value));
25
+ function check(text, evaluate = text => parse(textToStringValue(text))) {
26
+ const actual = evaluate(text);
27
+ assert.ok(actual, text);
28
+ assert.deepEqual(payload(actual), payload(fromJsonValue(JSON.parse(text))), text);
29
+ }
30
+
31
+ for (const text of [
32
+ " \t\r\n null \t", "true", "false", '""', "[ \t ]", "{ \r\n }",
33
+ '[[],{},null,true,false,[1,-2,3.14]]',
34
+ '{"a":1,"a":{"new":"type"},"":0,"__proto__":{"safe":true},"emoji😀":[1,2]}',
35
+ String.raw`"\"\\\/\b\f\n\r\t"`,
36
+ String.raw`"\uD834\uDD1E\uFAbC"`,
37
+ "0", "-0", "-42", "0.1", "1.25", "12E-2", "1e+20",
38
+ "0e999999999999999999", "-0.00e-999999999999999999", "-1e-999999999999999999"
39
+ ]) check(text);
40
+
41
+ // Exercise every Unicode encoding partition, including surrogate pairs.
42
+ const scalars = [
43
+ 0, 0x1f, 0x7f, 0x80, 0x7ff, 0x800, 0xfff, 0x1000, 0x7fff,
44
+ 0x8000, 0xcfff, 0xd000, 0xd7ff, 0xe000, 0xefff, 0xf000, 0xf7ff,
45
+ 0xf800, 0xf8ff, 0xf900, 0xf9ff, 0xfa00, 0xfbff, 0xfc00, 0xfdff,
46
+ 0xfe00, 0xffff, 0x10000, 0x1ffff, 0x20000, 0x3ffff, 0x40000,
47
+ 0x7ffff, 0x80000, 0xfffff, 0x100000, 0x10ffff
48
+ ];
49
+ for (const scalar of scalars) {
50
+ const text = JSON.stringify(String.fromCodePoint(scalar));
51
+ check(text);
52
+ check(text.replace(/[\u007f-\uffff]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`));
53
+ }
54
+ for (const text of [
55
+ "", " ", "nil", "True", "+1", "01", "-01", ".1", "1.", "1e", "1e+", "--1", "0x10",
56
+ "NaN", "Infinity", "1e999999999999999999", "[1,]", "[,1]", "[1 2]", "[",
57
+ '{"x":1,}', "{x:1}", '{"x" 1}', "{", "null true", '"x"x', '"unterminated',
58
+ String.raw`"\x20"`, String.raw`"\u123"`, String.raw`"\uZZZZ"`,
59
+ String.raw`"\uD800"`, String.raw`"\uDC00"`, String.raw`"\uD800\u0041"`,
60
+ String.raw`"\uDC00\uD800"`, '"line\nfeed"', "\u00a0null"
61
+ ]) assert.equal(parse(textToStringValue(text)), undefined, JSON.stringify(text));
62
+
63
+ // Use compiled Wasm for the expensive exact-rational boundary cases.
64
+ for (const text of [
65
+ "9007199254740993", "9007199254740995", "1.9999999999999999", "9.9999999999999999",
66
+ "1.00000000000000011102230246251565404236316680908203125",
67
+ "1.00000000000000011102230246251565404236316680908203126",
68
+ "5e-324", "2e-324", "2.2250738585072014e-308", "1.7976931348623157e308"
69
+ ]) check(text, fast);
70
+ for (const text of ["1e309", "-1.8e308"]) assert.equal(fast(text), undefined, text);
71
+
72
+ const text = '{"answer":42,"ok":true}';
73
+ const scratch = mkdtempSync(path.join(os.tmpdir(), "k-json-test-"));
74
+ try {
75
+ const artifact = path.join(scratch, "djson.klib");
76
+ const ieeeArtifact = path.join(scratch, "ieee.klib");
77
+ for (const args of [
78
+ ["--lib", "core.k", "Examples/ieee.k", ieeeArtifact],
79
+ ["--lib", ieeeArtifact, "Examples/djson.k", artifact]
80
+ ]) {
81
+ const built = spawnSync(process.execPath, ["objects/compile.mjs", ...args], {
82
+ cwd: new URL("..", import.meta.url)
83
+ });
84
+ assert.ifError(built.error);
85
+ assert.equal(built.status, 0, built.stderr.toString());
86
+ }
87
+ const cli = spawnSync(process.execPath, ["k.mjs", "--lib", artifact, "--export", "parseJson", "parseJson"], {
88
+ cwd: new URL("..", import.meta.url), input: encodeToWire(utf8(text))
89
+ });
90
+ assert.ifError(cli.error);
91
+ assert.equal(cli.status, 0, cli.stderr.toString());
92
+ assert.deepEqual(payload(decodeWire(cli.stdout).value), payload(fromJsonValue(JSON.parse(text))));
93
+ } finally {
94
+ rmSync(scratch, { recursive: true, force: true });
95
+ }
96
+ console.log("JSON text parser: grammar, Unicode, binary64 rounding, Wasm and CLI passed");
@@ -155,6 +155,7 @@ if (chromiumBin) {
155
155
  "djson.k",
156
156
  "djson.mjs",
157
157
  "ieee.k",
158
+ "ieee-arithmetics.k",
158
159
  "ieee.mjs",
159
160
  "int.mjs",
160
161
  "json.mjs",