@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.
Files changed (69) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/DOCS/CODECS.md +42 -40
  3. package/DOCS/FILE_FORMATS.md +28 -25
  4. package/DOCS/GETTING_STARTED.md +10 -15
  5. package/DOCS/PATTERNS.md +3 -3
  6. package/DOCS/REPL.md +3 -6
  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 +1 -2
  12. package/backends/llvm/tests/integration.sh +2 -6
  13. package/backends/wasm/tests/integration.sh +5 -10
  14. package/browser/shims/fs.mjs +2 -6
  15. package/canonical-pattern.mjs +9 -29
  16. package/codecs/djson.mjs +2 -3
  17. package/codecs/int.mjs +66 -14
  18. package/compiler.mjs +22 -12
  19. package/harness/suites/poly.mjs +9 -11
  20. package/index.mjs +119 -50
  21. package/lib/djson.k +976 -288
  22. package/lib/generic.k +686 -0
  23. package/lib/ieee.k +658 -639
  24. package/lib/integer.k +536 -0
  25. package/object.mjs +19 -12
  26. package/objects/README.md +6 -6
  27. package/package.json +1 -1
  28. package/scripts/benchmark-idempotency.mjs +16 -17
  29. package/scripts/benchmark.mjs +39 -29
  30. package/scripts/build-repl-html.mjs +45 -35
  31. package/scripts/perf-bigint-compare.mjs +279 -0
  32. package/scripts/perf-ieee.mjs +1 -5
  33. package/scripts/perf-int.mjs +12 -27
  34. package/scripts/perf-multiplication.mjs +8 -9
  35. package/scripts/perf-poly.mjs +7 -10
  36. package/scripts/render-benchmark.mjs +1 -1
  37. package/scripts/run-tests.mjs +4 -2
  38. package/scripts/test-package.mjs +4 -10
  39. package/tests/README.md +4 -5
  40. package/tests/helpers/cli.mjs +30 -7
  41. package/tests/integration.sh +5 -10
  42. package/tests/test-arithmetics.mjs +23 -16
  43. package/tests/test-djson-methods.mjs +16 -25
  44. package/tests/test-djson.mjs +272 -0
  45. package/tests/test-generic.mjs +237 -0
  46. package/tests/test-ieee-arithmetic.mjs +1 -5
  47. package/tests/test-ieee.mjs +153 -0
  48. package/tests/test-integer.mjs +264 -0
  49. package/tests/test-k-object.mjs +12 -18
  50. package/tests/test-kvm-polymorphic.mjs +6 -7
  51. package/tests/test-lib.mjs +62 -52
  52. package/tests/test-library-isolation.mjs +349 -26
  53. package/tests/test-parse-json.mjs +15 -24
  54. package/tests/test-poly.mjs +21 -16
  55. package/tests/test-repl-html.mjs +39 -44
  56. package/tests/test-repl.mjs +46 -59
  57. package/tests/test-structural-values.mjs +1 -1
  58. package/DOCS/book-combined.md +0 -3786
  59. package/DOCS/dependency-graph.md +0 -144
  60. package/Examples/arithmetics.k +0 -108
  61. package/Examples/esc.k +0 -9
  62. package/lib/arithmetics.k +0 -286
  63. package/lib/bit.k +0 -68
  64. package/lib/bits.k +0 -227
  65. package/lib/btrie.k +0 -187
  66. package/lib/list.k +0 -49
  67. package/lib/string.k +0 -588
  68. package/tests/test-ieee-text.mjs +0 -74
  69. package/tests/test-karatsuba.mjs +0 -25
