@fraczak/k 8.6.1 → 8.7.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 (75) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/DOCS/CODECS.md +20 -14
  3. package/DOCS/FILE_FORMATS.md +53 -12
  4. package/DOCS/GETTING_STARTED.md +15 -8
  5. package/DOCS/PATTERNS.md +10 -0
  6. package/DOCS/REPL.md +12 -7
  7. package/Examples/arithmetics.k +81 -468
  8. package/Examples/ieee-arithmetics.k +37 -33
  9. package/Examples/poly.k +107 -104
  10. package/README.md +19 -11
  11. package/backend-api.mjs +3 -1
  12. package/backends/llvm/README.md +1 -1
  13. package/backends/llvm/bin/k-llvm-build.mjs +5 -5
  14. package/backends/llvm/bin/k-llvm-compile.mjs +4 -4
  15. package/backends/llvm/bin/k-llvm.mjs +6 -6
  16. package/backends/llvm/src/cli.mjs +17 -15
  17. package/backends/llvm/tests/integration.sh +6 -1
  18. package/backends/wasm/README.md +3 -3
  19. package/backends/wasm/bin/k-wasm-compile.mjs +4 -4
  20. package/backends/wasm/bin/k-wasm.mjs +4 -4
  21. package/backends/wasm/src/cli.mjs +12 -10
  22. package/backends/wasm/src/wasm.mjs +4 -4
  23. package/backends/wasm/tests/integration.sh +24 -4
  24. package/browser/shims/fs.mjs +19 -3
  25. package/canonical-pattern.mjs +214 -57
  26. package/compiler.mjs +26 -0
  27. package/core.k +2 -1
  28. package/harness/suites/poly.mjs +14 -30
  29. package/index.mjs +67 -2
  30. package/k.mjs +14 -18
  31. package/kir.mjs +3 -1
  32. package/kvm.mjs +11 -11
  33. package/lib/arithmetics.k +286 -0
  34. package/lib/bit.k +68 -0
  35. package/lib/bits.k +227 -0
  36. package/lib/btrie.k +187 -0
  37. package/lib/djson.k +327 -0
  38. package/lib/ieee.k +709 -0
  39. package/lib/list.k +49 -0
  40. package/lib/string.k +588 -0
  41. package/named-patterns.mjs +2 -14
  42. package/object.mjs +32 -7
  43. package/objects/README.md +9 -3
  44. package/objects/compile.mjs +11 -14
  45. package/package.json +1 -1
  46. package/repl.mjs +24 -5
  47. package/scripts/benchmark-idempotency.mjs +22 -15
  48. package/scripts/benchmark.mjs +29 -10
  49. package/scripts/build-repl-html.mjs +41 -13
  50. package/scripts/perf-ieee.mjs +9 -1
  51. package/scripts/perf-int.mjs +10 -17
  52. package/scripts/perf-multiplication.mjs +9 -15
  53. package/scripts/perf-poly.mjs +16 -32
  54. package/scripts/run-tests.mjs +3 -2
  55. package/scripts/test-package.mjs +13 -2
  56. package/tests/helpers/cli.mjs +19 -3
  57. package/tests/integration.sh +25 -5
  58. package/tests/test-arithmetics.mjs +4 -2
  59. package/tests/test-djson-methods.mjs +21 -12
  60. package/tests/test-ieee-arithmetic.mjs +11 -3
  61. package/tests/test-ieee-text.mjs +19 -4
  62. package/tests/test-k-object.mjs +15 -4
  63. package/tests/test-karatsuba.mjs +1 -1
  64. package/tests/test-kvm-polymorphic.mjs +58 -34
  65. package/tests/test-lib.mjs +117 -0
  66. package/tests/test-library-isolation.mjs +381 -0
  67. package/tests/test-named-patterns.mjs +21 -3
  68. package/tests/test-parse-json.mjs +44 -14
  69. package/tests/test-poly.mjs +10 -4
  70. package/tests/test-repl-html.mjs +18 -7
  71. package/tests/test-repl.mjs +50 -35
  72. package/Examples/djson.k +0 -894
  73. package/Examples/ieee.k +0 -969
  74. package/Examples/karatsuba-mult.k +0 -227
  75. package/Examples/list.k +0 -10
