@fraczak/k 8.4.1 → 8.5.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.
Files changed (116) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/DOCS/ARCHITECTURE.md +83 -0
  3. package/DOCS/CODECS.md +93 -204
  4. package/DOCS/DICTIONARY.md +42 -1241
  5. package/DOCS/FILE_FORMATS.md +170 -625
  6. package/DOCS/GETTING_STARTED.md +164 -0
  7. package/DOCS/KIR_V1.md +22 -33
  8. package/DOCS/KVM_EXECUTION_MODEL.md +88 -481
  9. package/DOCS/PATTERNS.md +155 -138
  10. package/DOCS/POLYMORPHIC_IR.md +83 -101
  11. package/DOCS/PROFILING_AND_TRACING.md +52 -166
  12. package/DOCS/README.md +35 -0
  13. package/DOCS/REPL.md +100 -377
  14. package/DOCS/TEXTUAL_VALUES.md +53 -81
  15. package/DOCS/TYPE_DERIVATION.md +95 -234
  16. package/DOCS/book-combined.md +3786 -0
  17. package/Examples/arithmetics.k +45 -59
  18. package/Examples/djson.k +102 -112
  19. package/Examples/karatsuba-mult.k +2 -3
  20. package/Examples/list.k +6 -7
  21. package/Examples/nat.k +6 -6
  22. package/Examples/poly.k +45 -45
  23. package/LICENSE +15 -0
  24. package/README.md +72 -410
  25. package/backends/llvm/README.md +75 -97
  26. package/backends/llvm/src/kvm2llvm.mjs +5 -4
  27. package/backends/llvm/src/llvm.mjs +2 -1
  28. package/backends/llvm/tests/integration.sh +7 -0
  29. package/backends/llvm/tests/test-llvm.mjs +20 -0
  30. package/backends/wasm/README.md +88 -66
  31. package/backends/wasm/src/kvm2wasm.mjs +64 -18
  32. package/backends/wasm/tests/integration.sh +5 -0
  33. package/backends/wasm/tests/test-wasm.mjs +86 -2
  34. package/canonical-pattern.mjs +7 -3
  35. package/codecs/README.md +23 -261
  36. package/codecs/WIRE_FORMAT.md +132 -0
  37. package/core.k +5 -15
  38. package/named-patterns.mjs +19 -7
  39. package/objects/README.md +24 -109
  40. package/package.json +8 -3
  41. package/paper/Makefile +17 -0
  42. package/paper/k-paper.pdf +0 -0
  43. package/paper/k-paper.tex +435 -0
  44. package/parser.jison +0 -10
  45. package/parser.mjs +32 -43
  46. package/repl.mjs +74 -29
  47. package/scripts/benchmark-idempotency.mjs +3 -3
  48. package/scripts/run-tests.mjs +1 -1
  49. package/scripts/test-package.mjs +64 -0
  50. package/tests/README.md +66 -46
  51. package/tests/code-derivation/core.mjs +61 -0
  52. package/tests/helpers/cli.mjs +45 -0
  53. package/tests/integration.sh +2 -3
  54. package/tests/test-arithmetics.mjs +47 -237
  55. package/tests/test-djson-methods.mjs +71 -275
  56. package/tests/test-hash-normalization.mjs +22 -1
  57. package/tests/test-karatsuba.mjs +18 -126
  58. package/tests/test-named-patterns.mjs +174 -621
  59. package/tests/test-paper-examples.mjs +90 -0
  60. package/tests/test-poly.mjs +2 -2
  61. package/tests/test-repl-html.mjs +22 -10
  62. package/tests/test-repl.mjs +49 -41
  63. package/tests/test.mjs +27 -68
  64. package/AGENTS.md +0 -35
  65. package/CLAUDE.md +0 -64
  66. package/DOCS/BIG_PICTURE.md +0 -439
  67. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  68. package/DOCS/CANONICAL_PATTERNS.md +0 -362
  69. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  70. package/DOCS/CONVERGENCE.md +0 -123
  71. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  72. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  73. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  74. package/DOCS/Makefile +0 -99
  75. package/DOCS/NAMED_PATTERNS.md +0 -361
  76. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  77. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  78. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -134
  79. package/DOCS/book/01-introduction.md +0 -48
  80. package/DOCS/book/02-syntax-and-values.md +0 -110
  81. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  82. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  83. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  84. package/DOCS/book/06-values-in-memory.md +0 -1085
  85. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  86. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  87. package/DOCS/book/09-compiler-architecture.md +0 -160
  88. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  89. package/DOCS/book/14-canonical-serialization.md +0 -176
  90. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  91. package/DOCS/book/overview.txt +0 -68
  92. package/DOCS/book.md +0 -50
  93. package/Examples/bnat.k +0 -308
  94. package/Examples/buda.k +0 -66
  95. package/Examples/byte.k +0 -35
  96. package/Examples/code.k +0 -43
  97. package/Examples/vhdl_to_k.k +0 -67
  98. package/JOURNAL.md +0 -288
  99. package/TODO.md +0 -107
  100. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  101. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  102. package/backends/wasm/demo_ieee.mjs +0 -318
  103. package/browser/vfs-data.mjs +0 -21
  104. package/codecs/BINARY_FORMAT.md +0 -53
  105. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  106. package/codecs/pandoc.css +0 -71
  107. package/tests/code-derivation/blowup.mjs +0 -25
  108. package/tests/code-derivation/bnat.mjs +0 -11
  109. package/tests/code-derivation/dot.mjs +0 -37
  110. package/tests/code-derivation/index.mjs +0 -20
  111. package/tests/code-derivation/loop.mjs +0 -17
  112. package/tests/code-derivation/nat.mjs +0 -10
  113. package/tests/code-derivation/not-not.mjs +0 -14
  114. package/tests/code-derivation/product.mjs +0 -22
  115. package/tests/code-derivation/rlz.mjs +0 -13
  116. package/tests/test-fingerprint.mjs +0 -38