@@ -0,0 +1,264 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ import { fileURLToPath } from "node:url";
6
+ import k from "../index.mjs";
7
+ import { compileLibrary, loadLibrary } from "../object.mjs";
8
+ import { Value } from "../Value.mjs";
9
+ import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
10
+ import { parse as parseIntVal, print as printIntVal } from "../codecs/int.mjs";
11
+ import { withCompiledLibrary } from "./helpers/cli.mjs";
12
+
13
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
14
+ const integerSource = fs.readFileSync(path.join(root, "lib/integer.k"), "utf8");
15
+
16
+ // Self-contained module: lib/integer.k compiles standalone and converges completely.
17
+ const intLib = loadLibrary(compileLibrary(integerSource, {
18
+ source: "lib/integer.k"
19
+ }));
20
+
21
+ for (const [hash, rel] of Object.entries(intLib.rels)) {
22
+ assert.equal(
23
+ rel.typeDerivation?.status,
24
+ "converged",
25
+ `lib/integer.k relation ${hash} did not converge: ${JSON.stringify(rel.typeDerivation)}`
26
+ );
27
+ }
28
+
29
+ // Karatsuba is implemented directly inside `times`; no separate `karatsuba` export.
30
+ assert.equal(intLib.relAlias.karatsuba, undefined, "lib/integer.k must expose `times`, not `karatsuba`");
31
+
32
+ const compileRel = (name) => {
33
+ const alias = intLib.relAlias[name];
34
+ assert.ok(alias, `missing exported relation '${name}' in lib/integer.k`);
35
+ return k.compile(alias, { libraries: [intLib] });
36
+ };
37
+
38
+ const compiled = {
39
+ zero: compileRel("0"),
40
+ one: compileRel("1"),
41
+ nat: compileRel("nat"),
42
+ int: compileRel("int"),
43
+ isZero: compileRel("zero?"),
44
+ isPos: compileRel("pos?"),
45
+ isNeg: compileRel("neg?"),
46
+ abs: compileRel("abs"),
47
+ negate: compileRel("negate"),
48
+ inc: compileRel("inc"),
49
+ dec: compileRel("dec"),
50
+ cmp: compileRel("cmp"),
51
+ lt: compileRel("lt?"),
52
+ le: compileRel("le?"),
53
+ eq: compileRel("eq?"),
54
+ gt: compileRel("gt?"),
55
+ ge: compileRel("ge?"),
56
+ plus: compileRel("plus"),
57
+ minus: compileRel("minus"),
58
+ times: compileRel("times"),
59
+ divmod: compileRel("divmod"),
60
+ div: compileRel("div"),
61
+ mod: compileRel("mod"),
62
+ gcd: compileRel("gcd"),
63
+ lcm: compileRel("lcm")
64
+ };
65
+
66
+ function bitsFromStr(str) {
67
+ let v = Value.variant("_", Value.product({}));
68
+ for (let i = str.length - 1; i >= 0; i--) {
69
+ v = Value.variant(str[i], v);
70
+ }
71
+ return v;
72
+ }
73
+
74
+ const iVal = (n) => parseIntVal(String(n));
75
+ const toBig = (v) => BigInt(printIntVal(v));
76
+ const pair = (x, y) => Value.product({ x: iVal(x), y: iVal(y) });
77
+
78
+ function jsGcd(a, b) {
79
+ a = a < 0n ? -a : a;
80
+ b = b < 0n ? -b : b;
81
+ while (b !== 0n) {
82
+ [a, b] = [b, a % b];
83
+ }
84
+ return a;
85
+ }
86
+
87
+ function jsLcm(a, b) {
88
+ if (a === 0n || b === 0n) return 0n;
89
+ const aa = a < 0n ? -a : a;
90
+ const bb = b < 0n ? -b : b;
91
+ return (aa / jsGcd(aa, bb)) * bb;
92
+ }
93
+
94
+ // 1. Constants & normalization
95
+ assert.equal(toBig(compiled.zero(Value.product({}))), 0n);
96
+ assert.equal(toBig(compiled.one(Value.product({}))), 1n);
97
+ assert.equal(toBig(compiled.nat(bitsFromStr("000101"))), 5n);
98
+ assert.equal(toBig(compiled.nat(bitsFromStr("000"))), 0n);
99
+ assert.deepEqual(
100
+ compiled.int(Value.variant("-", bitsFromStr("000"))).toJSON(),
101
+ iVal(0n).toJSON(),
102
+ "int normalizer must canonicalize -0 to +0"
103
+ );
104
+
105
+ // 2. Predicates & unary relations
106
+ const unaryCases = [
107
+ 0n,
108
+ 1n,
109
+ -1n,
110
+ 2n,
111
+ -2n,
112
+ 255n,
113
+ -256n,
114
+ (1n << 64n) - 1n,
115
+ 1n << 64n,
116
+ -(1n << 64n),
117
+ -((1n << 64n) - 1n)
118
+ ];
119
+
120
+ for (const x of unaryCases) {
121
+ const vx = iVal(x);
122
+ assert.equal(Boolean(compiled.isZero(vx)), x === 0n, `zero?(${x})`);
123
+ assert.equal(Boolean(compiled.isPos(vx)), x > 0n, `pos?(${x})`);
124
+ assert.equal(Boolean(compiled.isNeg(vx)), x < 0n, `neg?(${x})`);
125
+ assert.equal(toBig(compiled.abs(vx)), x < 0n ? -x : x, `abs(${x})`);
126
+ assert.equal(toBig(compiled.negate(vx)), -x, `negate(${x})`);
127
+ assert.equal(toBig(compiled.inc(vx)), x + 1n, `inc(${x})`);
128
+ assert.equal(toBig(compiled.dec(vx)), x - 1n, `dec(${x})`);
129
+ }
130
+
131
+ // 3. Ordering & binary arithmetic vs BigInt oracle (small, cross-sign, and large multi-limb)
132
+ const operands = [
133
+ 0n,
134
+ 1n,
135
+ -1n,
136
+ 2n,
137
+ -2n,
138
+ 3n,
139
+ -3n,
140
+ 6n,
141
+ -7n,
142
+ 42n,
143
+ -99n,
144
+ 12345678901234567890n,
145
+ -98765432109876543210n,
146
+ (1n << 80n) - 3n,
147
+ -((1n << 95n) + 12345n),
148
+ (1n << 160n) + 999999999999999n
149
+ ];
150
+
151
+ for (const x of operands) {
152
+ for (const y of operands) {
153
+ const inp = pair(x, y);
154
+ const expectedOrd = x < y ? "lt" : x > y ? "gt" : "eq";
155
+ assert.equal(compiled.cmp(inp).tag, expectedOrd, `cmp(${x}, ${y})`);
156
+ assert.equal(Boolean(compiled.lt(inp)), x < y, `lt?(${x}, ${y})`);
157
+ assert.equal(Boolean(compiled.le(inp)), x <= y, `le?(${x}, ${y})`);
158
+ assert.equal(Boolean(compiled.eq(inp)), x === y, `eq?(${x}, ${y})`);
159
+ assert.equal(Boolean(compiled.gt(inp)), x > y, `gt?(${x}, ${y})`);
160
+ assert.equal(Boolean(compiled.ge(inp)), x >= y, `ge?(${x}, ${y})`);
161
+
162
+ assert.equal(toBig(compiled.plus(inp)), x + y, `plus(${x}, ${y})`);
163
+ assert.equal(toBig(compiled.minus(inp)), x - y, `minus(${x}, ${y})`);
164
+ assert.equal(toBig(compiled.times(inp)), x * y, `times(${x}, ${y})`);
165
+ }
166
+ }
167
+
168
+ // Multi-limb Karatsuba squaring & asymmetric products (256-bit)
169
+ const bigA = (1n << 255n) - 19n;
170
+ const bigB = (1n << 220n) + 0xdeadbeefcafebaben;
171
+ assert.equal(toBig(compiled.times(pair(bigA, bigA))), bigA * bigA);
172
+ assert.equal(toBig(compiled.times(pair(bigA, -bigB))), bigA * -bigB);
173
+ assert.equal(toBig(compiled.times(pair(-bigA, bigB))), -bigA * bigB);
174
+
175
+ // 4. Fast binary division (truncating semantics), remainder, gcd, lcm
176
+ const divCases = [
177
+ [0n, 3n],
178
+ [0n, -3n],
179
+ [7n, 3n],
180
+ [-7n, 3n],
181
+ [7n, -3n],
182
+ [-7n, -3n],
183
+ [6n, -3n],
184
+ [-6n, 3n],
185
+ [3n, 7n],
186
+ [-3n, 7n],
187
+ [98765432109876543210987654321n, 123456789012345n],
188
+ [-98765432109876543210987654321n, 123456789012345n],
189
+ [(1n << 256n) + 123456789n, (1n << 100n) + 999999999999n],
190
+ [-((1n << 256n) + 123456789n), -((1n << 100n) + 999999999999n)]
191
+ ];
192
+
193
+ for (const [x, y] of divCases) {
194
+ const inp = pair(x, y);
195
+ const dm = compiled.divmod(inp);
196
+ const q = toBig(dm.product.q);
197
+ const r = toBig(dm.product.r);
198
+ assert.equal(q, x / y, `divmod.q(${x}, ${y})`);
199
+ assert.equal(r, x % y, `divmod.r(${x}, ${y})`);
200
+ assert.equal(q * y + r, x, `divmod identity(${x}, ${y})`);
201
+ assert.equal(toBig(compiled.div(inp)), x / y, `div(${x}, ${y})`);
202
+ assert.equal(toBig(compiled.mod(inp)), x % y, `mod(${x}, ${y})`);
203
+ }
204
+
205
+ for (const x of [0n, 7n, -7n]) {
206
+ assert.equal(compiled.divmod(pair(x, 0n)), undefined, `divmod(${x}, 0) must fail`);
207
+ assert.equal(compiled.div(pair(x, 0n)), undefined, `div(${x}, 0) must fail`);
208
+ assert.equal(compiled.mod(pair(x, 0n)), undefined, `mod(${x}, 0) must fail`);
209
+ }
210
+
211
+ const gcdCases = [
212
+ [0n, 0n],
213
+ [0n, -18n],
214
+ [-18n, 0n],
215
+ [-48n, 18n],
216
+ [48n, -18n],
217
+ [-12n, -18n],
218
+ [6n << 80n, -9n << 80n],
219
+ [104729n * 999983n, 999983n * 1299709n]
220
+ ];
221
+
222
+ for (const [x, y] of gcdCases) {
223
+ const inp = pair(x, y);
224
+ assert.equal(toBig(compiled.gcd(inp)), jsGcd(x, y), `gcd(${x}, ${y})`);
225
+ assert.equal(toBig(compiled.lcm(inp)), jsLcm(x, y), `lcm(${x}, ${y})`);
226
+ }
227
+
228
+ // 5. Wasm & CLI chaining parity
229
+ const wasmInc = await instantiateWasmArtifact(
230
+ await compileWasmArtifact(intLib.relAlias.inc, { libraries: [intLib] })
231
+ );
232
+ assert.equal(toBig(wasmInc.executeValue(iVal(-1n))), 0n);
233
+ assert.equal(toBig(wasmInc.executeValue(iVal((1n << 64n) - 1n))), 1n << 64n);
234
+
235
+ const wasmSquare = await instantiateWasmArtifact(
236
+ await compileWasmArtifact(`{ () x, () y } ${intLib.relAlias.times}`, { libraries: [intLib] })
237
+ );
238
+ const sqInput = (1n << 140n) - 12345n;
239
+ assert.equal(toBig(wasmSquare.executeValue(iVal(sqInput))), sqInput * sqInput);
240
+
241
+ withCompiledLibrary(["lib/integer.k"], (library) => {
242
+ const parseCli = spawnSync(process.execPath, ["codecs/int.mjs", "--parse"], {
243
+ cwd: root,
244
+ input: "98765432109876543210\n"
245
+ });
246
+ assert.equal(parseCli.status, 0, parseCli.stderr?.toString());
247
+ const runCli = spawnSync(
248
+ process.execPath,
249
+ ["k.mjs", "--lib", library, "--use", "times", "{ () x, () y } times"],
250
+ { cwd: root, input: parseCli.stdout, maxBuffer: 8 * 1024 * 1024 }
251
+ );
252
+ assert.equal(runCli.status, 0, runCli.stderr?.toString());
253
+ const printCli = spawnSync(process.execPath, ["codecs/int.mjs", "--print"], {
254
+ cwd: root,
255
+ input: runCli.stdout
256
+ });
257
+ assert.equal(printCli.status, 0, printCli.stderr?.toString());
258
+ assert.equal(
259
+ printCli.stdout.toString("utf8").trim(),
260
+ String(98765432109876543210n * 98765432109876543210n)
261
+ );
262
+ });
263
+
264
+ console.log("lib/integer.k specification tests passed");
@@ -14,8 +14,7 @@ import {
14
14
  objectToFunction,
15
15
  runConvergedObject,
16
16
  decompileObjectBuffer,
17
- extractAliasesFromObject,
18
- parseHeaderUses
17
+ extractAliasesFromObject
19
18
  } from "../object.mjs";
