@fraczak/k 8.6.1 → 8.7.1

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 (75) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/DOCS/CODECS.md +20 -14
  3. package/DOCS/FILE_FORMATS.md +53 -12
  4. package/DOCS/GETTING_STARTED.md +15 -8
  5. package/DOCS/PATTERNS.md +10 -0
  6. package/DOCS/REPL.md +12 -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 -15
  17. package/backends/llvm/tests/integration.sh +6 -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 +4 -4
  23. package/backends/wasm/tests/integration.sh +24 -4
  24. package/browser/shims/fs.mjs +19 -3
  25. package/canonical-pattern.mjs +214 -57
  26. package/compiler.mjs +26 -0
  27. package/core.k +2 -1
  28. package/harness/suites/poly.mjs +14 -30
  29. package/index.mjs +67 -2
  30. package/k.mjs +14 -18
  31. package/kir.mjs +3 -1
  32. package/kvm.mjs +11 -11
  33. package/lib/arithmetics.k +286 -0
  34. package/lib/bit.k +68 -0
  35. package/lib/bits.k +227 -0
  36. package/lib/btrie.k +187 -0
  37. package/lib/djson.k +327 -0
  38. package/lib/ieee.k +709 -0
  39. package/lib/list.k +49 -0
  40. package/lib/string.k +588 -0
  41. package/named-patterns.mjs +2 -14
  42. package/object.mjs +32 -7
  43. package/objects/README.md +9 -3
  44. package/objects/compile.mjs +11 -14
  45. package/package.json +1 -1
  46. package/repl.mjs +24 -5
  47. package/scripts/benchmark-idempotency.mjs +22 -15
  48. package/scripts/benchmark.mjs +29 -10
  49. package/scripts/build-repl-html.mjs +41 -13
  50. package/scripts/perf-ieee.mjs +9 -1
  51. package/scripts/perf-int.mjs +10 -17
  52. package/scripts/perf-multiplication.mjs +9 -15
  53. package/scripts/perf-poly.mjs +16 -32
  54. package/scripts/run-tests.mjs +3 -2
  55. package/scripts/test-package.mjs +13 -2
  56. package/tests/helpers/cli.mjs +19 -3
  57. package/tests/integration.sh +25 -5
  58. package/tests/test-arithmetics.mjs +4 -2
  59. package/tests/test-djson-methods.mjs +21 -12
  60. package/tests/test-ieee-arithmetic.mjs +11 -3
  61. package/tests/test-ieee-text.mjs +19 -4
  62. package/tests/test-k-object.mjs +15 -4
  63. package/tests/test-karatsuba.mjs +1 -1
  64. package/tests/test-kvm-polymorphic.mjs +58 -34
  65. package/tests/test-lib.mjs +117 -0
  66. package/tests/test-library-isolation.mjs +381 -0
  67. package/tests/test-named-patterns.mjs +21 -3
  68. package/tests/test-parse-json.mjs +44 -14
  69. package/tests/test-poly.mjs +10 -4
  70. package/tests/test-repl-html.mjs +18 -7
  71. package/tests/test-repl.mjs +50 -35
  72. package/Examples/djson.k +0 -894
  73. package/Examples/ieee.k +0 -969
  74. package/Examples/karatsuba-mult.k +0 -227
  75. 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
 
@@ -540,17 +542,35 @@ function compileLibrary(script, options = {}) {
540
542
  importedLibraryMeta(options.libraries),
541
543
  buildMeta(annotated, options.source || null, options)
542
544
  );
543
- const relAlias = serialized.relAlias || {};
545
+
546
+ const libRelAlias = {};
547
+ if (options.libraries) {
548
+ for (const lib of options.libraries) {
549
+ Object.assign(libRelAlias, lib.relAlias || {});
550
+ }
551
+ }
552
+ Object.assign(libRelAlias, serialized.relAlias || {});
544
553
 
545
554
  // Key rels by canonical hash, rewrite internal refs to canonical hashes
546
555
  const libRels = {};
