@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/CHANGELOG.md CHANGED
@@ -5,7 +5,38 @@ 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.8.0] — 2026-11-13 — Standard Library Consolidation, Tail-Recursive Conventions, and Plain Dependency Comments
9
+
10
+ - **Standard Library Consolidation (`lib/`)**:
11
+ - Reorganize standard library modules into four focused files (`lib/generic.k`, `lib/integer.k`, `lib/ieee.k`, `lib/djson.k`), replacing `lib/bit.k`, `lib/bits.k`, `lib/arithmetics.k`, `lib/list.k`, `lib/btrie.k`, and `lib/string.k`.
12
+ - Make `lib/integer.k` completely self-contained with zero dependencies (defines `bit[]` and `bits[]` locally alongside arbitrary-precision signed integer arithmetic, Karatsuba `times`, `divmod`, `div`, `mod`, `gcd`, and `lcm`).
13
+ - Rename `parseJson` to `parse_json` in `lib/djson.k` and align helper names and signatures across `lib/`.
14
+ - Enforce uniform style and correctness conventions across all `lib/` modules: every `?`-suffixed relation is an identity filter (`?X -> ?X`), all recursive loops are strictly tail-recursive, internal helpers use `_`-prefixed names, discarded fields use descriptive `_<field>` labels, and redundant `()` compositions are removed.
15
+ - Add dedicated per-library specification test suites (`tests/test-generic.mjs`, `tests/test-integer.mjs`, `tests/test-ieee.mjs`, `tests/test-djson.mjs`) and update browser REPL (`scripts/build-repl-html.mjs`), example files, and `k-vscode` tests.
16
+ - **Plain Comment Handling & Library Isolation**:
17
+ - Remove `parseHeaderDirectives` and `parseHeaderUses` from `canonical-pattern.mjs`, `object.mjs`, `backend-api.mjs`, and `backends/llvm/src/cli.mjs` so `# --lib ...` comments are never parsed specially and remain strictly ordinary K comments across tests, scripts, and integration pipelines.
18
+ - Strengthen scope binding and transitive library pattern forwarding in `index.mjs`, `compiler.mjs`, `canonical-pattern.mjs`, and `object.mjs`, including `--use` redefinition warnings and expanded coverage in `tests/test-library-isolation.mjs`.
19
+ - **Example Cleanup & Browser REPL Documentation**:
20
+ - Remove obsolete `Examples/arithmetics.k` (superseded by `lib/integer.k`) and unused `Examples/esc.k`.
21
+ - Include `Examples/nat.k` in the browser REPL VFS alongside the remaining examples and update the `repl.html` dropdown and Help reference.
22
+ - **Documentation Cleanup**:
23
+ - Update `README.md`, `AGENTS.md`, `DOCS/CODECS.md`, `DOCS/FILE_FORMATS.md`, `DOCS/GETTING_STARTED.md`, `DOCS/PATTERNS.md`, `DOCS/REPL.md`, `objects/README.md`, and `tests/README.md` for the consolidated `lib/` structure, plain dependency comment convention, valid CLI pipelines, and fixed internal anchor links.
24
+
25
+ ## [8.7.1] — 2026-11-08 — Content-Addressable Library Isolation and Scope Binding Fixes
26
+
27
+ - **Strict Content-Addressable Library Isolation**:
28
+ - 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.
29
+ - Fix unintended leakage of friendly names into compilation scope when importing libraries.
30
+ - **Explicit Scope Binding (`--use`)**:
31
+ - Friendly names or aliases enter compilation scope only when explicitly requested via `--use <spec>` on the CLI or `useSpecs` in the API.
32
+ - Preserve exact 1-to-1 source line numbers in diagnostics and AST nodes without synthetic text preambles.
33
+ - **Eliminate Symbol Renaming Across `lib/` Modules**:
34
+ - Remove all `libname:localname` aliasing colons across `lib/*.k` header comments and bodies (`inc_bits`, `list_size`, etc.).
35
+ - Allow standard libraries to load cleanly in the REPL (`:load`) when prerequisites are loaded in order, with zero aliasing magic.
36
+ - **Library Isolation Test Suite**:
37
+ - Add `tests/test-library-isolation.mjs` verifying relation and pattern template isolation, hash-only access, explicit `--use`, exact line numbers, and sequential REPL `:load`.
38
+
39
+ ## [8.7.0] — 2026-11-07 — Standard Library Modularization and In-Memory Library Loading
9
40
 