20
19
 
21
20
  const value = parseValue("{a:{b:x,c:{}}}");
@@ -102,25 +101,20 @@ const recursiveNatPattern = new RegExp(
102
101
  assert.equal(natRoundTripSource, natDecompiledSource);
103
102
  assert.match(natDecompiledSource, recursiveNatPattern);
104
103
 
105
- const bitLib = loadLibrary(decodeObject(compileLibraryBuffer(
106
- fs.readFileSync("lib/bit.k", "utf8"),
107
- { source: "lib/bit.k" }
104
+ const coreLib = loadLibrary(decodeObject(compileLibraryBuffer(
105
+ fs.readFileSync("core.k", "utf8"),
106
+ { source: "core.k" }
108
107
  )));
109
- const bitsLib = loadLibrary(decodeObject(compileLibraryBuffer(
110
- fs.readFileSync("lib/bits.k", "utf8"),
111
- { source: "lib/bits.k", libraries: [bitLib] }
112
- )));
113
- const arithRaw = fs.readFileSync("lib/arithmetics.k", "utf8");
114
- const arithUses = parseHeaderUses(arithRaw).map((u) => u.use);
115
- const arithmeticsLibraryBuffer = compileLibraryBuffer(
116
- arithRaw,
117
- { source: "lib/arithmetics.k", libraries: [bitsLib], use: arithUses }
108
+ const integerRaw = fs.readFileSync("lib/integer.k", "utf8");
109
+ const integerLibraryBuffer = compileLibraryBuffer(
110
+ integerRaw,
111
+ { source: "lib/integer.k", libraries: [coreLib] }
118
112
  );
119
- const arithmeticsDecompiledSource = decompileObjectBuffer(arithmeticsLibraryBuffer);
120
- const arithmeticsRoundTripSource = decompileObjectBuffer(
121
- compileLibraryBuffer(arithmeticsDecompiledSource, { source: "lib/arithmetics.decompiled.k" })
113
+ const integerDecompiledSource = decompileObjectBuffer(integerLibraryBuffer);
114
+ const integerRoundTripSource = decompileObjectBuffer(
115
+ compileLibraryBuffer(integerDecompiledSource, { source: "lib/integer.decompiled.k" })
122
116
  );
123
- assert.equal(arithmeticsRoundTripSource, arithmeticsDecompiledSource);
117
+ assert.equal(integerRoundTripSource, integerDecompiledSource);
124
118
 
125
119
  // Imported relations have canonical keys without local aliases. They still
126
120
  // need legal definition names when the complete library is decompiled.
@@ -6,7 +6,7 @@ import {
6
6
  executeKVM
7
7
  } from "../kvm.mjs";
8
8
  import { compileObjectBuffer, decodeObject } from "../object.mjs";
9
- import { parseHeaderUses } from "../canonical-pattern.mjs";
9
+ import { useSpecsFor } from "./helpers/cli.mjs";
10
10
  import { objectToKIRP } from "../kir.mjs";
11
11
  import { fromObject, Value } from "../Value.mjs";
12
12
  import { lowerToWasm } from "../backends/wasm/src/kvm2wasm.mjs";
@@ -244,10 +244,9 @@ console.log("==> Starting Polymorphic kVM & Specialization Tests");
244
244
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-kvm-poly-"));
245
245
  try {
246
246
  let prevLib = null;
247
- 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()) {
248
248
  const nextLib = path.join(tmpDir, `step-${idx}.klib`);
249
- const fileSource = fs.readFileSync(path.join(__dirname, "..", src), "utf8");
250
- const uses = parseHeaderUses(fileSource).flatMap((u) => ["--use", u.use]);
249
+ const uses = useSpecsFor(src).flatMap((u) => ["--use", u]);
251
250
  const stepRes = spawnSync(process.execPath, [
252
251
  compileScript,
253
252
  ...(prevLib ? ["--lib", prevLib] : []),
@@ -266,7 +265,7 @@ console.log("==> Starting Polymorphic kVM & Specialization Tests");
266
265
  const failRes = spawnSync(process.execPath, [
267
266
  compileScript,
268
267
  "--lib", prevLib,
269
- "{succ int x,int y}+"
268
+ "{nat inc x, nat y}+"
270
269
  ], {
271
270
  cwd: path.join(__dirname, ".."),
272
271
  encoding: "utf8"
@@ -277,9 +276,9 @@ console.log("==> Starting Polymorphic kVM & Specialization Tests");
277
276
  const successRes = spawnSync(process.execPath, [
278
277
  compileScript,
279
278
  "--lib", prevLib,
280
- "--use", "plus:+ succ int",
279
+ "--use", "plus:+ inc nat",
281
280
  "--format", "kvm",
282
- "{succ int x,int y}+"
281
+ "{nat inc x, nat y}+"
283
282
  ], {
284
283
  cwd: path.join(__dirname, ".."),
285
284
  encoding: "utf8",
@@ -3,73 +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 { parseHeaderUses } from "../canonical-pattern.mjs";
6
+ import { useSpecsFor } from "./helpers/cli.mjs";
7
7
  import { fromJsonValue, toJsonValue } from "../codecs/djson.mjs";
8
- import { textToStringValue, stringValueToText } from "../codecs/runtime/unicode-string.mjs";
9
- import { encodeNumberToValue, decodeValueToNumber } from "../codecs/ieee.mjs";
8
+ import { textToStringValue } from "../codecs/runtime/unicode-string.mjs";
9
+ import { decodeValueToNumber } from "../codecs/ieee.mjs";
10
10
  import { parse as parseInt, parseIntStr, print as printInt } from "../codecs/int.mjs";
11
11
 
12
- const libFiles = [
13
- "lib/bit.k",
14
- "lib/bits.k",
15
- "lib/list.k",
16
- "lib/btrie.k",
17
- "lib/string.k",
18
- "lib/ieee.k",
19
- "lib/djson.k",
20
- "lib/arithmetics.k"
21
- ];
22
-
23
- const libs = [];
24
- for (const file of libFiles) {
25
- const source = readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
26
- const uses = parseHeaderUses(source).map((u) => u.use);
27
- const compiled = loadLibrary(
28
- compileLibrary(source, { source: file, libraries: libs, use: uses })
29
- );
30
- 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;
31
24
  }
32
25
 
33
- const ieeeLib = libs[5];
34
- const djsonLib = libs[6];
35
- const arithLib = 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
+ ]);
36
33
 
37
- const runArith = (op, value) =>
38
- 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);
39
38
  const runIeee = (op, value) =>
40
39
  k.compile(ieeeLib.relAlias[op], { libraries: [ieeeLib] })(value);
41
40
  const runDjson = (op, value) =>
42
41
  k.compile(djsonLib.relAlias[op], { libraries: [djsonLib] })(value);
43
42
 
44
- // 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šŸ˜€"));
45
45
  assert.equal(
46
- 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") }))),
47
54
  "42"
48
55
  );
49
56
  assert.equal(
50
- printInt(runArith("times", Value.product({ x: parseIntStr("-6"), y: parseIntStr("7") }))),
57
+ printInt(runInt("times", Value.product({ x: parseIntStr("-6"), y: parseIntStr("7") }))),
51
58
  "-42"
52
59
  );
53
60
  assert.equal(
54
- printInt(runArith("karatsuba", Value.product({ x: parseIntStr("123456"), y: parseIntStr("-654321") }))),
61
+ printInt(runInt("times", Value.product({ x: parseIntStr("123456"), y: parseIntStr("-654321") }))),
55
62
  String(123456n * -654321n)
56
63
  );
57
64
 
58
- // Verify lib/ieee.k text parsing, natural conversion, and exact decimal printing.
59
- for (const num of [0, -0, 1, -1, 3.141592653589793, 1e-10, 1e20, Infinity, -Infinity, NaN]) {
60
- const val = encodeNumberToValue(num);
61
- const text = stringValueToText(runIeee("printFloat64", val));
62
- const parsed = decodeValueToNumber(runIeee("parseFloat64", textToStringValue(text)));
63
- if (Number.isNaN(num)) {
64
- assert.ok(Number.isNaN(parsed));
65
- } else {
66
- assert.ok(Object.is(parsed, num), `round-trip ${num} via ${text}`);
67
- }
68
- }
69
-
65
+ // Verify lib/ieee.k conversion and negation helpers.
70
66
  for (const n of [0, 1, 2, 10, 42, 1024, 65535]) {
71
- 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
+ );
72
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
+ );
73
85
  }
74
86
 
75
87
  // Verify lib/djson.k methods and RFC 8259 JSON parser.
@@ -85,8 +97,8 @@ const result = (...args) => toJsonValue(method(...args));
85
97
  const doc = { name: "Alice", age: 30, tags: ["developer", "k"] };
86
98
  assert.equal(result("get", doc, { key: "name" }), "Alice");
87
99
  assert.equal(result("get", doc, { key: "age" }), 30);
88
- assert.ok(method("has?", doc, { key: "name" }));
89
- 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);
90
102
 
91
103
  const withCity = result("set", doc, { key: "city", val: "Paris" });
92
104
  assert.deepEqual(withCity, { ...doc, city: "Paris" });
@@ -97,14 +109,12 @@ const arr = [10, 20, 30];
97
109
  for (const [index, expected] of arr.entries()) {
98
110
  assert.equal(result("nth", arr, { index }), expected);
99
111
  }
100
- assert.ok(method("has_index?", arr, { index: 1 }));
101
- 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);
102
114
  assert.deepEqual(result("set_nth", arr, { index: 1, val: 99 }), [10, 99, 30]);
103
- assert.equal(toJsonValue(runDjson("length", fromJsonValue(arr))), 3);
104
- assert.equal(toJsonValue(runDjson("length", fromJsonValue(doc))), 3);
105
- assert.equal(toJsonValue(runDjson("length", fromJsonValue("hello"))), 5);
106
115
  assert.deepEqual(result("push", arr, { val: 40 }), [10, 20, 30, 40]);
107
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]);
108
118
 
109
119
  const sampleJson = JSON.stringify({
110
120
  nullVal: null,
@@ -113,5 +123,5 @@ const sampleJson = JSON.stringify({
113
123
  str: "hello\n\t\"world\"\\/\u0041\uD83D\uDE00",
114
124
  empty: [{}, []]
115
125
  });
116
- const parsedJson = toJsonValue(runDjson("parseJson", textToStringValue(sampleJson)));
126
+ const parsedJson = toJsonValue(runDjson("parse_json", textToStringValue(sampleJson)));
117
127
  assert.deepEqual(parsedJson, JSON.parse(sampleJson));