556
+ if (options.libraries) {
557
+ for (const lib of options.libraries) {
558
+ const lr = lib.rels || lib.defs?.rels || {};
559
+ for (const [name, rel] of Object.entries(lr)) {
560
+ if (name !== "__main__") {
561
+ libRels[name] = rel;
562
+ }
563
+ }
564
+ }
565
+ }
547
566
  for (const [name, rel] of Object.entries(serialized.rels)) {
548
567
  if (name === "__main__") continue;
549
- const canonicalName = relAlias[name] || name;
568
+ if (rel._library) continue;
569
+ const canonicalName = libRelAlias[name] || name;
550
570
  const { varRefs, ...relWithoutVarRefs } = rel;
551
571
  libRels[canonicalName] = {
552
572
  ...relWithoutVarRefs,
553
- def: rewriteRefsToCanonical(rel.def, relAlias)
573
+ def: rewriteRefsToCanonical(rel.def, libRelAlias)
554
574
  };
555
575
  }
556
576
  const libPatterns = {};
@@ -614,11 +634,12 @@ function compileLibrary(script, options = {}) {
614
634
  format: "k-object",
615
635
  codes: allCodes,
616
636
  rels: libRels,
617
- relAlias: serialized.relAlias,
637
+ relAlias: libRelAlias,
618
638
  patternAlias,
619
639
  compileStats: serialized.compileStats,
620
640
  meta: libMeta,
621
641
  patterns: libPatterns,
642
+ source: options.source || null,
622
643
  main: null
623
644
  };
624
645
  }
@@ -1067,7 +1088,9 @@ export {
1067
1088
  decompileObjectBuffer,
1068
1089
  extractAliasesFromObject,
1069
1090
  extractAliasesFromObjectBuffer,
1070
- buildExportPreamble
1091
+ buildUsePreamble,
1092
+ parseHeaderDirectives,
1093
+ parseHeaderUses
1071
1094
  };
1072
1095
 