@@ -0,0 +1,381 @@
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";
7
+
8
+ import k from "../index.mjs";
9
+ import { Value } from "../Value.mjs";
10
+ import {
11
+ compileObject,
12
+ compileObjectBuffer,
13
+ compileLibrary,
14
+ compileLibraryBuffer,
15
+ loadLibrary,
16
+ decodeObject,
17
+ objectToFunction
18
+ } from "../object.mjs";
19
+ import { createState, evaluateInput } from "../repl.mjs";
20
+
21
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
22
+ const node = process.execPath;
23
+ const compileMjs = path.join(root, "objects/compile.mjs");
24
+ const kMjs = path.join(root, "k.mjs");
25
+ const kPrintMjs = path.join(root, "codecs/k-print.mjs");
26
+ const unitParseMjs = path.join(root, "codecs/unit.mjs");
27
+
28
+ function runCommand(cmd, args, options = {}) {
29
+ const encoding = options.encoding !== undefined ? options.encoding : "utf8";
30
+ const result = spawnSync(cmd, args, {
31
+ cwd: root,
32
+ ...options,
33
+ encoding
34
+ });
35
+ return result;
36
+ }
37
+
38
+ console.log("==> Starting Library Isolation & Scope Binding Tests");
39
+
40
+ // -----------------------------------------------------------------------------
41
+ // §1. Relation Content-Addressable Isolation & Explicit Scope Binding
42
+ // -----------------------------------------------------------------------------
43
+ console.log("--> Test 1: Relations - Content-Addressable Isolation and --use");
44
+ {
45
+ const libSource = `
46
+ greet = {} |hello;
47
+ secret = {} |classified;
48
+ `;
49
+ const libObject = compileLibrary(libSource, { source: "test-lib1.k" });
50
+ const library = loadLibrary(libObject);
51
+
52
+ const greetHash = library.relAlias.greet;
53
+ const secretHash = library.relAlias.secret;
54
+ assert.ok(greetHash && greetHash.startsWith("@"), `Expected @hash for greet, got ${greetHash}`);
55
+ assert.ok(secretHash && secretHash.startsWith("@"), `Expected @hash for secret, got ${secretHash}`);
56
+
57
+ // 1.1 Without --use / useSpecs: friendly name 'greet' is NOT in scope
58
+ assert.throws(
59
+ () => compileObject("greet", { libraries: [library] }),
60
+ /No definition found for 'greet'/,
61
+ "Expected friendly name 'greet' to be inaccessible without --use"
62
+ );
63
+
64
+ // 1.2 Without --use / useSpecs: friendly name 'secret' is NOT in scope
65
+ assert.throws(
66
+ () => compileObject("secret", { libraries: [library] }),
67
+ /No definition found for 'secret'/,
68
+ "Expected friendly name 'secret' to be inaccessible without --use"
69
+ );
70
+
71
+ // 1.3 Without --use / useSpecs: accessing @greetHash directly by hash SUCCEEDS
72
+ const objByHash = compileObject(greetHash, { libraries: [library] });
73
+ const resByHash = objectToFunction(objByHash)(Value.product({}));
74
+ assert.equal(resByHash.tag, "hello", "Accessing library relation by @hash must succeed");
75
+
76
+ // 1.4 Accessing @secretHash directly by hash SUCCEEDS
77
+ const objSecretHash = compileObject(secretHash, { libraries: [library] });
78
+ const resSecret = objectToFunction(objSecretHash)(Value.product({}));
79
+ assert.equal(resSecret.tag, "classified", "Accessing secret relation by @hash must succeed");
80
+
81
+ // 1.5 With explicit useSpecs: ["greet"]:
82
+ // 'greet' is in scope, but 'secret' remains isolated
83
+ const objWithGreet = compileObject("greet", {
84
+ libraries: [library],
85
+ useSpecs: ["greet"]
86
+ });
87
+ const resGreet = objectToFunction(objWithGreet)(Value.product({}));
88
+ assert.equal(resGreet.tag, "hello", "'greet' must be in scope when specified via useSpecs");
89
+
90
+ assert.throws(
91
+ () => compileObject("secret", { libraries: [library], useSpecs: ["greet"] }),
92
+ /No definition found for 'secret'/,
93
+ "'secret' must NOT be in scope when only 'greet' was requested"
94
+ );
95
+
96
+ // 1.6 With aliasing useSpecs: ["greet:custom_hello"]:
97
+ // 'custom_hello' is in scope; 'greet' is NOT
98
+ const objAliased = compileObject("custom_hello", {
99
+ libraries: [library],
100
+ useSpecs: ["greet:custom_hello"]
101
+ });
102
+ const resAliased = objectToFunction(objAliased)(Value.product({}));
103
+ assert.equal(resAliased.tag, "hello", "Aliased name 'custom_hello' must resolve");
104
+
105
+ assert.throws(
106
+ () => compileObject("greet", { libraries: [library], useSpecs: ["greet:custom_hello"] }),
107
+ /No definition found for 'greet'/,
108
+ "Original name 'greet' must NOT be in scope when aliased to 'custom_hello'"
109
+ );
110
+ }
111
+ console.log(" Passed: Relation isolation and explicit scope binding verified.");
112
+
113
+ // -----------------------------------------------------------------------------
114
+ // §2. Pattern Template Content-Addressable Isolation & Explicit Scope Binding
115
+ // -----------------------------------------------------------------------------
116
+ console.log("--> Test 2: Pattern Templates - Content-Addressable Isolation and --use");
117
+ {
118
+ const libSource = `
119
+ pair[A, B] = { A first, B second };
120
+ triple[A, B, C] = { A first, B second, C third };
121
+ `;
122
+ const libObject = compileLibrary(libSource, { source: "test-patterns.k" });
123
+ const library = loadLibrary(libObject);
124
+
125
+ const pairHash = library.patternAlias.pair;
126
+ const tripleHash = library.patternAlias.triple;
127
+ assert.ok(pairHash && pairHash.startsWith("@"), `Expected @hash for pair, got ${pairHash}`);
128
+ assert.ok(tripleHash && tripleHash.startsWith("@"), `Expected @hash for triple, got ${tripleHash}`);
129
+
130
+ // 2.1 Without useSpecs: 'pair[]' is NOT in scope
131
+ assert.throws(
132
+ () => compileObject("is_pair = ?pair[{}, {}]; ()", { libraries: [library] }),
133
+ /Unknown pattern template 'pair\[\]'/,
134
+ "Expected pattern template 'pair[]' to be inaccessible without --use"
135
+ );
136
+
137
+ // 2.2 Without useSpecs: 'triple[]' is NOT in scope
138
+ assert.throws(
139
+ () => compileObject("is_triple = ?triple[{}, {}, {}]; ()", { libraries: [library] }),
140
+ /Unknown pattern template 'triple\[\]'/,
141
+ "Expected pattern template 'triple[]' to be inaccessible without --use"
142
+ );
143
+
144
+ // 2.3 Accessing @pairHash directly by hash SUCCEEDS
145
+ const objPairHash = compileObject(`
146
+ is_pair = ?${pairHash}[{}, {}];
147
+ {{} first, {} second} is_pair
148
+ `, { libraries: [library] });
149
+ const resPair = objectToFunction(objPairHash)(Value.product({}));
150
+ assert.equal(resPair.type, "{}");
151
+
152
+ // 2.4 With explicit useSpecs: ["pair"]:
153
+ // 'pair[]' is in scope; 'triple[]' remains isolated
154
+ const objPairUse = compileObject(`
155
+ is_pair = ?pair[{}, {}];
156
+ {{} first, {} second} is_pair
157
+ `, {
158
+ libraries: [library],
159
+ useSpecs: ["pair"]
160
+ });
161
+ const resPairUse = objectToFunction(objPairUse)(Value.product({}));
162
+ assert.equal(resPairUse.type, "{}");
163
+
164
+ assert.throws(
165
+ () => compileObject("is_triple = ?triple[{}, {}, {}]; ()", {
166
+ libraries: [library],
167
+ useSpecs: ["pair"]
168
+ }),
169
+ /Unknown pattern template 'triple\[\]'/,
170
+ "'triple[]' must NOT be in scope when only 'pair' was requested"
171
+ );
172
+
173
+ // 2.5 With aliasing useSpecs: ["pair:two_tuple"]:
174
+ const objPairAliased = compileObject(`
175
+ is_two = ?two_tuple[{}, {}];
176
+ {{} first, {} second} is_two
177
+ `, {
178
+ libraries: [library],
179
+ useSpecs: ["pair:two_tuple"]
180
+ });
181
+ const resPairAliased = objectToFunction(objPairAliased)(Value.product({}));
182
+ assert.equal(resPairAliased.type, "{}");
183
+
184
+ assert.throws(
185
+ () => compileObject("is_pair = ?pair[{}, {}]; ()", {
186
+ libraries: [library],
187
+ useSpecs: ["pair:two_tuple"]
188
+ }),
189
+ /Unknown pattern template 'pair\[\]'/
190
+ );
191
+ }
192
+ console.log(" Passed: Pattern template isolation and explicit scope binding verified.");
193
+
194
+ // -----------------------------------------------------------------------------
195
+ // §3. Local Definitions vs Unused Library Definitions (No Shadowing Ambiguity)
196
+ // -----------------------------------------------------------------------------
197
+ console.log("--> Test 3: Local definitions and unused library symbols");
198
+ {
199
+ const libSource = `
200
+ foo = {} |library_foo;
201
+ `;
202
+ const library = loadLibrary(compileLibrary(libSource, { source: "lib-foo.k" }));
203
+ const fooHash = library.relAlias.foo;
204
+
205
+ // Local file defines its own 'foo' without --use foo.
206
+ // The local 'foo' evaluates to local_foo.
207
+ // The library foo is only accessible via @fooHash.
208
+ const source = `
209
+ foo = {} |local_foo;
210
+ call_local = foo;
211
+ call_lib = ${fooHash};
212
+ { call_local local, call_lib lib }
213
+ `;
214
+ const compiled = compileObject(source, { libraries: [library] });
215
+ const result = objectToFunction(compiled)(Value.product({}));
216
+ assert.equal(result.product.local.tag, "local_foo");
217
+ assert.equal(result.product.lib.tag, "library_foo");
218
+ }
219
+ console.log(" Passed: Local definitions and library symbols do not clash without --use.");
220
+
221
+ // -----------------------------------------------------------------------------
222
+ // §4. CLI Invocations (compile.mjs and k.mjs)
223
+ // -----------------------------------------------------------------------------
224
+ console.log("--> Test 4: CLI enforcement of isolation and --use");
225
+ {
226
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-test-isolation-"));
227
+ try {
228
+ const libPath = path.join(tmpDir, "sample.klib");
229
+ const libSource = "greeting = {} |welcome; secret = {} |hidden;";
230
+ fs.writeFileSync(path.join(tmpDir, "sample.k"), libSource, "utf8");
231
+
232
+ // Build sample.klib
233
+ const buildLib = runCommand(node, [compileMjs, path.join(tmpDir, "sample.k"), libPath]);
234
+ assert.equal(buildLib.status, 0, buildLib.stderr);
235
+
236
+ const libObj = decodeObject(fs.readFileSync(libPath));
237
+ const greetingHash = libObj.relAlias.greeting;
238
+ assert.ok(greetingHash && greetingHash.startsWith("@"));
239
+
240
+ // 4.1 CLI compile.mjs without --use: referencing 'greeting' fails
241
+ const failCompile = runCommand(node, [
242
+ compileMjs,
243
+ "--lib", libPath,
244
+ "greeting",
245
+ path.join(tmpDir, "fail.ko")
246
+ ]);
247
+ assert.notEqual(failCompile.status, 0);
248
+ assert.match(failCompile.stderr, /No definition found for 'greeting'/);
249
+
250
+ // 4.2 CLI compile.mjs referencing @greetingHash succeeds
251
+ const hashKo = path.join(tmpDir, "hash.ko");
252
+ const passHashCompile = runCommand(node, [
253
+ compileMjs,
254
+ "--lib", libPath,
255
+ greetingHash,
256
+ hashKo
257
+ ]);
258
+ assert.equal(passHashCompile.status, 0, passHashCompile.stderr);
259
+ assert.ok(fs.existsSync(hashKo));
260
+
261
+ // 4.3 CLI compile.mjs with --use greeting succeeds
262
+ const greetKo = path.join(tmpDir, "greet.ko");
263
+ const passUseCompile = runCommand(node, [
264
+ compileMjs,
265
+ "--lib", libPath,
266
+ "--use", "greeting",
267
+ "greeting",
268
+ greetKo
269
+ ]);
270
+ assert.equal(passUseCompile.status, 0, passUseCompile.stderr);
271
+ assert.ok(fs.existsSync(greetKo));
272
+
273
+ // 4.4 CLI compile.mjs with --use greeting:my_hello succeeds
274
+ const aliasKo = path.join(tmpDir, "alias.ko");
275
+ const passAliasCompile = runCommand(node, [
276
+ compileMjs,
277
+ "--lib", libPath,
278
+ "--use", "greeting:my_hello",
279
+ "my_hello",
280
+ aliasKo
281
+ ]);
282
+ assert.equal(passAliasCompile.status, 0, passAliasCompile.stderr);
283
+
284
+ // 4.5 CLI k.mjs without --use fails
285
+ const unitBytes = runCommand(node, [unitParseMjs, "--parse"], { encoding: null }).stdout;
286
+ const failRun = runCommand(node, [kMjs, "--lib", libPath, "greeting"], {
287
+ input: unitBytes
288
+ });
289
+ assert.notEqual(failRun.status, 0);
290
+ assert.match(failRun.stderr, /No definition found for 'greeting'/);
291
+
292
+ // 4.6 CLI k.mjs with @greetingHash succeeds
293
+ const passHashRun = runCommand(node, [kMjs, "--lib", libPath, greetingHash], {
294
+ input: unitBytes,
295
+ encoding: null
296
+ });
297
+ assert.equal(passHashRun.status, 0, passHashRun.stderr?.toString());
298
+ const printHash = runCommand(node, [kPrintMjs], {
299
+ input: passHashRun.stdout,
300
+ encoding: "utf8"
301
+ });
302
+ assert.equal(printHash.stdout.trim(), '"welcome"');
303
+
304
+ // 4.7 CLI k.mjs with --use greeting succeeds
305
+ const passUseRun = runCommand(node, [kMjs, "--lib", libPath, "--use", "greeting", "greeting"], {
306
+ input: unitBytes,
307
+ encoding: null
308
+ });
309
+ assert.equal(passUseRun.status, 0, passUseRun.stderr?.toString());
310
+ const printUse = runCommand(node, [kPrintMjs], {
311
+ input: passUseRun.stdout,
312
+ encoding: "utf8"
313
+ });
314
+ assert.equal(printUse.stdout.trim(), '"welcome"');
315
+ } finally {
316
+ fs.rmSync(tmpDir, { recursive: true, force: true });
317
+ }
318
+ }
319
+ console.log(" Passed: CLI isolation and --use flags verified.");
320
+
321
+ // -----------------------------------------------------------------------------
322
+ // §5. Exact Line Number Preservation (No text synthesis or line offset)
323
+ // -----------------------------------------------------------------------------
324
+ console.log("--> Test 5: Exact 1-to-1 source line numbers in diagnostics");
325
+ {
326
+ const sourceWithComment = [
327
+ "# --lib lib/dummy.klib --use hello world",
328
+ "-- Comment line 2",
329
+ "-- Comment line 3",
330
+ "bad_definition = undefined_symbol;",
331
+ "()"
332
+ ].join("\n");
333
+
334
+ try {
335
+ compileObject(sourceWithComment, { source: "test-lines.k" });
336
+ assert.fail("Compilation should fail on undefined_symbol");
337
+ } catch (error) {
338
+ // line 4 must be reported exactly, not shifted by any synthesized preamble
339
+ assert.match(
340
+ error.message,
341
+ /lines 4:18\.\.\.4:34/,
342
+ `Error line must be line 4, got: ${error.message}`
343
+ );
344
+ }
345
+ }
346
+ console.log(" Passed: Exact line numbers preserved without offset.");
347
+
348
+ // -----------------------------------------------------------------------------
349
+ // §6. REPL Sequential :load of Standard Libraries (No Renaming Magic)
350
+ // -----------------------------------------------------------------------------
351
+ console.log("--> Test 6: REPL sequential :load of standard libraries");
352
+ {
353
+ const state = createState();
354
+ const libSequence = [
355
+ "lib/bit.k",
356
+ "lib/bits.k",
357
+ "lib/list.k",
358
+ "lib/btrie.k",
359
+ "lib/string.k",
360
+ "lib/ieee.k",
361
+ "lib/djson.k",
362
+ "lib/arithmetics.k"
363
+ ];
364
+
365
+ for (const libFile of libSequence) {
366
+ await evaluateInput(`:load ${libFile}`, state);
367
+ }
368
+
369
+ // Verify that symbols are accessible in REPL under their exact canonical names
370
+ assert.ok(state.relAliases.inc, "Expected 'inc' in REPL");
371
+ assert.ok(state.relAliases.inc_bits, "Expected 'inc_bits' in REPL");
372
+ assert.ok(state.relAliases.list_size, "Expected 'list_size' in REPL");
373
+ assert.ok(state.relAliases.reverse, "Expected 'reverse' in REPL");
374
+ assert.ok(state.patternAliases.bit, "Expected 'bit[]' in REPL");
375
+ assert.ok(state.patternAliases.list, "Expected 'list[T]' in REPL");
376
+ assert.ok(state.patternAliases.btrie, "Expected 'btrie[V]' in REPL");
377
+ assert.ok(state.patternAliases.unicode, "Expected 'unicode[]' in REPL");
378
+ }
379
+ console.log(" Passed: All standard libraries load cleanly in REPL without renaming.");
380
+
381
+ console.log("==> All Library Isolation & Scope Binding Tests Passed Successfully!");
@@ -3,7 +3,7 @@ import k from "../index.mjs";
3
3
  import { Value } from "../Value.mjs";
