@fraczak/k 8.6.0 → 8.7.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 (71) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/DOCS/CODECS.md +20 -14
  3. package/DOCS/FILE_FORMATS.md +79 -12
  4. package/DOCS/GETTING_STARTED.md +17 -8
  5. package/DOCS/PATTERNS.md +17 -0
  6. package/DOCS/REPL.md +15 -8
  7. package/Examples/arithmetics.k +81 -468
  8. package/Examples/ieee-arithmetics.k +37 -33
  9. package/Examples/poly.k +107 -104
  10. package/README.md +19 -11
  11. package/backend-api.mjs +3 -1
  12. package/backends/llvm/README.md +1 -1
  13. package/backends/llvm/bin/k-llvm-build.mjs +5 -5
  14. package/backends/llvm/bin/k-llvm-compile.mjs +4 -4
  15. package/backends/llvm/bin/k-llvm.mjs +6 -6
  16. package/backends/llvm/src/cli.mjs +17 -12
  17. package/backends/llvm/tests/integration.sh +4 -1
  18. package/backends/wasm/README.md +3 -3
  19. package/backends/wasm/bin/k-wasm-compile.mjs +4 -4
  20. package/backends/wasm/bin/k-wasm.mjs +4 -4
  21. package/backends/wasm/src/cli.mjs +12 -10
  22. package/backends/wasm/src/wasm.mjs +6 -2
  23. package/backends/wasm/tests/integration.sh +8 -3
  24. package/browser/shims/fs.mjs +19 -3
  25. package/canonical-pattern.mjs +351 -82
  26. package/core.k +2 -1
  27. package/harness/suites/poly.mjs +14 -30
  28. package/k.mjs +17 -13
  29. package/kvm.mjs +13 -9
  30. package/lib/arithmetics.k +287 -0
  31. package/lib/bit.k +68 -0
  32. package/lib/bits.k +221 -0
  33. package/lib/btrie.k +187 -0
  34. package/lib/djson.k +326 -0
  35. package/lib/ieee.k +709 -0
  36. package/lib/list.k +49 -0
  37. package/lib/string.k +588 -0
  38. package/named-patterns.mjs +2 -2
  39. package/object.mjs +52 -10
  40. package/objects/README.md +10 -3
  41. package/objects/compile.mjs +10 -8
  42. package/package.json +1 -1
  43. package/repl.mjs +227 -22
  44. package/scripts/benchmark-idempotency.mjs +22 -15
  45. package/scripts/benchmark.mjs +29 -10
  46. package/scripts/build-repl-html.mjs +49 -14
  47. package/scripts/perf-ieee.mjs +9 -1
  48. package/scripts/perf-int.mjs +10 -17
  49. package/scripts/perf-multiplication.mjs +9 -15
  50. package/scripts/perf-poly.mjs +16 -32
  51. package/scripts/run-tests.mjs +2 -2
  52. package/scripts/test-package.mjs +8 -2
  53. package/tests/helpers/cli.mjs +11 -3
  54. package/tests/integration.sh +9 -4
  55. package/tests/test-arithmetics.mjs +4 -2
  56. package/tests/test-djson-methods.mjs +16 -12
  57. package/tests/test-ieee-arithmetic.mjs +11 -3
  58. package/tests/test-ieee-text.mjs +15 -4
  59. package/tests/test-k-object.mjs +11 -3
  60. package/tests/test-karatsuba.mjs +1 -1
  61. package/tests/test-kvm-polymorphic.mjs +54 -34
  62. package/tests/test-lib.mjs +115 -0
  63. package/tests/test-named-patterns.mjs +12 -3
  64. package/tests/test-parse-json.mjs +33 -13
  65. package/tests/test-poly.mjs +10 -4
  66. package/tests/test-repl-html.mjs +18 -7
  67. package/tests/test-repl.mjs +154 -54
  68. package/Examples/djson.k +0 -894
  69. package/Examples/ieee.k +0 -969
  70. package/Examples/karatsuba-mult.k +0 -227
  71. package/Examples/list.k +0 -10
package/object.mjs CHANGED
@@ -5,7 +5,9 @@ import { TypePatternGraph } from "./TypePatternGraph.mjs";
5
5
  import { patterns2filters, prettyRel } from "./pretty.mjs";
6
6
  import {
7
7
  resolvePatternCanonicalInfo,
8
- buildExportPreamble,
8
+ buildUsePreamble,
9
+ parseHeaderDirectives,
10
+ parseHeaderUses,
9
11
  canonicalBoundaryFilterSources
10
12
  } from "./canonical-pattern.mjs";
