@fraczak/k 8.7.0 → 8.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +40 -8
  2. package/DOCS/CODECS.md +42 -40
  3. package/DOCS/FILE_FORMATS.md +41 -64
  4. package/DOCS/GETTING_STARTED.md +10 -17
  5. package/DOCS/PATTERNS.md +3 -10
  6. package/DOCS/REPL.md +5 -9
  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 +7 -11
  12. package/backends/llvm/tests/integration.sh +2 -4
  13. package/backends/wasm/src/wasm.mjs +2 -6
  14. package/backends/wasm/tests/integration.sh +17 -7
  15. package/browser/shims/fs.mjs +2 -6
  16. package/canonical-pattern.mjs +9 -32
  17. package/compiler.mjs +36 -0
  18. package/harness/suites/poly.mjs +9 -11
  19. package/index.mjs +140 -6
  20. package/k.mjs +4 -12
  21. package/kir.mjs +3 -1
  22. package/kvm.mjs +4 -8
  23. package/lib/djson.k +981 -294
  24. package/lib/generic.k +701 -0
  25. package/lib/ieee.k +662 -638
  26. package/lib/integer.k +542 -0
  27. package/named-patterns.mjs +0 -12
  28. package/object.mjs +22 -32
  29. package/objects/README.md +6 -7
  30. package/objects/compile.mjs +5 -10
  31. package/package.json +1 -1
  32. package/repl.mjs +4 -7
  33. package/scripts/benchmark-idempotency.mjs +16 -17
  34. package/scripts/benchmark.mjs +39 -29
  35. package/scripts/build-repl-html.mjs +45 -35
  36. package/scripts/perf-ieee.mjs +1 -5
  37. package/scripts/perf-int.mjs +12 -27
  38. package/scripts/perf-multiplication.mjs +8 -9
  39. package/scripts/perf-poly.mjs +7 -10
  40. package/scripts/render-benchmark.mjs +1 -1
  41. package/scripts/run-tests.mjs +5 -2
  42. package/scripts/test-package.mjs +6 -7
  43. package/tests/README.md +4 -5
  44. package/tests/helpers/cli.mjs +31 -0
  45. package/tests/integration.sh +17 -7
  46. package/tests/test-arithmetics.mjs +23 -16
  47. package/tests/test-djson-methods.mjs +19 -22
  48. package/tests/test-djson.mjs +273 -0
  49. package/tests/test-generic.mjs +239 -0
  50. package/tests/test-ieee-arithmetic.mjs +1 -5
  51. package/tests/test-ieee.mjs +153 -0
  52. package/tests/test-integer.mjs +264 -0
  53. package/tests/test-k-object.mjs +11 -14
  54. package/tests/test-kvm-polymorphic.mjs +7 -4
  55. package/tests/test-lib.mjs +62 -50
  56. package/tests/test-library-isolation.mjs +704 -0
  57. package/tests/test-named-patterns.mjs +13 -4
  58. package/tests/test-parse-json.mjs +20 -19
  59. package/tests/test-poly.mjs +21 -16
  60. package/tests/test-repl-html.mjs +39 -44
  61. package/tests/test-repl.mjs +46 -59
  62. package/DOCS/book-combined.md +0 -3786
  63. package/DOCS/dependency-graph.md +0 -144
  64. package/Examples/arithmetics.k +0 -108
  65. package/Examples/esc.k +0 -9
  66. package/lib/arithmetics.k +0 -287
  67. package/lib/bit.k +0 -68
  68. package/lib/bits.k +0 -221
  69. package/lib/btrie.k +0 -187
  70. package/lib/list.k +0 -49
  71. package/lib/string.k +0 -588
  72. package/tests/test-ieee-text.mjs +0 -70
  73. package/tests/test-karatsuba.mjs +0 -25
package/README.md CHANGED
@@ -63,25 +63,21 @@ relations, libraries, and codecs.
63
63
 
64
64
  | File | Purpose |
65
65
  | --- | --- |