4
4
  import { compileLibrary, extractAliasesFromObject } from "../object.mjs";
5
5
  import { validateObjectPayload } from "../objects/validate.mjs";
6
- import { buildExportPreamble, resolvePatternCanonicalInfo } from "../canonical-pattern.mjs";
6
+ import { buildUsePreamble, resolvePatternCanonicalInfo } from "../canonical-pattern.mjs";
7
7
 
8
8
  const BIT = "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg";
9
9
  const LIST = "@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe";
@@ -111,9 +111,11 @@ const aliases = extractAliasesFromObject(library);
111
111
  for (const expected of [/bit\[\] = @Mjusy/, /list\[X\] = @JagVex/, /pair\[A, B\] = @KqTB/]) {
112
112
  assert.match(aliases, expected);
113
113
  }
114
- const preamble = buildExportPreamble(["bit", "list:my_list"], [library]);
114
+ const preamble = buildUsePreamble(["bit", "list:my_list"], [library]);
115
115
  assert.match(preamble, /bit\[\] = @Mjusy/);
116
116
  assert.match(preamble, /my_list\[X\] = @JagVex/);
117
+ const usePreamble = buildUsePreamble(["bit list:my_list"], [library]);
118
+ assert.equal(usePreamble, preamble);
117
119
 
118
120
  {
119
121
  const out = evaluate(`
@@ -130,6 +132,13 @@ assert.equal(evaluate(`
130
132
  my_list[T] = ${LIST}[T];
131
133
  {{}|0 car, {}|nil cdr}|cons ?my_list[my_bit[]]
132
134
  `, { libraries: [library] }).tag, "cons");
135
+
136
+ // Library patterns are known by hash only unless --use / useSpecs is specified.
137
+ assert.throws(
138
+ () => evaluate("is_bit = ?bit[]; ()", { libraries: [library] }),
139
+ /Unknown pattern template 'bit\[\]'/
140
+ );
141
+
133
142
  assert.equal(evaluate(`
134
143
  is_bit = ?bit[];
135
144
  is_pair = ?${PAIR}[bit[],bit[]];
@@ -137,7 +146,16 @@ assert.equal(evaluate(`
137
146
  b = {}|0 is_bit;
138
147
  p = {b first, {}|1 second} is_pair;
139
148
  {p car, {}|nil cdr}|cons is_pair_list
140
- `, { libraries: [library] }).tag, "cons");
149
+ `, { libraries: [library], useSpecs: ["bit", "list"] }).tag, "cons");
150
+
151
+ assert.equal(evaluate(`
152
+ is_bit = ?my_bit[];
153
+ is_pair = ?${PAIR}[my_bit[],my_bit[]];
154
+ is_pair_list = ?my_list[${PAIR}[my_bit[],my_bit[]]];
155
+ b = {}|0 is_bit;
156
+ p = {b first, {}|1 second} is_pair;
157
+ {p car, {}|nil cdr}|cons is_pair_list
158
+ `, { libraries: [library], useSpecs: ["bit:my_bit", "list:my_list"] }).tag, "cons");
141
159
  assert.ok(evaluate(`
142
160
  @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X,Y] = {X x,Y y,Y z};
143
161
  {{} x,{} y,{} z} ?@A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[{},{}]
@@ -5,18 +5,36 @@ import path from "node:path";
5
5
  import { spawnSync } from "node:child_process";
6
6
  import k from "../index.mjs";
7
7
  import { compileLibrary, loadLibrary } from "../object.mjs";
8
+ import { parseHeaderUses } from "../canonical-pattern.mjs";
8
9
  import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
9
10
  import { fromJsonValue } from "../codecs/djson.mjs";
10
11
  import { textToStringValue } from "../codecs/runtime/unicode-string.mjs";
11
12
  import { parse as utf8 } from "../codecs/utf8.mjs";
12
13
  import { encodeToWire, decodeWire } from "../codecs/runtime/codec-sdk.mjs";
13
14
 
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]
15
+ let ieee = null;
16
+ for (const file of [
17
+ "lib/bit.k",
18
+ "lib/bits.k",
19
+ "lib/list.k",
20
+ "lib/btrie.k",
21
+ "lib/string.k",
22
+ "lib/ieee.k"
23
+ ]) {
24
+ const fileSource = readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
25
+ const uses = parseHeaderUses(fileSource).map((u) => u.use);
26
+ ieee = loadLibrary(compileLibrary(fileSource, {
27
+ source: file,
28
+ libraries: ieee ? [ieee] : [],
29
+ use: uses
30
+ }));
31
+ }
32
+ const djsonSource = readFileSync(new URL("../lib/djson.k", import.meta.url), "utf8");
33
+ const djsonUses = parseHeaderUses(djsonSource).map((u) => u.use);
34
+ const library = loadLibrary(compileLibrary(djsonSource, {
35
+ source: "lib/djson.k",
36
+ libraries: [ieee],
37
+ use: djsonUses
20
38
  }));
