@fraczak/k 8.7.1 → 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 (65) hide show
  1. package/CHANGELOG.md +17 -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/compiler.mjs +22 -12
  17. package/harness/suites/poly.mjs +9 -11
  18. package/index.mjs +119 -50
  19. package/lib/djson.k +981 -295
  20. package/lib/generic.k +701 -0
  21. package/lib/ieee.k +662 -638
  22. package/lib/integer.k +542 -0
  23. package/object.mjs +19 -12
  24. package/objects/README.md +6 -6
  25. package/package.json +1 -1
  26. package/scripts/benchmark-idempotency.mjs +16 -17
  27. package/scripts/benchmark.mjs +39 -29
  28. package/scripts/build-repl-html.mjs +45 -35
  29. package/scripts/perf-ieee.mjs +1 -5
  30. package/scripts/perf-int.mjs +12 -27
  31. package/scripts/perf-multiplication.mjs +8 -9
  32. package/scripts/perf-poly.mjs +7 -10
  33. package/scripts/render-benchmark.mjs +1 -1
  34. package/scripts/run-tests.mjs +4 -2
  35. package/scripts/test-package.mjs +4 -10
  36. package/tests/README.md +4 -5
  37. package/tests/helpers/cli.mjs +30 -7
  38. package/tests/integration.sh +5 -10
  39. package/tests/test-arithmetics.mjs +23 -16
  40. package/tests/test-djson-methods.mjs +17 -25
  41. package/tests/test-djson.mjs +273 -0
  42. package/tests/test-generic.mjs +239 -0
  43. package/tests/test-ieee-arithmetic.mjs +1 -5
  44. package/tests/test-ieee.mjs +153 -0
  45. package/tests/test-integer.mjs +264 -0
  46. package/tests/test-k-object.mjs +12 -18
  47. package/tests/test-kvm-polymorphic.mjs +6 -7
  48. package/tests/test-lib.mjs +62 -52
  49. package/tests/test-library-isolation.mjs +349 -26
  50. package/tests/test-parse-json.mjs +15 -24
  51. package/tests/test-poly.mjs +21 -16
  52. package/tests/test-repl-html.mjs +39 -44
  53. package/tests/test-repl.mjs +46 -59
  54. package/DOCS/book-combined.md +0 -3786
  55. package/DOCS/dependency-graph.md +0 -144
  56. package/Examples/arithmetics.k +0 -108
  57. package/Examples/esc.k +0 -9
  58. package/lib/arithmetics.k +0 -286
  59. package/lib/bit.k +0 -68
  60. package/lib/bits.k +0 -227
  61. package/lib/btrie.k +0 -187
  62. package/lib/list.k +0 -49
  63. package/lib/string.k +0 -588
  64. package/tests/test-ieee-text.mjs +0 -74
  65. package/tests/test-karatsuba.mjs +0 -25
@@ -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));
@@ -5,8 +5,10 @@ import path from "node:path";
5
5
  import { spawnSync } from "node:child_process";
6
6
  import { fileURLToPath } from "node:url";
7
7
 
8
- import k from "../index.mjs";
8
+ import k, { parse } from "../index.mjs";
9
9
  import { Value } from "../Value.mjs";
10
+ import { resolvePatternCanonicalInfo } from "../canonical-pattern.mjs";
11
+ import { validatePatternDefinitions } from "../named-patterns.mjs";
10
12
  import {
11
13
  compileObject,
12
14
  compileObjectBuffer,
@@ -198,23 +200,71 @@ console.log("--> Test 3: Local definitions and unused library symbols");
198
200
  {
199
201
  const libSource = `
200
202
  foo = {} |library_foo;
203
+ byte[] = { <{} 0, {} 1> b0, <{} 0, {} 1> b1 };
204
+ box[] = { byte[] item };
201
205
  `;
202
206
  const library = loadLibrary(compileLibrary(libSource, { source: "lib-foo.k" }));
203
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
+ }
204
222
 
205
223
  // 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.
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.
208
226
  const source = `
209
227
  foo = {} |local_foo;
210
228
  call_local = foo;
211
229
  call_lib = ${fooHash};
212
230
  { call_local local, call_lib lib }
213
231
  `;
214
- const compiled = compileObject(source, { libraries: [library] });
232
+ const { value: compiled, warnings: relWarnings } = captureWarnings(() =>
233
+ compileObject(source, { libraries: [library] })
234
+ );
235
+ assert.equal(relWarnings.length, 0, `Unexpected warning without --use: ${relWarnings}`);
215
236
  const result = objectToFunction(compiled)(Value.product({}));
216
237
  assert.equal(result.product.local.tag, "local_foo");
217
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
+ );
218
268
  }
219
269
  console.log(" Passed: Local definitions and library symbols do not clash without --use.");
220
270
 
@@ -350,32 +400,305 @@ console.log(" Passed: Exact line numbers preserved without offset.");
350
400
  // -----------------------------------------------------------------------------
351
401
  console.log("--> Test 6: REPL sequential :load of standard libraries");
352
402
  {
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);
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);
367
406
  }
368
407
 
369
408
  // 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");
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");
378
428
  }
379
429
  console.log(" Passed: All standard libraries load cleanly in REPL without renaming.");
380
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
+
381
704
  console.log("==> All Library Isolation & Scope Binding Tests Passed Successfully!");