@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
@@ -0,0 +1,704 @@
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, { parse } from "../index.mjs";
9
+ import { Value } from "../Value.mjs";
10
+ import { resolvePatternCanonicalInfo } from "../canonical-pattern.mjs";
11
+ import { validatePatternDefinitions } from "../named-patterns.mjs";
12
+ import {
13
+ compileObject,
14
+ compileObjectBuffer,
15
+ compileLibrary,
16
+ compileLibraryBuffer,
17
+ loadLibrary,
18
+ decodeObject,
19
+ objectToFunction
20
+ } from "../object.mjs";
21
+ import { createState, evaluateInput } from "../repl.mjs";
22
+
23
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
24
+ const node = process.execPath;
25
+ const compileMjs = path.join(root, "objects/compile.mjs");
26
+ const kMjs = path.join(root, "k.mjs");
27
+ const kPrintMjs = path.join(root, "codecs/k-print.mjs");
28
+ const unitParseMjs = path.join(root, "codecs/unit.mjs");
29
+
30
+ function runCommand(cmd, args, options = {}) {
31
+ const encoding = options.encoding !== undefined ? options.encoding : "utf8";
32
+ const result = spawnSync(cmd, args, {
33
+ cwd: root,
34
+ ...options,
35
+ encoding
36
+ });
37
+ return result;
38
+ }
39
+
40
+ console.log("==> Starting Library Isolation & Scope Binding Tests");
41
+
42
+ // -----------------------------------------------------------------------------
43
+ // §1. Relation Content-Addressable Isolation & Explicit Scope Binding
44
+ // -----------------------------------------------------------------------------
45
+ console.log("--> Test 1: Relations - Content-Addressable Isolation and --use");
46
+ {
47
+ const libSource = `
48
+ greet = {} |hello;
49
+ secret = {} |classified;
50
+ `;
51
+ const libObject = compileLibrary(libSource, { source: "test-lib1.k" });
52
+ const library = loadLibrary(libObject);
53
+
54
+ const greetHash = library.relAlias.greet;
55
+ const secretHash = library.relAlias.secret;
56
+ assert.ok(greetHash && greetHash.startsWith("@"), `Expected @hash for greet, got ${greetHash}`);
57
+ assert.ok(secretHash && secretHash.startsWith("@"), `Expected @hash for secret, got ${secretHash}`);
58
+
59
+ // 1.1 Without --use / useSpecs: friendly name 'greet' is NOT in scope
60
+ assert.throws(
61
+ () => compileObject("greet", { libraries: [library] }),
62
+ /No definition found for 'greet'/,
63
+ "Expected friendly name 'greet' to be inaccessible without --use"
64
+ );
65
+
66
+ // 1.2 Without --use / useSpecs: friendly name 'secret' is NOT in scope
67
+ assert.throws(
68
+ () => compileObject("secret", { libraries: [library] }),
69
+ /No definition found for 'secret'/,
70
+ "Expected friendly name 'secret' to be inaccessible without --use"
71
+ );
72
+
73
+ // 1.3 Without --use / useSpecs: accessing @greetHash directly by hash SUCCEEDS
74
+ const objByHash = compileObject(greetHash, { libraries: [library] });
75
+ const resByHash = objectToFunction(objByHash)(Value.product({}));
76
+ assert.equal(resByHash.tag, "hello", "Accessing library relation by @hash must succeed");
77
+
78
+ // 1.4 Accessing @secretHash directly by hash SUCCEEDS
79
+ const objSecretHash = compileObject(secretHash, { libraries: [library] });
80
+ const resSecret = objectToFunction(objSecretHash)(Value.product({}));
81
+ assert.equal(resSecret.tag, "classified", "Accessing secret relation by @hash must succeed");
82
+
83
+ // 1.5 With explicit useSpecs: ["greet"]:
84
+ // 'greet' is in scope, but 'secret' remains isolated
85
+ const objWithGreet = compileObject("greet", {
86
+ libraries: [library],
87
+ useSpecs: ["greet"]
88
+ });
89
+ const resGreet = objectToFunction(objWithGreet)(Value.product({}));
90
+ assert.equal(resGreet.tag, "hello", "'greet' must be in scope when specified via useSpecs");
91
+
92
+ assert.throws(
93
+ () => compileObject("secret", { libraries: [library], useSpecs: ["greet"] }),
94
+ /No definition found for 'secret'/,
95
+ "'secret' must NOT be in scope when only 'greet' was requested"
96
+ );
97
+
98
+ // 1.6 With aliasing useSpecs: ["greet:custom_hello"]:
99
+ // 'custom_hello' is in scope; 'greet' is NOT
100
+ const objAliased = compileObject("custom_hello", {
101
+ libraries: [library],
102
+ useSpecs: ["greet:custom_hello"]
103
+ });
104
+ const resAliased = objectToFunction(objAliased)(Value.product({}));
105
+ assert.equal(resAliased.tag, "hello", "Aliased name 'custom_hello' must resolve");
106
+
107
+ assert.throws(
108
+ () => compileObject("greet", { libraries: [library], useSpecs: ["greet:custom_hello"] }),
109
+ /No definition found for 'greet'/,
110
+ "Original name 'greet' must NOT be in scope when aliased to 'custom_hello'"
111
+ );
112
+ }
113
+ console.log(" Passed: Relation isolation and explicit scope binding verified.");
114
+
115
+ // -----------------------------------------------------------------------------
116
+ // §2. Pattern Template Content-Addressable Isolation & Explicit Scope Binding
117
+ // -----------------------------------------------------------------------------
118
+ console.log("--> Test 2: Pattern Templates - Content-Addressable Isolation and --use");
119
+ {
120
+ const libSource = `
121
+ pair[A, B] = { A first, B second };
122
+ triple[A, B, C] = { A first, B second, C third };
123
+ `;
124
+ const libObject = compileLibrary(libSource, { source: "test-patterns.k" });
125
+ const library = loadLibrary(libObject);
126
+
127
+ const pairHash = library.patternAlias.pair;
128
+ const tripleHash = library.patternAlias.triple;
129
+ assert.ok(pairHash && pairHash.startsWith("@"), `Expected @hash for pair, got ${pairHash}`);
130
+ assert.ok(tripleHash && tripleHash.startsWith("@"), `Expected @hash for triple, got ${tripleHash}`);
131
+
132
+ // 2.1 Without useSpecs: 'pair[]' is NOT in scope
133
+ assert.throws(
134
+ () => compileObject("is_pair = ?pair[{}, {}]; ()", { libraries: [library] }),
135
+ /Unknown pattern template 'pair\[\]'/,
136
+ "Expected pattern template 'pair[]' to be inaccessible without --use"
137
+ );
138
+
139
+ // 2.2 Without useSpecs: 'triple[]' is NOT in scope
140
+ assert.throws(
141
+ () => compileObject("is_triple = ?triple[{}, {}, {}]; ()", { libraries: [library] }),
142
+ /Unknown pattern template 'triple\[\]'/,
143
+ "Expected pattern template 'triple[]' to be inaccessible without --use"
144
+ );
145
+
146
+ // 2.3 Accessing @pairHash directly by hash SUCCEEDS
147
+ const objPairHash = compileObject(`
148
+ is_pair = ?${pairHash}[{}, {}];
149
+ {{} first, {} second} is_pair
150
+ `, { libraries: [library] });
151
+ const resPair = objectToFunction(objPairHash)(Value.product({}));
152
+ assert.equal(resPair.type, "{}");
153
+
154
+ // 2.4 With explicit useSpecs: ["pair"]:
155
+ // 'pair[]' is in scope; 'triple[]' remains isolated
156
+ const objPairUse = compileObject(`
157
+ is_pair = ?pair[{}, {}];
158
+ {{} first, {} second} is_pair
159
+ `, {
160
+ libraries: [library],
161
+ useSpecs: ["pair"]
162
+ });
163
+ const resPairUse = objectToFunction(objPairUse)(Value.product({}));
164
+ assert.equal(resPairUse.type, "{}");
165
+
166
+ assert.throws(
167
+ () => compileObject("is_triple = ?triple[{}, {}, {}]; ()", {
168
+ libraries: [library],
169
+ useSpecs: ["pair"]
170
+ }),
171
+ /Unknown pattern template 'triple\[\]'/,
172
+ "'triple[]' must NOT be in scope when only 'pair' was requested"
173
+ );
174
+
175
+ // 2.5 With aliasing useSpecs: ["pair:two_tuple"]:
176
+ const objPairAliased = compileObject(`
177
+ is_two = ?two_tuple[{}, {}];
178
+ {{} first, {} second} is_two
179
+ `, {
180
+ libraries: [library],
181
+ useSpecs: ["pair:two_tuple"]
182
+ });
183
+ const resPairAliased = objectToFunction(objPairAliased)(Value.product({}));
184
+ assert.equal(resPairAliased.type, "{}");
185
+
186
+ assert.throws(
187
+ () => compileObject("is_pair = ?pair[{}, {}]; ()", {
188
+ libraries: [library],
189
+ useSpecs: ["pair:two_tuple"]
190
+ }),
191
+ /Unknown pattern template 'pair\[\]'/
192
+ );
193
+ }
194
+ console.log(" Passed: Pattern template isolation and explicit scope binding verified.");
195
+
196
+ // -----------------------------------------------------------------------------
197
+ // §3. Local Definitions vs Unused Library Definitions (No Shadowing Ambiguity)
198
+ // -----------------------------------------------------------------------------
199
+ console.log("--> Test 3: Local definitions and unused library symbols");
200
+ {
201
+ const libSource = `
202
+ foo = {} |library_foo;
203
+ byte[] = { <{} 0, {} 1> b0, <{} 0, {} 1> b1 };
204
+ box[] = { byte[] item };
205
+ `;
206
+ const library = loadLibrary(compileLibrary(libSource, { source: "lib-foo.k" }));
207
+ const fooHash = library.relAlias.foo;
208
+ const libBoxHash = library.patternAlias.box;
209
+
210
+ // Helper to capture console.warn during compilation
211
+ function captureWarnings(fn) {
212
+ const warnings = [];
213
+ const origWarn = console.warn;
214
+ console.warn = (...args) => warnings.push(args.map(String).join(" "));
215
+ try {
216
+ const value = fn();
217
+ return { value, warnings };
218
+ } finally {
219
+ console.warn = origWarn;
220
+ }
221
+ }
222
+
223
+ // Local file defines its own 'foo' without --use foo.
224
+ // Also defines its own 'byte[]' and 'wrap[] = { byte[] item }' without --use byte[].
225
+ // Neither relation nor pattern resolution may leak library names or warn.
226
+ const source = `
227
+ foo = {} |local_foo;
228
+ call_local = foo;
229
+ call_lib = ${fooHash};
230
+ { call_local local, call_lib lib }
231
+ `;
232
+ const { value: compiled, warnings: relWarnings } = captureWarnings(() =>
233
+ compileObject(source, { libraries: [library] })
234
+ );
235
+ assert.equal(relWarnings.length, 0, `Unexpected warning without --use: ${relWarnings}`);
236
+ const result = objectToFunction(compiled)(Value.product({}));
237
+ assert.equal(result.product.local.tag, "local_foo");
238
+ assert.equal(result.product.lib.tag, "library_foo");
239
+
240
+ // Compile library redefining 'byte[]' locally without --use byte[]
241
+ const localWrapSource = `
242
+ byte[] = { <{} 0, {} 1> x0, <{} 0, {} 1> x1 };
243
+ wrap[] = { byte[] item };
244
+ `;
245
+ const expectedStandalone = loadLibrary(compileLibrary(localWrapSource, { source: "standalone.k" }));
246
+ const { value: chainedLibRaw, warnings: patWarnings } = captureWarnings(() =>
247
+ compileLibrary(localWrapSource, { source: "local-wrap.k", libraries: [library] })
248
+ );
249
+ const chainedLib = loadLibrary(chainedLibRaw);
250
+ assert.equal(patWarnings.length, 0, `Unexpected warning without --use: ${patWarnings}`);
251
+ assert.equal(
252
+ chainedLib.patternAlias.wrap,
253
+ expectedStandalone.patternAlias.wrap,
254
+ "wrap[] must hash against local byte[], not un-imported library byte[]"
255
+ );
256
+ assert.equal(
257
+ chainedLib.patternAlias.box,
258
+ libBoxHash,
259
+ "Un-modified inherited pattern box[] must keep its original hash"
260
+ );
261
+
262
+ // Referencing library's 'byte[]' in compileLibrary without --use or local definition must fail
263
+ assert.throws(
264
+ () => compileLibrary("bad_wrap[] = { byte[] item };", { source: "bad.k", libraries: [library] }),
265
+ /Unknown pattern template 'byte\[\]'/,
266
+ "compileLibrary must not leak library pattern friendly names without --use"
267
+ );
268
+ }
269
+ console.log(" Passed: Local definitions and library symbols do not clash without --use.");
270
+
271
+ // -----------------------------------------------------------------------------
272
+ // §4. CLI Invocations (compile.mjs and k.mjs)
273
+ // -----------------------------------------------------------------------------
274
+ console.log("--> Test 4: CLI enforcement of isolation and --use");
275
+ {
276
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-test-isolation-"));
277
+ try {
278
+ const libPath = path.join(tmpDir, "sample.klib");
279
+ const libSource = "greeting = {} |welcome; secret = {} |hidden;";
280
+ fs.writeFileSync(path.join(tmpDir, "sample.k"), libSource, "utf8");
281
+
282
+ // Build sample.klib
283
+ const buildLib = runCommand(node, [compileMjs, path.join(tmpDir, "sample.k"), libPath]);
284
+ assert.equal(buildLib.status, 0, buildLib.stderr);
285
+
286
+ const libObj = decodeObject(fs.readFileSync(libPath));
287
+ const greetingHash = libObj.relAlias.greeting;
288
+ assert.ok(greetingHash && greetingHash.startsWith("@"));
289
+
290
+ // 4.1 CLI compile.mjs without --use: referencing 'greeting' fails
291
+ const failCompile = runCommand(node, [
292
+ compileMjs,
293
+ "--lib", libPath,
294
+ "greeting",
295
+ path.join(tmpDir, "fail.ko")
296
+ ]);
297
+ assert.notEqual(failCompile.status, 0);
298
+ assert.match(failCompile.stderr, /No definition found for 'greeting'/);
299
+
300
+ // 4.2 CLI compile.mjs referencing @greetingHash succeeds
301
+ const hashKo = path.join(tmpDir, "hash.ko");
302
+ const passHashCompile = runCommand(node, [
303
+ compileMjs,
304
+ "--lib", libPath,
305
+ greetingHash,
306
+ hashKo
307
+ ]);
308
+ assert.equal(passHashCompile.status, 0, passHashCompile.stderr);
309
+ assert.ok(fs.existsSync(hashKo));
310
+
311
+ // 4.3 CLI compile.mjs with --use greeting succeeds
312
+ const greetKo = path.join(tmpDir, "greet.ko");
313
+ const passUseCompile = runCommand(node, [
314
+ compileMjs,
315
+ "--lib", libPath,
316
+ "--use", "greeting",
317
+ "greeting",
318
+ greetKo
319
+ ]);
320
+ assert.equal(passUseCompile.status, 0, passUseCompile.stderr);
321
+ assert.ok(fs.existsSync(greetKo));
322
+
323
+ // 4.4 CLI compile.mjs with --use greeting:my_hello succeeds
324
+ const aliasKo = path.join(tmpDir, "alias.ko");
325
+ const passAliasCompile = runCommand(node, [
326
+ compileMjs,
327
+ "--lib", libPath,
328
+ "--use", "greeting:my_hello",
329
+ "my_hello",
330
+ aliasKo
331
+ ]);
332
+ assert.equal(passAliasCompile.status, 0, passAliasCompile.stderr);
333
+
334
+ // 4.5 CLI k.mjs without --use fails
335
+ const unitBytes = runCommand(node, [unitParseMjs, "--parse"], { encoding: null }).stdout;
336
+ const failRun = runCommand(node, [kMjs, "--lib", libPath, "greeting"], {
337
+ input: unitBytes
338
+ });
339
+ assert.notEqual(failRun.status, 0);
340
+ assert.match(failRun.stderr, /No definition found for 'greeting'/);
341
+
342
+ // 4.6 CLI k.mjs with @greetingHash succeeds
343
+ const passHashRun = runCommand(node, [kMjs, "--lib", libPath, greetingHash], {
344
+ input: unitBytes,
345
+ encoding: null
346
+ });
347
+ assert.equal(passHashRun.status, 0, passHashRun.stderr?.toString());
348
+ const printHash = runCommand(node, [kPrintMjs], {
349
+ input: passHashRun.stdout,
350
+ encoding: "utf8"
351
+ });
352
+ assert.equal(printHash.stdout.trim(), '"welcome"');
353
+
354
+ // 4.7 CLI k.mjs with --use greeting succeeds
355
+ const passUseRun = runCommand(node, [kMjs, "--lib", libPath, "--use", "greeting", "greeting"], {
356
+ input: unitBytes,
357
+ encoding: null
358
+ });
359
+ assert.equal(passUseRun.status, 0, passUseRun.stderr?.toString());
360
+ const printUse = runCommand(node, [kPrintMjs], {
361
+ input: passUseRun.stdout,
362
+ encoding: "utf8"
363
+ });
364
+ assert.equal(printUse.stdout.trim(), '"welcome"');
365
+ } finally {
366
+ fs.rmSync(tmpDir, { recursive: true, force: true });
367
+ }
368
+ }
369
+ console.log(" Passed: CLI isolation and --use flags verified.");
370
+
371
+ // -----------------------------------------------------------------------------
372
+ // §5. Exact Line Number Preservation (No text synthesis or line offset)
373
+ // -----------------------------------------------------------------------------
374
+ console.log("--> Test 5: Exact 1-to-1 source line numbers in diagnostics");
375
+ {
376
+ const sourceWithComment = [
377
+ "# --lib lib/dummy.klib --use hello world",
378
+ "-- Comment line 2",
379
+ "-- Comment line 3",
380
+ "bad_definition = undefined_symbol;",
381
+ "()"
382
+ ].join("\n");
383
+
384
+ try {
385
+ compileObject(sourceWithComment, { source: "test-lines.k" });
386
+ assert.fail("Compilation should fail on undefined_symbol");
387
+ } catch (error) {
388
+ // line 4 must be reported exactly, not shifted by any synthesized preamble
389
+ assert.match(
390
+ error.message,
391
+ /lines 4:18\.\.\.4:34/,
392
+ `Error line must be line 4, got: ${error.message}`
393
+ );
394
+ }
395
+ }
396
+ console.log(" Passed: Exact line numbers preserved without offset.");
397
+
398
+ // -----------------------------------------------------------------------------
399
+ // §6. REPL Sequential :load of Standard Libraries (No Renaming Magic)
400
+ // -----------------------------------------------------------------------------
401
+ console.log("--> Test 6: REPL sequential :load of standard libraries");
402
+ {
403
+ const djsonState = createState();
404
+ for (const libFile of ["core.k", "lib/generic.k", "lib/ieee.k", "lib/djson.k"]) {
405
+ await evaluateInput(`:load ${libFile}`, djsonState);
406
+ }
407
+
408
+ // Verify that symbols are accessible in REPL under their exact canonical names
409
+ assert.ok(djsonState.relAliases.reverse, "Expected 'reverse' in REPL");
410
+ assert.ok(djsonState.relAliases.btrie_get, "Expected 'btrie_get' in REPL");
411
+ assert.ok(djsonState.relAliases.ratio_to_float64, "Expected 'ratio_to_float64' in REPL");
412
+ assert.ok(djsonState.relAliases.parse_json, "Expected 'parse_json' in REPL");
413
+ assert.ok(djsonState.patternAliases.bit, "Expected 'bit[]' in REPL");
414
+ assert.ok(djsonState.patternAliases.list, "Expected 'list[X]' in REPL");
415
+ assert.ok(djsonState.patternAliases.btrie, "Expected 'btrie[V]' in REPL");
416
+ assert.ok(djsonState.patternAliases.unicode, "Expected 'unicode[]' in REPL");
417
+ assert.ok(djsonState.patternAliases.float64, "Expected 'float64[]' in REPL");
418
+ assert.ok(djsonState.patternAliases.djson, "Expected 'djson[]' in REPL");
419
+
420
+ const intState = createState();
421
+ for (const libFile of ["core.k", "lib/integer.k"]) {
422
+ await evaluateInput(`:load ${libFile}`, intState);
423
+ }
424
+ assert.ok(intState.relAliases.inc, "Expected 'inc' in REPL");
425
+ assert.ok(intState.relAliases.times, "Expected 'times' in REPL");
426
+ assert.ok(intState.relAliases.divmod, "Expected 'divmod' in REPL");
427
+ assert.ok(intState.patternAliases.int, "Expected 'int[]' in REPL");
428
+ }
429
+ console.log(" Passed: All standard libraries load cleanly in REPL without renaming.");
430
+
431
+ // -----------------------------------------------------------------------------
432
+ // §7. --use Redefinition Warnings and Later-Definition-Wins Semantics
433
+ // -----------------------------------------------------------------------------
434
+ console.log("--> Test 7: --use redefinition warnings and later-definition-wins");
435
+ {
436
+ function withCapturedWarnings(fn) {
437
+ const warnings = [];
438
+ const origWarn = console.warn;
439
+ console.warn = (...args) => warnings.push(args.map(String).join(" "));
440
+ try {
441
+ const value = fn();
442
+ return { value, warnings };
443
+ } finally {
444
+ console.warn = origWarn;
445
+ }
446
+ }
447
+
448
+ const lib1 = loadLibrary(compileLibrary(`
449
+ greet = {} |from_lib1;
450
+ secret = {} |classified_lib1;
451
+ box[] = { {} lib1_tag };
452
+ alt[] = { {} alt_tag };
453
+ dual = {} |dual_rel;
454
+ dual[] = { {} dual_pat };
455
+ `, { source: "lib1.k" }));
456
+
457
+ const lib2 = loadLibrary(compileLibrary(`
458
+ greet = {} |from_lib2;
459
+ box[] = { {} lib2_tag };
460
+ `, { source: "lib2.k" }));
461
+
462
+ // 7.1 Local relation redefines --use relation: warn, later (local) wins
463
+ {
464
+ const { value: obj, warnings } = withCapturedWarnings(() =>
465
+ compileObject(
466
+ `greet = {} |local_override;\n{ greet local_res, ${lib1.relAlias.greet} hash_res }`,
467
+ { libraries: [lib1], useSpecs: ["greet"] }
468
+ )
469
+ );
470
+ assert.ok(
471
+ warnings.some((w) => /WARNING/.test(w) && /Relation 'greet'/.test(w)),
472
+ `Expected warning for redefined --use relation 'greet', got: ${JSON.stringify(warnings)}`
473
+ );
474
+ const out = objectToFunction(obj)(Value.product({}));
475
+ assert.equal(out.product.local_res.tag, "local_override");
476
+ assert.equal(out.product.hash_res.tag, "from_lib1");
477
+ }
478
+
479
+ // 7.2 Local pattern redefines --use pattern (both compileObject & compileLibrary): warn, local wins
480
+ {
481
+ const script = `
482
+ box[] = { {} local_tag };
483
+ outer[] = { box[] inner };
484
+ { {} local_tag } ?box[]
485
+ `;
486
+ const { value: obj, warnings } = withCapturedWarnings(() =>
487
+ compileObject(script, { libraries: [lib1], useSpecs: ["box[]"] })
488
+ );
489
+ assert.ok(
490
+ warnings.some((w) => /WARNING/.test(w) && /Pattern 'box\[\]'/.test(w)),
491
+ `Expected warning for redefined --use pattern 'box[]', got: ${JSON.stringify(warnings)}`
492
+ );
493
+ const out = objectToFunction(obj)(Value.product({}));
494
+ assert.equal(out.type, "{}");
495
+
496
+ const standaloneOuter = loadLibrary(
497
+ compileLibrary("box[] = { {} local_tag }; outer[] = { box[] inner };", { source: "standalone-outer.k" })
498
+ );
499
+ const { value: libOutRaw, warnings: libWarnings } = withCapturedWarnings(() =>
500
+ compileLibrary("box[] = { {} local_tag }; outer[] = { box[] inner };", {
501
+ source: "redef-lib.k",
502
+ libraries: [lib1],
503
+ useSpecs: ["box[]"]
504
+ })
505
+ );
506
+ const libOut = loadLibrary(libOutRaw);
507
+ assert.ok(libWarnings.some((w) => /WARNING/.test(w) && /Pattern 'box\[\]'/.test(w)));
508
+ assert.equal(libOut.patternAlias.outer, standaloneOuter.patternAlias.outer);
509
+ assert.notEqual(libOut.patternAlias.box, lib1.patternAlias.box);
510
+ }
511
+
512
+ // 7.3 Two --use specs binding the same local name: warn, later --use wins
513
+ {
514
+ const { value: relObj, warnings: relWarn } = withCapturedWarnings(() =>
515
+ compileObject("x", { libraries: [lib1], useSpecs: ["greet:x", "secret:x"] })
516
+ );
517
+ assert.ok(
518
+ relWarn.some((w) => /WARNING/.test(w) && /Relation 'x'/.test(w)),
519
+ `Expected warning for duplicate --use relation alias 'x', got: ${JSON.stringify(relWarn)}`
520
+ );
521
+ assert.equal(objectToFunction(relObj)(Value.product({})).tag, "classified_lib1");
522
+
523
+ const { value: patObj, warnings: patWarn } = withCapturedWarnings(() =>
524
+ compileObject("{ {} alt_tag } ?p[]", { libraries: [lib1], useSpecs: ["box[]:p", "alt[]:p"] })
525
+ );
526
+ assert.ok(
527
+ patWarn.some((w) => /WARNING/.test(w) && /Pattern 'p\[\]'/.test(w)),
528
+ `Expected warning for duplicate --use pattern alias 'p[]', got: ${JSON.stringify(patWarn)}`
529
+ );
530
+ assert.equal(objectToFunction(patObj)(Value.product({})).type, "{}");
531
+ }
532
+
533
+ // 7.4 Multiple libraries providing different definitions under the same --use name: warn, later lib wins
534
+ {
535
+ const { value: multiRel, warnings: mRelWarn } = withCapturedWarnings(() =>
536
+ compileObject("greet", { libraries: [lib1, lib2], useSpecs: ["greet"] })
537
+ );
538
+ assert.ok(mRelWarn.some((w) => /WARNING/.test(w) && /Relation 'greet'/.test(w)));
539
+ assert.equal(objectToFunction(multiRel)(Value.product({})).tag, "from_lib2");
540
+
541
+ const { value: multiPat, warnings: mPatWarn } = withCapturedWarnings(() =>
542
+ compileObject("{ {} lib2_tag } ?box[]", { libraries: [lib1, lib2], useSpecs: ["box[]"] })
543
+ );
544
+ assert.ok(mPatWarn.some((w) => /WARNING/.test(w) && /Pattern 'box\[\]'/.test(w)));
545
+ assert.equal(objectToFunction(multiPat)(Value.product({})).type, "{}");
546
+ }
547
+
548
+ // 7.5 Chained library carrying forward the same hash under [lib1, chained] with single --use: NO warning
549
+ {
550
+ const chainedFromLib1 = loadLibrary(
551
+ compileLibrary("extra = {} |extra;", { source: "chained.k", libraries: [lib1] })
552
+ );
553
+ const { value: chainedRes, warnings: chainWarn } = withCapturedWarnings(() =>
554
+ compileObject("greet", { libraries: [lib1, chainedFromLib1], useSpecs: ["greet"] })
555
+ );
556
+ assert.equal(chainWarn.length, 0, `Same-hash chained lookup should not warn: ${chainWarn}`);
557
+ assert.equal(objectToFunction(chainedRes)(Value.product({})).tag, "from_lib1");
558
+ }
559
+
560
+ // 7.6 Importing pattern `dual[]` and relation `dual` together in --use: NO false collision warning
561
+ {
562
+ const { value: dualObj, warnings: dualWarn } = withCapturedWarnings(() =>
563
+ compileObject("{ dual r, { {} dual_pat } ?dual[] p }", {
564
+ libraries: [lib1],
565
+ useSpecs: ["dual[]", "dual"]
566
+ })
567
+ );
568
+ assert.equal(dualWarn.length, 0, `Distinct pattern/rel namespaces must not warn: ${dualWarn}`);
569
+ const out = objectToFunction(dualObj)(Value.product({}));
570
+ assert.equal(out.product.r.tag, "dual_rel");
571
+ assert.equal(out.product.p.type, "{}");
572
+ }
573
+
574
+ // 7.7 CLI k.mjs & compile.mjs: --use + local redefinition emits WARNING on stderr while preserving binary stdout
575
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-test-use-warn-"));
576
+ try {
577
+ const libPath = path.join(tmpDir, "lib1.klib");
578
+ fs.writeFileSync(path.join(tmpDir, "lib1.k"), "greet = {} |from_lib1;", "utf8");
579
+ const buildLib = runCommand(node, [compileMjs, path.join(tmpDir, "lib1.k"), libPath]);
580
+ assert.equal(buildLib.status, 0, buildLib.stderr);
581
+
582
+ const unitBytes = runCommand(node, [unitParseMjs, "--parse"], { encoding: null }).stdout;
583
+ const cliRun = runCommand(node, [
584
+ kMjs, "--lib", libPath, "--use", "greet",
585
+ "greet = {} |cli_override; greet"
586
+ ], { input: unitBytes, encoding: null });
587
+ assert.equal(cliRun.status, 0, cliRun.stderr?.toString());
588
+ assert.match(
589
+ cliRun.stderr.toString("utf8"),
590
+ /WARNING:.*Relation 'greet' declared by --use/,
591
+ `Expected CLI stderr warning, got: ${cliRun.stderr.toString("utf8")}`
592
+ );
593
+ const printed = runCommand(node, [kPrintMjs], { input: cliRun.stdout, encoding: "utf8" });
594
+ assert.equal(printed.stdout.trim(), '"cli_override"');
595
+ } finally {
596
+ fs.rmSync(tmpDir, { recursive: true, force: true });
597
+ }
598
+ }
599
+ console.log(" Passed: --use redefinition warnings and later-definition-wins verified.");
600
+
601
+ // -----------------------------------------------------------------------------
602
+ // §8. Explicit Check That Local / Un-imported Names Do Not Leak
603
+ // -----------------------------------------------------------------------------
604
+ console.log("--> Test 8: Explicit non-leakage of local/un-imported names");
605
+ {
606
+ const libA = loadLibrary(compileLibrary(`
607
+ priv_rel = {} |from_libA_priv;
608
+ priv_pat[] = { {} libA_tag };
609
+ pub_rel = priv_rel;
610
+ pub_pat[] = { priv_pat[] inner };
611
+ `, { source: "libA.k" }));
612
+
613
+ // 8.1 Importing pub_rel / pub_pat[] via --use must NOT leak transitive priv_rel / priv_pat[]
614
+ assert.throws(
615
+ () => compileObject("priv_rel", { libraries: [libA], useSpecs: ["pub_rel", "pub_pat[]"] }),
616
+ /No definition found for 'priv_rel'/,
617
+ "Transitive helper relation 'priv_rel' must not leak when importing 'pub_rel'"
618
+ );
619
+ assert.throws(
620
+ () => compileObject("{{} libA_tag} ?priv_pat[]", {
621
+ libraries: [libA],
622
+ useSpecs: ["pub_rel", "pub_pat[]"]
623
+ }),
624
+ /Unknown pattern template 'priv_pat\[\]'/,
625
+ "Transitive helper pattern 'priv_pat[]' must not leak when importing 'pub_pat[]'"
626
+ );
627
+
628
+ // 8.2 Redefining local names in libB must NOT leak into libA's pub_rel / pub_pat[], nor leak out to libC
629
+ const libBWarnings = [];
630
+ const origWarn = console.warn;
631
+ console.warn = (...args) => libBWarnings.push(args.map(String).join(" "));
632
+ let libB;
633
+ try {
634
+ libB = loadLibrary(compileLibrary(`
635
+ priv_rel = {} |from_libB_local;
636
+ priv_pat[] = { {} libB_tag };
637
+ local_helper = priv_rel;
638
+ local_wrap[] = { priv_pat[] inner };
639
+ exposed_from_a = pub_rel;
640
+ exposed_pat_from_a[] = { pub_pat[] wrapped };
641
+ `, {
642
+ source: "libB.k",
643
+ libraries: [libA],
644
+ useSpecs: ["pub_rel", "pub_pat[]"]
645
+ }));
646
+ } finally {
647
+ console.warn = origWarn;
648
+ }
649
+ assert.equal(
650
+ libBWarnings.length,
651
+ 0,
652
+ `Redefining un-imported names must not emit warnings: ${libBWarnings}`
653
+ );
654
+
655
+ // Compiling downstream against libB with aliased --use: only explicit aliases enter scope
656
+ const downstream = compileObject(
657
+ "{ entry_rel r, { { {} libA_tag } inner } ?entry_pat[] p }",
658
+ {
659
+ libraries: [libB],
660
+ useSpecs: ["exposed_from_a:entry_rel", "pub_pat[]:entry_pat[]"]
661
+ }
662
+ );
663
+ const res = objectToFunction(downstream)(Value.product({}));
664
+ assert.equal(res.product.r.tag, "from_libA_priv");
665
+ assert.equal(res.product.p.type, "{}");
666
+
667
+ // Neither libA's priv/pub names nor libB's local/aliased-away names may leak into downstream scope
668
+ for (const hiddenRel of ["priv_rel", "pub_rel", "local_helper", "exposed_from_a"]) {
669
+ assert.throws(
670
+ () => compileObject(hiddenRel, {
671
+ libraries: [libB],
672
+ useSpecs: ["exposed_from_a:entry_rel", "pub_pat[]:entry_pat[]"]
673
+ }),
674
+ new RegExp(`No definition found for '${hiddenRel}'`),
675
+ `Un-imported local/library relation '${hiddenRel}' must not leak`
676
+ );
677
+ }
678
+ for (const hiddenPat of ["priv_pat", "pub_pat", "local_wrap", "exposed_pat_from_a"]) {
679
+ assert.throws(
680
+ () => compileObject(`x = ?${hiddenPat}[]; ()`, {
681
+ libraries: [libB],
682
+ useSpecs: ["exposed_from_a:entry_rel", "pub_pat[]:entry_pat[]"]
683
+ }),
684
+ new RegExp(`Unknown pattern template '${hiddenPat}\\[\\]'`),
685
+ `Un-imported local/library pattern '${hiddenPat}[]' must not leak`
686
+ );
687
+ }
688
+
689
+ // 8.3 Direct pattern resolution APIs must also enforce hash-only library imports
690
+ const parsedProbe = parse("probe[] = { priv_pat[] x }; ()");
691
+ assert.throws(
692
+ () => resolvePatternCanonicalInfo("probe", parsedProbe.defs.patterns.probe, { libraries: [libA, libB] }),
693
+ /Unknown pattern template 'priv_pat\[\]'/,
694
+ "resolvePatternCanonicalInfo must not leak friendly names from libraries"
695
+ );
696
+ assert.throws(
697
+ () => validatePatternDefinitions(parsedProbe.defs.patterns, { libraries: [libA, libB] }),
698
+ /Unknown pattern template 'priv_pat\[\]'/,
699
+ "validatePatternDefinitions must not leak friendly names from libraries"
700
+ );
701
+ }
702
+ console.log(" Passed: Local and un-imported names remain strictly isolated without leakage.");
703
+
704
+ console.log("==> All Library Isolation & Scope Binding Tests Passed Successfully!");