10
41
  - **Standard Library Modularization into `lib/`**:
11
42
  - Reorganize core library modules from `Examples/` into a dedicated `lib/` directory:
@@ -18,14 +49,15 @@ This project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
18
49
  - `lib/ieee.k`: Binary64 IEEE 754 float types and conversion (`float64[]`).
19
50
  - `lib/djson.k`: Universal dynamic JSON schema and RFC 8259 parser (`djson[]`).
20
51
  - 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]`.
52
+ - **In-Memory Library Loading & Dependency Comments (`# --lib ... --use ...`)**:
53
+ - Add leading `# --lib <dependency> --use <specs>` header comments to document library dependencies and symbol usage at the top of `.k` files without hardcoded hashes.
54
+ - `# --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.
55
+ - `--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.
56
+ - `--use <spec>` explicitly brings requested friendly names or aliases into compilation scope in memory without modifying source text or line numbers.
25
57
  - **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.
58
+ - Pass `--lib` and `--use` directly into compiler options across `compileLibrary`, `compileObject`, `k.mjs`, `kvm.mjs`, LLVM, and Wasm backends.
59
+ - REPL `:load` brings session library definitions into scope ambiently in memory.
60
+ - Update all benchmarks, test harnesses, documentation, and shell pipelines to use `lib/` modules.
29
61
 
30
62
  ## [8.6.1] — 2026-11-04 — REPL `:all-patterns` and Shared-Graph Boundary Pattern Printing
31
63
 
package/DOCS/CODECS.md CHANGED
@@ -116,45 +116,43 @@ witness derivation. General wire semantics are specified in
116
116
  `del`, `push`, `keys`, and `values`. The specializing JSON codec and dynamic
117
117
  JSON codec serve different schemas; they are not interchangeable encodings.
118
118
 
119
- The library references earlier `lib/` types by their canonical hashes. Its
120
- `number[]` is the IEEE `float64[]`; the sign, exponent, and fraction schemas
121
- are shared too. In the REPL, load `lib/bit.k`, `lib/bits.k`, `lib/list.k`,
122
- `lib/btrie.k`, `lib/string.k`, `lib/ieee.k`, then `lib/djson.k`. When
123
- compiling, chain the `lib/` modules in order so each `.klib` carries forward
124
- the accumulated definitions.
125
-
126
- `lib/ieee.k` contains the binary64 representation, constructors and
127
- predicates, and text conversion. Heavy add/subtract/multiply/divide definitions
128
- are in `Examples/ieee-arithmetics.k`; load that file after `lib/ieee.k`
129
- when arithmetic is needed. JSON parsing uses `lib/ieee.k` alone.
130
-
131
- `parseFloat64`: `string[]` → `float64[]` accepts JSON-style decimal syntax,
132
- an optional leading `+`, surrounding ASCII JSON whitespace, and the words
133
- `Infinity` and `NaN` with optional signs. Overflow yields signed infinity;
134
- underflow preserves signed zero. Invalid text is undefined.
135
- `printFloat64`: `float64[]` → `string[]` produces an exact decimal expansion
136
- for finite values, preserving signed zero. It prints infinities as `Infinity`
137
- or `-Infinity`, and all NaNs as `NaN`. Parsing NaN text selects one canonical
138
- payload; NaN payloads are not preserved through text.
139
- The printer prioritizes exact round-trips over shortest formatting: `0.1`
140
- prints as `0.1000000000000000055511151231257827021181583404541015625`.
141
-
142
- The library also defines `parseJson`: `string[]` → `djson[]`, entirely in k.
143
- It consumes one complete JSON document, including nested containers, Unicode
144
- escapes, and decimal numbers rounded to binary64. Invalid JSON, unpaired
119
+ `lib/integer.k` is completely self-contained, `lib/generic.k` and `lib/ieee.k`
120
+ depend on `core.k`, and `lib/djson.k` composes `core.k`, `lib/generic.k`,
121
+ and `lib/ieee.k`. Its `number[]` is the IEEE `float64[]`; the sign, exponent,
122
+ and fraction schemas are shared too. In the REPL, load `core.k`,
123
+ `lib/generic.k`, `lib/ieee.k`, then `lib/djson.k`. When compiling on the CLI,
124
+ chain each module in order with `--lib` so the single compiled `.klib` carries
125
+ forward all accumulated definitions.
126
+
127
+ `lib/ieee.k` contains the binary64 representation, constructors, identity
128
+ predicates (`zero_float64?`, `finite_float64?`, `inf_float64?`, `nan_float64?`),
129
+ negation (`negate_float64`), and rational/integer conversions
130
+ (`ratio_to_float64`, `bits_to_float64`). Heavy floating-point arithmetic is in
131
+ `Examples/ieee-arithmetics.k`; load that file after `lib/ieee.k` when arithmetic
132
+ is needed. IEEE text parsing and formatting are handled at boundaries by
133
+ `codecs/ieee.mjs`, while JSON decimal number parsing lives inside `lib/djson.k`.
134
+
135
+ `lib/djson.k` defines `parse_json`: `string[]` → `djson[]`, entirely in k.
136
+ It consumes one complete RFC 8259 JSON document, including nested containers,
137
+ Unicode escapes, and decimal numbers rounded to binary64. Invalid JSON, unpaired
145
138
  surrogate escapes, and numbers that overflow to infinity are undefined.