21
39
  const wasm = await instantiateWasmArtifact(await compileWasmArtifact(library.relAlias.parseJson, { libraries: [library] }));
22
40
  const fast = text => wasm.executeValue(textToStringValue(text));
@@ -72,19 +90,31 @@ for (const text of ["1e309", "-1.8e308"]) assert.equal(fast(text), undefined, te
72
90
  const text = '{"answer":42,"ok":true}';
73
91
  const scratch = mkdtempSync(path.join(os.tmpdir(), "k-json-test-"));
74
92
  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], {
93
+ const chain = [
94
+ "lib/bit.k",
95
+ "lib/bits.k",
96
+ "lib/list.k",
97
+ "lib/btrie.k",
98
+ "lib/string.k",
99
+ "lib/ieee.k",
100
+ "lib/djson.k"
101
+ ];
102
+ let prev = null;
103
+ for (let i = 0; i < chain.length; i++) {
104
+ const out = path.join(scratch, `step-${i}.klib`);
105
+ const fileSource = readFileSync(new URL(`../${chain[i]}`, import.meta.url), "utf8");
106
+ const uses = parseHeaderUses(fileSource).map((u) => u.use);
107
+ const useArgs = uses.flatMap((u) => ["--use", u]);
108
+ const args = ["objects/compile.mjs", ...(prev ? ["--lib", prev] : []), ...useArgs, chain[i], out];
109
+ const built = spawnSync(process.execPath, args, {
82
110
  cwd: new URL("..", import.meta.url)
83
111
  });
84
112
  assert.ifError(built.error);
85
113
  assert.equal(built.status, 0, built.stderr.toString());
114
+ prev = out;
86
115
  }
87
- const cli = spawnSync(process.execPath, ["k.mjs", "--lib", artifact, "--export", "parseJson", "parseJson"], {
116
+ const artifact = prev;
117
+ const cli = spawnSync(process.execPath, ["k.mjs", "--lib", artifact, "--use", "parseJson", "parseJson"], {
88
118
  cwd: new URL("..", import.meta.url), input: encodeToWire(utf8(text))
89
119
  });
90
120
  assert.ifError(cli.error);
@@ -6,14 +6,20 @@ import { fileURLToPath } from "node:url";
6
6
  import { createState, evaluateInput } from "../backend-api.mjs";
7
7
 
8
8
  const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
9
- const arithmeticsPath = path.join(root, "Examples/arithmetics.k");
10
- const polyPath = path.join(root, "Examples/poly.k");
9
+ const polySources = [
10
+ "lib/bit.k",
11
+ "lib/bits.k",
12
+ "lib/arithmetics.k",
13
+ "lib/list.k",
14
+ "Examples/poly.k"
15
+ ];
11
16
 
12
17
  console.log("==> Running Polymorphic List Tests (Examples/poly.k)");
13
18
 
14
19
  const state = createState();
15
- await evaluateInput(`:load ${arithmeticsPath}`, state);
16
- await evaluateInput(`:load ${polyPath}`, state);
20
+ for (const relPath of polySources) {
21
+ await evaluateInput(`:load ${path.join(root, relPath)}`, state);
22
+ }
17
23
 
18
24
  async function evalK(snippet) {
19
25
  const res = await evaluateInput(snippet, state);
@@ -151,6 +151,9 @@ if (chromiumBin) {
151
151
  const vfsList = await evaluateAsync(`window.kRepl.getAllVfsFiles().sort()`);
152
152
  const expectedFiles = [
153
153
  "arithmetics.k",
154
+ "bit.k",
155
+ "bits.k",
156
+ "btrie.k",
154
157
  "core.k",
155
158
  "djson.k",
156
159
  "djson.mjs",
@@ -159,28 +162,31 @@ if (chromiumBin) {
159
162
  "ieee.mjs",
160
163
  "int.mjs",
161
164
  "json.mjs",
162
- "karatsuba-mult.k",
165
+ "list.k",
163
166
  "poly.k",
167
+ "string.k",
164
168
  "unit.mjs",
165
169
  "utf8.mjs"
166
170
  ].sort();
167
171
  assert.deepStrictEqual(vfsList, expectedFiles, `getAllVfsFiles() must match curated files list, got: ${JSON.stringify(vfsList)}`);
168
172
 
169
- // Test :load arithmetics.k
173
+ // Test :load bit.k, bits.k, arithmetics.k
170
174
  const loadOut = await evaluateAsync(`(async () => {
175
+ await window.kRepl.executeCommand(":load bit.k");
176
+ await window.kRepl.executeCommand(":load bits.k");
171
177
  await window.kRepl.executeCommand(":load arithmetics.k");
172
178
  const lines = Array.from(document.querySelectorAll(".entry-line")).map(el => el.textContent);
173
179
  return lines[lines.length - 1];
174
180
  })()`);
175
181
  assert(loadOut.includes("loaded arithmetics.k"), `Expected loaded arithmetics.k, got: ${loadOut}`);
176
182
 
177
- // Test :load karatsuba-mult.k
178
- const loadKaratsubaOut = await evaluateAsync(`(async () => {
179
- await window.kRepl.executeCommand(":load karatsuba-mult.k");
183
+ // Test :load Examples/arithmetics.k
184
+ const loadExamplesArithOut = await evaluateAsync(`(async () => {
185
+ await window.kRepl.executeCommand(":load Examples/arithmetics.k");
180
186
  const lines = Array.from(document.querySelectorAll(".entry-line")).map(el => el.textContent);
181
187
  return lines[lines.length - 1];
182
188
  })()`);
183
- assert(loadKaratsubaOut.includes("loaded karatsuba-mult.k"), `Expected loaded karatsuba-mult.k, got: ${loadKaratsubaOut}`);
189
+ assert(loadExamplesArithOut.includes("loaded Examples/arithmetics.k"), `Expected loaded Examples/arithmetics.k, got: ${loadExamplesArithOut}`);
184
190
 
185
191
  // Test evaluating {1 int x, 1 int y} karatsuba
186
192
  const karatsubaVal = await evaluateAsync(`(async () => {
@@ -328,7 +334,9 @@ if (chromiumBin) {
328
334
 
329
335
  // Test JSON codec with float64 in browser: :input json.mjs then {"a":"Woj","n":123}
330
336
  await evaluateAsync(`(async () => {
331
- await window.kRepl.executeCommand(":load core.k");
337
+ await window.kRepl.executeCommand(":load list.k");
338
+ await window.kRepl.executeCommand(":load btrie.k");
339
+ await window.kRepl.executeCommand(":load string.k");
332
340
  await window.kRepl.executeCommand(":load ieee.k");
333
341
  await window.kRepl.executeCommand(":codec load json.mjs");
334
342
  await window.kRepl.executeCommand(":input json.mjs");
@@ -393,7 +401,10 @@ if (chromiumBin) {
393
401
  // Test :load poly.k and evaluate '10 int (gen_list sort)' in WASM mode
394
402
  const sortListResult = await evaluateAsync(`(async () => {
395
403
  await window.kRepl.executeCommand(":reset");
404
+ await window.kRepl.executeCommand(":load bit.k");
405
+ await window.kRepl.executeCommand(":load bits.k");
396
406
  await window.kRepl.executeCommand(":load arithmetics.k");
407
+ await window.kRepl.executeCommand(":load list.k");
397
408
  await window.kRepl.executeCommand(":load poly.k");
398
409
  await window.kRepl.executeCommand(":codec load int.mjs");
399
410
  await window.kRepl.executeCommand("10 int (gen_list sort)");