@fraczak/k 6.7.0 → 6.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.
package/DOCS/REPL.md CHANGED
@@ -33,29 +33,23 @@ complete.
33
33
  | Command | Meaning |
34
34
  | --- | --- |
35
35
  | `:help` | Show command summary |
36
- | `:type name = <...>` | Define a type alias |
37
36
  | `:type name` | Show the canonical definition of a type |
38
37
  | `:code name` | Alias for `:C name` |
39
- | `:rel name = expr` | Define a relation alias |
40
- | `:def name = expr` | Alias for `:rel` |
41
38
  | `:run expr` | Evaluate `expr` on the current value |
42
39
  | `:eval expr` | Alias for `:run` |
43
40
  | `:time expr` | Evaluate `expr` and report compilation and execution time |
44
- | `:timing [on\|off]` | Toggle compilation and execution timing reporting for all evaluations |
45
41
  | `:t name` | Show relation input/output filters |
46
42
  | `:d name` | Show relation definition |
47
43
  | `:C name` | Show canonical code definition |
48
44
  | `:codes` | List type aliases |
49
45
  | `:rels` | List relation aliases |
50
- | `:codec load name\|file` | Load a built-in codec (`int`, `utf8`, `json`, `ieee`, `unit`) or an ES module file |
51
- | `:codec define n t b` | Define an inline custom codec: `name type { parse: ..., print: ... }` |
46
+ | `:codec load file` | Load a codec from an ES module file (e.g. `:codec load codecs/int.mjs`) |
52
47
  | `:codec unload name` | Unload a registered codec |
53
48
  | `:codec list` | List loaded REPL codecs (alias: `:codecs`) |
54
- | `:input type [codec]` | Read the next line as codec input for a type |
49
+ | `:input <codec.mjs> [text]` | Read next input line or parse inline text using specified codec |
55
50
  | `:load [--no-alias] file` | Load `.k` source or `.klib` into the current state |
56
51
  | `:klib file` | Export the active relation closure as a `.klib` library |
57
52
  | `:ko file expr` | Export a `.ko` executable with `expr` as main |
58
- | `:val` | Print current value and JSON form |
59
53
  | `:reset` | Reset interpreter state |
60
54
  | `:quit` / `:exit` | Exit |
61
55
 
@@ -142,9 +136,8 @@ Tab completion covers:
142
136
 
143
137
  Type aliases also complete in `$name` position inside raw k input.
144
138
 
145
- For codec commands, completion covers `:codec load`, `:codec list`, file paths
146
- after `:codec load`, type names after `:input`, and loaded codec names
147
- after the input type.
139
+ For codec commands, completion covers `:codec load`, `:codec unload`, `:codec list`,
140
+ file paths after `:codec load`, and codec names after `:input`.
148
141
 
149
142
  ## Loading
150
143
 
@@ -162,75 +155,73 @@ unless `--no-alias` is used.
162
155
 
163
156
  ## Codecs
164
157
 
165
- REPL codecs are usually keyed by canonical code hashes. Patterns are not used
166
- for codec dispatch. A codec may also export `universal = true` to make it
167
- available for any type selected by `:input`; the parsed value is still validated
168
- against the requested type before it enters the session.
158
+ A codec is a recipe for translating between external text and enveloped *k* values:
159
+ - `parse(text)`: parses an external string into an enveloped *k* value.
160
+ - `print(value)`: serializes an enveloped *k* value to external string, throwing an `Error` if the value is not representable.
161
+
162
+ Codecs can define a family of target patterns (e.g. `int` parses/prints single integers as well as lists like `[0,1,2]`).
163
+
164
+ For printing in the REPL, every value is printed with the standard *k* envelope representation, followed by lines for all loaded codecs that can format it:
165
+ ```text
166
+ > 42 int
167
+ {}|_|0|1|0|1|0|1|+ ?<{} _, ...>
168
+ int: 42
169
+ ```
169
170
 
170
171
  For a complete guide to writing a new codec module, see
171
172
  [`CODECS.md`](./CODECS.md).
172
173
 
173
- ### `:codec load name|file`
174
+ ### `:codec load file`
174
175
 