146
139
  For example, decode UTF-8 to a k string, then parse that string in k:
147
140
 
148
141
  ```sh
149
- node objects/compile.mjs lib/bit.k /tmp/bit.klib
150
- node objects/compile.mjs --lib /tmp/bit.klib lib/bits.k /tmp/bits.klib
151
- node objects/compile.mjs --lib /tmp/bits.klib lib/list.k /tmp/list.klib
152
- node objects/compile.mjs --lib /tmp/list.klib lib/btrie.k /tmp/btrie.klib
153
- node objects/compile.mjs --lib /tmp/btrie.klib lib/string.k /tmp/string.klib
154
- node objects/compile.mjs --lib /tmp/string.klib lib/ieee.k /tmp/ieee.klib
155
- node objects/compile.mjs --lib /tmp/ieee.klib lib/djson.k /tmp/djson.klib
142
+ node objects/compile.mjs core.k /tmp/core.klib
143
+ node objects/compile.mjs --lib /tmp/core.klib \
144
+ --use 'bit[] bits[] list[X] byte[] ascii[] bmp_hi_common[] bmp_hi_private_use[] plane0[] plane_02_10[] unicode[] string[]' \
145
+ lib/generic.k /tmp/generic.klib
146
+ node objects/compile.mjs --lib /tmp/generic.klib \
147
+ --use 'bit[] bits[]' \
148
+ lib/ieee.k /tmp/ieee.klib
149
+ node objects/compile.mjs --lib /tmp/ieee.klib \
150
+ --use 'bit[] bits[] list[] byte[] ascii[] bmp_hi_common[] bmp_hi_private_use[] plane0[] plane_02_10[] unicode[] string[]' \
151
+ --use 'bool[] false? true? order[] lt? eq? gt? opt[] reverse trim_bits inc_bits btrie[] btrie_empty btrie_get btrie_set btrie_del btrie_entries_raw btrie_max_key btrie_bfs_values string_to_bits bits_to_string' \
152
+ --use 'sign[] float64[] pos_zero neg_zero finite_float64? ratio_to_float64' \
153
+ lib/djson.k /tmp/djson.klib
156
154
  printf '%s' '{"answer":42}' | node codecs/utf8.mjs --parse |
157
- node k.mjs --lib /tmp/djson.klib --use parseJson 'parseJson' |
155
+ node k.mjs --lib /tmp/djson.klib --use parse_json 'parse_json' |
158
156
  node codecs/djson.mjs --print
159
157
  ```
160
158
 
@@ -162,18 +160,22 @@ This prints `{"answer":42}`. Exact conversion near binary64 limits is expensive
162
160
  in the envelope-aware JavaScript interpreter; the Wasm backend runs the same
163
161
  relation with much less overhead.
164
162
 
