@fraczak/k 8.6.1 → 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 +22 -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 +13 -7
  7. package/Examples/arithmetics.k +81 -468
  8. package/Examples/ieee-arithmetics.k +37 -33
  9. package/Examples/poly.k +107 -104
  10. package/README.md +19 -11
  11. package/backend-api.mjs +3 -1
  12. package/backends/llvm/README.md +1 -1
  13. package/backends/llvm/bin/k-llvm-build.mjs +5 -5
  14. package/backends/llvm/bin/k-llvm-compile.mjs +4 -4
  15. package/backends/llvm/bin/k-llvm.mjs +6 -6
  16. package/backends/llvm/src/cli.mjs +17 -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 +217 -57
  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 +51 -9
  40. package/objects/README.md +10 -3
  41. package/objects/compile.mjs +10 -8
  42. package/package.json +1 -1
  43. package/repl.mjs +28 -6
  44. package/scripts/benchmark-idempotency.mjs +22 -15
  45. package/scripts/benchmark.mjs +29 -10
  46. package/scripts/build-repl-html.mjs +41 -13
  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 +50 -35
  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 = {};
@@ -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.1",
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
@@ -40,7 +40,9 @@ import {
40
40
  encodeLibrary,
41
41
  hydrateObject,
42
42
  loadLibrary,
43
- prettyRelation
43
+ prettyRelation,
44
+ buildUsePreamble,
45
+ parseHeaderUses
44
46
  } from "./object.mjs";
45
47
  import {
46
48
  propertyListToFilter,
@@ -859,9 +861,13 @@ function libraryOriginsFromSource(source, fullSource, lib, options) {
859
861
  const pat = parsed.defs?.patterns?.[name];
860
862
  if (!pat) continue;
861
863
  const info = canonicalPatternInfo(name, pat, {
862
- libraries: options.libraries,
864
+ libraries: [
865
+ ...(options.libraries || []),
866
+ ...(lib ? [lib] : [])
867
+ ],
863
868
  patterns: {
864
869
  ...(options.patterns || {}),
870
+ ...(lib?.patterns || {}),
865
871
  ...(parsed.defs?.patterns || {})
866
872
  }
867
873
  });
@@ -1340,6 +1346,16 @@ function resolveKFilePath(filePath) {
1340
1346
  const fromRepo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), filePath);
1341
1347
  if (fs.existsSync(fromRepo)) return fromRepo;
1342
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
+ }
1343
1359
  const withEx = filePath.startsWith("Examples/") ? filePath : `Examples/${filePath}`;