66
- | [lib/bit.k](lib/bit.k) | Bit, boolean, and ternary ordering (`bit[]`, `bool[]`, `order[]`) |
67
- | [lib/bits.k](lib/bits.k) | Arbitrary-width bit strings and 8-bit bytes (`bits[]`, `byte[]`) |
68
- | [lib/arithmetics.k](lib/arithmetics.k) | Signed arbitrary-precision integer arithmetic (`int[]`, `plus`, `minus`, `times`, `karatsuba`, `div`, `mod`, `gcd`, `lcm`) |
69
- | [lib/list.k](lib/list.k) | Parametric linked lists (`list[X]`) |
70
- | [lib/btrie.k](lib/btrie.k) | Parametric binary tries and optional values (`opt[V]`, `btrie[V]`) |
71
- | [lib/string.k](lib/string.k) | ASCII bytes, Unicode codepoints, and strings (`ascii[]`, `unicode[]`, `string[]`) |
72
- | [lib/ieee.k](lib/ieee.k) | Binary64 types and `parseFloat64` / `printFloat64` (`float64[]`) |
73
- | [lib/djson.k](lib/djson.k) | JSON text parsing (`parseJson`) and dynamic JSON operations (`djson[]`) |
74
- | [core.k](core.k) | Standalone bit, Unicode string, and self-hosted pattern schemas |
66
+ | [core.k](core.k) | Standalone bit, Unicode string, and self-hosted pattern schemas (`bit[]`, `bits[]`, `list[X]`, `string[]`, `pattern[]`) |
67
+ | [lib/generic.k](lib/generic.k) | Algebraic types, binary tries, and string/bit codecs (`bool[]`, `order[]`, `opt[V]`, `btrie[V]`, `string_to_bits`, `bits_to_string`) |
68
+ | [lib/integer.k](lib/integer.k) | Signed arbitrary-precision integer arithmetic (`int[]`, `nat`, `int`, `plus`, `minus`, `times` via Karatsuba, `divmod`, `div`, `mod`, `gcd`, `lcm`) |
69
+ | [lib/ieee.k](lib/ieee.k) | Binary64 types, predicates, negation, and rational conversions (`float64[]`, `negate_float64`, `bits_to_float64`, `ratio_to_float64`) |
70
+ | [lib/djson.k](lib/djson.k) | RFC 8259 JSON parser (`parse_json`) and dynamic JSON operations (`djson[]`, `get`, `nth`, `set`, `del`, `push`, `keys`, `values`) |
75
71
  | [Examples/nat.k](Examples/nat.k) | Small Peano arithmetic example |
76
- | [Examples/arithmetics.k](Examples/arithmetics.k) | Factorial, Fibonacci, and exact rational arithmetic (`rat[]`); load `lib/bit.k`, `lib/bits.k`, and `lib/arithmetics.k` first |
77
- | [Examples/poly.k](Examples/poly.k) | Polymorphic list operations indexed by `int[]`; load `lib/bit.k`, `lib/bits.k`, `lib/arithmetics.k`, and `lib/list.k` first |
78
- | [Examples/ieee-arithmetics.k](Examples/ieee-arithmetics.k) | Binary64 arithmetic returning `{result, flags}`; load `lib/bit.k` through `lib/ieee.k` first |
79
-
80
- Load libraries explicitly with `:load` in the REPL. Source files declare
81
- dependencies and imported symbols via `# --lib <dependency> --use <specs>`
82
- header directives at the top of the file, allowing compilation with
83
- `--lib <dependency.klib>` without repeating `--use` flags on the CLI.
84
- Command-line `--use` flags remain available for ad-hoc expressions. See
72
+ | [Examples/poly.k](Examples/poly.k) | Polymorphic list operations indexed by `int[]`; load `lib/integer.k` first |
73
+ | [Examples/ieee-arithmetics.k](Examples/ieee-arithmetics.k) | Binary64 arithmetic returning `{result, flags}`; load `core.k` and `lib/ieee.k` first |
74
+
75
+ Load libraries explicitly with `:load` in the REPL. Leading
76
+ `# --lib <dependency> --use <specs>` lines in source files are ordinary
77
+ human-readable comments documenting expected dependencies. On the CLI,
78
+ `--lib <dependency.klib>` makes library definitions available in memory by
79
+ content hash (`@<hash>`), while `--use` explicitly brings requested friendly
80
+ names or aliases into compilation scope. See
85
81
  [file formats and tools](DOCS/FILE_FORMATS.md).
86
82
 
87
83
  ## JavaScript API
package/backend-api.mjs CHANGED
@@ -21,9 +21,7 @@ export {
21
21
  compileLibrary,
22
22
  decodeObject,
23
23
  loadLibrary,
24
- buildUsePreamble,
25
- parseHeaderDirectives,
26
- parseHeaderUses
24
+ buildUsePreamble
27
25
  } from "./object.mjs";
28
26
  export { createState, evaluateInput } from "./repl.mjs";
29
27
  export { parse as parseFloat64, print as printFloat64 } from "./codecs/ieee.mjs";
@@ -5,8 +5,7 @@ import {
5
5
  compileObjectBuffer,
6
6
  decodeObject,
7
7
  loadLibrary,
8
- buildUsePreamble,
9
- parseHeaderUses
8
+ buildUsePreamble
10
9
  } from "@fraczak/k/object.mjs";
11
10
 