165
- The compiled IEEE library also supports a complete text round-trip in k:
163
+ The IEEE library can also convert bit sequences directly to `float64[]` and
164
+ format them with `codecs/ieee.mjs`:
166
165
 
167
166
  ```sh
168
- printf '%s' '1.5' | node codecs/utf8.mjs --parse |
169
- node k.mjs --lib /tmp/ieee.klib --use parseFloat64 --use printFloat64 'parseFloat64 printFloat64' |
170
- node codecs/utf8.mjs --print
167
+ node codecs/unit.mjs --parse |
168
+ node k.mjs --lib /tmp/ieee.klib --use bits_to_float64 '{} |_ |0 |1 |0 |1 |0 |1 bits_to_float64' |
169
+ node codecs/ieee.mjs --print
171
170
  ```
172
171
 
173
- For arithmetic, compile the optional layer against the same IEEE library:
172
+ For arithmetic, compile the optional layer against the same IEEE library
173
+ using explicit `--use` bindings:
174
174
 
175
175
  ```sh
176
- node objects/compile.mjs --lib /tmp/ieee.klib Examples/ieee-arithmetics.k /tmp/ieee-arithmetics.klib
176
+ node objects/compile.mjs --lib /tmp/ieee.klib \
177
+ --use '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?' \
178
+ Examples/ieee-arithmetics.k /tmp/ieee-arithmetics.klib
177
179
  ```
178
180
 
179
181
  `k-parse` and `k-print` use [textual k values](TEXTUAL_VALUES.md), rather than
@@ -67,93 +67,70 @@ This prints `"hello"`. `--lib` loads a dependency; it does not select library
67
67
  output. These are equivalent ways to generate a library from source:
68
68
 
69
69
  ```sh
70
- node objects/compile.mjs lib/bit.k /tmp/bit.klib
71
- node objects/compile.mjs --lib /tmp/bit.klib lib/bits.k /tmp/bits.klib
72
- node objects/compile.mjs --lib /tmp/bits.klib lib/arithmetics.k /tmp/k-math.klib
70
+ node objects/compile.mjs lib/integer.k /tmp/integer.klib
71
+ node objects/compile.mjs --format klib lib/integer.k /tmp/integer.klib
73
72
  ```
74
73
 
75
74
  Only one `--lib` is accepted on the command line by current CLI tools. Chained
76
75
  libraries carry forward definitions from their predecessors, so compiling a
77
76
  series of libraries extends the environment cumulatively.
78
77
 
79
- ### Source header directives (`# --lib ... --use ...`)
78
+ ### Source dependency comments
80
79
 
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:
80
+ To document expected dependencies and recommended `--use` symbols without
81
+ scattering hardcoded content hashes (`@hash`) throughout source code, `.k` files
82
+ can include ordinary `# --lib ...` comments near the top of the file:
84
83
 
85
84
  ```k
86
85
  # --lib <dependency-path> --use <spec1> <spec2> ...
87
86
  ```
88
87
 
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:
88
+ Because `#` is a standard one-line comment character in k, these lines are valid
89
+ k syntax and are ignored completely by the compiler and CLI tools (they are
90
+ **not** parsed as compiler directives). By convention, `# --lib <path> --use ...`
91
+ lists:
92
+
93
+ - `<dependency-path>`: the expected dependency (for example, `core.k` or `lib/generic.k`).
94
+ - `--use` specs:
95
+ - `name`: references a library relation or pattern under the same name.
96
+ - `libname:localname`: aliases a library relation or pattern `libname` under `localname`.
97
+ - `pattern[Params]`: references a named pattern with its parameter signature (e.g. `btrie[V]` or `byte[]`).
98
+ - `pattern[Params]:localname[Params]`: aliases a named pattern under `localname` (e.g. `float64[]:number[]`).
99
+
100
+ Multiple `# --lib` comment lines may appear when a file uses several libraries:
111
101
 
112
102
  ```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
103
+ # --lib core.k --use bit[] bits[]
115
104
  ```
