@fraczak/k 8.7.1 → 8.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/DOCS/CODECS.md +42 -40
  3. package/DOCS/FILE_FORMATS.md +28 -25
  4. package/DOCS/GETTING_STARTED.md +10 -15
  5. package/DOCS/PATTERNS.md +3 -3
  6. package/DOCS/REPL.md +3 -6
  7. package/Examples/ieee-arithmetics.k +14 -29
  8. package/Examples/poly.k +18 -29
  9. package/README.md +14 -18
  10. package/backend-api.mjs +1 -3
  11. package/backends/llvm/src/cli.mjs +1 -2
  12. package/backends/llvm/tests/integration.sh +2 -6
  13. package/backends/wasm/tests/integration.sh +5 -10
  14. package/browser/shims/fs.mjs +2 -6
  15. package/canonical-pattern.mjs +9 -29
  16. package/codecs/djson.mjs +2 -3
  17. package/codecs/int.mjs +66 -14
  18. package/compiler.mjs +22 -12
  19. package/harness/suites/poly.mjs +9 -11
  20. package/index.mjs +119 -50
  21. package/lib/djson.k +976 -288
  22. package/lib/generic.k +686 -0
  23. package/lib/ieee.k +658 -639
  24. package/lib/integer.k +536 -0
  25. package/object.mjs +19 -12
  26. package/objects/README.md +6 -6
  27. package/package.json +1 -1
  28. package/scripts/benchmark-idempotency.mjs +16 -17
  29. package/scripts/benchmark.mjs +39 -29
  30. package/scripts/build-repl-html.mjs +45 -35
  31. package/scripts/perf-bigint-compare.mjs +279 -0
  32. package/scripts/perf-ieee.mjs +1 -5
  33. package/scripts/perf-int.mjs +12 -27
  34. package/scripts/perf-multiplication.mjs +8 -9
  35. package/scripts/perf-poly.mjs +7 -10
  36. package/scripts/render-benchmark.mjs +1 -1
  37. package/scripts/run-tests.mjs +4 -2
  38. package/scripts/test-package.mjs +4 -10
  39. package/tests/README.md +4 -5
  40. package/tests/helpers/cli.mjs +30 -7
  41. package/tests/integration.sh +5 -10
  42. package/tests/test-arithmetics.mjs +23 -16
  43. package/tests/test-djson-methods.mjs +16 -25
  44. package/tests/test-djson.mjs +272 -0
  45. package/tests/test-generic.mjs +237 -0
  46. package/tests/test-ieee-arithmetic.mjs +1 -5
  47. package/tests/test-ieee.mjs +153 -0
  48. package/tests/test-integer.mjs +264 -0
  49. package/tests/test-k-object.mjs +12 -18
  50. package/tests/test-kvm-polymorphic.mjs +6 -7
  51. package/tests/test-lib.mjs +62 -52
  52. package/tests/test-library-isolation.mjs +349 -26
  53. package/tests/test-parse-json.mjs +15 -24
  54. package/tests/test-poly.mjs +21 -16
  55. package/tests/test-repl-html.mjs +39 -44
  56. package/tests/test-repl.mjs +46 -59
  57. package/tests/test-structural-values.mjs +1 -1
  58. package/DOCS/book-combined.md +0 -3786
  59. package/DOCS/dependency-graph.md +0 -144
  60. package/Examples/arithmetics.k +0 -108
  61. package/Examples/esc.k +0 -9
  62. package/lib/arithmetics.k +0 -286
  63. package/lib/bit.k +0 -68
  64. package/lib/bits.k +0 -227
  65. package/lib/btrie.k +0 -187
  66. package/lib/list.k +0 -49
  67. package/lib/string.k +0 -588
  68. package/tests/test-ieee-text.mjs +0 -74
  69. package/tests/test-karatsuba.mjs +0 -25
