@fraczak/k 8.7.1 → 8.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/DOCS/CODECS.md +42 -40
  3. package/DOCS/FILE_FORMATS.md +28 -25
  4. package/DOCS/GETTING_STARTED.md +10 -15
  5. package/DOCS/PATTERNS.md +3 -3
  6. package/DOCS/REPL.md +3 -6
  7. package/Examples/ieee-arithmetics.k +14 -29
  8. package/Examples/poly.k +18 -29
  9. package/README.md +14 -18
  10. package/backend-api.mjs +1 -3
  11. package/backends/llvm/src/cli.mjs +1 -2
  12. package/backends/llvm/tests/integration.sh +2 -6
  13. package/backends/wasm/tests/integration.sh +5 -10
  14. package/browser/shims/fs.mjs +2 -6
  15. package/canonical-pattern.mjs +9 -29
  16. package/codecs/djson.mjs +2 -3
  17. package/codecs/int.mjs +66 -14
  18. package/compiler.mjs +22 -12
  19. package/harness/suites/poly.mjs +9 -11
  20. package/index.mjs +119 -50
  21. package/lib/djson.k +976 -288
  22. package/lib/generic.k +686 -0
  23. package/lib/ieee.k +658 -639
  24. package/lib/integer.k +536 -0
  25. package/object.mjs +19 -12
  26. package/objects/README.md +6 -6
  27. package/package.json +1 -1
  28. package/scripts/benchmark-idempotency.mjs +16 -17
  29. package/scripts/benchmark.mjs +39 -29
  30. package/scripts/build-repl-html.mjs +45 -35
  31. package/scripts/perf-bigint-compare.mjs +279 -0
  32. package/scripts/perf-ieee.mjs +1 -5
  33. package/scripts/perf-int.mjs +12 -27
  34. package/scripts/perf-multiplication.mjs +8 -9
  35. package/scripts/perf-poly.mjs +7 -10
  36. package/scripts/render-benchmark.mjs +1 -1
  37. package/scripts/run-tests.mjs +4 -2
  38. package/scripts/test-package.mjs +4 -10
  39. package/tests/README.md +4 -5
  40. package/tests/helpers/cli.mjs +30 -7
  41. package/tests/integration.sh +5 -10
  42. package/tests/test-arithmetics.mjs +23 -16
  43. package/tests/test-djson-methods.mjs +16 -25
  44. package/tests/test-djson.mjs +272 -0
  45. package/tests/test-generic.mjs +237 -0
  46. package/tests/test-ieee-arithmetic.mjs +1 -5
  47. package/tests/test-ieee.mjs +153 -0
  48. package/tests/test-integer.mjs +264 -0
  49. package/tests/test-k-object.mjs +12 -18
  50. package/tests/test-kvm-polymorphic.mjs +6 -7
  51. package/tests/test-lib.mjs +62 -52
  52. package/tests/test-library-isolation.mjs +349 -26
  53. package/tests/test-parse-json.mjs +15 -24
  54. package/tests/test-poly.mjs +21 -16
  55. package/tests/test-repl-html.mjs +39 -44
  56. package/tests/test-repl.mjs +46 -59
  57. package/tests/test-structural-values.mjs +1 -1
  58. package/DOCS/book-combined.md +0 -3786
  59. package/DOCS/dependency-graph.md +0 -144
  60. package/Examples/arithmetics.k +0 -108
  61. package/Examples/esc.k +0 -9
  62. package/lib/arithmetics.k +0 -286
  63. package/lib/bit.k +0 -68
  64. package/lib/bits.k +0 -227
  65. package/lib/btrie.k +0 -187
  66. package/lib/list.k +0 -49
  67. package/lib/string.k +0 -588
  68. package/tests/test-ieee-text.mjs +0 -74
  69. package/tests/test-karatsuba.mjs +0 -25
@@ -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!");
@@ -5,40 +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
+ import { useSpecsFor } from "./helpers/cli.mjs";
9
9
  import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
10
10
  import { fromJsonValue } from "../codecs/djson.mjs";
11
11
  import { textToStringValue } from "../codecs/runtime/unicode-string.mjs";
12
12
  import { parse as utf8 } from "../codecs/utf8.mjs";
13
13
  import { encodeToWire, decodeWire } from "../codecs/runtime/codec-sdk.mjs";
14
14
 
15
- let ieee = null;
15
+ let prev = null;
16
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",
17
+ "core.k",
18
+ "lib/generic.k",
22
19
  "lib/ieee.k"
