@fraczak/k 8.7.0 → 8.8.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.
Files changed (73) hide show
  1. package/CHANGELOG.md +40 -8
  2. package/DOCS/CODECS.md +42 -40
  3. package/DOCS/FILE_FORMATS.md +41 -64
  4. package/DOCS/GETTING_STARTED.md +10 -17
  5. package/DOCS/PATTERNS.md +3 -10
  6. package/DOCS/REPL.md +5 -9
  7. package/Examples/ieee-arithmetics.k +14 -29
  8. package/Examples/poly.k +18 -29
  9. package/README.md +14 -18
  10. package/backend-api.mjs +1 -3
  11. package/backends/llvm/src/cli.mjs +7 -11
  12. package/backends/llvm/tests/integration.sh +2 -4
  13. package/backends/wasm/src/wasm.mjs +2 -6
  14. package/backends/wasm/tests/integration.sh +17 -7
  15. package/browser/shims/fs.mjs +2 -6
  16. package/canonical-pattern.mjs +9 -32
  17. package/compiler.mjs +36 -0
  18. package/harness/suites/poly.mjs +9 -11
  19. package/index.mjs +140 -6
  20. package/k.mjs +4 -12
  21. package/kir.mjs +3 -1
  22. package/kvm.mjs +4 -8
  23. package/lib/djson.k +981 -294
  24. package/lib/generic.k +701 -0
  25. package/lib/ieee.k +662 -638
  26. package/lib/integer.k +542 -0
  27. package/named-patterns.mjs +0 -12
  28. package/object.mjs +22 -32
  29. package/objects/README.md +6 -7
  30. package/objects/compile.mjs +5 -10
  31. package/package.json +1 -1
  32. package/repl.mjs +4 -7
  33. package/scripts/benchmark-idempotency.mjs +16 -17
  34. package/scripts/benchmark.mjs +39 -29
  35. package/scripts/build-repl-html.mjs +45 -35
  36. package/scripts/perf-ieee.mjs +1 -5
  37. package/scripts/perf-int.mjs +12 -27
  38. package/scripts/perf-multiplication.mjs +8 -9
  39. package/scripts/perf-poly.mjs +7 -10
  40. package/scripts/render-benchmark.mjs +1 -1
  41. package/scripts/run-tests.mjs +5 -2
  42. package/scripts/test-package.mjs +6 -7
  43. package/tests/README.md +4 -5
  44. package/tests/helpers/cli.mjs +31 -0
  45. package/tests/integration.sh +17 -7
  46. package/tests/test-arithmetics.mjs +23 -16
  47. package/tests/test-djson-methods.mjs +19 -22
  48. package/tests/test-djson.mjs +273 -0
  49. package/tests/test-generic.mjs +239 -0
  50. package/tests/test-ieee-arithmetic.mjs +1 -5
  51. package/tests/test-ieee.mjs +153 -0
  52. package/tests/test-integer.mjs +264 -0
  53. package/tests/test-k-object.mjs +11 -14
  54. package/tests/test-kvm-polymorphic.mjs +7 -4
  55. package/tests/test-lib.mjs +62 -50
  56. package/tests/test-library-isolation.mjs +704 -0
  57. package/tests/test-named-patterns.mjs +13 -4
  58. package/tests/test-parse-json.mjs +20 -19
  59. package/tests/test-poly.mjs +21 -16
  60. package/tests/test-repl-html.mjs +39 -44
  61. package/tests/test-repl.mjs +46 -59
  62. package/DOCS/book-combined.md +0 -3786
  63. package/DOCS/dependency-graph.md +0 -144
  64. package/Examples/arithmetics.k +0 -108
  65. package/Examples/esc.k +0 -9
  66. package/lib/arithmetics.k +0 -287
  67. package/lib/bit.k +0 -68
  68. package/lib/bits.k +0 -221
  69. package/lib/btrie.k +0 -187
  70. package/lib/list.k +0 -49
  71. package/lib/string.k +0 -588
  72. package/tests/test-ieee-text.mjs +0 -70
  73. package/tests/test-karatsuba.mjs +0 -25
@@ -101,23 +101,20 @@ 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" }
104
+ const coreLib = loadLibrary(decodeObject(compileLibraryBuffer(
105
+ fs.readFileSync("core.k", "utf8"),
106
+ { source: "core.k" }
107
107
  )));