1344
1360
  try {
1345
1361
  if (fs.existsSync(withEx)) return withEx;
@@ -1348,14 +1364,18 @@ function resolveKFilePath(filePath) {
1348
1364
  const fromRepoEx = path.resolve(path.dirname(fileURLToPath(import.meta.url)), withEx);
1349
1365
  if (fs.existsSync(fromRepoEx)) return fromRepoEx;
1350
1366
  } catch {}
1351
- 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;
1352
1372
  try {
1353
- if (fs.existsSync(strippedEx)) return strippedEx;
1373
+ if (fs.existsSync(stripped)) return stripped;
1354
1374
  } catch {}
1355
1375
  try {
1356
1376
  const fromRepoStripped = path.resolve(
1357
1377
  path.dirname(fileURLToPath(import.meta.url)),
1358
- strippedEx
1378
+ stripped
1359
1379
  );
1360
1380
  if (fs.existsSync(fromRepoStripped)) return fromRepoStripped;
1361
1381
  } catch {}
@@ -1374,8 +1394,10 @@ function loadSourceOrKlib(state, targetPath, options = {}) {
1374
1394
  } else {
1375
1395
  restoreCodes(state);
1376
1396
  const source = fs.readFileSync(loadPath, "utf8");
1397
+ const headerUses = parseHeaderUses(source);
1398
+ const usePreamble = buildUsePreamble(headerUses, [stateLibrary(state)]);
1377
1399
  const preamble = aliasPreamble(state, definedNamesInSource(source));
1378
- const fullSource = [preamble, source].filter(Boolean).join("\n");
1400
+ const fullSource = [preamble, usePreamble, source].filter(Boolean).join("\n");
1379
1401
  const compileOptions = {
1380
1402
  source: targetPath,
1381
1403
  libraries: [stateLibrary(state)],
@@ -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();
@@ -159,15 +159,32 @@ function sourceNameForSuite(suite) {
159
159
  }
160
160
 
161
161
  let ieeeDependencies;
162
+ let arithDependencies;
162
163
  function dependenciesForSuite(suite) {
163
- if (suite !== "ieee") return [];
164
- if (!ieeeDependencies) {
165
- const core = loadLibrary(compileLibrary(fs.readFileSync(path.join(kRoot, "core.k"), "utf8")));
166
- ieeeDependencies = [loadLibrary(compileLibrary(fs.readFileSync(path.join(kRoot, "Examples/ieee.k"), "utf8"), {
167
- libraries: [core]
168
- }))];
164
+ if (suite === "ieee") {
165
+ if (!ieeeDependencies) {
166
+ let prev = null;
167
+ for (const f of ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k", "lib/ieee.k"]) {
168
+ prev = loadLibrary(compileLibrary(fs.readFileSync(path.join(kRoot, f), "utf8"), {
169
+ source: f,
170
+ libraries: prev ? [prev] : []
171
+ }));
172
+ }
173
+ ieeeDependencies = [prev];
174
+ }
175
+ return ieeeDependencies;
169
176
  }
170
- return ieeeDependencies;
177
+ if (!arithDependencies) {
178
+ let prev = null;
179
+ for (const f of ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"]) {
180
+ prev = loadLibrary(compileLibrary(fs.readFileSync(path.join(kRoot, f), "utf8"), {
181
+ source: f,
182
+ libraries: prev ? [prev] : []
183
+ }));
184
+ }
185
+ arithDependencies = [prev];
186
+ }
187
+ return arithDependencies;
171
188
  }
172
189
 
173
190
  function stripTrailingUnitMain(source) {
@@ -472,9 +489,11 @@ async function prepareBackendRunner(job, relation, inputVal, state) {
472
489
 
473
490
  async function prepareState(suite) {
474
491
  const state = createState();
475
- if (suite === "ieee") {
476
- await evaluateInput(`:load ${path.join(kRoot, "core.k")}`, state);
477
- await evaluateInput(`:load ${path.join(kRoot, "Examples/ieee.k")}`, state);
492
+ const deps = suite === "ieee"
493
+ ? ["lib/bit.k", "lib/bits.k", "lib/list.k", "lib/btrie.k", "lib/string.k", "lib/ieee.k"]
494
+ : ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"];
495
+ for (const dep of deps) {
496
+ await evaluateInput(`:load ${path.join(kRoot, dep)}`, state);
478
497
  }
479
498
  await evaluateInput(`:load ${suiteSourcePath(suite)}`, state);
480
499
  return state;
@@ -78,21 +78,41 @@ if (fs.existsSync(coreKPath)) {
78
78
  vfsFiles["core.k"] = fs.readFileSync(coreKPath, "utf8");
79
79
  }
80
80
 
81
- // Add verified k-code files
82
- const verifiedExamples = [
81
+ // Add verified lib/ k-code files
82
+ const verifiedLibs = [
83
+ "bit.k",
84
+ "bits.k",
83
85
  "arithmetics.k",
86
+ "list.k",
87
+ "btrie.k",
88
+ "string.k",
84
89
  "ieee.k",
85
- "ieee-arithmetics.k",
86
- "poly.k",
87
- "karatsuba-mult.k",
88
90
  "djson.k"
89
91
  ];
92
+ const libDir = path.join(projectRoot, "lib");
93
+ for (const filename of verifiedLibs) {
94
+ const fullPath = path.join(libDir, filename);
95
+ if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
96
+ const content = fs.readFileSync(fullPath, "utf8");
97
+ vfsFiles[filename] = content;
98
+ vfsFiles[`lib/${filename}`] = content;
99
+ }
100
+ }
101
+
102
+ // Add verified Examples/ k-code files
103
+ const verifiedExamples = [
104
+ "arithmetics.k",
105
+ "ieee-arithmetics.k",
106
+ "poly.k"
107
+ ];
90
108
  const examplesDir = path.join(projectRoot, "Examples");
91
109
  for (const filename of verifiedExamples) {
92
110
  const fullPath = path.join(examplesDir, filename);
93
111
  if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
94
112
  const content = fs.readFileSync(fullPath, "utf8");
95
- vfsFiles[filename] = content;
113
+ if (!(filename in vfsFiles)) {
114
+ vfsFiles[filename] = content;
115
+ }
96
116
  vfsFiles[`Examples/${filename}`] = content;
97
117
  }
98
118
  }
@@ -1688,14 +1708,22 @@ const htmlContent = `<!DOCTYPE html>
1688
1708
  <div class="control-group">
1689
1709
  <select id="example-select" title="Choose an example or expression">
1690
1710
  <option value="">-- Example / Expression --</option>
1691
- <optgroup label="Standard Examples">
1711
+ <optgroup label="Standard Libraries (lib/)">
1712
+ <option value="lib/bit.k">lib/bit.k</option>
1713
+ <option value="lib/bits.k">lib/bits.k</option>
1714
+ <option value="lib/arithmetics.k">lib/arithmetics.k</option>
1715
+ <option value="lib/list.k">lib/list.k</option>
1716
+ <option value="lib/btrie.k">lib/btrie.k</option>
1717
+ <option value="lib/string.k">lib/string.k</option>
1718
+ <option value="lib/ieee.k">lib/ieee.k</option>
1719
+ <option value="lib/djson.k">lib/djson.k</option>
1720
+ </optgroup>
1721
+ <optgroup label="Examples">
1692
1722
  <option value="core.k">core.k</option>
1693
- <option value="arithmetics.k">arithmetics.k</option>
1694
- <option value="ieee.k">ieee.k</option>
1695
- <option value="ieee-arithmetics.k">ieee-arithmetics.k</option>
1696
- <option value="poly.k">poly.k</option>
1697
- <option value="karatsuba-mult.k">karatsuba-mult.k</option>
1698
- <option value="djson.k">djson.k</option>
1723
+ <option value="Examples/nat.k">Examples/nat.k</option>
1724
+ <option value="Examples/arithmetics.k">Examples/arithmetics.k</option>
1725
+ <option value="Examples/poly.k">Examples/poly.k</option>
1726
+ <option value="Examples/ieee-arithmetics.k">Examples/ieee-arithmetics.k</option>
1699
1727
  </optgroup>
1700
1728
  <optgroup label="Quick Expressions">
1701
1729
  <option value="expr:{} | ok">{} | ok</option>
@@ -223,7 +223,15 @@ function pkirLaneName() {
223
223
 
224
224
  console.log("==> Initializing IEEE types and arithmetic");
225
225
  const state = createState();
226
- for (const name of ["core.k", "Examples/ieee.k", "Examples/ieee-arithmetics.k"]) {
226
+ for (const name of [
227
+ "lib/bit.k",
228
+ "lib/bits.k",
229
+ "lib/list.k",
230
+ "lib/btrie.k",
231
+ "lib/string.k",
232
+ "lib/ieee.k",
233
+ "Examples/ieee-arithmetics.k"
234
+ ]) {
227
235
  await evaluateInput(`:load ${fileURLToPath(import.meta.resolve(`@fraczak/k/${name}`))}`, state);
228
236
  }
229
237
 
@@ -202,10 +202,11 @@ function pkirLaneName() {
202
202
  return "PKIR (Wasm persistent)";
203
203
  }
204
204
 
205
- console.log("==> Initializing state and loading @fraczak/k/Examples/arithmetics.k");
205
+ console.log("==> Initializing state and loading @fraczak/k/lib/arithmetics.k");
206
206
  const state = createState();
207
- const arithmeticsPath = fileURLToPath(import.meta.resolve("@fraczak/k/Examples/arithmetics.k"));
208
- await evaluateInput(`:load ${arithmeticsPath}`, state);
207
+ for (const relPath of ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"]) {
208
+ await evaluateInput(`:load ${fileURLToPath(import.meta.resolve(`@fraczak/k/${relPath}`))}`, state);
209
+ }
209
210
 
210
211
  for (const op of ops) {
211
212
  await evaluateInput(`${benchNames[op]} = {inc x, () y} ${op};`, state);
@@ -217,13 +218,10 @@ function intValue(text) {
217
218
 
218
219
  console.log("==> Preparing relations");
219
220
  const relations = {};
220
- const arithmeticsSource = fs.readFileSync(arithmeticsPath, "utf8");
221
- const arithmeticsLibrarySource = arithmeticsSource.replace(/\s*\(\)\s*$/, "\n");
222
221
  for (const op of ops) {
223
222
  const name = benchNames[op];
224
223
  relations[op] = prepareRelation(state, name, {
225
- source: `${arithmeticsLibrarySource}\n${name} = {inc x, () y} ${op};\n${name}`,
226
- sourceLabel: `@fraczak/k/Examples/arithmetics.k#${name}`
224
+ sourceLabel: `@fraczak/k/lib/arithmetics.k#${name}`
227
225
  });
228
226
  }
229
227
  codes.load(state.codes);
@@ -776,12 +774,10 @@ const squaringStepTimeoutMs = parsePositiveIntEnv("SQUARING_STEP_TIMEOUT_MS", 60
776
774
  console.log("\n=================== SQUARING SCALE & MEMORY BENCHMARK ===================");
777
775
  console.log(`Algorithms: times vs karatsuba (${squaringSteps} successive squarings doubling bit length)`);
778
776
 
779
- // Load and initialize Karatsuba multiplication relation
780
- const karatsubaPath = fileURLToPath(import.meta.resolve("@fraczak/k/Examples/karatsuba-mult.k"));
781
- const karatsubaSource = fs.readFileSync(karatsubaPath, "utf8");
782
- const karatsubaLibrarySource = karatsubaSource.replace(/\s*\(\)\s*$/, "\n");
783
777
  const stateKara = createState();
784
- await evaluateInput(`:load ${karatsubaPath}`, stateKara);
778
+ for (const relPath of ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k"]) {
779
+ await evaluateInput(`:load ${fileURLToPath(import.meta.resolve(`@fraczak/k/${relPath}`))}`, stateKara);
780
+ }
785
781
  codes.load(stateKara.codes);
786
782
 
787
783
  const sInitialVal = intValue(squaringInputText);
@@ -793,8 +789,7 @@ const squaringAlgos = [
793
789
  name: "times",
794
790
  title: "Long Multiplication (times)",
795
791
  expr: "s = {()x,()y}times;",
796
- librarySource: arithmeticsLibrarySource,
797
- sourceLabel: "@fraczak/k/Examples/arithmetics.k#s",
792
+ sourceLabel: "@fraczak/k/lib/arithmetics.k#s",
798
793
  state: state,
799
794
  relName: "s"
800
795
  },
@@ -803,8 +798,7 @@ const squaringAlgos = [
803
798
  name: "karatsuba",
804
799
  title: "Karatsuba Multiplication (karatsuba)",
805
800
  expr: "s = {()x,()y}karatsuba;",
806
- librarySource: karatsubaLibrarySource,
807
- sourceLabel: "@fraczak/k/Examples/karatsuba-mult.k#s",
801
+ sourceLabel: "@fraczak/k/lib/arithmetics.k#s",
808
802
  state: stateKara,
809
803
  relName: "s"
810
804
  }
@@ -815,7 +809,6 @@ for (const algo of squaringAlgos) {
815
809
  await evaluateInput(algo.expr, algo.state);
816
810
  codes.load(algo.state.codes);
817
811
  algo.rel = prepareRelation(algo.state, algo.relName, {
818
- source: `${algo.librarySource}\n${algo.expr}\n${algo.relName}`,
819
812
  sourceLabel: algo.sourceLabel
820
813
  });
821
814
 
@@ -231,14 +231,11 @@ console.log(
231
231
  console.log("-".repeat(72) + "\n");
232
232
 
233
233
  // 1. Map algorithms to their source files
234
- const algoFiles = {
235
- times: fileURLToPath(
236
- import.meta.resolve("../Examples/arithmetics.k")
237
- ),
238
- karatsuba: fileURLToPath(
239
- import.meta.resolve("../Examples/karatsuba-mult.k")
240
- )
241
- };
234
+ const arithLibChain = [
235
+ fileURLToPath(import.meta.resolve("../lib/bit.k")),
236
+ fileURLToPath(import.meta.resolve("../lib/bits.k")),
237
+ fileURLToPath(import.meta.resolve("../lib/arithmetics.k"))
238
+ ];
242
239
 
243
240
  const cacheDir = makeCacheDir("k-mult-perf-");
244
241
 
@@ -250,12 +247,12 @@ const algoServers = { llvm: {}, "llvm-pkir": {}, wasm: {}, pkir: {} };
250
247
  let commonState = null;
251
248
 
252
249
  for (const algo of selectedAlgos) {
253
- const filePath = algoFiles[algo] || algoFiles.times;
254
- const rawSource = fs.readFileSync(filePath, "utf8");
255
- const libSource = rawSource.replace(/\s*\(\)\s*$/, "\n");
250
+ const filePath = arithLibChain[arithLibChain.length - 1];
256
251
 
257
252
  const algoState = createState();
258
- await evaluateInput(`:load ${filePath}`, algoState);
253
+ for (const libPath of arithLibChain) {
254
+ await evaluateInput(`:load ${libPath}`, algoState);
255
+ }
259
256
  codes.load(algoState.codes);
260
257
 
261
258
  if (!commonState) commonState = algoState;
@@ -264,10 +261,7 @@ for (const algo of selectedAlgos) {
264
261
  await evaluateInput(`${relName} = {()x, ()y} ${algo};`, algoState);
265
262
  codes.load(algoState.codes);
266
263
 
267
- const relSource =
268
- `${libSource}\n${relName} = {()x, ()y} ${algo};\n${relName}`;
269
264
  const prepared = prepareRelation(algoState, relName, {
270
- source: relSource,
271
265
  sourceLabel: `${filePath}#${relName}`
272
266
  });
273
267
  prepared.state = algoState;