23
20
  ]) {
24
21
  const fileSource = readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
25
- const uses = parseHeaderUses(fileSource).map((u) => u.use);
26
- ieee = loadLibrary(compileLibrary(fileSource, {
22
+ const uses = useSpecsFor(file);
23
+ prev = loadLibrary(compileLibrary(fileSource, {
27
24
  source: file,
28
- libraries: ieee ? [ieee] : [],
25
+ libraries: prev ? [prev] : [],
29
26
  use: uses
30
27
  }));
31
28
  }
32
29
  const djsonSource = readFileSync(new URL("../lib/djson.k", import.meta.url), "utf8");
33
- const djsonUses = parseHeaderUses(djsonSource).map((u) => u.use);
34
30
  const library = loadLibrary(compileLibrary(djsonSource, {
35
31
  source: "lib/djson.k",
36
- libraries: [ieee],
37
- use: djsonUses
32
+ libraries: [prev],
33
+ use: useSpecsFor("lib/djson.k")
38
34
  }));
39
- const wasm = await instantiateWasmArtifact(await compileWasmArtifact(library.relAlias.parseJson, { libraries: [library] }));
35
+ const wasm = await instantiateWasmArtifact(await compileWasmArtifact(library.relAlias.parse_json, { libraries: [library] }));
40
36
  const fast = text => wasm.executeValue(textToStringValue(text));
41
- const parse = k.compile(library.relAlias.parseJson, { libraries: [library] });
37
+ const parse = k.compile(library.relAlias.parse_json, { libraries: [library] });
42
38
  const payload = value => JSON.parse(JSON.stringify(value));
43
39
  function check(text, evaluate = text => parse(textToStringValue(text))) {
44
40
  const actual = evaluate(text);
@@ -91,20 +87,15 @@ const text = '{"answer":42,"ok":true}';
91
87
  const scratch = mkdtempSync(path.join(os.tmpdir(), "k-json-test-"));
92
88
  try {
93
89
  const chain = [
94
- "lib/bit.k",
95
- "lib/bits.k",
96
- "lib/list.k",
97
- "lib/btrie.k",
98
- "lib/string.k",
90
+ "core.k",
91
+ "lib/generic.k",
99
92
  "lib/ieee.k",
100
93
  "lib/djson.k"
101
94
  ];
102
95
  let prev = null;
103
96
  for (let i = 0; i < chain.length; i++) {
104
97
  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]);
98
+ const useArgs = useSpecsFor(chain[i]).flatMap((u) => ["--use", u]);
108
99
  const args = ["objects/compile.mjs", ...(prev ? ["--lib", prev] : []), ...useArgs, chain[i], out];
109
100
  const built = spawnSync(process.execPath, args, {
110
101
  cwd: new URL("..", import.meta.url)
@@ -114,7 +105,7 @@ try {
114
105
  prev = out;
115
106
  }
116
107
  const artifact = prev;
117
- const cli = spawnSync(process.execPath, ["k.mjs", "--lib", artifact, "--use", "parseJson", "parseJson"], {
108
+ const cli = spawnSync(process.execPath, ["k.mjs", "--lib", artifact, "--use", "parse_json", "parse_json"], {
118
109
  cwd: new URL("..", import.meta.url), input: encodeToWire(utf8(text))
119
110
  });
120
111
  assert.ifError(cli.error);
@@ -7,10 +7,8 @@ import { createState, evaluateInput } from "../backend-api.mjs";
7
7
 
8
8
  const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
9
9
  const polySources = [
10
- "lib/bit.k",
11
- "lib/bits.k",
12
- "lib/arithmetics.k",
13
- "lib/list.k",
10
+ "core.k",
11
+ "lib/integer.k",
14
12
  "Examples/poly.k"
15
13
  ];
16
14
 
@@ -63,14 +61,14 @@ async function evalK(snippet) {
63
61
  {
64
62
  const res0 = await evalK(`
65
63
  l = {{}|item0 car, {{}|item1 car, {{}|item2 car, nil cdr} cons cdr} cons cdr} cons;
66
- {0 int n, l xs} get_nth
64
+ {0 nat n, l xs} get_nth
67
65
  `);
68
66
  assert.match(res0, /\|item0/);
69
67
 
70
- const res1 = await evalK(`{1 int n, l xs} get_nth`);
68
+ const res1 = await evalK(`{1 n, l xs} get_nth`);
71
69
  assert.match(res1, /\|item1/);
72
70
 
73
- const res2 = await evalK(`{2 int n, l xs} get_nth`);
71
+ const res2 = await evalK(`{{}|_|0|1 nat n, l xs} get_nth`);
74
72
  assert.match(res2, /\|item2/);
75
73
  console.log("Test 4 (get_nth): Passed");
76
74
  }
@@ -79,7 +77,7 @@ async function evalK(snippet) {
79
77
  {
80
78
  const res = await evalK(`
81
79
  l = {{}|a car, {{}|b car, {{}|c car, {{}|d car, nil cdr} cons cdr} cons cdr} cons cdr} cons;
82
- {2 int n, l xs} split_by
80
+ {{}|_|0|1 nat n, l xs} split_by
83
81
  `);
84
82
  assert.match(res, /first/);
85
83
  assert.match(res, /second/);
@@ -90,12 +88,12 @@ async function evalK(snippet) {
90
88
  {
91
89
  const resTake = await evalK(`
92
90
  l = {{}|a car, {{}|b car, {{}|c car, nil cdr} cons cdr} cons cdr} cons;
93
- {2 int n, l xs} take
91
+ {{}|_|0|1 nat n, l xs} take
94
92
  `);
95
93
  assert.match(resTake, /\|a car.*\|b car/);
96
94
 
97
95
  const resDrop = await evalK(`
98
- {2 int n, l xs} drop
96
+ {{}|_|0|1 nat n, l xs} drop
99
97
  `);
100
98
  assert.match(resDrop, /\|c car/);
101
99
  console.log("Test 6 (take & drop): Passed");
@@ -104,7 +102,7 @@ async function evalK(snippet) {
104
102
  // Test 7: Repeat
105
103
  {
106
104
  const res = await evalK(`
107
- {3 int n, {}|val x} repeat
105
+ {{}|_|1|1 nat n, {}|val x} repeat
108
106
  `);
109
107
  assert.match(res, /\|val car.*\|val car.*\|val car/);
110
108
  console.log("Test 7 (repeat): Passed");
@@ -124,7 +122,7 @@ async function evalK(snippet) {
124
122
  {
125
123
  const res = await evalK(`
126
124
  l1 = {{}|k1 car, {{}|k2 car, nil cdr} cons cdr} cons;
127
- l2 = {1 int car, {2 int car, nil cdr} cons cdr} cons;
125
+ l2 = {1 car, {{}|_|0|1 nat car, nil cdr} cons cdr} cons;
128
126
  {l1 xs, l2 ys} zip
129
127
  `);
130
128
  assert.match(res, /\|k1 x/);
@@ -138,19 +136,22 @@ async function evalK(snippet) {
138
136
  assert.match(resNil, /\|nil/);
139
137
 
140
138
  const resSingle = await evalK(`
141
- l = {1 int car, nil cdr} cons;
139
+ l = {1 car, nil cdr} cons;
142
140
  l sort
143
141
  `);
144
142
  assert.match(resSingle, /1/);
145
143
 
146
144
  const resSplit = await evalK(`
147
- l4 = {1 int car, {2 int car, {3 int car, {4 int car, nil cdr} cons cdr} cons cdr} cons cdr} cons;
145
+ n2 = {}|_|0|1 nat;
146
+ n3 = {}|_|1|1 nat;
147
+ n4 = {}|_|0|0|1 nat;
148
+ l4 = {1 car, {n2 car, {n3 car, {n4 car, nil cdr} cons cdr} cons cdr} cons cdr} cons;
148
149
  l4 split
149
150
  `);
150
151
  assert.match(resSplit, /first.*second/);
151
152
 
152
153
  const resSorted = await evalK(`
153
- gt_int? = { { .x /"+" x, .y /"+" y } GT if, () then } .then;
154
+ gt_int? = { { .x x, .y y } gt? if, () then } .then;
154
155
  _merge = <
155
156
  {.xs /nil if, .ys then} .then,
156
157
  {.ys /nil if, .xs then} .then,
@@ -167,7 +168,11 @@ async function evalK(snippet) {
167
168
  |cons split {.first _sort xs, .second _sort ys} _merge
168
169
  >
169
170
  > ? list[X];
170
- l = {5 int car, {2 int car, {4 int car, {1 int car, {3 int car, nil cdr} cons cdr} cons cdr} cons cdr} cons cdr} cons;
171
+ n2 = {}|_|0|1 nat;
172
+ n3 = {}|_|1|1 nat;
173
+ n4 = {}|_|0|0|1 nat;
174
+ n5 = {}|_|1|0|1 nat;
175
+ l = {n5 car, {n2 car, {n4 car, {1 car, {n3 car, nil cdr} cons cdr} cons cdr} cons cdr} cons cdr} cons;
171
176
  l _sort
172
177
  `);
173
178
  assert.match(resSorted, /\|1.*\|0\|1.*\|1\|1.*\|0\|0\|1.*\|1\|0\|1/);