@@ -1,285 +1,81 @@
1
- // tests/test-djson-methods.mjs
2
- // Test suite for standard dynamic JSON methods working on json? type.
3
-
4
1
  import assert from "node:assert/strict";
5
2
  import { readFileSync } from "node:fs";
6
- import path from "node:path";
7
- import { fileURLToPath } from "node:url";
8
-
9
3
  import k from "../index.mjs";
10
4
  import { Value } from "../Value.mjs";
11
- import {
12
- fromJsonValue,
13
- toJsonValue
14
- } from "../codecs/djson.mjs";
15
- import {
16
- textToStringValue,
17
- stringValueToText
18
- } from "../codecs/runtime/unicode-string.mjs";
19
-
20
- const root = path.resolve(
21
- path.dirname(fileURLToPath(import.meta.url)),
22
- ".."
23
- );
24
- const libPath = path.join(root, "Examples", "djson.k");
25
- const djsonK = readFileSync(libPath, "utf8");
26
-
27
- function compileOp(op) {
28
- return k.compile(`${djsonK}\n${op}\n`);
5
+ import { compileLibrary, loadLibrary } from "../object.mjs";
6
+ import { fromJsonValue, toJsonValue } from "../codecs/djson.mjs";
7
+ import { textToStringValue, stringValueToText } from "../codecs/runtime/unicode-string.mjs";
8
+ import { parse as parseInt } from "../codecs/int.mjs";
9
+
10
+ const source = readFileSync(new URL("../Examples/djson.k", import.meta.url), "utf8");
11
+ const library = loadLibrary(compileLibrary(source));
12
+ const run = (op, value) => k.compile(library.relAlias[op], { libraries: [library] })(value);
13
+
14
+ function method(op, json, { key, index, val } = {}) {
15
+ const fields = { json: fromJsonValue(json) };
16
+ if (key !== undefined) fields.key = textToStringValue(key);
17
+ if (index !== undefined) fields.index = parseInt(String(index)).value;
18
+ if (val !== undefined) fields.val = fromJsonValue(val);
19
+ return run(op, Value.product(fields));
29
20
  }
21
+ const result = (...args) => toJsonValue(method(...args));
30
22
 
31
- function makeIndex(n) {
32
- if (n === 0) {
33
- return Value.variant(
34
- "0",
35
- Value.variant("_", Value.product({}))
36
- );
37
- }
38
- const s = n.toString(2);
39
- let v = Value.variant("_", Value.product({}));
40
- for (let i = s.length - 1; i >= 0; i--) {
41
- v = Value.variant(s[i], v);
42
- }
43
- return v;
23
+ // Object access, missing keys, updates and preservation.
24
+ const doc = { name: "Alice", age: 30, tags: ["developer", "k"] };
25
+ for (const key of ["name", "age"]) {
26
+ assert.equal(result("get", doc, { key }), doc[key], key);
44
27
  }
45
-
46
- console.log("==> Running Dynamic JSON (json?) Methods Test Suite");
47
-
48
- // Test 1: Object Accessors (get, has?, set, del)
49
- console.log("--> Test 1: Object Accessors (get, has?, set, del)");
50
- {
51
- const fnGet = compileOp("get");
52
- const fnHas = compileOp("has?");
53
- const fnSet = compileOp("set");
54
- const fnDel = compileOp("del");
55
-
56
- const doc = {
57
- name: "Alice",
58
- age: 30,
59
- tags: ["developer", "k"]
60
- };
61
- const kDoc = fromJsonValue(doc);
62
-
63
- // get "name"
64
- const resName = fnGet(Value.product({
65
- key: textToStringValue("name"),
66
- json: kDoc
67
- }));
68
- assert.equal(toJsonValue(resName), "Alice");
69
-
70
- // get "age"
71
- const resAge = fnGet(Value.product({
72
- key: textToStringValue("age"),
73
- json: kDoc
74
- }));
75
- assert.equal(toJsonValue(resAge), 30);
76
-
77
- // has? hit
78
- const hit = fnHas(Value.product({
79
- key: textToStringValue("name"),
80
- json: kDoc
81
- }));
82
- assert.ok(hit);
83
-
84
- // has? miss
85
- const miss = fnHas(Value.product({
86
- key: textToStringValue("missing"),
87
- json: kDoc
88
- }));
89
- assert.equal(miss, undefined);
90
-
91
- // set "city" = "Paris"
92
- const withCity = fnSet(Value.product({
93
- key: textToStringValue("city"),
94
- val: fromJsonValue("Paris"),
95
- json: kDoc
96
- }));
97
- assert.equal(toJsonValue(withCity).city, "Paris");
98
- assert.equal(toJsonValue(withCity).name, "Alice");
99
-
100
- // del "age"
101
- const withoutAge = fnDel(Value.product({
102
- key: textToStringValue("age"),
103
- json: withCity
104
- }));
105
- assert.equal(toJsonValue(withoutAge).age, undefined);
106
- assert.equal(toJsonValue(withoutAge).city, "Paris");
107
-
108
- console.log(" Passed: Object get, has?, set, del on json?.");
28
+ assert.ok(method("has?", doc, { key: "name" }));
29
+ assert.equal(method("has?", doc, { key: "missing" }), undefined);
30
+ const withCity = result("set", doc, { key: "city", val: "Paris" });
31
+ assert.deepEqual(withCity, { ...doc, city: "Paris" });
32
+ const withoutAge = result("del", withCity, { key: "age" });
33
+ assert.deepEqual(withoutAge, { name: "Alice", tags: doc.tags, city: "Paris" });
34
+
35
+ // Array lookup and sparse index membership after deletion.
36
+ const list = [10, 20, 30];
37
+ for (const [index, expected] of list.entries()) {
38
+ assert.equal(result("nth", list, { index }), expected, `index ${index}`);
109
39
  }
110
-
111
- // Test 2: List Accessors (nth, has_index?, set_nth, del_nth, push)
112
- console.log("--> Test 2: List Accessors (nth, set_nth, del_nth, push)");
113
- {
114
- const fnNth = compileOp("nth");
115
- const fnHasIdx = compileOp("has_index?");
116
- const fnSetNth = compileOp("set_nth");
117
- const fnDelNth = compileOp("del_nth");
118
- const fnPush = compileOp("push");
119
-
120
- const list = [10, 20, 30];
121
- const kList = fromJsonValue(list);
122
-
123
- // nth 0, 1, 2
124
- assert.equal(
125
- toJsonValue(fnNth(Value.product({
126
- index: makeIndex(0),
127
- json: kList
128
- }))),
129
- 10
130
- );
131
- assert.equal(
132
- toJsonValue(fnNth(Value.product({
133
- index: makeIndex(1),
134
- json: kList
135
- }))),
136
- 20
137
- );
138
- assert.equal(
139
- toJsonValue(fnNth(Value.product({
140
- index: makeIndex(2),
141
- json: kList
142
- }))),
143
- 30
144
- );
145
-
146
- // has_index? hit and miss
147
- assert.ok(fnHasIdx(Value.product({
148
- index: makeIndex(1),
149
- json: kList
150
- })));
151
- assert.equal(
152
- fnHasIdx(Value.product({
153
- index: makeIndex(99),
154
- json: kList
155
- })),
156
- undefined
157
- );
158
-
159
- // set_nth 1 -> 99
160
- const updatedList = fnSetNth(Value.product({
161
- index: makeIndex(1),
162
- val: fromJsonValue(99),
163
- json: kList
164
- }));
165
- assert.deepEqual(toJsonValue(updatedList), [10, 99, 30]);
166
-
167
- // del_nth 1
168
- const delList = fnDelNth(Value.product({
169
- index: makeIndex(1),
170
- json: updatedList
171
- }));
172
- assert.deepEqual(toJsonValue(delList), [10, 30]);
173
- assert.equal(
174
- fnHasIdx(Value.product({
175
- index: makeIndex(1),
176
- json: delList
177
- })),
178
- undefined
179
- );
180
-
181
- // push 40
182
- const pushed = fnPush(Value.product({
183
- val: fromJsonValue(40),
184
- json: kList
185
- }));
186
- assert.deepEqual(toJsonValue(pushed), [10, 20, 30, 40]);
187
-
188
- console.log(" Passed: List nth, set_nth, del_nth, push on json?.");
40
+ assert.ok(method("has_index?", list, { index: 1 }));
41
+ assert.equal(method("has_index?", list, { index: 99 }), undefined);
42
+ const updated = method("set_nth", list, { index: 1, val: 99 });
43
+ assert.deepEqual(toJsonValue(updated), [10, 99, 30]);
44
+ const deleted = run("del_nth", Value.product({
45
+ json: updated, index: parseInt("1").value
46
+ }));
47
+ assert.deepEqual(toJsonValue(deleted), [10, 30]);
48
+ assert.equal(run("has_index?", Value.product({
49
+ json: deleted, index: parseInt("1").value
50
+ })), undefined);
51
+ assert.deepEqual(result("push", list, { val: 40 }), [10, 20, 30, 40]);
52
+
53
+ // Ordered keys/values, including the raw cons-list boundary.
54
+ const record = fromJsonValue({ b: 2, a: 1, c: 3 });
55
+ assert.deepEqual(toJsonValue(run("keys", record)), ["a", "b", "c"]);
56
+ const keys = [];
57
+ let cursor = run("keys_raw", record);
58
+ while (cursor.tag === "cons") {
59
+ keys.push(stringValueToText(cursor.value.product.car));
60
+ cursor = cursor.value.product.cdr;
189
61
  }
190
-
191
- // Test 3: Keys and Values (keys, keys_raw, values, values_raw)
192
- console.log("--> Test 3: Keys and Values (keys, values)");
193
- {
194
- const fnKeys = compileOp("keys");
195
- const fnKeysRaw = compileOp("keys_raw");
196
- const fnValues = compileOp("values");
197
- const fnValuesRaw = compileOp("values_raw");
198
-
199
- const doc = { b: 2, a: 1, c: 3 };
200
- const kDoc = fromJsonValue(doc);
201
-
202
- // keys (json? list of string)
203
- const resKeys = fnKeys(kDoc);
204
- assert.deepEqual(toJsonValue(resKeys), ["a", "b", "c"]);
205
-
206
- // keys_raw (raw K cons-list of strings)
207
- const resKeysRaw = fnKeysRaw(kDoc);
208
- const rawKeyStrings = [];
209
- let curr = resKeysRaw;
210
- while (curr && curr.type === "<>" && curr.tag === "cons") {
211
- rawKeyStrings.push(stringValueToText(curr.value.product.car));
212
- curr = curr.value.product.cdr;
213
- }
214
- assert.deepEqual(rawKeyStrings, ["a", "b", "c"]);
215
-
216
- // values on object (json? list of values)
217
- const resValues = fnValues(kDoc);
218
- assert.deepEqual(toJsonValue(resValues), [1, 2, 3]);
219
-
220
- // values on list (json? identity)
221
- const listJson = fromJsonValue([100, 200]);
222
- assert.deepEqual(toJsonValue(fnValues(listJson)), [100, 200]);
223
-
224
- console.log(" Passed: Keys and values extraction on json?.");
62
+ assert.equal(cursor.tag, "nil");
63
+ assert.deepEqual(keys, ["a", "b", "c"]);
64
+ assert.deepEqual(toJsonValue(run("values", record)), [1, 2, 3]);
65
+ assert.deepEqual(toJsonValue(run("values", fromJsonValue([100, 200]))), [100, 200]);
66
+
67
+ for (const [value, expected] of [
68
+ [{ x: 1, y: 2, z: 3, w: 4 }, 4], [["a", "b", "c"], 3], ["hello", 5]
69
+ ]) assert.equal(toJsonValue(run("length", fromJsonValue(value))), expected);
70
+
71
+ for (const [type, value] of [
72
+ ["object", { a: 1 }], ["list", [1, 2]], ["string", "hi"],
73
+ ["number", 3.14], ["bool", true], ["null", null]
74
+ ]) {
75
+ const input = fromJsonValue(value);
76
+ assert.equal(run("type_of", input).tag, type);
77
+ assert.ok(run(`is_${type}?`, input), type);
225
78
  }
226
-
227
- // Test 4: Cardinality and Length (length, length_nat)
228
- console.log("--> Test 4: Cardinality and Length (length, length_nat)");
229
- {
230
- const fnLength = compileOp("length");
231
-
232
- const kObj = fromJsonValue({ x: 1, y: 2, z: 3, w: 4 });
233
- const kArr = fromJsonValue(["a", "b", "c"]);
234
- const kStr = fromJsonValue("hello");
235
-
236
- // length returns json? number (float64)
237
- assert.equal(toJsonValue(fnLength(kObj)), 4);
238
- assert.equal(toJsonValue(fnLength(kArr)), 3);
239
- assert.equal(toJsonValue(fnLength(kStr)), 5);
240
-
241
- console.log(
242
- " Passed: Length queries on json? object, list, string."
243
- );
244
- }
245
-
246
- // Test 5: Type Predicates and type_of
247
- console.log("--> Test 5: Type Predicates and type_of");
248
- {
249
- const fnTypeOf = compileOp("type_of");
250
- const fnIsObj = compileOp("is_object?");
251
- const fnIsList = compileOp("is_list?");
252
- const fnIsStr = compileOp("is_string?");
253
- const fnIsNum = compileOp("is_number?");
254
- const fnIsBool = compileOp("is_bool?");
255
- const fnIsNull = compileOp("is_null?");
256
-
257
- const kObj = fromJsonValue({ a: 1 });
258
- const kArr = fromJsonValue([1, 2]);
259
- const kStr = fromJsonValue("hi");
260
- const kNum = fromJsonValue(3.14);
261
- const kBool = fromJsonValue(true);
262
- const kNull = fromJsonValue(null);
263
-
264
- assert.equal(fnTypeOf(kObj).tag, "object");
265
- assert.equal(fnTypeOf(kArr).tag, "list");
266
- assert.equal(fnTypeOf(kStr).tag, "string");
267
- assert.equal(fnTypeOf(kNum).tag, "number");
268
- assert.equal(fnTypeOf(kBool).tag, "bool");
269
- assert.equal(fnTypeOf(kNull).tag, "null");
270
-
271
- assert.ok(fnIsObj(kObj));
272
- assert.equal(fnIsObj(kArr), undefined);
273
-
274
- assert.ok(fnIsList(kArr));
275
- assert.equal(fnIsList(kObj), undefined);
276
-
277
- assert.ok(fnIsStr(kStr));
278
- assert.ok(fnIsNum(kNum));
279
- assert.ok(fnIsBool(kBool));
280
- assert.ok(fnIsNull(kNull));
281
-
282
- console.log(" Passed: Type predicates and type_of inspection.");
283
- }
284
-
285
- console.log("==> All Dynamic JSON Methods Tests Passed Successfully!");
79
+ assert.equal(run("is_object?", fromJsonValue([1, 2])), undefined);
80
+ assert.equal(run("is_list?", fromJsonValue({ a: 1 })), undefined);
81
+ console.log("dynamic JSON methods: ok");
@@ -3,6 +3,7 @@
3
3
  import assert from "node:assert/strict";
4
4
  import { annotate } from "../index.mjs";
5
5
  import { hash } from "../hash.mjs";
6
+ import codes, { encodeCodeToString } from "../codes.mjs";
6
7
 
7
8
  const nameRegex = /^[a-zA-Z0-9_+][a-zA-Z0-9_?!+]*$/;
8
9
 
@@ -129,4 +130,24 @@ y
129
130
  );
130
131
  }
131
132
 
132
- console.log("test-hash-normalization: ok");
133
+ const codeDefs = {
134
+ bits: { code: "union", union: { "0": "bits", "1": "bits", "_": "{}" } },
135
+ nat: { code: "union", union: { zero: "{}", succ: "nat" } },
136
+ pair: { code: "product", product: { x: "nat", y: "nat" } },
137
+ b: { code: "product", product: { x: "bits", y: "bits" } },
138
+ tree: { code: "union", union: {
139
+ binary: "binNode",
140
+ leaf: "nat",
141
+ unary: "unNode"
142
+ } },
143
+ binNode: { code: "product", product: { value: "nat", left: "tree", right: "tree" } },
144
+ unNode: { code: "product", product: { value: "nat", tree: "tree" } },
145
+ "{}": { code: "product", product: {} }
146
+ };
147
+
148
+ for (const [name, representative] of Object.entries(codes.register(codeDefs))) {
149
+ assert.equal(hash(encodeCodeToString(representative)), representative,
150
+ `canonical code fingerprint: ${name}`);
151
+ }
152
+
153
+ console.log("hash normalization and code fingerprints: ok");
@@ -1,133 +1,25 @@
1
1
  import assert from "node:assert/strict";
2
- import fs from "node:fs";
3
- import os from "node:os";
4
- import path from "node:path";
5
- import { spawnSync } from "node:child_process";
6
- import { fileURLToPath } from "node:url";
2
+ import { withCompiledLibrary, runLibrary, integer } from "./helpers/cli.mjs";
7
3
 
8
- const scriptDir = path.dirname(fileURLToPath(import.meta.url));
9
- const root = path.resolve(scriptDir, "..");
10
- const node = process.execPath;
11
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-karatsuba-"));
12
- const libPath = path.join(tmpDir, "karatsuba-mult.klib");
13
- const kSource = path.join(root, "Examples/karatsuba-mult.k");
14
- const program = "{() x, () y} karatsuba";
4
+ const large = "11111112222223333334444444555555666666777777788888899999900000011111122222233333344444455555";
15
5
 
16
- const smallInput =
17
- "111111122222233333344444445555556666667777777888888999999000000" +
18
- "11111122222233333344444455555";
6
+ withCompiledLibrary("Examples/karatsuba-mult.k", (library) => {
7
+ const multiply = (source, input) =>
8
+ integer(runLibrary(library, ["karatsuba"], source, input), source);
19
9
 
20
- function run(command, args, options = {}) {
21
- const result = spawnSync(command, args, {
22
- cwd: root,
23
- input: options.input,
24
- encoding: options.encoding ?? null,
25
- maxBuffer: 64 * 1024 * 1024
26
- });
27
- if (result.error && result.status == null) throw result.error;
28
- return result;
29
- }
30
-
31
- function assertOk(result, label) {
32
- if (result.status !== 0) {
33
- const stderr = Buffer.isBuffer(result.stderr)
34
- ? result.stderr.toString("utf8")
35
- : String(result.stderr ?? "");
36
- const stdout = Buffer.isBuffer(result.stdout)
37
- ? result.stdout.toString("utf8")
38
- : String(result.stdout ?? "");
39
- assert.fail(
40
- `${label} failed (status ${result.status})\n` +
41
- `STDERR:\n${stderr}\nSTDOUT:\n${stdout}`
42
- );
43
- }
44
- }
45
-
46
- function parseIntWire(text) {
47
- const result = run(node, ["codecs/int.mjs", "--parse"], {
48
- input: `${text}\n`
49
- });
50
- assertOk(result, `parse int ${text}`);
51
- return result.stdout;
52
- }
53
-
54
- function printIntWire(wire, label) {
55
- const result = run(node, ["codecs/int.mjs", "--print"], {
56
- input: wire,
57
- encoding: "utf8"
58
- });
59
- assertOk(result, `${label} print`);
60
- return result.stdout.trim();
61
- }
62
-
63
- function runKaratsuba(inputText) {
64
- const wire = parseIntWire(inputText);
65
- const result = run(node, [
66
- "k.mjs",
67
- "--lib", libPath,
68
- "--export", "karatsuba:karatsuba",
69
- program
70
- ], { input: wire });
71
- assertOk(result, `native karatsuba(${inputText})`);
72
- return printIntWire(result.stdout, `native karatsuba`);
73
- }
74
-
75
- function expectedSquare(inputText) {
76
- const n = BigInt(inputText);
77
- return (n * n).toString();
78
- }
79
-
80
- try {
81
- assertOk(
82
- run(node, ["objects/compile.mjs", kSource, libPath], {
83
- encoding: "utf8"
84
- }),
85
- "compile Examples/karatsuba-mult.k"
86
- );
87
-
88
- const testInputs = [
89
- "0",
90
- "1",
91
- "-1",
92
- "7",
93
- "-7",
94
- "42",
95
- "-42",
96
- "123456789",
97
- "-123456789",
98
- "987654321987654321",
99
- "-987654321987654321",
100
- smallInput,
101
- `-${smallInput}`
102
- ];
103
-
104
- for (const input of testInputs) {
105
- assert.equal(
106
- runKaratsuba(input),
107
- expectedSquare(input),
108
- `karatsuba square(${input.slice(0, 20)}...) mismatch`
109
- );
10
+ for (const input of [
11
+ "0", "1", "-1", "7", "-7", "42", "-42", "123456789", "-123456789",
12
+ "987654321987654321", "-987654321987654321", large, `-${large}`
13
+ ]) {
14
+ const n = BigInt(input);
15
+ assert.equal(multiply("{() x, () y} karatsuba", input), String(n * n),
16
+ `karatsuba square(${input})`);
110
17
  }
111
18
 
112
- // Test asymmetric pair multiplication with mixed signs via int list
113
- const pairWire = parseIntWire(
114
- "[12345678901234567890, -98765432109876543210]"
115
- );
116
- const pairProgram = "/cons { .car x, .cdr /cons .car y } karatsuba";
117
- const resPair = run(node, [
118
- "k.mjs",
119
- "--lib", libPath,
120
- "--export", "karatsuba:karatsuba",
121
- pairProgram
122
- ], { input: pairWire });
123
- assertOk(resPair, "pair multiplication");
124
- assert.equal(
125
- printIntWire(resPair.stdout, "pair multiplication"),
126
- (12345678901234567890n * -98765432109876543210n).toString(),
127
- "asymmetric pair multiplication should match BigInt oracle"
128
- );
19
+ assert.equal(multiply("/cons { .car x, .cdr /cons .car y } karatsuba",
20
+ "[12345678901234567890, -98765432109876543210]"),
21
+ String(12345678901234567890n * -98765432109876543210n),
22
+ "asymmetric mixed-sign multiplication");
23
+ });
129
24
 
130
- console.log("OK");
131
- } finally {
132
- fs.rmSync(tmpDir, { recursive: true, force: true });
133
- }
25
+ console.log("Karatsuba CLI and BigInt oracles: ok");