116
105
 
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:
106
+ #### How `--lib` and `--use` Work
107
+
108
+ When source code is compiled with library dependencies (`k-compile`, `k.mjs`, `compileLibrary`, `compileObject`, or the REPL's `:load`):
109
+
110
+ 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.
111
+ 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.
112
+ 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`. If a name declared via `--use` is redefined (by another `--use` binding or by a local definition), the compiler emits a warning and the later definition wins.
113
+ 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.
114
+
115
+ #### Command-Line Usage
116
+
117
+ - Compile a library or dependent file using explicit `--lib` / `--use` flags:
143
118
  ```sh
144
- node objects/compile.mjs --lib /tmp/bits.klib lib/list.k /tmp/list.klib
119
+ node objects/compile.mjs lib/integer.k /tmp/integer.klib
120
+ node objects/compile.mjs --lib /tmp/integer.klib \
121
+ --use "int[] nat int pos? neg? zero? gt? inc dec" \
122
+ Examples/poly.k /tmp/poly.klib
145
123
  ```
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`:
124
+ - Command-line `--use spec` flags bring relations into scope for evaluation:
148
125
  ```sh
149
126
  printf '42\n' | node codecs/int.mjs --parse |
150
- node k.mjs --lib /tmp/k-math.klib --use inc 'inc' |
127
+ node k.mjs --lib /tmp/integer.klib --use inc 'inc' |
151
128
  node codecs/int.mjs --print
152
129
  ```
153
130
 
154
- This prints `43`. Numeral names such as `5` in the arithmetic library are
155
- relations producing bit trees. `5 int` constructs a signed integer; numeral
156
- names are not builtin literals.
131
+ This prints `43`. `lib/integer.k` defines `0` and `1` as signed integers
132
+ and `nat` to lift unsigned bit sequences such as `{} |_ |1 |0 |1 nat` (5);
133
+ numeral names are not builtin literals.
157
134
 
158
135
  ## Inspect and decompile
159
136
 
@@ -117,12 +117,10 @@ constraints. Derivation convergence does not prove that every program terminates
117
117
 
118
118
  ## Libraries and external numbers
119
119
 
120
- Load the integer library chain and a codec explicitly:
120
+ Load the self-contained integer library and a codec explicitly:
121
121
 
122
122
  ```text
123
- :load lib/bit.k
124
- :load lib/bits.k
125
- :load lib/arithmetics.k
123
+ :load lib/integer.k
126
124
  :codec load codecs/int.mjs
127
125
  :input int.mjs 42
128
126
  ```
@@ -130,10 +128,10 @@ Load the integer library chain and a codec explicitly:
130
128
  Now evaluate `inc` to obtain 43. The codec prints the decimal representation
131
129
  alongside the structural value.
132
130
 
133
- For list operations, load `lib/list.k` and `Examples/poly.k`:
131
+ For list operations, load `Examples/poly.k` on top of `lib/integer.k`:
134
132
 
135
133
  ```text
136
- :load lib/list.k
134
+ :load lib/integer.k
137
135
  :load Examples/poly.k
138
136
  ```
139
137
 
@@ -145,21 +143,16 @@ The command-line runtime receives binary schema+payload data, so use codecs
145
143
  at text boundaries. From the repository root:
146
144
 
147
145
  ```sh
148
- node objects/compile.mjs lib/bit.k /tmp/bit.klib
149
- node objects/compile.mjs --lib /tmp/bit.klib lib/bits.k /tmp/bits.klib
150
- node objects/compile.mjs --lib /tmp/bits.klib lib/arithmetics.k /tmp/arithmetics.klib
146
+ node objects/compile.mjs lib/integer.k /tmp/integer.klib
151
147
  printf '42\n' | node codecs/int.mjs --parse |
152
- node k.mjs --lib /tmp/arithmetics.klib --use inc 'inc' |
148
+ node k.mjs --lib /tmp/integer.klib --use inc 'inc' |
153
149
  node codecs/int.mjs --print
154
150
  ```
155
151
 
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.
152
+ This prints `43`. When compiling or evaluating with `--lib`, library
153
+ definitions are carried in memory indexed by their canonical content hashes
154
+ (`@<hash>`), and `--use` explicitly brings requested friendly names (or
155
+ `libname:localname` aliases) into scope.
163
156
 
164
157
  To compile a small executable object and run it:
165
158
 
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 dependency comments
40
40
 
41
- Files can declare library dependencies and imported symbols using header comment directives at the very top of the file:
41
+ Files can document expected library dependencies and imported symbols using ordinary `#` comments near the 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 ignored completely by the compiler and tools. When compiling with `--lib`, definitions from the library are available in memory strictly 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-dependency-comments) for complete details.
55
48
 
