@fraczak/k 8.7.0 → 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.
package/CHANGELOG.md CHANGED
@@ -5,7 +5,21 @@ All notable changes to this project will be documented here.
5
5
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
6
6
  This project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
- ## [8.7.0] — 2026-11-07 — Standard Library Modularization and Source Header Directives
8
+ ## [8.7.1] — 2026-11-08 — Content-Addressable Library Isolation and Scope Binding Fixes
9
+
10
+ - **Strict Content-Addressable Library Isolation**:
11
+ - Loading a library with `--lib` makes relations and pattern templates available in memory strictly by their `@<hash>`. Friendly names (aliases recorded in library metadata) never enter compilation scope by default.
12
+ - Fix unintended leakage of friendly names into compilation scope when importing libraries.
13
+ - **Explicit Scope Binding (`--use`)**:
14
+ - Friendly names or aliases enter compilation scope only when explicitly requested via `--use <spec>` on the CLI or `useSpecs` in the API.
15
+ - Preserve exact 1-to-1 source line numbers in diagnostics and AST nodes without synthetic text preambles.
16
+ - **Eliminate Symbol Renaming Across `lib/` Modules**:
17
+ - Remove all `libname:localname` aliasing colons across `lib/*.k` header comments and bodies (`inc_bits`, `list_size`, etc.).
18
+ - Allow standard libraries to load cleanly in the REPL (`:load`) when prerequisites are loaded in order, with zero aliasing magic.
19
+ - **Library Isolation Test Suite**:
20
+ - Add `tests/test-library-isolation.mjs` verifying relation and pattern template isolation, hash-only access, explicit `--use`, exact line numbers, and sequential REPL `:load`.
21
+
22
+ ## [8.7.0] — 2026-11-07 — Standard Library Modularization and In-Memory Library Loading
9
23
 
10
24
  - **Standard Library Modularization into `lib/`**:
11
25
  - Reorganize core library modules from `Examples/` into a dedicated `lib/` directory:
@@ -18,14 +32,15 @@ This project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
18
32
  - `lib/ieee.k`: Binary64 IEEE 754 float types and conversion (`float64[]`).
19
33
  - `lib/djson.k`: Universal dynamic JSON schema and RFC 8259 parser (`djson[]`).
20
34
  - Remove all hardcoded content hashes (`@hash`) from standard library source files.
21
- - **Source Header Directives (`# --lib ... --use ...`)**:
22
- - Add leading `# --lib <dependency> --use <specs>` comment directives to declare library dependencies and imported symbols at the top of `.k` files without hardcoded hashes.
23
- - Implement scoped origin resolution in the compiler so that name clashes across chained dependencies (e.g. `inc` in `lib/bits.k` vs. `lib/arithmetics.k`) resolve unambiguously to the intended origin.
24
- - Support relation and pattern alias specs: `name`, `libname:localname`, `pattern[Params]`, and `pattern[Params]:localname[Params]`.
35
+ - **In-Memory Library Loading & Dependency Comments (`# --lib ... --use ...`)**:
36
+ - Add leading `# --lib <dependency> --use <specs>` header comments to document library dependencies and symbol usage at the top of `.k` files without hardcoded hashes.
37
+ - `# --lib` lines remain strictly human-readable comments (never synthesized as text preambles), preserving exact 1-to-1 source line numbers in diagnostics, AST nodes, and warnings.
38
+ - `--lib <dependency.klib>` makes library relations and patterns available in memory indexed strictly by their content hashes (`@hash`); friendly names are never in scope by default.
39
+ - `--use <spec>` explicitly brings requested friendly names or aliases into compilation scope in memory without modifying source text or line numbers.
25
40
  - **Toolchain & REPL Integration**:
26
- - Support automatic header directive extraction across `compileLibrary`, `compileObject`, `k.mjs`, `kvm.mjs`, LLVM, and Wasm backends.
27
- - REPL `:load` automatically parses header directives from source and binds aliases against the active session's loaded libraries.
28
- - Update all benchmarks, test harnesses, documentation, and shell pipelines to use `lib/` and header directives.
41
+ - Pass `--lib` and `--use` directly into compiler options across `compileLibrary`, `compileObject`, `k.mjs`, `kvm.mjs`, LLVM, and Wasm backends.
42
+ - REPL `:load` brings session library definitions into scope ambiently in memory.
43
+ - Update all benchmarks, test harnesses, documentation, and shell pipelines to use `lib/` modules.
29
44
 