1073
1096
  export default {
@@ -1090,5 +1113,7 @@ export default {
1090
1113
  decompileObjectBuffer,
1091
1114
  extractAliasesFromObject,
1092
1115
  extractAliasesFromObjectBuffer,
1093
- buildExportPreamble
1116
+ buildUsePreamble,
1117
+ parseHeaderDirectives,
1118
+ parseHeaderUses
1094
1119
  };
package/objects/README.md CHANGED
@@ -19,9 +19,15 @@ 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 documented directly in the source file header via
26
+ `# --lib <dependency> --use <specs>` comments. When `--lib` is provided on the
27
+ command line, all library relations and patterns are available in memory during
28
+ compilation. CLI `--use` flags allow creating in-memory aliases when needed.
24
29
 
25
30
  The [file-format reference](../DOCS/FILE_FORMATS.md) is the source for container
26
- fields, executable/library distinctions, aliases, and complete workflows.
31
+ fields, executable/library distinctions, header directives, aliases, and
32
+ complete workflows.
27
33
  [KIR-P](../DOCS/KIR_V1.md) documents the portable backend export.
@@ -8,8 +8,7 @@ import {
8
8
  compileLibrary,
9
9
  compileLibraryBuffer,
10
10
  decodeObject,
11
- loadLibrary,
12
- buildExportPreamble
11
+ loadLibrary
13
12
  } from "../object.mjs";
14
13
  import { objectToKVMArtifact } from "../kvm.mjs";
15
14
 
@@ -34,7 +33,7 @@ function helpText() {
34
33
  " --format fmt Output format: ko, klib, or kvm.",
35
34
  " Overrides extension detection.",
36
35
  " --lib file Load one .klib or .k library before compiling.",
37
- " --export spec Export library alias into scope. Repeatable.",
36
+ " --use spec Use library alias in scope (repeatable).",
38
37
  " spec is 'name' or 'libname:localname'.",
39
38
  " -h, --help Show this help.",
40
39
  "",
@@ -50,7 +49,7 @@ function helpText() {
50
49
  ` ${prog} program.k -o program.ko`,
51
50
  ` ${prog} program.k program.klib`,
52
51
  ` ${prog} program.k program.kvm`,
53
- ` ${prog} --lib core.klib --export add program.k program.ko`
52
+ ` ${prog} --lib core.klib --use add program.k program.ko`
54
53
  ].join("\n");
55
54
  }
56
55
 
@@ -123,7 +122,7 @@ try {
123
122
  const libraries = [];
124
123
  let format = null;
125
124
  let explicitOutput = null;
126
- const exports = [];
125
+ const useSpecs = [];
127
126
 
128
127
  while (args.length > 0) {
129
128
  if (args[0] === "--") {
@@ -147,11 +146,11 @@ try {
147
146
  } else {
148
147
  libraries.push(loadLibrary(decodeObject(fs.readFileSync(libPath))));
149
148
  }
150
- } else if (args[0] === "--export") {
149
+ } else if (args[0] === "--use") {
151
150
  args.shift();
152
151
  const spec = args.shift();
153
- if (!spec) throw new Error("--export requires a spec argument (name or libname:localname)");
154
- exports.push(spec);
152
+ if (!spec) throw new Error("--use requires a spec argument (name or libname:localname)");
153
+ useSpecs.push(spec);
155
154
  } else if (args[0] === "--format") {
156
155
  args.shift();
157
156
  format = args.shift();
@@ -211,16 +210,14 @@ try {
211
210
  : input.kind === "inline"
212
211
  ? input.source
213
212
  : fs.readFileSync(input.path, "utf8");
214
- const preamble = buildExportPreamble(exports, libraries);
215
- const source = preamble + rawSource;
216
- const opts = { source: input.sourceName, libraries };
213
+ const opts = { source: input.sourceName, libraries, useSpecs };
217
214
 
218
215
  if (outputFormat === "ko") {
219
- output = compileObjectBuffer(source, opts);
216
+ output = compileObjectBuffer(rawSource, opts);
220
217
  } else if (outputFormat === "klib") {
221
- output = compileLibraryBuffer(source, opts);
218
+ output = compileLibraryBuffer(rawSource, opts);
222
219
  } else if (outputFormat === "kvm") {
223
- const object = decodeObject(compileObjectBuffer(source, opts));
220
+ const object = decodeObject(compileObjectBuffer(rawSource, opts));
224
221
  output = objectToKVM(object);
225
222
  }
226
223
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fraczak/k",
3
- "version": "8.6.1",
3
+ "version": "8.7.1",
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
@@ -859,9 +859,13 @@ function libraryOriginsFromSource(source, fullSource, lib, options) {
859
859
  const pat = parsed.defs?.patterns?.[name];
860
860
  if (!pat) continue;
861
861
  const info = canonicalPatternInfo(name, pat, {
862
- libraries: options.libraries,
862
+ libraries: [
863
+ ...(options.libraries || []),
864
+ ...(lib ? [lib] : [])
865
+ ],
863
866
  patterns: {
864
867
  ...(options.patterns || {}),
868
+ ...(lib?.patterns || {}),
865
869
  ...(parsed.defs?.patterns || {})
866
870
  }
867
871
  });
@@ -1340,6 +1344,16 @@ function resolveKFilePath(filePath) {
1340
1344
  const fromRepo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), filePath);
1341
1345
  if (fs.existsSync(fromRepo)) return fromRepo;
1342
1346
  } catch {}
1347
+ if (!filePath.startsWith("lib/") && !filePath.startsWith("Examples/")) {
1348
+ const withLib = `lib/${filePath}`;
1349
+ try {
1350
+ if (fs.existsSync(withLib)) return withLib;
1351
+ } catch {}
1352
+ try {
1353
+ const fromRepoLib = path.resolve(path.dirname(fileURLToPath(import.meta.url)), withLib);
1354
+ if (fs.existsSync(fromRepoLib)) return fromRepoLib;
1355
+ } catch {}
1356
+ }
1343
1357
  const withEx = filePath.startsWith("Examples/") ? filePath : `Examples/${filePath}`;
1344
1358
  try {
1345
1359
  if (fs.existsSync(withEx)) return withEx;
@@ -1348,14 +1362,18 @@ function resolveKFilePath(filePath) {
1348
1362
  const fromRepoEx = path.resolve(path.dirname(fileURLToPath(import.meta.url)), withEx);
1349
1363
  if (fs.existsSync(fromRepoEx)) return fromRepoEx;
1350
1364
  } catch {}
1351
- const strippedEx = filePath.startsWith("Examples/") ? filePath.slice("Examples/".length) : filePath;
1365
+ const stripped = filePath.startsWith("lib/")
1366
+ ? filePath.slice("lib/".length)
1367
+ : filePath.startsWith("Examples/")
1368
+ ? filePath.slice("Examples/".length)
1369
+ : filePath;
1352
1370
  try {
1353
- if (fs.existsSync(strippedEx)) return strippedEx;
1371
+ if (fs.existsSync(stripped)) return stripped;
1354
1372
  } catch {}
1355
1373
  try {
1356
1374
  const fromRepoStripped = path.resolve(
1357
1375
  path.dirname(fileURLToPath(import.meta.url)),
1358
- strippedEx
1376
+ stripped
1359
1377
  );
1360
1378
  if (fs.existsSync(fromRepoStripped)) return fromRepoStripped;
1361
1379
  } catch {}
@@ -1374,7 +1392,8 @@ function loadSourceOrKlib(state, targetPath, options = {}) {
1374
1392
  } else {
1375
1393
  restoreCodes(state);
1376
1394
  const source = fs.readFileSync(loadPath, "utf8");
1377
- const preamble = aliasPreamble(state, definedNamesInSource(source));
1395
+ const usedNames = new Set(definedNamesInSource(source));
1396
+ const preamble = aliasPreamble(state, usedNames);
1378
1397
  const fullSource = [preamble, source].filter(Boolean).join("\n");
1379
1398
  const compileOptions = {
1380
1399
  source: targetPath,
@@ -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;
@@ -193,48 +193,32 @@ function pkirLaneName() {
193
193
  }
194
194
 
195
195
 
196
- console.log("==> Loading @fraczak/k/Examples/arithmetics.k as library");
197
- const arithmeticsPath = fileURLToPath(import.meta.resolve("@fraczak/k/Examples/arithmetics.k"));
198
- const arithmeticsSource = fs.readFileSync(arithmeticsPath, "utf8");
199
- const arithmeticsLib = loadLibrary(compileLibrary(arithmeticsSource, { source: arithmeticsPath }));
196
+ console.log("==> Loading @fraczak/k/lib/{bit,bits,arithmetics,list}.k as libraries");
197
+ let depLib = null;
198
+ for (const relPath of ["lib/bit.k", "lib/bits.k", "lib/arithmetics.k", "lib/list.k"]) {
199
+ const filePath = fileURLToPath(import.meta.resolve(`@fraczak/k/${relPath}`));
200
+ depLib = loadLibrary(compileLibrary(fs.readFileSync(filePath, "utf8"), {
201
+ source: filePath,
202
+ libraries: depLib ? [depLib] : []
203
+ }));
204
+ }
200
205
 
201
- console.log("==> Compiling @fraczak/k/Examples/poly.k with explicit library exports");
206
+ console.log("==> Compiling @fraczak/k/Examples/poly.k with library dependencies");
202
207
  const polyPath = fileURLToPath(import.meta.resolve("@fraczak/k/Examples/poly.k"));
203
208
  const polySource = fs.readFileSync(polyPath, "utf8");
204
-
205
- function buildExportPreamble(exports, libraries) {
206
- const aliasMap = {};
207
- for (const lib of libraries) {
208
- for (const [name, hash] of Object.entries(lib.relAlias || {})) {
209
- if (name !== "__main__") aliasMap[name] = hash;
210
- }
211
- }
212
- const lines = [];
213
- for (const spec of exports) {
214
- const [libName, localName] = spec.includes(":") ? spec.split(":", 2) : [spec, spec];
215
- const hash = aliasMap[libName];
216
- if (!hash) throw new Error(`--export: '${libName}' not found in loaded libraries`);
217
- const body = hash.startsWith("@") ? hash.slice(1) : hash;
218
- lines.push(`${localName} = @${body};`);
219
- }
220
- return lines.join("\n") + "\n";
221
- }
222
-
223
- const neededExports = ["0", "int", "inc", "dec", "nat", "zero_int?", "neg?", "GT"];
224
- const exportPreamble = buildExportPreamble(neededExports, [arithmeticsLib]);
225
- const polyLib = loadLibrary(compileLibrary(exportPreamble + polySource, {
209
+ const polyLib = loadLibrary(compileLibrary(polySource, {
226
210
  source: polyPath,
227
- libraries: [arithmeticsLib]
211
+ libraries: [depLib]
228
212
  }));
229
213
 
230
214
  const state = {
231
- codes: { ...arithmeticsLib.codes, ...polyLib.codes },
232
- rels: { ...arithmeticsLib.rels, ...polyLib.rels },
215
+ codes: { ...depLib.codes, ...polyLib.codes },
216
+ rels: { ...depLib.rels, ...polyLib.rels },
233
217
  typeAliases: {},
234
218
  relAliases: { ...polyLib.relAlias },
235
- meta: { ...arithmeticsLib.meta, ...polyLib.meta }
219
+ meta: { ...depLib.meta, ...polyLib.meta }
236
220
  };
237
- for (const [hash, entry] of Object.entries(arithmeticsLib.meta)) {
221
+ for (const [hash, entry] of Object.entries(depLib.meta)) {
238
222
  if (entry.type === "code") {
239
223
  for (const origin of entry.origins || []) {
240
224
  if (origin.name) state.typeAliases[origin.name] = hash;