12
11
  export function readAll(stream) {
@@ -118,10 +117,9 @@ export async function compileProgramInputToObject(
118
117
  const specs = useSpecs.length > 0 ? useSpecs : exportSpecs;
119
118
  let object;
120
119
  if (input.kind === "inline-source") {
121
- const allSpecs = [...parseHeaderUses(input.source), ...specs];
122
- const preamble = buildUsePreamble(allSpecs, libraries);
123
- const objBuffer = compileObjectBuffer(preamble + input.source, {
120
+ const objBuffer = compileObjectBuffer(input.source, {
124
121
  libraries,
122
+ useSpecs: specs,
125
123
  source: input.sourceName
126
124
  });
127
125
  object = decodeObject(objBuffer);
@@ -130,19 +128,17 @@ export async function compileProgramInputToObject(
130
128
  throw new Error("stdin source requested without a stdin stream");
131
129
  }
132
130
  const source = (await readAll(stdin)).toString("utf8");
133
- const allSpecs = [...parseHeaderUses(source), ...specs];
134
- const preamble = buildUsePreamble(allSpecs, libraries);
135
- const objBuffer = compileObjectBuffer(preamble + source, {
131
+ const objBuffer = compileObjectBuffer(source, {
136
132
  libraries,
133
+ useSpecs: specs,
137
134
  source: input.sourceName
138
135
  });
139
136
  object = decodeObject(objBuffer);
140
137
  } else if (input.kind === "source-file") {
141
138
  const source = fs.readFileSync(input.path, "utf8");
142
- const allSpecs = [...parseHeaderUses(source), ...specs];
143
- const preamble = buildUsePreamble(allSpecs, libraries);
144
- const objBuffer = compileObjectBuffer(preamble + source, {
139
+ const objBuffer = compileObjectBuffer(source, {
145
140
  libraries,
141
+ useSpecs: specs,
146
142
  source: input.sourceName
147
143
  });
148
144
  object = decodeObject(objBuffer);
@@ -121,10 +121,8 @@ printf '2' \
121
121
 
122
122
  node --input-type=module -e "import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import { encodeToWire, decodeWire } from '../../codecs/runtime/prefix-codec.mjs'; import { parse, INT_PATTERN } from '../../codecs/int.mjs'; const input = encodeToWire(parse('2'), INT_PATTERN); const header = Buffer.alloc(4); header.writeUInt32BE(input.length); const child = spawn(process.argv[1], ['--server']); const chunks = []; const stderr = []; child.stdout.on('data', (chunk) => chunks.push(chunk)); child.stderr.on('data', (chunk) => stderr.push(chunk)); child.stdin.end(Buffer.concat([header, input])); const status = await new Promise((resolve, reject) => { child.on('error', reject); child.on('close', resolve); }); assert.equal(status, 0, Buffer.concat(stderr).toString('utf8')); const output = Buffer.concat(chunks); const length = output.readUInt32BE(0); assert.equal(output.length, 4 + length); assert.deepEqual(decodeWire(output.subarray(4)).value.toJSON(), parse('2').toJSON());" "$TMP_DIR/id-int-exe"
123
123
 
124
- node ../../objects/compile.mjs ../../lib/bit.k "$TMP_DIR/bit.klib"
125
- node ../../objects/compile.mjs --lib "$TMP_DIR/bit.klib" ../../lib/bits.k "$TMP_DIR/bits.klib"
126
- node ../../objects/compile.mjs --lib "$TMP_DIR/bits.klib" ../../lib/arithmetics.k "$TMP_DIR/arithmetics.klib"
127
- node ./bin/k-llvm-build.mjs --lib "$TMP_DIR/arithmetics.klib" --use times 's = ?< <bits 0, bits 1, {} _>=bits "+", bits "-" > {()x, ()y} times; s' -o "$TMP_DIR/square-exe"
124
+ node ../../objects/compile.mjs ../../lib/integer.k "$TMP_DIR/integer.klib"
125
+ node ./bin/k-llvm-build.mjs --lib "$TMP_DIR/integer.klib" --use times 's = ?< <bits 0, bits 1, {} _>=bits "+", bits "-" > {()x, ()y} times; s' -o "$TMP_DIR/square-exe"
128
126
  printf '987654321' \
129
127
  | node ../../codecs/int.mjs --parse \
130
128
  | "$TMP_DIR/square-exe" \
@@ -3,8 +3,6 @@ import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import {
5
5
  annotate,
6
- buildUsePreamble,
7
- parseHeaderUses,
8
6
  decodeWire,
9
7
  encodeToWire,
10
8
  exportPatternGraph,
@@ -651,14 +649,12 @@ async function compileWasmArtifact(
651
649
  } = {}
652
650
  ) {
653
651
  const specs = use.length > 0 ? use : exports;
654
- const allSpecs = [...parseHeaderUses(source), ...specs];
655
- const preamble = buildUsePreamble(allSpecs, libraries);
656
- const fullSource = preamble + source;
657
652
  const options = {
658
653
  libraries,
654
+ useSpecs: specs,
659
655
  ...(sourceName ? { source: sourceName } : {})
660
656
  };
661
- let defs = annotate(fullSource, options);
657
+ let defs = annotate(source, options);
662
658
 
663
659
  let typingMode = "generic";
664
660
  if (inputEnvelopePattern) {
@@ -172,13 +172,23 @@ printf '{"x":{"a":{}},"y":{"b":{}}}\n' |
172
172
  node "$K_ROOT/codecs/k-print.mjs" |
173
173
  grep -qx '"b"'
174
174
 
175
- node "$K_ROOT/objects/compile.mjs" "$K_ROOT/lib/bit.k" "$TMP_DIR/bit.klib"
176
- node "$K_ROOT/objects/compile.mjs" --lib "$TMP_DIR/bit.klib" "$K_ROOT/lib/bits.k" "$TMP_DIR/bits.klib"
177
- node "$K_ROOT/objects/compile.mjs" --lib "$TMP_DIR/bits.klib" "$K_ROOT/lib/list.k" "$TMP_DIR/list.klib"
178
- node "$K_ROOT/objects/compile.mjs" --lib "$TMP_DIR/list.klib" "$K_ROOT/lib/btrie.k" "$TMP_DIR/btrie.klib"
179
- node "$K_ROOT/objects/compile.mjs" --lib "$TMP_DIR/btrie.klib" "$K_ROOT/lib/string.k" "$TMP_DIR/string.klib"
180
- node "$K_ROOT/objects/compile.mjs" --lib "$TMP_DIR/string.klib" "$K_ROOT/lib/ieee.k" "$TMP_DIR/ieee-types.klib"
181
- node "$K_ROOT/objects/compile.mjs" --lib "$TMP_DIR/ieee-types.klib" "$K_ROOT/Examples/ieee-arithmetics.k" "$TMP_DIR/ieee.klib"
175
+ compile_step() {
176
+ local prev="$1"
177
+ local src="$2"
178
+ local out="$3"
179
+ local use_spec="$4"
180
+ local uses=()
181
+ [ -n "$use_spec" ] && uses=(--use "$use_spec")
182
+ if [ -n "$prev" ]; then
183
+ node "$K_ROOT/objects/compile.mjs" --lib "$prev" "${uses[@]}" "$src" "$out"
184
+ else
185
+ node "$K_ROOT/objects/compile.mjs" "${uses[@]}" "$src" "$out"
186
+ fi
187
+ }
188
+
189
+ compile_step "" "$K_ROOT/core.k" "$TMP_DIR/core.klib" ""
190
+ compile_step "$TMP_DIR/core.klib" "$K_ROOT/lib/ieee.k" "$TMP_DIR/ieee-types.klib" "bit[] bits[]"
191
+ compile_step "$TMP_DIR/ieee-types.klib" "$K_ROOT/Examples/ieee-arithmetics.k" "$TMP_DIR/ieee.klib" "bit[] sign[] exp11[] frac52[] float64[] all_ones_exponent? exp0 finite_float64? frac0 inf_float64? nan_float64? neg_inf neg_zero negate_float64 pos_inf pos_zero qnan zero_exponent? zero_float64?"
182
192
  if node ./bin/k-wasm-compile.mjs --lib "$TMP_DIR/ieee.klib" --lib "$TMP_DIR/ieee.klib" --use mul:times "{()x,()y} times .result" "$TMP_DIR/repeated-lib.wasm" >/dev/null 2>&1; then
183
193
  echo "--lib unexpectedly accepted more than once" >&2
184
194
  exit 1
@@ -60,12 +60,8 @@ export function getVfsFile(path) {
60
60
 
61
61
  const CURATED_VFS_FILES = [
62
62
  "core.k",
63
- "bit.k",
64
- "bits.k",
65
- "arithmetics.k",
66
- "list.k",
67
- "btrie.k",
68
- "string.k",
63
+ "generic.k",
64
+ "integer.k",
69
65
  "ieee.k",
70
66
  "djson.k",
71
67
  "ieee-arithmetics.k",
@@ -273,7 +273,7 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
273
273
  }
274
274
  const formalParams = pat.params || [];
275
275
  const formalCount = formalParams.length;
276
- const allPatterns = { ...(options.patterns || {}) };
276
+ const allPatterns = {};
277
277
  if (options.libraries) {
278
278
  for (const lib of options.libraries) {
279
279
  const lp =
@@ -281,9 +281,16 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
281
281
  lib.defs?.patterns ||
282
282
  lib.sourceDefs?.patterns ||
283
283
  {};
284
- Object.assign(allPatterns, lp);
284
+ for (const [patName, patDef] of Object.entries(lp)) {
285
+ if (patName.startsWith("@") && !(patName in allPatterns)) {
286
+ allPatterns[patName] = patDef;
287
+ }
288
+ }
285
289
  }
286
290
  }
291
+ if (options.patterns) {
292
+ Object.assign(allPatterns, options.patterns);
293
+ }
287
294
  if (name && pat) allPatterns[name] = pat;
288
295
 
289
296
  let pathMap = {};
@@ -415,34 +422,6 @@ export function canonicalPatternHash(name, pat, options = {}) {
415
422
  return resolvePatternCanonicalInfo(name, pat, options).hash;
416
423
  }
417
424
 
418
- export function parseHeaderDirectives(source) {
419
- if (!source || typeof source !== "string") return [];
420
- const directives = [];
421
- const lines = source.split(/\r?\n/);
422
- for (const line of lines) {
423
- const trimmed = line.trim();
424
- if (!trimmed || trimmed.startsWith("--") || trimmed.startsWith("//") || trimmed.startsWith("%")) {
425
- continue;
426
- }
427
- if (trimmed.startsWith("#")) {
428
- const match = trimmed.match(/^#\s*--?lib\s+(\S+)\s+--use\s+(.+)$/);
429
- if (match) {
430
- directives.push({ lib: match[1], use: match[2].trim() });
431
- }
432
- continue;
433
- }
434
- if (trimmed.match(/^[a-zA-Z0-9_?!+-]+(?:\[[^\]]*\])?\s*=\s*@[a-zA-Z0-9_-]+(?:\[[^\]]*\])?\s*;/)) {
435
- continue;
436
- }
437
- break;
438
- }
439
- return directives;
440
- }
441
-
442
- export function parseHeaderUses(source) {
443
- return parseHeaderDirectives(source);
444
- }
445
-
446
425
  function buildMapsForLibrary(lib) {
447
426
  const relMap = {};
448
427
  const patMap = {};
@@ -932,8 +911,6 @@ export default {
932
911
  resolvePatternCanonicalInfo,
933
912
  canonicalPatternHash,
934
913
  buildUsePreamble,
935
- parseHeaderDirectives,
936
- parseHeaderUses,
937
914
  canonicalBoundaryFilterSources,
938
915
  instantiateCanonicalFilter
939
916
  };
package/compiler.mjs CHANGED
@@ -18,6 +18,42 @@ function compileTypes(representatives, rels, options = {}) {
18
18
  // }
19
19
 
20
20
  const relAlias = {};
21
+ if (options.libraries) {
22
+ for (const lib of options.libraries) {
23
+ const lr = lib.rels || lib.defs?.rels || {};
24
+ for (const k of Object.keys(lr)) {
25
+ if (k.startsWith("@")) {
26
+ relAlias[k] = k;
27
+ }
28
+ }
29
+ }
30
+ if (options._useRelAlias) {
31
+ for (const [localName, relHash] of Object.entries(options._useRelAlias)) {
32
+ if (rels[localName]?._library) {
33
+ relAlias[localName] = relHash;
34
+ }
35
+ }
36
+ } else {
37
+ const useSpecs = [...(options.useSpecs || options.use || [])];
38
+ for (const spec of useSpecs) {
39
+ const parts = spec.trim().split(/[\s,]+/);
40
+ for (const item of parts) {
41
+ if (!item) continue;
42
+ const [rawLib, rawLocal] = item.includes(":") ? item.split(":", 2) : [item, item];
43
+ if (/\[.*\]$/.test(rawLib.trim()) || /\[.*\]$/.test(rawLocal.trim())) continue;
44
+ const libName = rawLib.replace(/\[.*\]$/, "").trim();
45
+ const localName = rawLocal.replace(/\[.*\]$/, "").trim();
46
+ if (!rels[localName]?._library) continue;
47
+ for (const lib of options.libraries) {
48
+ const relHash = lib.relAlias?.[libName] || (libName.startsWith("@") ? libName : null);
49
+ if (relHash) {
50
+ relAlias[localName] = relHash;
51
+ }
52
+ }
53
+ }
54
+ }
55
+ }
56
+ }
21
57
  const compileStats = {
22
58
  sccs: []
23
59
  };
@@ -10,7 +10,6 @@ import {
10
10
  lowerToKVM,
11
11
  run,
12
12
  run_converged,
13
- valueForCode,
14
13
  Value
15
14
  } from "../../backend-api.mjs";
16
15
  import { compileLibrary, loadLibrary, decodeObject, compileObjectBuffer } from "../../object.mjs";
@@ -19,24 +18,23 @@ import { BenchmarkSuite } from "../suite.mjs";
19
18
  import { inputPatternForObjectRelation } from "../../backends/llvm/src/executable.mjs";
20
19
  import { prepareRelation } from "../../backends/llvm/tests/perf-support.mjs";
21
20
 
21
+ const POLY_USE_SPECS = ["int[] nat int pos? neg? zero? gt? inc dec"];
22
+
22
23
  export async function createPolySuite({ listLength = 40, cacheDir = null } = {}) {
23
24
  const ops = ["reverse", "concat", "split_by", "get_nth", "length"];
24
25
  const benchNames = Object.fromEntries(ops.map(op => [op, `bench_${op}`]));
25
26
 
26
- let depLib = null;
27
- for (const relPath of ["../../lib/bit.k", "../../lib/bits.k", "../../lib/arithmetics.k", "../../lib/list.k"]) {
28
- const filePath = fileURLToPath(import.meta.resolve(relPath));
29
- depLib = loadLibrary(compileLibrary(fs.readFileSync(filePath, "utf8"), {
30
- source: filePath,
31
- libraries: depLib ? [depLib] : []
32
- }));
33
- }
27
+ const integerPath = fileURLToPath(import.meta.resolve("../../lib/integer.k"));
28
+ const depLib = loadLibrary(compileLibrary(fs.readFileSync(integerPath, "utf8"), {
29
+ source: integerPath
30
+ }));
34
31
 
35
32
  const polyPath = fileURLToPath(import.meta.resolve("../../Examples/poly.k"));
36
33
  const polySource = fs.readFileSync(polyPath, "utf8");
37
34
  const polyLib = loadLibrary(compileLibrary(polySource, {
38
35
  source: polyPath,
39
- libraries: [depLib]
36
+ libraries: [depLib],
37
+ use: POLY_USE_SPECS
40
38
  }));
41
39
 
42
40
  const state = {
@@ -60,7 +58,7 @@ export async function createPolySuite({ listLength = 40, cacheDir = null } = {})
60
58
  }
61
59
 
62
60
  function intValue(text) {
63
- return valueForCode(parseIntValue(text), state.typeAliases.int, codes.find);
61
+ return parseIntValue(text);
64
62
  }
65
63
 
66
64
  function makeList(elements) {
package/index.mjs CHANGED
@@ -35,28 +35,162 @@ function runScriptOnData(script, data, options = {}) {
35
35
  runScriptOnData.doc = "Run 'script' (string) on 'data': (script,data) -> data";
36
36
 
37
37
 
38
+ function resolveUseImports(useSpecs, libraries) {
39
+ const importedPatterns = new Map();
40
+ const importedRels = new Map();
41
+ if (!libraries || useSpecs.length === 0) {
42
+ return { importedPatterns, importedRels };
43
+ }
44
+
45
+ for (const spec of useSpecs) {
46
+ const parts = spec.trim().split(/[\s,]+/);
47
+ for (const item of parts) {
48
+ if (!item) continue;
49
+ const [rawLib, rawLocal] = item.includes(":") ? item.split(":", 2) : [item, item];
50
+ const hasExplicitBrackets =
51
+ /\[.*\]$/.test(rawLib.trim()) || /\[.*\]$/.test(rawLocal.trim());
52
+ const libName = rawLib.replace(/\[.*\]$/, "").trim();
53
+ const localName = rawLocal.replace(/\[.*\]$/, "").trim();
54
+
55
+ let matchedRel = null;
56
+ if (!hasExplicitBrackets && libName !== "__main__" && localName !== "__main__") {
57
+ for (const lib of libraries) {
58
+ const libRels = lib.rels || lib.defs?.rels || {};
59
+ const relHash = lib.relAlias?.[libName] || (libName.startsWith("@") ? libName : null);
60
+ const rel = (relHash && libRels[relHash]) || libRels[libName];
61
+ if (!rel) continue;
62
+ const resolvedHash = relHash || libName;
63
+ if (matchedRel && matchedRel.hash && resolvedHash && matchedRel.hash !== resolvedHash) {
64
+ console.warn(
65
+ `WARNING: Relation '${localName}' declared by --use is redefined; later definition wins.`
66
+ );
67
+ }
68
+ matchedRel = { hash: resolvedHash, rel };
69
+ }
70
+ }
71
+
72
+ if (matchedRel) {
73
+ if (importedRels.has(localName)) {
74
+ console.warn(
75
+ `WARNING: Relation '${localName}' declared by --use is redefined; later definition wins.`
76
+ );
77
+ }
78
+ importedRels.set(localName, matchedRel);
79
+ continue;
80
+ }
81
+
82
+ let matchedPat = null;
83
+ for (const lib of libraries) {
84
+ const libPatterns = lib.patterns || lib.defs?.patterns || lib.sourceDefs?.patterns || {};
85
+ const patHash = lib.patternAlias?.[libName] || (libName.startsWith("@") ? libName : null);
86
+ const pat = (patHash && libPatterns[patHash]) || libPatterns[libName];
87
+ if (!pat) continue;
88
+ const resolvedHash = patHash || pat._canonical || null;
89
+ if (
90
+ matchedPat &&
91
+ ((matchedPat.hash && resolvedHash && matchedPat.hash !== resolvedHash) ||
92
+ (!matchedPat.hash && matchedPat.pat !== pat))
93
+ ) {
94
+ console.warn(
95
+ `WARNING: Pattern '${localName}[]' declared by --use is redefined; later definition wins.`
96
+ );
97
+ }
98
+ matchedPat = { hash: resolvedHash, pat };
99
+ }
100
+
101
+ if (matchedPat) {
102
+ if (importedPatterns.has(localName)) {
103
+ console.warn(
104
+ `WARNING: Pattern '${localName}[]' declared by --use is redefined; later definition wins.`
105
+ );
106
+ }
107
+ importedPatterns.set(localName, matchedPat);
108
+ }
109
+ }
110
+ }
111
+
112
+ return { importedPatterns, importedRels };
113
+ }
114
+
38
115
  function annotate(script, options = {}) {
39
116
  const { defs, exp } = parse(script);
40
117
 
41
118
  const representatives = codes.register(defs.codes);
42
- const rels = {...defs.rels, "__main__": {def: exp}};
119
+ const localPatterns = { ...(defs.patterns || {}) };
120
+ const localRels = { ...(defs.rels || {}) };
121
+ const useSpecs = [...(options.useSpecs || options.use || [])];
122
+ const { importedPatterns, importedRels } = resolveUseImports(
123
+ useSpecs,
124
+ options.libraries
125
+ );
43
126
 
44
- validatePatternDefinitions(defs.patterns || {}, options);
45
- expandPatternsInRels(rels, defs.patterns || {}, options);
127
+ // 1. Inject library @hash patterns; friendly names only come from --use or local definitions.
128
+ defs.patterns = {};
129
+ if (options.libraries) {
130
+ for (const lib of options.libraries) {
131
+ const libPatterns =
132
+ lib.patterns ||
133
+ lib.defs?.patterns ||
134
+ lib.sourceDefs?.patterns ||
135
+ {};
136
+ for (const [name, pat] of Object.entries(libPatterns)) {
137
+ if (name.startsWith("@") && !(name in defs.patterns)) {
138
+ defs.patterns[name] = pat;
139
+ }
140
+ }
141
+ }
142
+ }
46
143
 
47
- // Inject library relations into the rels table so @hash refs resolve
144
+ // 2. Apply --use pattern aliases, then local pattern definitions (later wins with warning on collision).
145
+ for (const [localName, { pat }] of importedPatterns.entries()) {
146
+ defs.patterns[localName] = pat;
147
+ }
148
+ for (const [name, pat] of Object.entries(localPatterns)) {
149
+ if (!name.startsWith("@") && importedPatterns.has(name)) {
150
+ console.warn(
151
+ `WARNING: Pattern '${name}[]' declared by --use is redefined by local definition; later definition wins.`
152
+ );
153
+ }
154
+ defs.patterns[name] = pat;
155
+ }
156
+
157
+ validatePatternDefinitions(defs.patterns, options);
158
+
159
+ // 3. Inject library @hash relations, then --use relation aliases, then local relations.
160
+ const rels = {};
48
161
  if (options.libraries) {
49
162
  for (const lib of options.libraries) {
50
163
  const libRels = lib.rels || lib.defs?.rels || {};
51
164
  for (const [name, rel] of Object.entries(libRels)) {
52
- if (!(name in rels)) {
165
+ if (name.startsWith("@") && !(name in rels)) {
53
166
  rels[name] = { ...rel, _library: true };
54
167
  }
55
168
  }
56
169
  }
57
170
  }
58
171
 
59
- const { relAlias, compileStats } = compileTypes(representatives, rels, options);
172
+ const useRelHashes = {};
173
+ for (const [localName, { hash, rel }] of importedRels.entries()) {
174
+ rels[localName] = { ...rel, _library: true };
175
+ if (hash) useRelHashes[localName] = hash;
176
+ }
177
+ for (const [name, rel] of Object.entries(localRels)) {
178
+ if (!name.startsWith("@") && importedRels.has(name)) {
179
+ console.warn(
180
+ `WARNING: Relation '${name}' declared by --use is redefined by local definition; later definition wins.`
181
+ );
182
+ delete useRelHashes[name];
183
+ }
184
+ rels[name] = rel;
185
+ }
186
+ rels.__main__ = { def: exp };
187
+
188
+ expandPatternsInRels(rels, defs.patterns, options);
189
+
190
+ const { relAlias, compileStats } = compileTypes(representatives, rels, {
191
+ ...options,
192
+ _useRelAlias: useRelHashes
193
+ });
60
194
 
61
195
  return {rels, representatives, relAlias, compileStats, sourceDefs: defs};
62
196
  }
package/k.mjs CHANGED
@@ -12,9 +12,7 @@ import {
12
12
  compileLibrary,
13
13
  decodeObject,
14
14
  objectToFunction,
15
- loadLibrary,
16
- buildUsePreamble,
17
- parseHeaderUses
15
+ loadLibrary
18
16
  } from "./object.mjs";
19
17
 
20
18
  let kScript, inputStream;
@@ -68,9 +66,7 @@ function compileFile(filePath, libraries, useSpecs = []) {
68
66
  return objectToFunction(decodeObject(buffer));
69
67
  } catch {
70
68
  const raw = buffer.toString("utf8");
71
- const allSpecs = [...parseHeaderUses(raw), ...useSpecs];
72
- const preamble = buildUsePreamble(allSpecs, libraries);
73
- return k.compile(preamble + raw, { libraries });
69
+ return k.compile(raw, { libraries, useSpecs });
74
70
  }
75
71
  }
76
72
 
@@ -122,13 +118,9 @@ function compileFile(filePath, libraries, useSpecs = []) {
122
118
  );
123
119
  }
124
120
  if (isFile(arg)) return compileFile(arg, libraries, useSpecs);
125
- const allSpecs = [...parseHeaderUses(arg), ...useSpecs];
126
- const preamble = buildUsePreamble(allSpecs, libraries);
127
- return preamble + arg;
121
+ return k.compile(arg, { libraries, useSpecs });
128
122
  })(args.shift());
129
- let kScript = typeof kScriptStr === "function"
130
- ? kScriptStr
131
- : k.compile(kScriptStr, { libraries });
123
+ let kScript = kScriptStr;
132
124
  inputStream = (function (arg) {
133
125
  if (arg == null) {
134
126
  return stdin;
package/kir.mjs CHANGED
@@ -581,9 +581,11 @@ export function retypeObjectRelation(object, relationName, inputPattern, options
581
581
 
582
582
  const target = resolveRelation(object, relationName);
583
583
  const source = `?${propertyListToFilter(inputPattern)} __kir_target__`;
584
+ const helperRels = Object.keys(object.rels || {}).filter((k) => k !== "__main__");
584
585
  const retypedObject = hydrateObject(compileObject(source, {
585
586
  source: options.source || "<kir-retype>",
586
- libraries: [relationLibraryWithTarget(object, target.rel)]
587
+ libraries: [relationLibraryWithTarget(object, target.rel)],
588
+ use: ["__kir_target__", ...helperRels]
587
589
  }));
588
590
  return objectToKIRP(retypedObject);
589
591
  }
package/kvm.mjs CHANGED
@@ -13,9 +13,7 @@ import {
13
13
  compileLibrary,
14
14
  compileObjectBuffer,
15
15
  decodeObject,
16
- loadLibrary,
17
- buildUsePreamble,
18
- parseHeaderUses
16
+ loadLibrary
19
17
  } from "./object.mjs";
20
18
  import codes from "./codes.mjs";
21
19
  import { isMainEntrypoint } from "./codecs/runtime/cli-entry.mjs";
@@ -1041,15 +1039,13 @@ async function main() {
1041
1039
  throw error;
1042
1040
  }
1043
1041
  const raw = buffer.toString("utf8");
1044
- const allSpecs = [...parseHeaderUses(raw), ...useSpecs];
1045
1042
  return {
1046
1043
  kind: "source",
1047
- source: buildUsePreamble(allSpecs, libraries) + raw
1044
+ source: raw
1048
1045
  };
1049
1046
  }
1050
1047
  }
1051
- const allSpecs = [...parseHeaderUses(arg), ...useSpecs];
1052
- return { kind: "source", source: buildUsePreamble(allSpecs, libraries) + arg };
1048
+ return { kind: "source", source: arg };
1053
1049
  })(args.shift());
1054
1050
 
1055
1051
  const inputStream = (function (arg) {
@@ -1065,7 +1061,7 @@ async function main() {
1065
1061
 
1066
1062
  const object = programInput.kind === "object"
1067
1063
  ? programInput.object
1068
- : decodeObject(compileObjectBuffer(programInput.source, { libraries }));
1064
+ : decodeObject(compileObjectBuffer(programInput.source, { libraries, useSpecs }));
1069
1065
  const kir = objectToKIRP(object);
1070
1066
  const mainRelName = kir.main;
1071
1067
  const mainRel = kir.rels[mainRelName];