30
45
  ## [8.6.1] — 2026-11-04 — REPL `:all-patterns` and Shared-Graph Boundary Pattern Printing
31
46
 
@@ -76,75 +76,49 @@ Only one `--lib` is accepted on the command line by current CLI tools. Chained
76
76
  libraries carry forward definitions from their predecessors, so compiling a
77
77
  series of libraries extends the environment cumulatively.
78
78
 
79
- ### Source header directives (`# --lib ... --use ...`)
79
+ ### Source header comments (`# --lib ... --use ...`)
80
80
 
81
- To avoid scattering hardcoded content hashes (`@hash`) throughout source code,
82
- `.k` files declare their library dependencies and imported symbols using header
83
- comment directives at the very top of the file:
81
+ To clearly document dependencies and recommended compilation options without scattering hardcoded content hashes (`@hash`) throughout source code, `.k` files declare their library dependencies and imported symbols using header comments at the very top of the file:
84
82
 
85
83
  ```k
86
84
  # --lib <dependency-path> --use <spec1> <spec2> ...
87
85
  ```
88
86
 
89
- #### Syntax
90
-
91
- 1. **Placement**: Directives must appear in the first comment block at the very
92
- top of the file, before any relation or pattern definitions.
93
- 2. **Comment prefix**: Directives start with `# --lib` (or `# lib`). Because `#`
94
- is a standard one-line comment character in k, the line is fully valid k
95
- syntax and is ignored by basic parsers.
96
- 3. **Target library**: `<dependency-path>` indicates the library providing the
97
- symbols (for example, `lib/bits.k` or `lib/string.k`).
98
- 4. **Import specs**: `--use` is followed by one or more whitespace- or
99
- comma-separated specs:
100
- - `name`: imports the relation or pattern `name` into local scope under the
101
- same name (emits `name = @hash;` or `name[X] = @hash[X];`).
102
- - `libname:localname`: imports the relation or pattern `libname` under a local
103
- alias `localname` (emits `localname = @hash;`).
104
- - `pattern[Params]`: imports a named pattern explicitly with its parameter
105
- signature (e.g. `btrie[V]` or `byte[]`).
106
- - `pattern[Params]:localname[Params]`: imports a named pattern under a local
107
- alias (e.g. `float64[]:number[]`).
108
-
109
- Multiple `# --lib` lines can be declared to import from different libraries or
110
- to group imports logically:
87
+ #### Syntax & Convention
88
+
89
+ 1. **Placement**: Comments appear in the first comment block at the very top of the file, before any relation or pattern definitions.
90
+ 2. **Comment prefix**: Lines start with `# --lib`. Because `#` is a standard one-line comment character in k, the line is fully valid k syntax and is treated purely as a comment. It is **not** an active compiler directive.
91
+ 3. **Target library**: `<dependency-path>` indicates the library providing the symbols (for example, `lib/bits.k` or `lib/string.k`).
92
+ 4. **Symbol specs**: `--use` lists the symbols used from the library:
93
+ - `name`: references a library relation or pattern under the same name.
94
+ - `libname:localname`: aliases a library relation or pattern `libname` under a local name `localname`.
95
+ - `pattern[Params]`: references a named pattern with its parameter signature (e.g. `btrie[V]` or `byte[]`).
96
+ - `pattern[Params]:localname[Params]`: aliases a named pattern under a local name (e.g. `float64[]:number[]`).
97
+
98
+ Multiple `# --lib` lines can be declared to document multiple dependencies:
111
99
 
112
100
  ```k
113
- # --lib lib/bits.k --use trim inv_loop inv cmp
114
- # --lib lib/bits.k --use inc:inc_bits dec:dec_bits plus:plus_bits minus:minus_bits mul:mul_bits
101
+ # --lib lib/bits.k --use trim inv_loop inv cmp inc_bits dec_bits plus_bits minus_bits mul_bits
115
102
  ```
116
103
 