56
49
  ## Pattern syntax
57
50
 
package/DOCS/REPL.md CHANGED
@@ -48,21 +48,17 @@ Regular evaluations include timing; there is no separate timing command.
48
48
  ## Loading and aliases
49
49
 
50
50
  ```text
51
- :load lib/bit.k
52
- :load lib/bits.k
53
- :load lib/arithmetics.k
54
- :load lib/list.k
51
+ :load lib/integer.k
55
52
  :load Examples/poly.k
56
53
  ```
57
54
 
58
55
  Libraries are loaded explicitly. `poly.k` depends on definitions in
59
- `lib/arithmetics.k` and `lib/list.k`, so load them in dependency order. Loading
56
+ `lib/integer.k`, so load them in dependency order. Loading
60
57
  a codec does not automatically load its corresponding k library.
61
58
 
62
59
  `: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
60
+ JSON `.klib`. All relations and patterns in the current session library context
61
+ are available in memory during compilation. It recovers relation and pattern aliases
66
62
  unless `--no-alias` is specified. Source libraries' terminal expressions are not
67
63
  run by `:load`.
68
64
 
@@ -96,7 +92,7 @@ See [patterns and canonical identity](PATTERNS.md).
96
92
  inc
97
93
  ```
98
94
 
99
- Load `lib/bit.k`, `lib/bits.k`, and `lib/arithmetics.k` before using `inc`.
95
+ Load `lib/integer.k` before using `inc`.
100
96
  The codec supplies the integer value; the library supplies the relation.
101
97
 
102
98
  Codecs export `parse` and `print`. Input uses the codec explicitly selected
@@ -1,8 +1,6 @@
1
+ # --lib lib/ieee.k --use 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?
1
2
  -- IEEE binary64 arithmetic.
2
3
 
3
- bit[] = < {} 0, {} 1 >;
4
- sign[] = < {} "+", {} "-" >;
5
-
6
4
  0 = {} |0 ?bit[];
7
5
  1 = {} |1 ?bit[];
8
6
  0? = ?X /0 |0 ?X;
@@ -13,32 +11,19 @@ sign[] = < {} "+", {} "-" >;
13
11
  +? = ?sign[] /"+" +;
14
12
  -? = ?sign[] /"-" -;
15
13
 