@@ -176,10 +176,9 @@ compile_step() {
176
176
  local prev="$1"
177
177
  local src="$2"
178
178
  local out="$3"
179
+ local use_spec="$4"
179
180
  local uses=()
180
- while IFS= read -r line; do
181
- [ -n "$line" ] && uses+=(--use "$line")
182
- done < <(node -e 'import("'$K_ROOT'/canonical-pattern.mjs").then(m => { for (const u of m.parseHeaderUses(fs.readFileSync(process.argv[1],"utf8"))) console.log(u.use); })' "$src" 2>/dev/null || true)
181
+ [ -n "$use_spec" ] && uses=(--use "$use_spec")
183
182
  if [ -n "$prev" ]; then
184
183
  node "$K_ROOT/objects/compile.mjs" --lib "$prev" "${uses[@]}" "$src" "$out"
185
184
  else
@@ -187,13 +186,9 @@ compile_step() {
187
186
  fi
188
187
  }
189
188
 
190
- compile_step "" "$K_ROOT/lib/bit.k" "$TMP_DIR/bit.klib"
191
- compile_step "$TMP_DIR/bit.klib" "$K_ROOT/lib/bits.k" "$TMP_DIR/bits.klib"
192
- compile_step "$TMP_DIR/bits.klib" "$K_ROOT/lib/list.k" "$TMP_DIR/list.klib"
193
- compile_step "$TMP_DIR/list.klib" "$K_ROOT/lib/btrie.k" "$TMP_DIR/btrie.klib"
194
- compile_step "$TMP_DIR/btrie.klib" "$K_ROOT/lib/string.k" "$TMP_DIR/string.klib"
195
- compile_step "$TMP_DIR/string.klib" "$K_ROOT/lib/ieee.k" "$TMP_DIR/ieee-types.klib"
196
- compile_step "$TMP_DIR/ieee-types.klib" "$K_ROOT/Examples/ieee-arithmetics.k" "$TMP_DIR/ieee.klib"
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?"
197
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
198
193
  echo "--lib unexpectedly accepted more than once" >&2
199
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,31 +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
- break;
435
- }
436
- return directives;
437
- }
438
-
439
- export function parseHeaderUses(source) {
440
- return parseHeaderDirectives(source);
441
- }
442
-
443
425
  function buildMapsForLibrary(lib) {
444
426
  const relMap = {};
445
427
  const patMap = {};
@@ -929,8 +911,6 @@ export default {
929
911
  resolvePatternCanonicalInfo,
930
912
  canonicalPatternHash,
931
913
  buildUsePreamble,
932
- parseHeaderDirectives,
933
- parseHeaderUses,
934
914
  canonicalBoundaryFilterSources,
935
915
  instantiateCanonicalFilter
936
916
  };
package/codecs/djson.mjs CHANGED
@@ -16,7 +16,7 @@
16
16
  * >
17
17
  *
18
18
  * - In `list`, element at index i >= 0 is stored at the canonical binary
19
- * bit-path of i (0 -> [0], 1 -> [1], 2 -> [1,0], 3 -> [1,1], ...).
19
+ * bit-path of i (0 -> [], 1 -> [1], 2 -> [1,0], 3 -> [1,1], ...).
20
20
  * - In `object`, entry with key k is stored at the prefix-free Unicode
21
21
  * character bit-path of k.
22
22
  */
@@ -167,7 +167,7 @@ function readBitsMSB(bits, offset, width) {
167
167
  }
168
168
 
169
169
  export function indexToBitPath(index) {
170
- if (index === 0) return [0];
170
+ if (index === 0) return [];
171
171
  const bits = [];
172
172
  let n = index;
173
173
  while (n > 0) {
@@ -179,7 +179,6 @@ export function indexToBitPath(index) {
179
179
  }
180
180
 
181
181
  export function bitPathToIndex(bits) {
182
- if (bits.length === 1 && bits[0] === 0) return 0;
183
182
  let n = 0;
184
183
  for (const b of bits) {
185
184
  n = n * 2 + b;
package/codecs/int.mjs CHANGED
@@ -32,12 +32,42 @@ const INT_LIST_PATTERN = patternFromFilter(`
32
32
  > = list
33
33
  `);
34
34
 
35
- // Build bits Value (MSB outermost) from a non-negative BigInt.
36
- function buildBits(n) {
37
- const bitChars = n === 0n ? ["0"] : n.toString(2).split("");
35
+ const DEC_BASE = 1_000_000_000;
36
+ const DEC_CHUNK = 9;
37
+ const BIT_CHUNK = 20;
38
+ const BIT_BASE = 1 << BIT_CHUNK; // 2^20 * 10^9 < Number.MAX_SAFE_INTEGER
39
+
40
+ // Build bits Value (MSB outermost) directly from a validated non-negative decimal string.
41
+ function decimalToBits(str) {
38
42
  let v = Value.variant("_", Value.product({}));
39
- for (let i = bitChars.length - 1; i >= 0; i--) {
40
- v = Value.variant(bitChars[i], v);
43
+ if (str === "0") return v;
44
+ const limbs = [];
45
+ const firstLen = str.length % DEC_CHUNK || DEC_CHUNK;
46
+ limbs.push(Number(str.slice(0, firstLen)));
47
+ for (let i = firstLen; i < str.length; i += DEC_CHUNK) {
48
+ limbs.push(Number(str.slice(i, i + DEC_CHUNK)));
49
+ }
50
+ let start = 0;
51
+ while (start < limbs.length) {
52
+ let rem = 0;
53
+ for (let i = start; i < limbs.length; i++) {
54
+ const cur = rem * DEC_BASE + limbs[i];
55
+ const q = Math.floor(cur / BIT_BASE);
56
+ limbs[i] = q;
57
+ rem = cur - q * BIT_BASE;
58
+ }
59
+ while (start < limbs.length && limbs[start] === 0) start++;
60
+ if (start < limbs.length) {
61
+ for (let b = 0; b < BIT_CHUNK; b++) {
62
+ v = Value.variant((rem & 1) === 1 ? "1" : "0", v);
63
+ rem >>>= 1;
64
+ }
65
+ } else {
66
+ while (rem > 0) {
67
+ v = Value.variant((rem & 1) === 1 ? "1" : "0", v);
68
+ rem >>>= 1;
69
+ }
70
+ }
41
71
  }
42
72
  return v;
43
73
  }
@@ -51,9 +81,8 @@ function parseIntStr(str) {
51
81
  if (!/^(0|[1-9][0-9]*)$/.test(str)) {
52
82
  throw new Error(`Invalid integer syntax: ${JSON.stringify(str)}`);
53
83
  }
54
- const n = BigInt(str);
55
- if (n === 0n) sign = "+";
56
- return Value.variant(sign, buildBits(n));
84
+ if (str === "0") sign = "+";
85
+ return Value.variant(sign, decimalToBits(str));
57
86
  }
58
87
 
59
88
  // Parse a list of decimal integers, e.g. "[0,1,2]" or "[]"
@@ -94,15 +123,38 @@ function printSingleInt(value) {
94
123
  throw new Error("Not a valid k int value");
95
124
  }
96
125
  const sign = value.tag;
97
- let bits = "";
126
+ const limbs = []; // base-10^9, least-significant limb at index 0
98
127
  let node = value.value;
99
128
  while (isVariant(node) && node.tag !== "_") {
100
- bits += node.tag;
101
- node = node.value;
129
+ let chunkVal = 0;
130
+ let chunkBits = 0;
131
+ while (chunkBits < BIT_CHUNK && isVariant(node) && node.tag !== "_") {
132
+ if (node.tag !== "0" && node.tag !== "1") {
133
+ throw new Error("Not a valid k int value");
134
+ }
135
+ chunkVal = (chunkVal << 1) | (node.tag === "1" ? 1 : 0);
136
+ chunkBits++;
137
+ node = node.value;
138
+ }
139
+ const mult = 1 << chunkBits;
140
+ let carry = chunkVal;
141
+ for (let i = 0; i < limbs.length; i++) {
142
+ const cur = limbs[i] * mult + carry;
143
+ carry = Math.floor(cur / DEC_BASE);
144
+ limbs[i] = cur - carry * DEC_BASE;
145
+ }
146
+ if (carry > 0) {
147
+ limbs.push(carry);
148
+ }
149
+ }
150
+ if (!isVariant(node) || node.tag !== "_" || !isProduct(node.value) || Object.keys(node.value.product).length !== 0) {
151
+ throw new Error("Not a valid k int value");
152
+ }
153
+ if (limbs.length === 0) return "0";
154
+ let digits = String(limbs[limbs.length - 1]);
155
+ for (let i = limbs.length - 2; i >= 0; i--) {
156
+ digits += String(limbs[i]).padStart(DEC_CHUNK, "0");
102
157
  }
103
- const n = bits === "" ? 0n : BigInt("0b" + bits);
104
- const digits = n.toString(10);
105
- if (n === 0n) return "0";
106
158
  return (sign === "-" ? "-" : "") + digits;
107
159
  }
108
160
 
package/compiler.mjs CHANGED
@@ -27,18 +27,28 @@ function compileTypes(representatives, rels, options = {}) {
27
27
  }
28
28
  }
29
29
  }
30
- const useSpecs = [...(options.useSpecs || options.use || [])];
31
- for (const spec of useSpecs) {
32
- const parts = spec.trim().split(/[\s,]+/);
33
- for (const item of parts) {
34
- if (!item) continue;
35
- const [rawLib, rawLocal] = item.includes(":") ? item.split(":", 2) : [item, item];
36
- const libName = rawLib.replace(/\[.*\]$/, "").trim();
37
- const localName = rawLocal.replace(/\[.*\]$/, "").trim();
38
- for (const lib of options.libraries) {
39
- const relHash = lib.relAlias?.[libName] || (libName.startsWith("@") ? libName : null);
40
- if (relHash) {
41
- relAlias[localName] = relHash;
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
+ }
42
52
  }
43
53
  }
44
54
  }
@@ -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,14 +35,97 @@ 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
- // 1. Inject library patterns into defs.patterns before validation and expansion
45
- // NOTE: Library patterns are known by their hashes ONLY unless --use is specified.
127
+ // 1. Inject library @hash patterns; friendly names only come from --use or local definitions.
128
+ defs.patterns = {};
46
129
  if (options.libraries) {
47
130
  for (const lib of options.libraries) {
48
131
  const libPatterns =
@@ -51,44 +134,30 @@ function annotate(script, options = {}) {
51
134
  lib.sourceDefs?.patterns ||
52
135
  {};
53
136
  for (const [name, pat] of Object.entries(libPatterns)) {
54
- if (name.startsWith("@") && !(name in (defs.patterns || {}))) {
55
- if (!defs.patterns) defs.patterns = {};
137
+ if (name.startsWith("@") && !(name in defs.patterns)) {
56
138
  defs.patterns[name] = pat;
57
139
  }
58
140
  }
59
141
  }
60
142
  }
61
143
 
62
- // 2. Handle pattern aliases from useSpecs / use (e.g. float64[]:number[])
63
- const useSpecs = [...(options.useSpecs || options.use || [])];
64
- if (options.libraries && useSpecs.length > 0) {
65
- for (const spec of useSpecs) {
66
- const parts = spec.trim().split(/[\s,]+/);
67
- for (const item of parts) {
68
- if (!item) continue;
69
- const [rawLib, rawLocal] = item.includes(":") ? item.split(":", 2) : [item, item];
70
- const libName = rawLib.replace(/\[.*\]$/, "").trim();
71
- const localName = rawLocal.replace(/\[.*\]$/, "").trim();
72
- for (const lib of options.libraries) {
73
- const libPatterns = lib.patterns || lib.defs?.patterns || lib.sourceDefs?.patterns || {};
74
- const patHash = lib.patternAlias?.[libName] || (libName.startsWith("@") ? libName : null);
75
- const pat = (patHash && libPatterns[patHash]) || libPatterns[libName];
76
- if (pat) {
77
- if (!defs.patterns) defs.patterns = {};
78
- if (!(localName in defs.patterns)) {
79
- defs.patterns[localName] = pat;
80
- }
81
- }
82
- }
83
- }
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
+ );
84
153
  }
154
+ defs.patterns[name] = pat;
85
155
  }
86
156
 
87
- validatePatternDefinitions(defs.patterns || {}, options);
88
- expandPatternsInRels(rels, defs.patterns || {}, options);
157
+ validatePatternDefinitions(defs.patterns, options);
89
158
 
90
- // 3. Inject library relations into the rels table so @hash refs resolve
91
- // NOTE: Library relations are known by their hashes ONLY unless --use is specified.
159
+ // 3. Inject library @hash relations, then --use relation aliases, then local relations.
160
+ const rels = {};
92
161
  if (options.libraries) {
93
162
  for (const lib of options.libraries) {
94
163
  const libRels = lib.rels || lib.defs?.rels || {};
@@ -100,28 +169,28 @@ function annotate(script, options = {}) {
100
169
  }
101
170
  }
102
171
 
103
- // 4. Handle relation aliases from useSpecs / use (e.g. inc:inc_bits)
104
- if (options.libraries && useSpecs.length > 0) {
105
- for (const spec of useSpecs) {
106
- const parts = spec.trim().split(/[\s,]+/);
107
- for (const item of parts) {
108
- if (!item) continue;
109
- const [rawLib, rawLocal] = item.includes(":") ? item.split(":", 2) : [item, item];
110
- const libName = rawLib.replace(/\[.*\]$/, "").trim();
111
- const localName = rawLocal.replace(/\[.*\]$/, "").trim();
112
- for (const lib of options.libraries) {
113
- const libRels = lib.rels || lib.defs?.rels || {};
114
- const relHash = lib.relAlias?.[libName] || (libName.startsWith("@") ? libName : null);
115
- const rel = (relHash && libRels[relHash]) || libRels[libName];
116
- if (rel && !(localName in rels)) {
117
- rels[localName] = { ...rel, _library: true };
118
- }
119
- }
120
- }
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];
121
183
  }
184
+ rels[name] = rel;
122
185
  }
186
+ rels.__main__ = { def: exp };
187
+
188
+ expandPatternsInRels(rels, defs.patterns, options);
123
189
 
124
- const { relAlias, compileStats } = compileTypes(representatives, rels, options);
190
+ const { relAlias, compileStats } = compileTypes(representatives, rels, {
191
+ ...options,
192
+ _useRelAlias: useRelHashes
193
+ });
125
194
 
126
195
  return {rels, representatives, relAlias, compileStats, sourceDefs: defs};
127
196
  }