117
- #### How the compiler interprets header directives
118
-
119
- When source code is compiled with library dependencies (`k-compile`, `k.mjs`,
120
- `compileLibrary`, `compileObject`, or the REPL's `:load`):
121
-
122
- 1. **Extraction**: The compiler extracts all `# --lib` directives from the
123
- leading comment block.
124
- 2. **Scoped origin resolution**: Symbols are looked up against the loaded
125
- libraries. If multiple loaded libraries contain definitions with the same
126
- name (for example, `inc` in `lib/bits.k` for bit-tree increments versus `inc`
127
- in `lib/arithmetics.k` for signed integer increments), the directive
128
- `# --lib lib/bits.k --use inc:inc_bits` checks the metadata origins of the
129
- libraries to bind the exact definition authored in `lib/bits.k`.
130
- 3. **Preamble generation**: The compiler generates an in-memory alias preamble
131
- mapping each symbol to its canonical hash (e.g. `inc_bits = @RFYjYZZ...;`)
132
- and prepends it to the compilation unit.
133
- 4. **Deduplication**: Aliases are deduplicated by local target name, avoiding
134
- redundant definitions if a symbol is referenced across multiple directives
135
- or CLI options.
136
-
137
- #### Interaction with CLI `--lib` and `--use`
138
-
139
- - When compiling a source file that already declares its imports via `# --lib`
140
- header comments, you only need to supply `--lib <file.klib>` on the command
141
- line. You **do not** need to repeat the `--use` flags; the compiler reads them
142
- directly from the source header:
104
+ #### How `--lib` and `--use` Work
105
+
106
+ When source code is compiled with library dependencies (`k-compile`, `k.mjs`, `compileLibrary`, `compileObject`, or the REPL's `:load`):
107
+
108
+ 1. **Content-Addressed Availability (Hash-Only)**: When `--lib file.klib` is supplied, all relations and patterns defined in the library are available in memory indexed strictly by their content hashes (`@<hash>`). Friendly names (the aliases recorded in library metadata) are **never** in scope by default.
109
+ 2. **Explicit Symbol Scope (`--use`)**: To bring a library relation or pattern into scope under a friendly name, `--use <spec>` must be specified (or `useSpecs` passed in the compiler API). The compiler resolves the spec against the library's metadata aliases and binds the friendly or aliased name directly in the in-memory symbol tables.
110
+ 3. **No Automatic Ingestion or Precedence Ambiguity**: Because library friendly names are not in scope without `--use`, there is no implicit shadowing or "precedence". Local definitions define local names; library definitions are accessed by `@<hash>` or by the names explicitly brought into scope via `--use`.
111
+ 4. **No Text Synthesis or Line Offset**: The compiler never synthesizes source code or prepends preamble text to user files. Source text remains completely untouched, preserving exact 1-to-1 line numbers in AST nodes, diagnostics, warnings, and error messages.
112
+
113
+ #### Command-Line Usage
114
+
115
+ - Compile a file using a pre-compiled library and explicit `--use` bindings (as documented in the file's header comments):
143
116
  ```sh
144
- node objects/compile.mjs --lib /tmp/bits.klib lib/list.k /tmp/list.klib
117
+ node objects/compile.mjs --lib /tmp/bits.klib \
118
+ --use "trim inv_loop inv cmp inc_bits dec_bits plus_bits minus_bits mul_bits" \
119
+ lib/arithmetics.k /tmp/arithmetics.klib
145
120
  ```
146
- - Command-line `--use spec` flags remain available for ad-hoc snippets or to
147
- override/supplement aliases when invoking `k.mjs` or `k-compile`:
121
+ - Command-line `--use spec` flags bring relations into scope for evaluation:
148
122
  ```sh
149
123
  printf '42\n' | node codecs/int.mjs --parse |
150
124
  node k.mjs --lib /tmp/k-math.klib --use inc 'inc' |
@@ -153,13 +153,11 @@ printf '42\n' | node codecs/int.mjs --parse |
153
153
  node codecs/int.mjs --print
154
154
  ```
155
155
 
156
- This prints `43`. When compiling chained libraries such as `lib/bits.k` or
157
- `lib/arithmetics.k`, dependencies and imported aliases are declared directly in
158
- the source header comments (`# --lib ... --use ...`), so explicit `--use` flags
159
- are not needed on the compile command line. For ad-hoc expressions on the CLI,
160
- `--use inc` brings the library relation into scope from the command line.
161
- Library relations and patterns are also accessible by their canonical content
162
- hashes.
156
+ This prints `43`. When compiling with `--lib /tmp/bits.klib`, all definitions
157
+ from the library are available in memory during compilation.
158
+ For ad-hoc expressions on the CLI, `--use inc` brings the library relation
159
+ into scope under a local alias. Library relations and patterns are also
160
+ accessible by their canonical content hashes.
163
161
 
164
162
  To compile a small executable object and run it:
165
163
 
package/DOCS/PATTERNS.md CHANGED
@@ -36,22 +36,15 @@ Relations can refer to other definitions in the same source, including recursive
36
36
  references. Labels can be identifiers or quoted strings with escapes. Line
37
37
  comments use `--`, `//`, `#`, or `%`; block comments use `/* ... */`.
38
38
 
39
- ### Source header directives and library imports
39
+ ### Source header comments and library dependencies
40
40
 
41
- Files can declare library dependencies and imported symbols using header comment directives at the very top of the file:
41
+ Files document their library dependencies and imported symbols using header comments at the very top of the file:
42
42
 
43
43
  ```k
44
44
  # --lib <dependency-path> --use <spec1> <spec2> ...
45
45
  ```
46
46
 
47
- Because `#` is a standard line comment character in k, this directive is valid k syntax and is ignored by basic parsers. The compilation toolchain (`k-compile`, `compileLibrary`, `k.mjs`, `kvm.mjs`, backends, and the REPL) inspects the first comment block and automatically binds each imported symbol to its canonical content hash:
48
-
49
- - `name`: imports relation or pattern `name` into local scope under the same name.
50
- - `libname:localname`: imports relation or pattern `libname` under a local alias `localname`.
51
- - `pattern[Params]`: imports a named pattern template explicitly with parameter signature (e.g. `btrie[V]` or `byte[]`).
52
- - `pattern[Params]:localname[Params]`: imports a named pattern template under a local alias (e.g. `float64[]:number[]`).
53
-
54
- Directives can be repeated across multiple lines to import from multiple libraries or group symbols. Scoped origin resolution ensures that if multiple loaded libraries define relations with the same name (such as `inc` in `lib/bits.k` for bit trees vs. `inc` in `lib/arithmetics.k` for signed integers), the directive binds to the definition authored in `<dependency-path>`. This avoids hardcoding content hashes (`@hash`) in source files. See [file formats and tools](FILE_FORMATS.md#source-header-directives---lib-----use---) for complete details.
47
+ Because `#` is a standard line comment character in k, these lines are valid k syntax and remain purely comments. They document the dependency relations for readers and build tools. When compiling with `--lib`, definitions from the library are available in memory by their content hashes (`@<hash>`), and `--use` brings requested friendly names or aliases into the local compilation scope. See [file formats and tools](FILE_FORMATS.md#source-header-comments---lib-----use---) for complete details.
55
48
 
56
49
  ## Pattern syntax
57
50
 
package/DOCS/REPL.md CHANGED
@@ -60,9 +60,8 @@ Libraries are loaded explicitly. `poly.k` depends on definitions in
60
60
  a codec does not automatically load its corresponding k library.
61
61
 
62
62
  `:load` compiles a `.k` file in the current library context or loads a plain
63
- JSON `.klib`. When compiling a `.k` file, it reads any `# --lib <path> --use <specs>`
64
- header directives in the leading comment block and resolves them against the
65
- loaded libraries in the session. It recovers relation and pattern aliases
63
+ JSON `.klib`. All relations and patterns in the current session library context
64
+ are available in memory during compilation. It recovers relation and pattern aliases
66
65
  unless `--no-alias` is specified. Source libraries' terminal expressions are not
67
66
  run by `:load`.
68
67
 
package/README.md CHANGED
@@ -77,11 +77,11 @@ relations, libraries, and codecs.
77
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
78
  | [Examples/ieee-arithmetics.k](Examples/ieee-arithmetics.k) | Binary64 arithmetic returning `{result, flags}`; load `lib/bit.k` through `lib/ieee.k` first |
79
79
 
80
- Load libraries explicitly with `:load` in the REPL. Source files declare
80
+ Load libraries explicitly with `:load` in the REPL. Source files document
81
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
82
+ header comments at the top of the file. Supplying `--lib <dependency.klib>`
83
+ brings all library definitions into scope in memory during compilation.
84
+ Command-line `--use` flags allow defining in-memory aliases. See
85
85
  [file formats and tools](DOCS/FILE_FORMATS.md).
86
86
 
87
87
  ## JavaScript API
@@ -118,10 +118,9 @@ export async function compileProgramInputToObject(
118
118
  const specs = useSpecs.length > 0 ? useSpecs : exportSpecs;
119
119
  let object;
120
120
  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, {
121
+ const objBuffer = compileObjectBuffer(input.source, {
124
122
  libraries,
123
+ useSpecs: specs,
125
124
  source: input.sourceName
126
125
  });
127
126
  object = decodeObject(objBuffer);
@@ -130,19 +129,17 @@ export async function compileProgramInputToObject(
130
129
  throw new Error("stdin source requested without a stdin stream");
131
130
  }
132
131
  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, {
132
+ const objBuffer = compileObjectBuffer(source, {
136
133
  libraries,
134
+ useSpecs: specs,
137
135
  source: input.sourceName
138
136
  });
139
137
  object = decodeObject(objBuffer);
140
138
  } else if (input.kind === "source-file") {
141
139
  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, {
140
+ const objBuffer = compileObjectBuffer(source, {
145
141
  libraries,
142
+ useSpecs: specs,
146
143
  source: input.sourceName
147
144
  });
148
145
  object = decodeObject(objBuffer);
@@ -123,7 +123,9 @@ node --input-type=module -e "import assert from 'node:assert/strict'; import { s
123
123
 
124
124
  node ../../objects/compile.mjs ../../lib/bit.k "$TMP_DIR/bit.klib"
125
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"
126
+ node ../../objects/compile.mjs --lib "$TMP_DIR/bits.klib" \
127
+ --use "trim inv_loop inv cmp inc_bits dec_bits plus_bits minus_bits mul_bits" \
128
+ ../../lib/arithmetics.k "$TMP_DIR/arithmetics.klib"
127
129
  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"
128
130
  printf '987654321' \
129
131
  | node ../../codecs/int.mjs --parse \
@@ -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,28 @@ 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 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)
183
+ if [ -n "$prev" ]; then
184
+ node "$K_ROOT/objects/compile.mjs" --lib "$prev" "${uses[@]}" "$src" "$out"
185
+ else
186
+ node "$K_ROOT/objects/compile.mjs" "${uses[@]}" "$src" "$out"
187
+ fi
188
+ }
189
+
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"
182
197
  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
198
  echo "--lib unexpectedly accepted more than once" >&2
184
199
  exit 1
@@ -431,9 +431,6 @@ export function parseHeaderDirectives(source) {
431
431
  }
432
432
  continue;
433
433
  }
434
- if (trimmed.match(/^[a-zA-Z0-9_?!+-]+(?:\[[^\]]*\])?\s*=\s*@[a-zA-Z0-9_-]+(?:\[[^\]]*\])?\s*;/)) {
435
- continue;
436
- }
437
434
  break;
438
435
  }
439
436
  return directives;
package/compiler.mjs CHANGED
@@ -18,6 +18,32 @@ 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
+ 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;
42
+ }
43
+ }
44
+ }
45
+ }
46
+ }
21
47
  const compileStats = {
22
48
  sccs: []
23
49
  };