16
- # --lib lib/bit.k --use not_bit and_bit or_bit xor_bit
17
- not_bit = @WAu2W28Cay64FmGXCumzmrgbMiEnSjyNUETbSzXtCvEw;
18
- and_bit = @4iKmE8nmJDxBMREydctSER6UnbA5ufURFJjr4mtKt9AZ;
19
- or_bit = @FYe6xjtJKkYaiVT6UahWqGsfmihAyvwiqWE4zaEYekkz;
20
- xor_bit = @QecMdpq96xrRQyYENRgJvqhbYnxyqb66Uxc4mrdWSFpu;
21
-
22
- # --lib lib/ieee.k --use exp11[] frac52[] float64[]
23
- exp11[] = @F2KGfE24DhFGChv6pVAb4pkC9YWvt5izpnnwFDTLfG2h[];
24
- frac52[] = @ziwtSeiWqhQZjbpnB2TpWhSJCDTWfX2QzGvPd3DdVJCZ[];
25
- float64[] = @AR4sFGMwXgjj5p7dhi8sJKDWNbrXxLefQUCBRNm5fP6t[];
26
-
27
- # --lib lib/ieee.k --use 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?
28
- all_ones_exponent? = @G4gtCwkTyvUKAjhAKFFj5bfAMfW53t8A6CRxXpTyafcS;
29
- exp0 = @5CevJXf7TxM9xpnE6d7wUPxCNUCb8hjcyDxK27Qdb99d;
30
- finite_float64? = @rXgbm83aU9KXZKsnUTKaMa6xE4L4SYr53QKWj55HgTXX;
31
- frac0 = @cEAdYip46Ce9nsZS8HvRg6iHqeLaAzWBcB5PvWyZHcPz;
32
- inf_float64? = @EHkVn6SrkQf9xx5j7nxBpA4wrMbrmnkNZGAGVHZESTbE;
33
- nan_float64? = @C4gMueJKY8pkL4sXhA9Mm4myUdMfMnKLDNsJijr4Gzmw;
34
- neg_inf = @dDUVHjeQsLRfZ9P2faLv7uHd94w8XUxhug9xJr3CxhGA;
35
- neg_zero = @KkPWjqrqkhgNXTTeG8J7ZZhBUjVmN9nRnp42j6nRtb8V;
36
- negate_float64 = @3V9Ve52CnGsvJ9xxHgBwL47L4ac3Xh98bPuLJLHgeU78;
37
- pos_inf = @8paZ6U6NYfRBsnQHEJQFxtSWsET5WyAZBDUWaZkcPtmz;
38
- pos_zero = @QTRfm3S4BKsqqt7WDPAPhfNA2dajxcj9iyAtvnqpMcdf;
39
- qnan = @tS5xBCNSeuX3ahkFgk8wpX8nB6XrH9teHvYhhKxTFu7h;
40
- zero_exponent? = @NqwhAUhQMnLpZgCevmmMtDFcSLtfxLgkbq85ckwgrKHy;
41
- zero_float64? = @4p9tjLASFGTZCbW7sha7JzZDBkCNuVwyLhLKiQfBJSNV;
14
+ not_bit = ?bit[] < /0 1, /1 0 > ?bit[];
15
+ and_bit = ?{ bit[] x, bit[] y } <
16
+ { .x 0? _x, .y ?bit[] _y } 0,
17
+ { .x 1? _x, .y ?bit[] y } .y
18
+ > ?bit[];
19
+ or_bit = ?{ bit[] x, bit[] y } <
20
+ { .x 1? _x, .y ?bit[] _y } 1,
21
+ { .x 0? _x, .y ?bit[] y } .y
22
+ > ?bit[];
23
+ xor_bit = ?{ bit[] x, bit[] y } <
24
+ { .x 0? _x, .y ?bit[] y } .y,
25
+ { .x 1? _x, .y ?bit[] y } .y not_bit
26
+ > ?bit[];
42
27
 
43
28
  // Arithmetic-specific patterns and ripple-carry helpers.
44
29
 
package/Examples/poly.k CHANGED
@@ -1,11 +1,11 @@
1
+ # --lib lib/integer.k --use int[] nat int pos? neg? zero? gt? inc dec
1
2
  -- Examples/poly.k — Polymorphic list operations indexed by int[]
2
3
 
3
4
  ---------------------------------------------------------------
4
- -- §1. Base Patterns, Primitives & Imported Relations
5
+ -- §1. Base Patterns & Primitives
5
6
  ---------------------------------------------------------------
6
7
 
7
8
  bits[] = < {} _, B 0, B 1 > = B;
8
- int[] = < bits[] -, bits[] + >;
9
9
  list[X] = < {} nil, { X car, L cdr } cons > = L;
10
10
 
11
11
  _ = {} |_ ?bits[];
@@ -24,25 +24,21 @@ cdr = ?list[X] /cons .cdr;
24
24
  nil? = un_nil nil;
25
25
  singleton = { () car, nil cdr } cons;
26
26
 
27
- # --lib lib/arithmetics.k --use nat int neg? zero_int? GT inc dec
28
- nat = @ktrZRefK3zvnUqYYisWBH3MgzcQJD9hs2P5LeSJ7tFrA;
29
- int = @BgUayEar88hcmcAYM5giDsucyGbtumbaXpyussK8k7vm;
30
- neg? = @Hwv3CjPRgtJDb7ZGn7cReF9iZ25LFpjv2MXRBJyUGBij;
31
- zero_int? = @eYsSuRAeFTejC7W9mLLtxuSeebLuszMGxadnZsg4iuUf;
32
- GT = @qWipdJHEEG3KccU4RVFLrWciLCvP2Cbz7myNxjNtvUCP;
33
- inc = @FpWRmLNa6guwACtpwYUAuX3usE27WqAKPzQxrVRtyKND;
34
- dec = @3YRXdfNimGSWfSpCcTzBauTU7HRrjLUFMp4dbRZGhJXv;
35
-
36
- # --lib lib/list.k --use rev_append reverse
37
- rev_append = @7xb2uLU5cS7XgmFbKMrvg4UwpcTQ3whSMzBMeaSnGwkm;
38
- reverse = @peiZq2evd5u4Qk42AT3W4YmWZZ3JAeXNKTnmDtpb9EZh;
39
-
40
27
  ---------------------------------------------------------------