108
- const bitsLib = loadLibrary(decodeObject(compileLibraryBuffer(
109
- fs.readFileSync("lib/bits.k", "utf8"),
110
- { source: "lib/bits.k", libraries: [bitLib] }
111
- )));
112
- const arithmeticsLibraryBuffer = compileLibraryBuffer(
113
- fs.readFileSync("lib/arithmetics.k", "utf8"),
114
- { source: "lib/arithmetics.k", libraries: [bitsLib] }
108
+ const integerRaw = fs.readFileSync("lib/integer.k", "utf8");
109
+ const integerLibraryBuffer = compileLibraryBuffer(
110
+ integerRaw,
111
+ { source: "lib/integer.k", libraries: [coreLib] }
115
112
  );
116
- const arithmeticsDecompiledSource = decompileObjectBuffer(arithmeticsLibraryBuffer);
117
- const arithmeticsRoundTripSource = decompileObjectBuffer(
118
- compileLibraryBuffer(arithmeticsDecompiledSource, { source: "lib/arithmetics.decompiled.k" })
113
+ const integerDecompiledSource = decompileObjectBuffer(integerLibraryBuffer);
114
+ const integerRoundTripSource = decompileObjectBuffer(
115
+ compileLibraryBuffer(integerDecompiledSource, { source: "lib/integer.decompiled.k" })
119
116
  );
120
- assert.equal(arithmeticsRoundTripSource, arithmeticsDecompiledSource);
117
+ assert.equal(integerRoundTripSource, integerDecompiledSource);
121
118
 
122
119
  // Imported relations have canonical keys without local aliases. They still
123
120
  // need legal definition names when the complete library is decompiled.
@@ -6,6 +6,7 @@ import {
6
6
  executeKVM
7
7
  } from "../kvm.mjs";
8
8
  import { compileObjectBuffer, decodeObject } from "../object.mjs";
9
+ import { useSpecsFor } from "./helpers/cli.mjs";
9
10
  import { objectToKIRP } from "../kir.mjs";
10
11
  import { fromObject, Value } from "../Value.mjs";
11
12
  import { lowerToWasm } from "../backends/wasm/src/kvm2wasm.mjs";
@@ -243,11 +244,13 @@ console.log("==> Starting Polymorphic kVM & Specialization Tests");
243
244
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-kvm-poly-"));
244
245
  try {
245
246
  let prevLib = null;
246
- for (const [idx, src] of ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"].entries()) {
247
+ for (const [idx, src] of ["core.k", "lib/integer.k"].entries()) {
247
248
  const nextLib = path.join(tmpDir, `step-${idx}.klib`);
249
+ const uses = useSpecsFor(src).flatMap((u) => ["--use", u]);
248
250
  const stepRes = spawnSync(process.execPath, [
249
251
  compileScript,
250
252
  ...(prevLib ? ["--lib", prevLib] : []),
253
+ ...uses,
251
254
  src,
252
255
  nextLib
253
256
  ], {
@@ -262,7 +265,7 @@ console.log("==> Starting Polymorphic kVM & Specialization Tests");
262
265
  const failRes = spawnSync(process.execPath, [
263
266
  compileScript,
264
267
  "--lib", prevLib,
265
- "{succ int x,int y}+"
268
+ "{nat inc x, nat y}+"
266
269
  ], {
267
270
  cwd: path.join(__dirname, ".."),
268
271
  encoding: "utf8"
@@ -273,9 +276,9 @@ console.log("==> Starting Polymorphic kVM & Specialization Tests");
273
276
  const successRes = spawnSync(process.execPath, [
274
277
  compileScript,
275
278
  "--lib", prevLib,
276
- "--use", "plus:+ succ int",
279
+ "--use", "plus:+ inc nat",
277
280
  "--format", "kvm",
278
- "{succ int x,int y}+"
281
+ "{nat inc x, nat y}+"
279
282
  ], {
280
283
  cwd: path.join(__dirname, ".."),
281
284
  encoding: "utf8",
@@ -3,71 +3,85 @@ import { readFileSync } from "node:fs";
3
3
  import k from "../index.mjs";
4
4
  import { Value } from "../Value.mjs";
5
5
  import { compileLibrary, loadLibrary } from "../object.mjs";
6
+ import { useSpecsFor } from "./helpers/cli.mjs";
6
7
  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";
8
+ import { textToStringValue } from "../codecs/runtime/unicode-string.mjs";
9
+ import { decodeValueToNumber } from "../codecs/ieee.mjs";
9
10
  import { parse as parseInt, parseIntStr, print as printInt } from "../codecs/int.mjs";
10
11
 
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);
12
+ function compileChain(files) {
13
+ const libs = [];
14
+ let current = null;
15
+ for (const file of files) {
16
+ const source = readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
17
+ const uses = useSpecsFor(file);
18
+ current = loadLibrary(
19
+ compileLibrary(source, { source: file, libraries: current ? [current] : [], use: uses })
20
+ );
21
+ libs.push(current);
22
+ }
23
+ return libs;
29
24
  }
30
25
 
31
- const arithLib = libs[2];
32
- const ieeeLib = libs[6];
33
- const djsonLib = libs[7];
26
+ const [, integerLib] = compileChain(["core.k", "lib/integer.k"]);
27
+ const [, genericLib, ieeeLib, djsonLib] = compileChain([
28
+ "core.k",
29
+ "lib/generic.k",
30
+ "lib/ieee.k",
31
+ "lib/djson.k"
32
+ ]);
34
33
 
35
- const runArith = (op, value) =>
36
- k.compile(arithLib.relAlias[op], { libraries: [arithLib] })(value);
34
+ const runInt = (op, value) =>
35
+ k.compile(integerLib.relAlias[op], { libraries: [integerLib] })(value);
36
+ const runGeneric = (op, value) =>
37
+ k.compile(genericLib.relAlias[op], { libraries: [genericLib] })(value);
37
38
  const runIeee = (op, value) =>
38
39
  k.compile(ieeeLib.relAlias[op], { libraries: [ieeeLib] })(value);
39
40
  const runDjson = (op, value) =>
40
41
  k.compile(djsonLib.relAlias[op], { libraries: [djsonLib] })(value);
41
42
 
42
- // Verify lib/arithmetics.k integer operations.
43
+ // Verify lib/generic.k string_to_bits <-> bits_to_string round-trip.
44
+ const encodedStrBits = runGeneric("string_to_bits", textToStringValue("kšŸ˜€"));
43
45
  assert.equal(
44
- printInt(runArith("plus", Value.product({ x: parseIntStr("19"), y: parseIntStr("23") }))),
46
+ runDjson("string?", Value.variant("string", runGeneric("bits_to_string", encodedStrBits)))
47
+ .value.type,
48
+ "<>"
49
+ );
50
+
51
+ // Verify lib/integer.k integer operations (Karatsuba is implemented in times).
52
+ assert.equal(
53
+ printInt(runInt("plus", Value.product({ x: parseIntStr("19"), y: parseIntStr("23") }))),
45
54
  "42"
46
55
  );
47
56
  assert.equal(
48
- printInt(runArith("times", Value.product({ x: parseIntStr("-6"), y: parseIntStr("7") }))),
57
+ printInt(runInt("times", Value.product({ x: parseIntStr("-6"), y: parseIntStr("7") }))),
49
58
  "-42"
50
59
  );
51
60
  assert.equal(
52
- printInt(runArith("karatsuba", Value.product({ x: parseIntStr("123456"), y: parseIntStr("-654321") }))),
61
+ printInt(runInt("times", Value.product({ x: parseIntStr("123456"), y: parseIntStr("-654321") }))),
53
62
  String(123456n * -654321n)
54
63
  );
55
64
 
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
-
65
+ // Verify lib/ieee.k conversion and negation helpers.
68
66
  for (const n of [0, 1, 2, 10, 42, 1024, 65535]) {
69
- const f = decodeValueToNumber(runIeee("natToFloat64", parseInt(String(n)).value));
67
+ const bits = parseInt(String(n)).value;
68
+ const f = decodeValueToNumber(
69
+ runIeee(
70
+ "ratio_to_float64",
71
+ Value.product({
72
+ sign: Value.variant("+", Value.product({})),
73
+ num: bits,
74
+ den: parseInt("1").value
75
+ })
76
+ )
77
+ );
70
78
  assert.equal(f, n);
79
+ const posFloat = runIeee("bits_to_float64", bits);
80
+ assert.equal(decodeValueToNumber(posFloat), n);
81
+ assert.equal(
82
+ decodeValueToNumber(runIeee("negate_float64", posFloat)),
83
+ n === 0 ? -0 : -n
84
+ );
71
85
  }
72
86
 
73
87
  // Verify lib/djson.k methods and RFC 8259 JSON parser.
@@ -83,8 +97,8 @@ const result = (...args) => toJsonValue(method(...args));
83
97
  const doc = { name: "Alice", age: 30, tags: ["developer", "k"] };
84
98
  assert.equal(result("get", doc, { key: "name" }), "Alice");
85
99
  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);
100
+ assert.ok(method("has_key?", doc, { key: "name" }));
101
+ assert.equal(method("has_key?", doc, { key: "missing" }), undefined);
88
102
 
89
103
  const withCity = result("set", doc, { key: "city", val: "Paris" });
90
104
  assert.deepEqual(withCity, { ...doc, city: "Paris" });
@@ -95,14 +109,12 @@ const arr = [10, 20, 30];
95
109
  for (const [index, expected] of arr.entries()) {
96
110
  assert.equal(result("nth", arr, { index }), expected);
97
111
  }
98
- assert.ok(method("has_index?", arr, { index: 1 }));
99
- assert.equal(method("has_index?", arr, { index: 99 }), undefined);
112
+ assert.ok(method("has_nth?", arr, { index: 1 }));
113
+ assert.equal(method("has_nth?", arr, { index: 99 }), undefined);
100
114
  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
115
  assert.deepEqual(result("push", arr, { val: 40 }), [10, 20, 30, 40]);
105
116
  assert.deepEqual(new Set(toJsonValue(runDjson("keys", fromJsonValue(doc)))), new Set(["name", "age", "tags"]));
117
+ assert.deepEqual(toJsonValue(runDjson("values", fromJsonValue(arr))), [10, 20, 30]);
106
118
 
107
119
  const sampleJson = JSON.stringify({
108
120
  nullVal: null,
@@ -111,5 +123,5 @@ const sampleJson = JSON.stringify({
111
123
  str: "hello\n\t\"world\"\\/\u0041\uD83D\uDE00",
112
124
  empty: [{}, []]
113
125
  });
114
- const parsedJson = toJsonValue(runDjson("parseJson", textToStringValue(sampleJson)));
126
+ const parsedJson = toJsonValue(runDjson("parse_json", textToStringValue(sampleJson)));
115
127
  assert.deepEqual(parsedJson, JSON.parse(sampleJson));