package/index.mjs CHANGED
@@ -41,21 +41,86 @@ function annotate(script, options = {}) {
41
41
  const representatives = codes.register(defs.codes);
42
42
  const rels = {...defs.rels, "__main__": {def: exp}};
43
43
 
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.
46
+ if (options.libraries) {
47
+ for (const lib of options.libraries) {
48
+ const libPatterns =
49
+ lib.patterns ||
50
+ lib.defs?.patterns ||
51
+ lib.sourceDefs?.patterns ||
52
+ {};
53
+ for (const [name, pat] of Object.entries(libPatterns)) {
54
+ if (name.startsWith("@") && !(name in (defs.patterns || {}))) {
55
+ if (!defs.patterns) defs.patterns = {};
56
+ defs.patterns[name] = pat;
57
+ }
58
+ }
59
+ }
60
+ }
61
+
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
+ }
84
+ }
85
+ }
86
+
44
87
  validatePatternDefinitions(defs.patterns || {}, options);
45
88
  expandPatternsInRels(rels, defs.patterns || {}, options);
46
89
 
47
- // Inject library relations into the rels table so @hash refs resolve
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.
48
92
  if (options.libraries) {
49
93
  for (const lib of options.libraries) {
50
94
  const libRels = lib.rels || lib.defs?.rels || {};
51
95
  for (const [name, rel] of Object.entries(libRels)) {
52
- if (!(name in rels)) {
96
+ if (name.startsWith("@") && !(name in rels)) {
53
97
  rels[name] = { ...rel, _library: true };
54
98
  }
55
99
  }
56
100
  }
57
101
  }
58
102
 
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
+ }
121
+ }
122
+ }
123
+
59
124
  const { relAlias, compileStats } = compileTypes(representatives, rels, options);