175
- Loads either a built-in codec by name (`int`, `utf8`, `json`, `ieee`, `unit`) or an ES module file. Loading a built-in codec automatically loads its corresponding `.k` definition file if not already present:
176
- - `int` auto-loads `Examples/arithmetics.k`
177
- - `ieee` auto-loads `Examples/ieee.k`
178
- - `utf8`, `json`, `unit` auto-load `Examples/core.k`
176
+ Loads a codec module from an ES module file (e.g. `:codec load codecs/int.mjs`). Codecs are identified by their file name, and export `parse(text)` and `print(value)` functions.
179
177
 
180
- Loading a codec also creates code aliases matching the codec name (e.g. `$ int = @...`, `$ float64 = @...`, `$ utf8 = @...`).
178
+ ### `:codec unload name`
181
179
 
182
- An external codec module exports:
180
+ Unloads a previously loaded codec by name (e.g. `:codec unload int.mjs`).
183
181
 
184
- ```js
185
- export const name = "utf8";
186
- export const codes = ["@..."];
187
- export function parse(text) { /* text -> Value */ }
188
- export function print(value) { /* Value -> text */ }
189
- ```
182
+ ### `:codec list` (or `:codecs`)
190
183
 
191
- A codec may export `patterns` instead of `codes`; each pattern must be a closed
192
- property-list pattern that can be canonicalized to a code hash, and that hash is
193
- recalculated by the REPL. A universal codec exports `universal = true` instead
194
- of `codes` or `patterns`.
184
+ Lists all currently loaded codecs and their source files.
195
185
 
196
- ### `:codec define name type { parse: ..., print: ... }`
186
+ ### `:input <codec.mjs> [text]`
197
187
 
198
- Registers a dynamic custom codec directly from the REPL:
188
+ Parses external input using the specified codec file.
199
189
 
200
- ```k
201
- > :type bool = <{} true, {} false>
202
- > :codec define yn bool ({ parse: (t) => Value.variant(t.trim() === 'yes' ? 'true' : 'false', Value.product({})), print: (v) => v.tag === 'true' ? 'YES' : 'NO' })
203
- ```
204
-
205
- ### `:codec unload name`
190
+ - **Interactive mode**: `:input <codec.mjs>` switches the REPL prompt to `<codec.mjs>> `, and the next input line is parsed using that codec:
191
+ ```text
192
+ > :input json.mjs
193
+ json.mjs> {"hello": "world"}
194
+ {...} ?<{...}>
195
+ json.mjs: {"hello":"world"}
196
+ ```
206
197
 
207
- Unloads a previously registered codec by name.
198
+ - **One-line mode**: `:input <codec.mjs> <text>` immediately parses `<text>`:
199
+ ```text
200
+ > :input int.mjs 42
201
+ {}|_|0|1|0|1|0|1|+ ?<{} _, ...>
202
+ int.mjs: 42
208
203
 
209
- ### `:input type [codec]`
204
+ > :input int.mjs [0,1,2]
205
+ {...} ?<{...}>
206
+ int.mjs: [0,1,2]
207
+ ```
210
208
 
211
- Resolves `type` to a canonical code hash, selects the registered codec, and
212
- consumes the next line verbatim as codec input. `type` may be a type alias, a
213
- canonical code hash, or an inline type expression such as
214
- `<{} true, {} false>`. The parsed value is validated against that type before
215
- becoming the current value.
209
+ Entering `:input` with no arguments displays usage and a list of loaded codecs.
216
210
 
217
211
  ## Timing and Profiling
218
212
 
219
- ### `:time expr`
220
-
221
- Evaluates `expr` and reports the elapsed time broken down into compilation
222
- (type derivation + WebAssembly lowering/compilation) and runtime execution:
213
+ Timing reporting is enabled by default for all evaluations, reporting elapsed time
214
+ broken down into compilation (type derivation + WebAssembly lowering/compilation) and runtime execution:
223
215
 
224
216
  ```text
225
- > :time {10 int x, 5 int y} plus
217
+ > {10 int x, 5 int y} plus
226
218
  {}|_|1|1|1|1|+ ?<{} _, ...>
227
219
  /* comp: 12.4ms, exec: 0.8ms */
228
220
  ```
229
221
 
230
- ### `:timing [on|off]`
222
+ ### `:time expr`
231
223
 