11
13
 
@@ -476,7 +478,16 @@ function collectReachable(mainName, rels, allCodes) {
476
478
  }
477
479
 
478
480
  function compileObject(script, options = {}) {
479
- const annotated = annotate(script, options);
481
+ let scriptToAnnotate = script;
482
+ if (typeof script === "string" && options.libraries?.length > 0) {
483
+ const headerUses = parseHeaderUses(script);
484
+ const allSpecs = [...headerUses, ...(options.useSpecs || options.use || [])];
485
+ if (allSpecs.length > 0) {
486
+ const preamble = buildUsePreamble(allSpecs, options.libraries);
487
+ scriptToAnnotate = preamble + script;
488
+ }
489
+ }
490
+ const annotated = annotate(scriptToAnnotate, options);
480
491
  const allCodes = stripDebugFieldsFromCodes(codes.dump());
481
492
  const serialized = serializeAnnotated(annotated);
482
493
  const meta = mergeMetaEntries(
@@ -533,24 +544,50 @@ function rewriteRefsToCanonical(exp, relAlias) {
533
544
  }
534
545
 
535
546
  function compileLibrary(script, options = {}) {
536
- const annotated = annotateLibrary(script, options);
547
+ let scriptToAnnotate = script;
548
+ if (typeof script === "string" && options.libraries?.length > 0) {
549
+ const headerUses = parseHeaderUses(script);
550
+ const allSpecs = [...headerUses, ...(options.useSpecs || options.use || [])];
551
+ if (allSpecs.length > 0) {
552
+ const preamble = buildUsePreamble(allSpecs, options.libraries);
553
+ scriptToAnnotate = preamble + script;
554
+ }
555
+ }
556
+ const annotated = annotateLibrary(scriptToAnnotate, options);
537
557
  const allCodes = stripDebugFieldsFromCodes(codes.dump());
538
558
  const serialized = serializeAnnotated(annotated);
539
559
  const meta = mergeMetaEntries(
540
560
  importedLibraryMeta(options.libraries),
541
561
  buildMeta(annotated, options.source || null, options)
542
562
  );
543
- const relAlias = serialized.relAlias || {};
563
+
564
+ const libRelAlias = {};
565
+ if (options.libraries) {
566
+ for (const lib of options.libraries) {
567
+ Object.assign(libRelAlias, lib.relAlias || {});
568
+ }
569
+ }
570
+ Object.assign(libRelAlias, serialized.relAlias || {});
544
571
 
545
572
  // Key rels by canonical hash, rewrite internal refs to canonical hashes
546
573
  const libRels = {};
574
+ if (options.libraries) {
575
+ for (const lib of options.libraries) {
576
+ const lr = lib.rels || lib.defs?.rels || {};
577
+ for (const [name, rel] of Object.entries(lr)) {
578
+ if (name !== "__main__") {
579
+ libRels[name] = rel;
580
+ }
581
+ }
582
+ }
583
+ }
547
584
  for (const [name, rel] of Object.entries(serialized.rels)) {
548
585
  if (name === "__main__") continue;
549
- const canonicalName = relAlias[name] || name;
586
+ const canonicalName = libRelAlias[name] || name;
550
587
  const { varRefs, ...relWithoutVarRefs } = rel;
551
588
  libRels[canonicalName] = {
552
589
  ...relWithoutVarRefs,
553
- def: rewriteRefsToCanonical(rel.def, relAlias)
590
+ def: rewriteRefsToCanonical(rel.def, libRelAlias)
554
591
  };
555
592
  }
556
593
  const libPatterns = {};
@@ -593,7 +630,7 @@ function compileLibrary(script, options = {}) {
593
630
  _canonicalDef: info.def,
594
631
  _canonicalParams: info.canonicalParams,
595
632
  _graphParams: info.canonicalParams,
596
- _aliasArgs: info.aliasArgs,
633
+ _aliasArgs: info.canonicalParams || [],
597
634
  _canonicalFilterAst: info.canonicalFilterAst
598
635
  };
599
636
  }
@@ -614,11 +651,12 @@ function compileLibrary(script, options = {}) {
614
651
  format: "k-object",
615
652
  codes: allCodes,
616
653
  rels: libRels,
617
- relAlias: serialized.relAlias,
654
+ relAlias: libRelAlias,
618
655
  patternAlias,
619
656
  compileStats: serialized.compileStats,
620
657
  meta: libMeta,
621
658
  patterns: libPatterns,
659
+ source: options.source || null,
622
660
  main: null
623
661
  };
624
662
  }
@@ -1067,7 +1105,9 @@ export {
1067
1105
  decompileObjectBuffer,
1068
1106
  extractAliasesFromObject,
1069
1107
  extractAliasesFromObjectBuffer,
1070
- buildExportPreamble
1108
+ buildUsePreamble,
1109
+ parseHeaderDirectives,
1110
+ parseHeaderUses
1071
1111
  };
1072
1112
 
1073
1113
  export default {
@@ -1090,5 +1130,7 @@ export default {
1090
1130
  decompileObjectBuffer,
1091
1131
  extractAliasesFromObject,
1092
1132
  extractAliasesFromObjectBuffer,
1093
- buildExportPreamble
1133
+ buildUsePreamble,
1134
+ parseHeaderDirectives,
1135
+ parseHeaderUses
1094
1136
  };
package/objects/README.md CHANGED
@@ -19,9 +19,16 @@ node objects/validate.mjs /tmp/k-ok.ko
19
19
  ```
20
20
 
21
21
  `--lib` loads a dependency. It does not select library output; use a `.klib`
22
- output filename or `--format klib`. Friendly library names need explicit
23
- `--export` mappings.
22
+ output filename or `--format klib`.
23
+
24
+ When compiling source files, required library dependencies and friendly aliases
25
+ can be declared directly in the source file header via
26
+ `# --lib <dependency> --use <specs>` comment directives. The compiler
27
+ automatically parses these directives and synthesizes the required bindings, so
28
+ explicit CLI `--use` flags are only needed for ad-hoc snippets or command-line
29
+ expressions.
24
30
 
25
31
  The [file-format reference](../DOCS/FILE_FORMATS.md) is the source for container
26
- fields, executable/library distinctions, aliases, and complete workflows.
32
+ fields, executable/library distinctions, header directives, aliases, and
33
+ complete workflows.
27
34
  [KIR-P](../DOCS/KIR_V1.md) documents the portable backend export.
@@ -9,7 +9,8 @@ import {
9
9
  compileLibraryBuffer,
10
10
  decodeObject,
11
11
  loadLibrary,
12
- buildExportPreamble
12
+ buildUsePreamble,
13
+ parseHeaderUses
13
14
  } from "../object.mjs";
14
15
  import { objectToKVMArtifact } from "../kvm.mjs";
15
16
 
@@ -34,7 +35,7 @@ function helpText() {
34
35
  " --format fmt Output format: ko, klib, or kvm.",
35
36
  " Overrides extension detection.",
36
37
  " --lib file Load one .klib or .k library before compiling.",
37
- " --export spec Export library alias into scope. Repeatable.",
38
+ " --use spec Use library alias in scope (repeatable).",
38
39
  " spec is 'name' or 'libname:localname'.",
39
40
  " -h, --help Show this help.",
40
41
  "",
@@ -50,7 +51,7 @@ function helpText() {
50
51
  ` ${prog} program.k -o program.ko`,
51
52
  ` ${prog} program.k program.klib`,
52
53
  ` ${prog} program.k program.kvm`,
53
- ` ${prog} --lib core.klib --export add program.k program.ko`
54
+ ` ${prog} --lib core.klib --use add program.k program.ko`
54
55
  ].join("\n");
55
56
  }
56
57
 
@@ -123,7 +124,7 @@ try {
123
124
  const libraries = [];
124
125
  let format = null;
125
126
  let explicitOutput = null;
126
- const exports = [];
127
+ const useSpecs = [];
127
128
 
128
129
  while (args.length > 0) {
129
130
  if (args[0] === "--") {
@@ -147,11 +148,11 @@ try {
147
148
  } else {
148
149
  libraries.push(loadLibrary(decodeObject(fs.readFileSync(libPath))));
149
150
  }
150
- } else if (args[0] === "--export") {
151
+ } else if (args[0] === "--use") {
151
152
  args.shift();
152
153
  const spec = args.shift();
153
- if (!spec) throw new Error("--export requires a spec argument (name or libname:localname)");
154
- exports.push(spec);
154
+ if (!spec) throw new Error("--use requires a spec argument (name or libname:localname)");
155
+ useSpecs.push(spec);
155
156
  } else if (args[0] === "--format") {
156
157
  args.shift();
157
158
  format = args.shift();
@@ -211,7 +212,8 @@ try {
211
212
  : input.kind === "inline"
212
213
  ? input.source
213
214
  : fs.readFileSync(input.path, "utf8");
214
- const preamble = buildExportPreamble(exports, libraries);
215
+ const allSpecs = [...parseHeaderUses(rawSource), ...useSpecs];
216
+ const preamble = buildUsePreamble(allSpecs, libraries);
215
217
  const source = preamble + rawSource;
216
218
  const opts = { source: input.sourceName, libraries };
217
219
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fraczak/k",
3
- "version": "8.6.0",
3
+ "version": "8.7.0",
4
4
  "description": "k — a language for content-addressable schemas and data transformations over algebraic data types (products and tagged unions); includes runtime, contract derivation, REPL, and codec toolchain",
5
5
  "publishConfig": {
6
6
  "access": "public"
package/repl.mjs CHANGED
@@ -28,6 +28,8 @@ import {
28
28
  prettyFilter
29
29
  } from "./pretty.mjs";
30
30
  import {
31
+ canonicalBoundaryFilterSources,
32
+ instantiateCanonicalFilter,
31
33
  resolvePatternCanonicalInfo as canonicalPatternInfo
32
34
  } from "./canonical-pattern.mjs";
33
35
  import {
@@ -38,7 +40,9 @@ import {
38
40
  encodeLibrary,
39
41
  hydrateObject,
40
42
  loadLibrary,
41
- prettyRelation
43
+ prettyRelation,
44
+ buildUsePreamble,
45
+ parseHeaderUses
42
46
  } from "./object.mjs";
43
47
  import {
44
48
  propertyListToFilter,
@@ -61,6 +65,7 @@ import {
61
65
  const NAME_RE = /^[a-zA-Z0-9_+-][a-zA-Z0-9_?!+-]*$/;
62
66
  const COMMAND_NAMES = [
63
67
  "help", "rel", "pattern", "pat", "patterns", "pats",
68
+ "all-patterns", "all-pat",
64
69
  "codecs", "rels", "codec", "input", "reset", "klib", "ko", "load",
65
70
  "engine", "wasm", "pkir", "js", "limit",
66
71
  "max-pat-length", "maxPatLength",
@@ -112,7 +117,7 @@ function createState(options = {}) {
112
117
  lastTiming: null,
113
118
  showTiming: true,
114
119
  printLimit: options.printLimit ?? Infinity,
115
- maxPatLength: options.maxPatLength ?? 30
120
+ maxPatLength: options.maxPatLength ?? 45
116
121
  };
117
122
  }
118
123
 
@@ -285,6 +290,20 @@ function recoverAliasesFromMeta(state, lib) {
285
290
  state.typeAliases[origin.name] = hash;
286
291
  } else if (type === "pattern") {
287
292
  state.patternAliases[origin.name] = hash;
293
+ if (!state.patterns[origin.name] && state.patterns[hash]) {
294
+ const canonPat = state.patterns[hash];
295
+ state.patterns[origin.name] = {
296
+ params: origin.params || [],
297
+ filter: canonPat.filter,
298
+ _canonical: hash,
299
+ _canonicalDef: canonPat._canonicalDef,
300
+ _canonicalParams: origin.params || [],
301
+ _graphParams: entry.params || canonPat._graphParams || [],
302
+ _aliasArgs: origin.aliasArgs || origin.params || [],
303
+ _canonicalFilterAst:
304
+ canonPat._canonicalFilterAst || canonPat.filter
305
+ };
306
+ }
288
307
  } else if (type === "rel" || hash in state.rels) {
289
308
  state.relAliases[origin.name] = hash;
290
309
  }
@@ -504,10 +523,6 @@ function resolvePatternCanonicalName(state, name, pat) {
504
523
  function prettyPattern(name, pat, state = null) {
505
524
  const info = resolvePatternCanonicalInfo(state, name, pat);
506
525
  const isHash = typeof name === "string" && name.startsWith("@");
507
- const isDirectAlias =
508
- pat?.filter?.type === "pattern_apply" &&
509
- typeof pat.filter.pattern === "string" &&
510
- pat.filter.pattern.startsWith("@");
511
526
 
512
527
  const paramList =
513
528
  isHash && (info.canonicalParams || pat?.params)
@@ -515,18 +530,28 @@ function prettyPattern(name, pat, state = null) {
515
530
  : (pat?.params || info.params || []);
516
531
  const params = paramList.join(", ");
517
532
 
533
+ const aliasArgs = info.aliasArgs || pat?.params || [];
534
+ const canonicalAst =
535
+ info.canonicalFilterAst ||
536
+ (info.hash ? state?.patterns?.[info.hash]?._canonicalFilterAst : null);
537
+ const canonicalParams =
538
+ info.canonicalParams ||
539
+ (info.hash ? state?.patterns?.[info.hash]?._graphParams : null) ||
540
+ [];
541
+
518
542
  let filterStr;
519
543
  if (isHash) {
520
544
  filterStr =
521
545
  info.def || (pat?.filter ? prettyFilter(pat.filter) : "()");
522
- } else if (pat?.filter && !isDirectAlias) {
523
- filterStr = prettyFilter(pat.filter);
546
+ } else if (canonicalAst) {
547
+ filterStr = prettyFilter(
548
+ instantiateCanonicalFilter(canonicalAst, canonicalParams, aliasArgs)
549
+ );
524
550
  } else {
525
551
  filterStr =
526
552
  info.def || (pat?.filter ? prettyFilter(pat.filter) : "()");
527
553
  }
528
554
 
529
- const aliasArgs = info.aliasArgs || pat?.params || [];
530
555
  const argStr = aliasArgs.join(", ");
531
556
  const suffix =
532
557
  info.hash && !isHash ? ` -- ${info.hash}[${argStr}]` : "";
@@ -568,6 +593,142 @@ function listPatternAliases(state) {
568
593
  return aliases.join("\n");
569
594
  }
570
595
 
596
+ function collectRelFilterPairs(exp, pairs = []) {
597
+ if (!exp) return pairs;
598
+ switch (exp.op) {
599
+ case "filter":
600
+ if (exp.patterns?.length >= 2) {
601
+ pairs.push([exp.patterns[0], exp.patterns[1]]);
602
+ }
603
+ break;
604
+ case "comp":
605
+ exp.comp.forEach((child) => collectRelFilterPairs(child, pairs));
606
+ break;
607
+ case "union":
608
+ exp.union.forEach((child) => collectRelFilterPairs(child, pairs));
609
+ break;
610
+ case "product":
611
+ exp.product.forEach(({ exp: child }) =>
612
+ collectRelFilterPairs(child, pairs)
613
+ );
614
+ break;
615
+ }
616
+ return pairs;
617
+ }
618
+
619
+ function registerRelationPatterns(state) {
620
+ if (!state?.rels) return;
621
+ if (!state.patterns) state.patterns = {};
622
+ const rels = reachableRelations(
623
+ state.rels,
624
+ Object.values(state.relAliases || {})
625
+ );
626
+ let registeredAny = false;
627
+ for (const rel of Object.values(rels)) {
628
+ if (rel._patternsRegistered) continue;
629
+ if (rel.typePatternGraph && rel.def?.patterns?.length >= 2) {
630
+ const pairs = [
631
+ [rel.def.patterns[0], rel.def.patterns[1]],
632
+ ...collectRelFilterPairs(rel.def)
633
+ ];
634
+ for (const pair of pairs) {
635
+ canonicalBoundaryFilterSources(rel.typePatternGraph, pair, {
636
+ libraries: [stateLibrary(state)],
637
+ patterns: state.patterns,
638
+ registerPatterns: state.patterns,
639
+ maxPatLength: state.maxPatLength
640
+ });
641
+ }
642
+ registeredAny = true;
643
+ }
644
+ Object.defineProperty(rel, "_patternsRegistered", {
645
+ value: true,
646
+ configurable: true
647
+ });
648
+ }
649
+ if (registeredAny) {
650
+ state.codes = codes.dump();
651
+ }
652
+ }
653
+
654
+ function listAllPatterns(state) {
655
+ registerRelationPatterns(state);
656
+ const byHash = new Map();
657
+ const names = [
658
+ ...new Set([
659
+ ...Object.keys(state?.patternAliases || {}),
660
+ ...Object.keys(state?.patterns || {})
661
+ ])
662
+ ].filter((name) => !name.startsWith("@")).sort();
663
+
664
+ for (const name of names) {
665
+ const pat =
666
+ state?.patterns?.[name] ||
667
+ (state?.patternAliases?.[name]
668
+ ? state?.patterns?.[state.patternAliases[name]]
669
+ : null);
670
+ const info = resolvePatternCanonicalInfo(state, name, pat);
671
+ const hash =
672
+ info?.hash || state?.patternAliases?.[name] || null;
673
+ if (!hash) continue;
674
+ const canonicalPat = state?.patterns?.[hash];
675
+ if (!byHash.has(hash)) {
676
+ const canonicalParams =
677
+ info?.canonicalParams ||
678
+ canonicalPat?._graphParams ||
679
+ canonicalPat?.params ||
680
+ state?.meta?.[hash]?.params ||
681
+ [];
682
+ const def =
683
+ info?.def ||
684
+ canonicalPat?._canonicalDef ||
685
+ (canonicalPat?.filter ? prettyFilter(canonicalPat.filter) : "()");
686
+ byHash.set(hash, { canonicalParams, def, aliases: [] });
687
+ }
688
+ const formalParams = pat?.params || [];
689
+ const paramStr =
690
+ formalParams.length > 0
691
+ ? `[${formalParams.join(",")}]`
692
+ : "[]";
693
+ const args = info?.aliasArgs || formalParams;
694
+ const argStr =
695
+ args.length > 0
696
+ ? `[${args.join(",")}]`
697
+ : "[]";
698
+ byHash.get(hash).aliases.push(`${name}${paramStr} = @${argStr}`);
699
+ }
700
+
701
+ for (const [key, pat] of Object.entries(state?.patterns || {})) {
702
+ if (!key.startsWith("@") || byHash.has(key)) continue;
703
+ const info = resolvePatternCanonicalInfo(state, key, pat);
704
+ const canonicalParams =
705
+ info?.canonicalParams ||
706
+ pat?._graphParams ||
707
+ pat?.params ||
708
+ state?.meta?.[key]?.params ||
709
+ [];
710
+ const def =
711
+ info?.def ||
712
+ pat?._canonicalDef ||
713
+ (pat?.filter ? prettyFilter(pat.filter) : "()");
714
+ byHash.set(key, { canonicalParams, def, aliases: [] });
715
+ }
716
+
717
+ if (byHash.size === 0) return "(none)";
718
+ const lines = [];
719
+ for (const hash of [...byHash.keys()].sort()) {
720
+ const { canonicalParams, def, aliases } = byHash.get(hash);
721
+ const paramStr =
722
+ canonicalParams.length > 0
723
+ ? `[${canonicalParams.join(",")}]`
724
+ : "[]";
725
+ const suffix =
726
+ aliases.length > 0 ? ` -- ${aliases.join(", ")}` : "";
727
+ lines.push(`${hash}${paramStr} = ${def};${suffix}`);
728
+ }
729
+ return lines.join("\n");
730
+ }
731
+
571
732
  function listPatterns(stateOrPatterns) {
572
733
  if (
573
734
  stateOrPatterns &&
@@ -700,9 +861,13 @@ function libraryOriginsFromSource(source, fullSource, lib, options) {
700
861
  const pat = parsed.defs?.patterns?.[name];
701
862
  if (!pat) continue;
702
863
  const info = canonicalPatternInfo(name, pat, {
703
- libraries: options.libraries,
864
+ libraries: [
865
+ ...(options.libraries || []),
866
+ ...(lib ? [lib] : [])
867
+ ],
704
868
  patterns: {
705
869
  ...(options.patterns || {}),
870
+ ...(lib?.patterns || {}),
706
871
  ...(parsed.defs?.patterns || {})
707
872
  }
708
873
  });
@@ -1181,6 +1346,16 @@ function resolveKFilePath(filePath) {
1181
1346
  const fromRepo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), filePath);
1182
1347
  if (fs.existsSync(fromRepo)) return fromRepo;
1183
1348
  } catch {}
1349
+ if (!filePath.startsWith("lib/") && !filePath.startsWith("Examples/")) {
1350
+ const withLib = `lib/${filePath}`;
1351
+ try {
1352
+ if (fs.existsSync(withLib)) return withLib;
1353
+ } catch {}
1354
+ try {
1355
+ const fromRepoLib = path.resolve(path.dirname(fileURLToPath(import.meta.url)), withLib);
1356
+ if (fs.existsSync(fromRepoLib)) return fromRepoLib;
1357
+ } catch {}
1358
+ }
1184
1359
  const withEx = filePath.startsWith("Examples/") ? filePath : `Examples/${filePath}`;
1185
1360
  try {
1186
1361
  if (fs.existsSync(withEx)) return withEx;
@@ -1189,14 +1364,18 @@ function resolveKFilePath(filePath) {
1189
1364
  const fromRepoEx = path.resolve(path.dirname(fileURLToPath(import.meta.url)), withEx);
1190
1365
  if (fs.existsSync(fromRepoEx)) return fromRepoEx;
1191
1366
  } catch {}
1192
- const strippedEx = filePath.startsWith("Examples/") ? filePath.slice("Examples/".length) : filePath;
1367
+ const stripped = filePath.startsWith("lib/")
1368
+ ? filePath.slice("lib/".length)
1369
+ : filePath.startsWith("Examples/")
1370
+ ? filePath.slice("Examples/".length)
1371
+ : filePath;
1193
1372
  try {
1194
- if (fs.existsSync(strippedEx)) return strippedEx;
1373
+ if (fs.existsSync(stripped)) return stripped;
1195
1374
  } catch {}
1196
1375
  try {
1197
1376
  const fromRepoStripped = path.resolve(
1198
1377
  path.dirname(fileURLToPath(import.meta.url)),
1199
- strippedEx
1378
+ stripped
1200
1379
  );
1201
1380
  if (fs.existsSync(fromRepoStripped)) return fromRepoStripped;
1202
1381
  } catch {}
@@ -1215,8 +1394,10 @@ function loadSourceOrKlib(state, targetPath, options = {}) {
1215
1394
  } else {
1216
1395
  restoreCodes(state);
1217
1396
  const source = fs.readFileSync(loadPath, "utf8");
1397
+ const headerUses = parseHeaderUses(source);
1398
+ const usePreamble = buildUsePreamble(headerUses, [stateLibrary(state)]);
1218
1399
  const preamble = aliasPreamble(state, definedNamesInSource(source));
1219
- const fullSource = [preamble, source].filter(Boolean).join("\n");
1400
+ const fullSource = [preamble, usePreamble, source].filter(Boolean).join("\n");
1220
1401
  const compileOptions = {
1221
1402
  source: targetPath,
1222
1403
  libraries: [stateLibrary(state)],
@@ -1230,13 +1411,22 @@ function loadSourceOrKlib(state, targetPath, options = {}) {
1230
1411
  lib,
1231
1412
  compileOptions
1232
1413
  );
1414
+ const { patternNames } = userDefinedNames(source);
1415
+ const definedSet = new Set(patternNames);
1416
+ const patterns = { ...(state.patterns || {}) };
1417
+ for (const [k, v] of Object.entries(lib.patterns || {})) {
1418
+ if (k.startsWith("@") || definedSet.has(k) || !(k in patterns)) {
1419
+ patterns[k] = v;
1420
+ }
1421
+ }
1233
1422
  mergeLibrary(
1234
1423
  state,
1235
1424
  {
1236
1425
  ...lib,
1237
1426
  relAlias,
1238
1427
  patternAlias,
1239
- meta
1428
+ meta,
1429
+ patterns
1240
1430
  },
1241
1431
  targetPath,
1242
1432
  { loadAliases }
@@ -1312,10 +1502,13 @@ function compileSnippetArtifacts(source, state, sourceName = "<repl>") {
1312
1502
  );
1313
1503
  const annotated = annotateWithOptionalIdentity(fullSource, options);
1314
1504
  const { patternNames } = userDefinedNames(source);
1315
- const patterns = {
1316
- ...(state.patterns || {}),
1317
- ...(lib.patterns || {})
1318
- };
1505
+ const definedSet = new Set(patternNames);
1506
+ const patterns = { ...(state.patterns || {}) };
1507
+ for (const [k, v] of Object.entries(lib.patterns || {})) {
1508
+ if (k.startsWith("@") || definedSet.has(k) || !(k in patterns)) {
1509
+ patterns[k] = v;
1510
+ }
1511
+ }
1319
1512
  return {
1320
1513
  annotated,
1321
1514
  lib: {
@@ -1641,6 +1834,10 @@ async function evaluateCommand(line, state) {
1641
1834
  }
1642
1835
  }
1643
1836
  }
1837
+ if (!pat) {
1838
+ registerRelationPatterns(state);
1839
+ pat = state.patterns?.[patternName];
1840
+ }
1644
1841
  } else {
1645
1842
  pat = state.patterns?.[patternName];
1646
1843
  if (!pat && state.patternAliases?.[patternName]) {
@@ -1654,7 +1851,13 @@ async function evaluateCommand(line, state) {
1654
1851
  }
1655
1852
  case "patterns":
1656
1853
  case "pats":
1854
+ restoreCodes(state);
1657
1855
  return [listPatternAliases(state)];
1856
+ case "all-patterns":
1857
+ case "all-pats":
1858
+ case "all-pat":
1859
+ restoreCodes(state);
1860
+ return [listAllPatterns(state)];
1658
1861
  case "codec":
1659
1862
  case "codecs":
1660
1863
  return loadCodec(arg, state);
@@ -1774,8 +1977,9 @@ function helpText() {
1774
1977
  ":rels list relation aliases",
1775
1978
  ":pattern name show named pattern definition (alias :pat)",
1776
1979
  ":patterns list pattern aliases (alias :pats)",
1980
+ ":all-patterns list canonical patterns and aliases (alias :all-pat)",
1777
1981
  ":limit [num|none] set maximum characters for value output",
1778
- ":max-pat-length [n|none] max inline pattern length in :rel (default 30)",
1982
+ ":max-pat-length [n|none] max inline pattern length in :rel (default 45)",
1779
1983
  ":codec load file load a codec module from file",
1780
1984
  ":codec unload name unload a registered codec",
1781
1985
  ":codec list list loaded codecs (or simply :codecs)",
@@ -1814,7 +2018,7 @@ function cliUsage() {
1814
2018
  console.log(" --js Shortcut for --engine=js.");
1815
2019
  console.log(" --limit=<num> Set maximum characters for output.");
1816
2020
  console.log(" --max-pat-length=<num> Set max inline pattern length in :rel");
1817
- console.log(" (default: 30).");
2021
+ console.log(" (default: 45).");
1818
2022
  console.log(" -h, --help Show this help.");
1819
2023
  }
1820
2024
 
@@ -2031,5 +2235,6 @@ export {
2031
2235
  patternFromFilter,
2032
2236
  prettyPattern,
2033
2237
  resolvePatternCanonicalName,
2034
- listPatterns
2238
+ listPatterns,
2239
+ listAllPatterns
2035
2240
  };
@@ -8,9 +8,9 @@ import { performance } from "node:perf_hooks";
8
8
 
9
9
  const DEFAULT_EXAMPLES = [
10
10
  "Examples/nat.k",
11
- "Examples/list.k",
12
- "Examples/arithmetics.k",
13
- "Examples/ieee.k",
11
+ "lib/list.k",
12
+ "lib/arithmetics.k",
13
+ "lib/ieee.k",
14
14
  "Examples/ieee-arithmetics.k"
15
15
  ];
16
16
 
@@ -24,8 +24,8 @@ for K source files through the .klib object format.
24
24
  Arguments:
25
25
  example.k ...
26
26
  One or more .k source files to benchmark.
27
- (default: Examples/nat.k Examples/list.k
28
- Examples/arithmetics.k Examples/ieee.k
27
+ (default: Examples/nat.k lib/list.k
28
+ lib/arithmetics.k lib/ieee.k
29
29
  Examples/ieee-arithmetics.k)
30
30
 
31
31
  Options:
@@ -83,17 +83,24 @@ for (const example of benchmarkExamples) {
83
83
  for (let i = 0; i < iterations; i++) {
84
84
  const out = mkdtempSync(join(tmpdir(), `k-idempotency-bench-${example.replaceAll("/", "_")}-`));
85
85
  try {
86
- const isIEEE = resolve(example) === resolve("Examples/ieee.k");
87
- const isArithmetic = resolve(example) === resolve("Examples/ieee-arithmetics.k");
86
+ const depsByTarget = new Map([
87
+ [resolve("lib/bits.k"), ["lib/bit.k"]],
88
+ [resolve("lib/arithmetics.k"), ["lib/bit.k", "lib/bits.k"]],
89
+ [resolve("Examples/arithmetics.k"), ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"]],
90
+ [resolve("lib/list.k"), ["lib/bit.k", "lib/bits.k"]],
91
+ [resolve("Examples/poly.k"), ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k", "lib/list.k"]],
92
+ [resolve("lib/btrie.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k"]],
93
+ [resolve("lib/string.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k"]],
94
+ [resolve("lib/ieee.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k"]],
95
+ [resolve("lib/djson.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k", "lib/ieee.k"]],
96
+ [resolve("Examples/ieee-arithmetics.k"), ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k", "lib/ieee.k"]]
97
+ ]);
98
+ const deps = depsByTarget.get(resolve(example)) || [];
88
99
  let dependency;
89
- if (isIEEE || isArithmetic) {
90
- dependency = join(out, "core.klib");
91
- run(["objects/compile.mjs", "core.k", dependency]);
92
- }
93
- if (isArithmetic) {
94
- const ieee = join(out, "ieee.klib");
95
- run(["objects/compile.mjs", "--lib", dependency, "Examples/ieee.k", ieee]);
96
- dependency = ieee;
100
+ for (const [idx, dep] of deps.entries()) {
101
+ const nextDep = join(out, `dep-${idx}.klib`);
102
+ run(["objects/compile.mjs", ...(dependency ? ["--lib", dependency] : []), dep, nextDep]);
103
+ dependency = nextDep;
97
104
  }
98
105
  const library = dependency ? ["--lib", dependency] : [];
99
106
  const t0 = performance.now();