60
125
 
61
126
  return {rels, representatives, relAlias, compileStats, sourceDefs: defs};
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];
package/lib/arithmetics.k CHANGED
@@ -1,5 +1,4 @@
1
- # --lib lib/bits.k --use trim inv_loop inv cmp
2
- # --lib lib/bits.k --use inc:inc_bits dec:dec_bits plus:plus_bits minus:minus_bits mul:mul_bits
1
+ # --lib lib/bits.k --use trim inv_loop inv cmp inc_bits dec_bits plus_bits minus_bits mul_bits
3
2
 
4
3
  -- lib/arithmetics.k — Signed arbitrary-precision integers (int[])
5
4
 
package/lib/bits.k CHANGED
@@ -219,3 +219,9 @@ mul_loop = <
219
219
  >;
220
220
 
221
221
  mul = { .x inv x, .y y, _ acc } mul_loop;
222
+
223
+ inc_bits = inc;
224
+ dec_bits = dec;
225
+ plus_bits = plus;
226
+ minus_bits = minus;
227
+ mul_bits = mul;
package/lib/djson.k CHANGED
@@ -1,8 +1,8 @@
1
1
  # --lib lib/bits.k --use inc lt? plus minus times1024
2
2
  # --lib lib/list.k --use reverse
3
- # --lib lib/btrie.k --use btrie[V] nth_trie put_nth remove_nth obj_size:list_size obj_size obj_values_raw values_to_trie
3
+ # --lib lib/btrie.k --use btrie[V] nth_trie put_nth remove_nth list_size obj_size obj_values_raw values_to_trie
4
4
  # --lib lib/string.k --use unicode[] string[] eq_char? _quote_ _backslash_ _slash_ _bs_ _ff_ _lf_ _cr_ _tab_ n_char u_char l_char t_char r_char e_char f_char a_char s_char quote_char backslash_char slash_char b_char comma_char colon_char open_array close_array open_object close_object ws minus_char digit hex4 c1024 c55296 c56320 c57344 c65536 dot put remove str_len obj_keys_raw to_unicode
5
- # --lib lib/ieee.k --use float64[]:number[] finite_float64? natToFloat64 scanFloat64
5
+ # --lib lib/ieee.k --use float64[] finite_float64? natToFloat64 scanFloat64
6
6
 
7
7
  -- lib/djson.k — Universal dynamic JSON schema (djson[]), methods, and RFC 8259 parser
8
8
 
@@ -13,7 +13,8 @@
13
13
  bit[] = < {} 0, {} 1 >;
14
14
  bool[] = < {} true, {} false >;
15
15
  bits[] = < {} _, B 0, B 1 > = B;
16
- list[X] = < {} nil, { X car, L cdr } cons > = L;
16
+ list[X] = < {} nil, { X car, L cdr } cons > = L;
17
+ number[] = float64[];
17
18
 
18
19
  is0 = ?bit[] /0;
19
20
  true_bool = {} |true ?bool[];
package/lib/list.k CHANGED
@@ -1,4 +1,4 @@
1
- # --lib lib/bits.k --use inc:inc_bits
1
+ # --lib lib/bits.k --use inc_bits
2
2
 
3
3
  -- lib/list.k — Parametric linked lists (list[X])
4
4