41
28
  -- §2. Polymorphic List Operations
42
29
  ---------------------------------------------------------------
43
30
 
44
- -- Decrement a positive integer and normalize
45
- pred_int = dec un_pos nat pos_int;
31
+ -- Reverse-append x onto y: {x, y} -> list
32
+ rev_append = ?{ list[X] x, list[X] y } <
33
+ { .x un_nil if, .y then } .then,
34
+ { .x cdr x, { .x car car, .y cdr } cons y } rev_append
35
+ > ?list[X];
36
+
37
+ -- Reverse a list: xs -> list
38
+ reverse = { () x, nil y } rev_append;
39
+
40
+ -- Decrement a positive integer
41
+ pred_int = pos? dec;
46
42
 
47
43
  -- Concatenate two lists: {xs, ys} -> list
48
44
  concat = { .xs reverse x, .ys y } rev_append;
@@ -52,17 +48,17 @@ length_loop = <
52
48
  { .xs un_nil if, .acc then } .then,
53
49
  { .xs cdr xs, .acc inc acc } length_loop
54
50
  >;
55
- length = { () xs, 0 int acc } length_loop;
51
+ length = { () xs, 0 nat acc } length_loop;
56
52
 
57
53
  -- Get N-th element of a list (0-indexed): {n, xs} -> element
58
54
  get_nth = <
59
- { .n zero_int? if, .xs car then } .then,
55
+ { .n zero? if, .xs car then } .then,
60
56
  { .n pred_int n, .xs cdr xs } get_nth
61
57
  >;
62
58
 
63
59
  -- Split list at index N: {n, xs} -> {first, second}
64
60
  split_by_loop = <
65
- { .n zero_int? if, { .acc reverse first, .xs second } then } .then,
61
+ { .n zero? if, { .acc reverse first, .xs second } then } .then,
66
62
  { .xs un_nil if, { .acc reverse first, nil second } then } .then,
67
63
  { .n pred_int n, .xs cdr xs, { .xs car car, .acc cdr } cons acc } split_by_loop
68
64
  >;
@@ -73,14 +69,14 @@ take = split_by .first;
73
69
 
74
70
  -- Drop the first N elements of a list: {n, xs} -> list
75
71
  drop = <
76
- { .n zero_int? if, .xs then } .then,
72
+ { .n zero? if, .xs then } .then,
77
73
  { .xs un_nil if, nil then } .then,
78
74
  { .n pred_int n, .xs cdr xs } drop
79
75
  >;
80
76
 
81
77
  -- Repeat element X, N times: {n, x} -> list
82
78
  repeat_loop = <
83
- { .n zero_int? if, .acc then } .then,
79
+ { .n zero? if, .acc then } .then,
84
80
  { .n pred_int n, .x x, { .x car, .acc cdr } cons acc } repeat_loop
85
81
  >;
86
82
  repeat = { .n n, .x x, nil acc } repeat_loop;
@@ -106,13 +102,6 @@ gen_list_loop = <
106
102
  >;
107
103
  gen_list = { () n, nil list } gen_list_loop;
108
104
 
109
- -- Identity filter on {x, y} when x > y
110
- gt? = <
111
- { .x un_neg if1, .y un_pos if2, () then } .then,
112
- { { .x un_neg y, .y un_neg x } GT if, () then } .then,
113
- { { .x un_pos x, .y un_pos y } GT if, () then } .then
114
- >;
115
-
116
105
  -- Split list into two halves by alternating elements: xs -> {first, second}
117
106
  split_loop = <
118
107
  { .xs un_nil if, { .first first, .second second } then } .then,