232
- Toggles automatic timing reporting for every snippet or expression evaluated in
233
- the session.
224
+ Evaluates `expr` with explicit timing and records performance metrics in session state.
234
225
 
235
226
  ## Web REPL (Studio)
236
227
 
@@ -279,11 +270,9 @@ Evaluated values print in k syntax together with the inferred envelope:
279
270
  ## Example Session
280
271
 
281
272
  ```text
282
- > :type nat = <{} 0, nat +1>
283
- $ nat = @...
284
- > :rel inc = |+1
285
- inc = @...
286
- > {} |0
273
+ > $ nat = < {} 0, nat +1 >;
274
+ > inc = | +1;
275
+ > {} | 0
287
276
  {}|0 ?<{} 0, ...>
288
277
  > :t inc
289
278
  inc : ?X0 --> ?<X0 +1, ...> (@...)
@@ -92,6 +92,7 @@ _fromBitList =
92
92
 
93
93
  --------------------------------------
94
94
  $ int = < bits '+', bits '-' >;
95
+ $ ints = <{int car, ints cdr} cons, {} nil>;
95
96
 
96
97
  remove_leading_zeros = <
97
98
  /0 remove_leading_zeros,
package/Examples/poly.k CHANGED
@@ -65,3 +65,49 @@ zip = <
65
65
  {.xs cdr xs, .ys cdr ys} zip cdr
66
66
  } cons
67
67
  >;
68
+
69
+ -- Gen list of intgers: n -> [0, 1, ..., n]
70
+ gen_list = {() n, nil list} gen_list_;
71
+ gen_list_ = <
72
+ {.n neg? if, .list then} .then,
73
+ {.n dec n, {.n car, .list cdr} cons list} gen_list_
74
+ >;
75
+
76
+ -- Identity filter on {x, y} when x is greater than y: ?{X x, X y}=Y -> ?Y
77
+ gt? =
78
+ <
79
+ {.x/- if1, .y/+ if2, () then} .then,
80
+ {{.x/- y, .y/- x} GT if, () then} .then,
81
+ {{.x/+ x, .y/+ y} GT if, () then} .then
82
+ >
83
+ ;
84
+
85
+ -- Split list into two halves by alternating elements: xs -> {first, second}
86
+ split = {() xs, nil first, nil second} _split;
87
+ _split = <
88
+ {.xs /nil if, {.first first, .second second} then} .then,
89
+ {.xs cdr /nil if, {{.xs car car, .first cdr} cons first, .second second} then} .then,
90
+ {.xs cdr cdr xs, {.xs car car, .first cdr} cons first, {.xs cdr car car, .second cdr} cons second} _split
91
+ >;
92
+
93
+ -- Merge two sorted lists: {xs, ys} -> list
94
+ merge = <
95
+ {.xs /nil if, .ys then} .then,
96
+ {.ys /nil if, .xs then} .then,
97
+ {
98
+ {.xs car x, .ys car y} gt? if,
99
+ {.ys car car, {.xs xs, .ys cdr ys} merge cdr} cons then
100
+ } .then,
101
+ {.xs car car, {.xs cdr xs, .ys ys} merge cdr} cons
102
+ >;
103
+
104
+ -- Sort a list in ascending order (merge sort): xs -> list
105
+ sort = list? <
106
+ /nil nil,
107
+ /cons <
108
+ {.cdr /nil if, .car singleton then} .then,
109
+ |cons split {.first sort xs, .second sort ys} merge
110
+ >
111
+ > list?;
112
+
113
+
package/TODO.md ADDED
@@ -0,0 +1,112 @@
1
+ # Web REPL Improvements & Conceptual Cleanup Plan
2
+
3
+ This document details the issues, conceptual improvements, and completed enhancements for the `k` Web REPL (`browser/repl-browser.mjs`, `scripts/build-repl-html.mjs`, and `repl.html`).
4
+
5
+ ---
6
+
7
+ ## 1. General Branding & Visual Cleanup
8
+
9
+ ### Removal of `λ` (Lambda) Symbol
10
+ - [x] Remove `<span class="brand-lambda">λ</span>` from the navbar in `scripts/build-repl-html.mjs`.
11
+ - [x] Remove the `.brand-lambda` CSS class.
12
+ - [x] Update welcome banner in `browser/repl-browser.mjs` to `k interactive repl`.
13
+ - [x] Replace `λ` in string codec sample inputs with ASCII/Unicode text samples (e.g. `"abc"`).
14
+
15
+ ---
16
+
17
+ ## 2. Help Modal (`? Help` / `:help`) Overhaul
18
+
19
+ ### Language Overview & Grammar Categorization
20
+ - [x] **Language Overview**: Short, positive, accessible description: `k` is a concise language of types and relations (functions) over tree-like (JSON-like) documents.
21
+ - [x] **Content-Addressed Identity**: Functions and types are identified by their canonical content hash (`@...`) derived directly from their structure; local names are just temporary aliases used for recursion and readability.
22
+ - [x] **Three Clean Grammar Categories**:
23
+ 1. **Definitions (Local Aliases)**:
24
+ - `name = relExpr;` &mdash; Relation alias (e.g. `swap = { . y x, . x y };`).
25
+ - `$ name = typeExpr;` &mdash; Type alias (e.g. `$ bool = < {} true, {} false >;`).
26
+ 2. **Type Expressions (`typeExpr`)**: Schemas describing tree-like documents:
27
+ - `{ Type_1 label_1, ..., Type_k label_k }` &mdash; Product type of arity $k$ (labeled records, e.g. `{float64 x, string n}`; special case: `{}` is the 0-ary product).
28
+ - `< Type_1 tag_1, ..., Type_k tag_k >` &mdash; Union type of arity $k$ (tagged sum of variants, e.g. `<int ok, string err>`).
29
+ - `name` / `@hash` &mdash; Type reference.
30
+ 3. **Relation Expressions (`relExpr`)**: Functions transforming an input document to an output document:
31
+ - `{ rel_1 label_1, ..., rel_k label_k }` &mdash; Product of arity $k$ (evaluates relations into record fields; special case: `{}` evaluates 0 relations, producing empty record `{}`).
32
+ - `< rel_1, ..., rel_k >` &mdash; Union / ordered choice of arity $k$ (evaluates relations in order until one succeeds).
33
+ - `( rel_1 ... rel_k )` &mdash; Composition of arity $k$ (sequentially composes relations; special case: `()` is the 0-ary composition denoting identity; parentheses can be omitted when non-empty: `f g`).
34
+ - `. label` &mdash; Field projection (extracts field `label`).
35
+ - `/ tag` &mdash; Variant branch projection (extracts payload of variant `tag`).
36
+ - `| tag` &mdash; Variant constructor (wraps document into variant `tag`).
37
+ - `$ typeExpr` &mdash; Type constraint (asserts input matches schema; compile-time Type Error on mismatch).
38
+ - `name` / `@hash` &mdash; Relation reference.
39
+ - [x] **Simplified Intro**:
40
+ - Made arbitrary arity explicit across products `{...}`, unions `<...>`, and compositions `(...)`; explained `{}` and `()` as the natural 0-ary special cases; omitted the pattern/filter expressions table from the introductory reference.
41
+ - [x] **Replaced Misleading Expressions & Snippets**:
42
+ - Removed phantom concepts (`10` as literal, "bit-path", `{10 int x, 5 int y} plus` in default state).
43
+ - Added self-contained snippets (`{} | ok`, `not = < / true | false, / false | true >;`, `$ bool = < {} true, {} false >;`, `not = $ bool < / true | false, {} | true > $ bool;`, `swap = { . y x, . x y };`).
44
+ - [x] **Command Reference Table**:
45
+ - Added `:time <expr>`.
46
+ - Removed obsolete commands: `:rel <name> = expr`, `:val`, `:timing [on|off]`, `:codec define n t b`.
47
+ - Updated `:type <name>` to purely inspect and display type definitions (type definition is native via `$ name = typeExpr;`).
48
+ - Timing is now always enabled by default across all evaluations.
49
+ - Updated `:input` documentation to note the interactive browser dialog.
50
+ - Clarified `:codes` (type aliases/hashes) and `:rels` (relation aliases).
51
+
52
+ ---
53
+
54
+ ## 3. Codecs Modal Overhaul
55
+
56
+ ### Concept Correction: External Format Adapters
57
+ - [x] Reframed codecs as format adapters translating external text to/from $k$ values defined as pairs `(filter, tree)`.
58
+ - [x] **Type-Specific Codecs**:
59
+ - `int`: Converts decimal integers to/from `$ int = < bits '+', bits '-' >`.
60
+ - `ieee`: Converts decimal floats to/from `$ float64` records (`sign`, `exponent`, `fraction`).
61
+ - `utf8`: Converts text to/from `$ string` (aliased to `$ utf8`), a list of Unicode scalar values (`$ unicode`) partitioned by Unicode planes.
62
+ - `unit`: Converts to/from `{}`.
63
+ - [x] **Parameterized Codecs**:
64
+ - `json`: JSON text is untyped; deserializing JSON requires a target $k$ type schema parameter (e.g. `:input {float64 x, string n} json`).
65
+ - [x] **Custom Codec Studio**:
66
+ - Updated explanation to emphasize pairs `(filter, tree)`.
67
+ - Fixed `yn` preset to provide self-contained type definition `$ bool = < {} true, {} false >;`.
68
+ - Fixed `blank` preset with proper Value payload formatting.
69
+
70
+ ---
71
+
72
+ ## 4. 'Input' Modal Overhaul
73
+
74
+ - [x] **Parameterized Codec Support**:
75
+ - Converted "Target Type" control into an editable combobox / text input with datalist autocomplete for known aliases, while allowing arbitrary composite type expressions (`{float64 x, string n}`, `<int ok, string err>`).
76
+ - Integrated `resolveInputTypeHash(state, rawType)` into live validation and modal submit.
77
+ - Marked `json` as a Parameterized Codec requiring a target type schema.
78
+ - Added composite quick samples demonstrating type + JSON payload pairs (e.g. `{float64 x, string n}` with `{"x":12, "n":"Woj"}`).
79
+ - Preserved CLI-specified type expressions when opening via `:input <type> [codec]`.
80
+
81
+ ---
82
+
83
+ ## 5. Welcome Banner
84
+
85
+ - [x] Shortened initial welcome message to just the title line: `k interactive repl`.
86
+ - [x] Removed secondary description and quick link lists to keep the terminal prompt clean and uncluttered.
87
+
88
+ ---
89
+
90
+ ## 6. Curated VFS & Navbar Examples Dropdown
91
+
92
+ - [x] Added `poly.k` to `verifiedExamples` and `#example-select`.
93
+ - [x] Structured Navbar Examples dropdown into self-contained basic expressions vs. library-dependent workflows.
94
+ - [x] Removed `:val` from example dropdown list.
95
+ - [x] Fixed `() ()` option display text.
96
+
97
+ ---
98
+
99
+ ## 7. Responsive Navbar & Obsolete Command Removal
100
+
101
+ - [x] **Responsive Navbar on Narrow Screens**:
102
+ - Changed `.navbar` from fixed `height: 48px;` to `min-height: 48px; height: auto; flex-wrap: wrap; padding: 6px 16px; gap: 8px 12px;`.
103
+ - Styled `.nav-right` with `flex-wrap: wrap; justify-content: flex-end; min-width: 0;` so controls wrap smoothly without overflowing or clipping buttons (such as `? Help`).
104
+ - Added comprehensive responsive media query for narrow screens ($\le 768\text{px}$) with full width wrapping and adaptable control inputs.
105
+ - Verified via headless Chromium CDP automated tests that `#btn-help` is completely visible and interactable at narrow viewport widths (e.g. 600px).
106
+ - [x] **Removed Obsolete Commands**:
107
+ - Removed `:rel <name> = expr` and `:def` (relations are defined using native syntax `name = expr;`).
108
+ - Removed `:type <name> = <...>` definition syntax from `:type` (types are defined using native syntax `$ name = typeExpr;`; `:type <name>` remains for inspecting type definitions).
109
+ - Removed `:val` completely.
110
+ - Removed `:timing [on|off]` (timing reporting is now permanently enabled by default for all evaluations; `:time <expr>` remains for explicit timing).
111
+ - Removed `:codec define n t b` (custom codecs are created using the browser Custom Codec Studio UI or loaded from modules via `:codec load`).
112
+