@fraczak/k 8.4.1 → 8.5.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.
Files changed (116) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/DOCS/ARCHITECTURE.md +83 -0
  3. package/DOCS/CODECS.md +93 -204
  4. package/DOCS/DICTIONARY.md +42 -1241
  5. package/DOCS/FILE_FORMATS.md +170 -625
  6. package/DOCS/GETTING_STARTED.md +164 -0
  7. package/DOCS/KIR_V1.md +22 -33
  8. package/DOCS/KVM_EXECUTION_MODEL.md +88 -481
  9. package/DOCS/PATTERNS.md +155 -138
  10. package/DOCS/POLYMORPHIC_IR.md +83 -101
  11. package/DOCS/PROFILING_AND_TRACING.md +52 -166
  12. package/DOCS/README.md +35 -0
  13. package/DOCS/REPL.md +100 -377
  14. package/DOCS/TEXTUAL_VALUES.md +53 -81
  15. package/DOCS/TYPE_DERIVATION.md +95 -234
  16. package/DOCS/book-combined.md +3786 -0
  17. package/Examples/arithmetics.k +45 -59
  18. package/Examples/djson.k +102 -112
  19. package/Examples/karatsuba-mult.k +2 -3
  20. package/Examples/list.k +6 -7
  21. package/Examples/nat.k +6 -6
  22. package/Examples/poly.k +45 -45
  23. package/LICENSE +15 -0
  24. package/README.md +72 -410
  25. package/backends/llvm/README.md +75 -97
  26. package/backends/llvm/src/kvm2llvm.mjs +5 -4
  27. package/backends/llvm/src/llvm.mjs +2 -1
  28. package/backends/llvm/tests/integration.sh +7 -0
  29. package/backends/llvm/tests/test-llvm.mjs +20 -0
  30. package/backends/wasm/README.md +88 -66
  31. package/backends/wasm/src/kvm2wasm.mjs +64 -18
  32. package/backends/wasm/tests/integration.sh +5 -0
  33. package/backends/wasm/tests/test-wasm.mjs +86 -2
  34. package/canonical-pattern.mjs +7 -3
  35. package/codecs/README.md +23 -261
  36. package/codecs/WIRE_FORMAT.md +132 -0
  37. package/core.k +5 -15
  38. package/named-patterns.mjs +19 -7
  39. package/objects/README.md +24 -109
  40. package/package.json +8 -3
  41. package/paper/Makefile +17 -0
  42. package/paper/k-paper.pdf +0 -0
  43. package/paper/k-paper.tex +435 -0
  44. package/parser.jison +0 -10
  45. package/parser.mjs +32 -43
  46. package/repl.mjs +74 -29
  47. package/scripts/benchmark-idempotency.mjs +3 -3
  48. package/scripts/run-tests.mjs +1 -1
  49. package/scripts/test-package.mjs +64 -0
  50. package/tests/README.md +66 -46
  51. package/tests/code-derivation/core.mjs +61 -0
  52. package/tests/helpers/cli.mjs +45 -0
  53. package/tests/integration.sh +2 -3
  54. package/tests/test-arithmetics.mjs +47 -237
  55. package/tests/test-djson-methods.mjs +71 -275
  56. package/tests/test-hash-normalization.mjs +22 -1
  57. package/tests/test-karatsuba.mjs +18 -126
  58. package/tests/test-named-patterns.mjs +174 -621
  59. package/tests/test-paper-examples.mjs +90 -0
  60. package/tests/test-poly.mjs +2 -2
  61. package/tests/test-repl-html.mjs +22 -10
  62. package/tests/test-repl.mjs +49 -41
  63. package/tests/test.mjs +27 -68
  64. package/AGENTS.md +0 -35
  65. package/CLAUDE.md +0 -64
  66. package/DOCS/BIG_PICTURE.md +0 -439
  67. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  68. package/DOCS/CANONICAL_PATTERNS.md +0 -362
  69. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  70. package/DOCS/CONVERGENCE.md +0 -123
  71. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  72. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  73. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  74. package/DOCS/Makefile +0 -99
  75. package/DOCS/NAMED_PATTERNS.md +0 -361
  76. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  77. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  78. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -134
  79. package/DOCS/book/01-introduction.md +0 -48
  80. package/DOCS/book/02-syntax-and-values.md +0 -110
  81. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  82. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  83. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  84. package/DOCS/book/06-values-in-memory.md +0 -1085
  85. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  86. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  87. package/DOCS/book/09-compiler-architecture.md +0 -160
  88. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  89. package/DOCS/book/14-canonical-serialization.md +0 -176
  90. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  91. package/DOCS/book/overview.txt +0 -68
  92. package/DOCS/book.md +0 -50
  93. package/Examples/bnat.k +0 -308
  94. package/Examples/buda.k +0 -66
  95. package/Examples/byte.k +0 -35
  96. package/Examples/code.k +0 -43
  97. package/Examples/vhdl_to_k.k +0 -67
  98. package/JOURNAL.md +0 -288
  99. package/TODO.md +0 -107
  100. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  101. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  102. package/backends/wasm/demo_ieee.mjs +0 -318
  103. package/browser/vfs-data.mjs +0 -21
  104. package/codecs/BINARY_FORMAT.md +0 -53
  105. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  106. package/codecs/pandoc.css +0 -71
  107. package/tests/code-derivation/blowup.mjs +0 -25
  108. package/tests/code-derivation/bnat.mjs +0 -11
  109. package/tests/code-derivation/dot.mjs +0 -37
  110. package/tests/code-derivation/index.mjs +0 -20
  111. package/tests/code-derivation/loop.mjs +0 -17
  112. package/tests/code-derivation/nat.mjs +0 -10
  113. package/tests/code-derivation/not-not.mjs +0 -14
  114. package/tests/code-derivation/product.mjs +0 -22
  115. package/tests/code-derivation/rlz.mjs +0 -13
  116. package/tests/test-fingerprint.mjs +0 -38
package/CHANGELOG.md CHANGED
@@ -5,6 +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.5.1] — 2026-10-31 — Fix Union Tail-Call Optimization in Wasm and LLVM Backends
9
+
10
+ - **Restrict Union Tail-Call Optimization to Final Branch (#3)**:
11
+ - Fix unsound self-tail-call optimization on non-final union branches in
12
+ `backends/wasm/src/kvm2wasm.mjs`, `backends/llvm/src/kvm2llvm.mjs`, and
13
+ `backends/llvm/src/llvm.mjs`. Only the final branch (`i === N - 1`) of a
14
+ union is in tail position; earlier branches must execute regular calls so
15
+ that failure of a recursive call properly backtracks to subsequent branches
16
+ with the original union input.
17
+ - Extend `feedsSelfTailCall` (`tailCallInputTargets`) in
18
+ `backends/wasm/src/kvm2wasm.mjs` so factored tail-recursive unions
19
+ (`< { ... }, { ... } > self` in tail position) continue to forward product
20
+ fields directly into `$tail_in_*` locals and jump to `$tail_loop` without
21
+ intermediate arena allocation.
22
+
23
+ ## [8.5.0] — 2026-10-28 — Documentation and Test Cleanup
24
+
25
+ - Replace the obsolete book, duplicated paper rendering, design plans, and
26
+ completed work logs with a shorter documentation index, walkthrough, and
27
+ current language/tool references. Preserve the published paper source and PDF.
28
+ - Consolidate repetitive test fixtures and derivation cases, replace print-only
29
+ checks with assertions, and include the paper examples in the main suite.
30
+ Paper tests now read examples from the LaTeX source.
31
+ - Reuse compiled dynamic JSON library definitions and shared arithmetic CLI
32
+ setup while retaining numerical oracles and structural regression checks.
33
+ - Correct benchmark defaults and remove the obsolete standalone Wasm demo.
34
+ - Exclude generated browser VFS data and agent instructions from npm packages,
35
+ declare the Node.js runtime minimum, and include the declared ISC license.
36
+ - Add package installation smoke checks, release CI, and a pre-publication test
37
+ gate. Parser generation now stops if either grammar fails.
38
+ - Prefer Chrome for browser tests and skip unavailable browser launchers.
39
+
8
40
  ## [8.4.1] — 2026-10-23 — Strict Pattern Validation & Autohook Removal
9
41
 
10
42
  ### Strict Pattern Template Validation & Variable Distinction
@@ -0,0 +1,83 @@
1
+ # Compiler and runtime
2
+
3
+ This guide maps the current JavaScript implementation. Start with the
4
+ [walkthrough](GETTING_STARTED.md) for language use.
5
+
6
+ ## Source and contract derivation
7
+
8
+ 1. `parser.jison` generates the source parser, `parser.mjs`.
9
+ 2. `index.mjs` parses source, validates/expands named patterns, and invokes
10
+ `compiler.mjs`.
11
+ 3. `augmentation.mjs` creates local input/output constraints.
12
+ 4. `TypePatternGraph.mjs` and `typing.mjs` represent and unify constraints.
13
+ 5. `Graph.mjs` and `convergence.mjs` process dependency groups, iterating
14
+ recursive groups until convergence or the configured budget.
15
+ 6. `codes.mjs` normalizes closed schema graphs; `export.mjs` assigns canonical
16
+ relation names. `canonical-pattern.mjs` handles pattern skeletons and routing.
17
+
18
+ `annotate(source, options)` returns relations, aliases, source definitions, and
19
+ compilation statistics. [Contract derivation](TYPE_DERIVATION.md) describes
20
+ the rules and tuning options.
21
+
22
+ ## Execution and values
23
+
24
+ `Value.mjs` represents products and variants with an optional `pattern`.
25
+ At wire boundaries, the pattern and payload are serialized together.
26
+
27
+ `run.mjs` implements the reference evaluator. Its envelope-aware path
28
+ intersects arriving patterns with compiled constraints and carries subpatterns
29
+ through projection and construction. A schema contradiction is a type error;
30
+ ordinary undefinedness is a separate partial-function result.
31
+
32
+ The envelope-free `run_converged` path requires converged derivation.
33
+ Specialized execution can use static patterns instead of carrying them through
34
+ every operation. This does not remove the need to validate input boundaries.
35
+
36
+ Shared input/output pattern nodes express shared schema constraints. They are
37
+ not a value-provenance analysis.
38
+
39
+ ## Artifacts and execution layers
40
+
41
+ `object.mjs` packages and loads `.ko` and `.klib` definitions.
42
+ Loading hydrates stored graphs without parsing source again.
43
+ [File formats](FILE_FORMATS.md) documents the payload and tools.
44
+
45
+ The execution representations have distinct roles:
46
+
47
+ | Representation | Implementation | Role |
48
+ | --- | --- | --- |
49
+ | KIR-P | `kir.mjs` | Portable export of object relations and pattern graphs |
50
+ | kVM | `kvm.mjs` | Register instructions, polymorphic templates, and specialization |
51
+ | PKIR | `pkir.mjs`, `access-table.mjs` | Experimental schema-state/layout-witness execution |
52
+
53
+ KIR-P envelope specialization (`retypeObjectRelation` and related functions)
54
+ can rerun contract derivation. kVM template specialization (`specializeKVM`)
55
+ works on already lowered templates and their principal contracts.
56
+ Do not treat these as the same pass.
57
+
58
+ The Wasm and LLVM backends lower kVM instructions through
59
+ `backends/wasm/src/kvm2wasm.mjs` and `backends/llvm/src/kvm2llvm.mjs`.
60
+ Their PKIR paths adapt the layout-oriented representation for target lowering.
61
+ `backend-api.mjs` exposes the shared compiler/backend API.
62
+
63
+ See the [KIR-P](KIR_V1.md), [kVM](KVM_EXECUTION_MODEL.md), and
64
+ [PKIR](POLYMORPHIC_IR.md) references for their contracts.
65
+
66
+ ## Codecs and user interfaces
67
+
68
+ - `valueParser.jison` / `valueIO.mjs` parse textual boundary values.
69
+ - `codecs/runtime/codec.mjs` implements pattern operations.
70
+ - `codecs/runtime/prefix-codec.mjs` encodes and decodes the wire format,
71
+ including lazy decoding.
72
+ - `codecs/runtime/codec-sdk.mjs` provides codec helpers and the common CLI runner.
73
+ - `repl.mjs` manages sessions; `repl-codecs.mjs` handles codec loading/rendering.
74
+ - `browser/repl-browser.mjs` implements the browser UI.
75
+ - `scripts/build-repl-html.mjs` bundles browser shims, VFS libraries, codecs,
76
+ and Wasm resources into one HTML file.
77
+
78
+ `core.k` defines the fixed `pattern[]` schema used to decode a stream's leading
79
+ pattern value. This does not automatically import the library into user scope.
80
+
81
+ The [wire specification](../codecs/WIRE_FORMAT.md) and
82
+ [codec authoring guide](CODECS.md) define these boundaries.
83
+ Verification commands and suite registration are in [tests/README.md](../tests/README.md).
package/DOCS/CODECS.md CHANGED
@@ -1,121 +1,62 @@
1
- # Writing Codecs
2
-
3
- A codec is an ES module that translates between an external domain format
4
- and enveloped **k** `Value` objects `(P, v)`. The same module serves two
5
- entry points:
6
-
7
- - a standalone command-line filter supporting `--parse`, `--print`,
8
- and `--help`,
9
- - a REPL module loaded with `:codec load <file.mjs>`.
10
-
11
- The command-line entry point reads or writes the binary pattern+value
12
- stream. The REPL entry point provides interactive parsing
13
- (`:input <codec.mjs>`) and multi-codec output formatting.
14
-
15
- ## Architecture & Mental Model
16
-
17
- In `k`, there are no primitive numbers, strings, or built-in numerical
18
- literals. All data is represented as algebraic shapes (e.g. bits, units,
19
- products, and tagged unions). A codec bridges external formats with
20
- these structural *k* values:
21
-
22
- - `parse(text)` translates external text to an enveloped *k* value (a
23
- `Value` with an associated closed pattern envelope `(P, v)`).
24
- - `print(value)` translates an enveloped *k* value into formatted
25
- external text, throwing an `Error` if the value is not representable.
26
- - `doc` (optional string) documents the accepted syntax and semantic
27
- representation.
28
-
29
- Codecs are identified directly by their file name. They do not export
30
- artificial identifiers like `name` or pattern registries like
31
- `patterns = [...]`.
32
-
33
- In the REPL:
34
- - **Input**: The user explicitly chooses which codec to parse with:
35
- - Interactive mode: `:input <codec.mjs>` sets the prompt to
36
- `<codec.mjs>> `, and the next entered line is parsed with that codec.
37
- - One-line mode: `:input <codec.mjs> <text>` immediately parses
38
- `<text>` using that codec.
39
- - **Output**: Any evaluated *k* value is displayed in its standard *k*
40
- envelope representation, followed by formatting from **all loaded
41
- codecs** that can represent it:
42
- ```text
43
- > :input int.mjs 42
44
- {}|_|0|1|0|1|0|1|+ ?<{} _, ...>
45
- int.mjs: 42
46
- ```
47
- Every loaded codec attempts `codec.print(value)`. If it succeeds, the
48
- REPL prints `<codec.mjs>: <formatted>`. If it throws, the codec is
49
- silently ignored for that value.
50
-
51
- ## Module Interface
52
-
53
- A codec module exports:
1
+ # Writing codecs
54
2
 
55
- ```js
56
- export const doc = "Description of syntax and usage.";
3
+ A codec converts an external representation into an enveloped k `Value` and
4
+ back again. The common runner makes the same module usable from a shell pipeline
5
+ and the [REPL](REPL.md).
57
6
 
58
- export function parse(text) {
59
- // parse text into an enveloped k Value (P, v) using
60
- // withPattern(value, pattern)
61
- }
7
+ ## Module contract
62
8
 
63
- export function print(value) {
64
- // return formatted text
65
- // throw Error if value is not representable
66
- }
67
- ```
9
+ A standard text codec exports:
68
10
 
69
- `parse` should throw an `Error` for invalid external text. `print` should
70
- throw when the value is not representable by the external format. REPL
71
- output suppresses `print` errors so loaded codecs only output when they
72
- recognize the value.
11
+ - `parse(text)`: return a `Value` with a pattern; throw on invalid input.
12
+ - `print(value)`: return external text; throw when the value cannot be represented.
13
+ - `doc`: optional help text describing syntax and representation.
73
14
 
74
- ## The Codec SDK & Runner
15
+ The REPL identifies a codec by its file name. Input uses a selected codec;
16
+ output tries all loaded codecs and displays each successful rendering.
75
17
 
76
- To eliminate CLI stream boilerplate, codecs import from
77
- `./runtime/codec-sdk.mjs` and invoke `runCodecCLI`:
18
+ Import helpers from `codecs/runtime/codec-sdk.mjs`:
78
19
 
79
- ```js
80
- import { Value, isVariant, withPattern, runCodecCLI } from "./runtime/codec-sdk.mjs";
81
- ```
20
+ | Helper | Purpose |
21
+ | --- | --- |
22
+ | `Value.product` / `Value.variant` | Construct structural values |
23
+ | `isProduct` / `isVariant` | Recognize values structurally |
24
+ | `withPattern` | Attach a pattern to a value |
25
+ | `patternFromFilter` | Derive a normalized pattern from k source |
26
+ | `encodeToWire` / `decodeWire` | Convert enveloped values to/from binary streams |
27
+ | `decodeWireLazy` | Decode with bitstream-backed value access |
28
+ | `runCodecCLI` | Entrypoint detection, flags, stdin/stdout, and wire conversion |
82
29
 
83
- `runCodecCLI(import.meta.url, { parse, print, doc })` automatically
84
- handles:
85
- 1. Entrypoint detection (no-op when loaded as a module or in browsers).
86
- 2. `-h` and `--help` CLI flag handling.
87
- 3. `--parse` and `--print` stream piping and wire encoding/decoding.
30
+ Derive fixed schemas through `patternFromFilter` rather than maintaining a
31
+ duplicate handwritten graph. Codecs whose structure depends on external input,
32
+ such as JSON, can derive document-specific patterns.
88
33
 
89
- ## Minimal Type-Specific Codec Example
34
+ ## Complete example
90
35
 
91
- This codec accepts `yes` and `no` for the type `<{} false, {} true>`.
92
- Patterns are derived by `k` from filter expressions via
93
- `patternFromFilter`:
36
+ Save this as `codecs/yesno.mjs`. It maps `yes`/`no` to unit variants under
37
+ the boolean schema:
94
38
 
95
39
  ```js
96
40
  #!/usr/bin/env node
97
-
98
- import { Value, isVariant, withPattern, patternFromFilter, runCodecCLI } from "./runtime/codec-sdk.mjs";
41
+ import {
42
+ Value, isProduct, isVariant, withPattern, patternFromFilter, runCodecCLI
43
+ } from "./runtime/codec-sdk.mjs";
99
44
 
100
45
  const BOOL_PATTERN = patternFromFilter("?< {} false, {} true >");
101
-
102
- export const doc = `
103
- Boolean codec: accepts 'yes' and 'no'.
104
- `;
46
+ export const doc = "Boolean codec: accepts yes or no.";
105
47
 
106
48
  export function parse(text) {
107
49
  const word = text.trim();
108
- if (word === "yes") {
109
- return withPattern(Value.variant("true", Value.product({})), BOOL_PATTERN);
110
- }
111
- if (word === "no") {
112
- return withPattern(Value.variant("false", Value.product({})), BOOL_PATTERN);
113
- }
114
- throw new Error("expected yes or no");
50
+ const tag = word === "yes" ? "true" : word === "no" ? "false" : null;
51
+ if (!tag) throw new Error("expected yes or no");
52
+ return withPattern(Value.variant(tag, Value.product({})), BOOL_PATTERN);
115
53
  }
116
54
 
117
55
  export function print(value) {
118
- if (!isVariant(value)) throw new Error("expected bool variant");
56
+ if (!isVariant(value) || !isProduct(value.value) ||
57
+ Object.keys(value.value.product).length !== 0) {
58
+ throw new Error("expected a boolean unit variant");
59
+ }
119
60
  if (value.tag === "true") return "yes";
120
61
  if (value.tag === "false") return "no";
121
62
  throw new Error("expected true or false");
@@ -124,122 +65,70 @@ export function print(value) {
124
65
  runCodecCLI(import.meta.url, { parse, print, doc });
125
66
  ```
126
67
 
127
- ### Using in the REPL:
68
+ From the repository root:
128
69
 
129
- ```text
130
- > :codec load ./codecs/yesno.mjs
131
- loaded codec yesno.mjs
132
- > :input yesno.mjs yes
133
- {}|true ?<{} false, {} true>
134
- yesno.mjs: yes
70
+ ```sh
71
+ printf 'yes\n' | node codecs/yesno.mjs --parse |
72
+ node codecs/yesno.mjs --print
135
73
  ```
136
74
 
137
- ### Using as a CLI Pipeline Filter:
75
+ This prints `yes`. In the REPL:
138
76
 
139
- ```sh
140
- printf 'yes\n' | ./codecs/yesno.mjs --parse | ./codecs/yesno.mjs --print
141
- # Output: yes
77
+ ```text
78
+ :codec load codecs/yesno.mjs
79
+ :input yesno.mjs yes
142
80
  ```
143
81
 
144
- ## Built-in Codecs
145
-
146
- The `codecs/` directory provides the following standard codecs:
147
-
148
- - **`int.mjs` (`k-int`)**: Decimal integers and bracketed integer lists
149
- (e.g. `42`, `-15`, `[1, 2, 3]`) mapped to signed binary bit trees and
150
- `cons`/`nil` lists.
151
- - **`ieee.mjs` (`k-ieee`)**: IEEE 754 64-bit floating-point numbers
152
- (`sign`, `exponent`, `fraction`).
153
- - **`utf8.mjs` (`k-utf8`) & `utf16.mjs` (`k-utf16`)**: Unicode strings
154
- encoded as `cons`/`nil` code-point lists (`str` in `core.k`).
155
- - **`unit.mjs` (`k-unit`)**: The unit value `{}`.
156
- - **`json.mjs` (`k-json`) — Schema-Specializing JSON**:
157
- Derives a document-specific pattern for each JSON value:
158
- - JSON objects map directly to products `{ field: val, ... }`.
159
- - JSON arrays map to indexed products `{ "0": a0, "1": a1, ... }`.
160
- - Ideal for record-oriented projection (e.g. `.user .name`).
161
- - **`djson.mjs` (`k-djson`) — Universal Dynamic JSON (Binary Bit-Trie)**:
162
- Maps every JSON document to a single universal recursive named
163
- pattern `djson[]`:
164
- ```k
165
- btrie[V] = < {} nil, { opt[V] val, T 0, T 1 } trie > = T;
166
-
167
- djson[] = <
168
- number[] number,
169
- string[] string,
170
- bool[] bool,
171
- {} null,
172
- btrie[J] list,
173
- btrie[J] object
174
- > = J;
175
- ```
176
- Uses a unified 27-node binary bit-trie for both arrays and objects.
177
- Array indices (`bits?`) and string keys are stored along MSB-to-LSB
178
- bit paths, enabling $O(|K|)$ lookup via direct `.0`/`.1` projections
179
- with zero allocations and zero character-equality loops.
180
- Accompanied by a complete standard library on `json?` in
181
- [`Examples/djson.k`](../Examples/djson.k) (`get`, `nth`, `has?`,
182
- `has_index?`, `set`, `del`, `set_nth`, `del_nth`, `push`, `keys`,
183
- `keys_raw`, `values`, `values_raw`, `length`, `length_nat`,
184
- `type_of`).
185
-
186
- ## Testing a Codec
187
-
188
- For CLI codecs, test both directions in a pipeline:
82
+ The REPL displays the structural value and `yesno.mjs: yes`.
189
83
 
190
- ```sh
191
- printf 'yes\n' | node codecs/yesno.mjs --parse | \
192
- node codecs/yesno.mjs --print
193
- ```
84
+ ## CLI behavior
194
85
 
195
- For REPL codecs, add a focused case to
196
- [`../tests/test-repl.mjs`](../tests/test-repl.mjs):
86
+ `runCodecCLI(import.meta.url, { parse, print, doc })` acts only when the module
87
+ is invoked as the entrypoint:
197
88
 
198
- ```js
199
- const state = createState();
200
- let output = await evaluateInput(":codec load ./codecs/yesno.mjs", state);
201
- assert.match(output[0], /^loaded codec yesno\.mjs/);
202
- output = await evaluateInput(":input yesno.mjs", state);
203
- assert.equal(promptForState(state), "yesno.mjs> ");
204
- output = await evaluateInput("yes", state);
205
- assert.match(output[0], /yesno\.mjs: yes/);
206
- output = await evaluateInput(":input yesno.mjs no", state);
207
- assert.match(output[0], /yesno\.mjs: no/);
208
- ```
89
+ - `--parse` reads external input and writes a binary schema+payload stream.
90
+ - `--print` reads that stream and writes the external rendering.
91
+ - `-h` / `--help` writes usage and `doc`.
92
+ - Errors go to stderr and cause a nonzero exit.
209
93
 
210
- Then run the full suite before committing:
94
+ Text rendering normally adds a newline. Modules handling binary external input
95
+ can set `readBuffer: true`; `addNewline: false` suppresses the output newline.
96
+ A zero-argument `parse` can produce a value without reading stdin, as the unit
97
+ codec does.
211
98
 
212
- ```sh
213
- npm test
214
- ```
99
+ The pattern is selected from the parsed value, a module-supplied pattern, or
100
+ witness derivation. General wire semantics are specified in
101
+ [WIRE_FORMAT.md](../codecs/WIRE_FORMAT.md).
102
+
103
+ ## Existing codecs
104
+
105
+ | Module / installed command | Representation |
106
+ | --- | --- |
107
+ | `int.mjs` / `k-int` | Decimal integers and integer lists as signed bit trees |
108
+ | `ieee.mjs` / `k-ieee` | Binary64 floats as sign/exponent/fraction records |
109
+ | `utf8.mjs` / `k-utf8` | UTF-8 text as the Unicode scalar list `string[]` from core.k |
110
+ | `utf16.mjs` / `k-utf16` | UTF-16 external bytes mapped to the same string structure |
111
+ | `unit.mjs` / `k-unit` | Unit |
112
+ | `json.mjs` / `k-json` | Document-specific schemas: objects as products, arrays as indexed products |
113
+ | `djson.mjs` / `k-djson` | One recursive JSON representation using binary tries for objects and arrays |
114
+
115
+ `Examples/djson.k` supplies operations such as `get`, `nth`, `set`,
116
+ `del`, `push`, `keys`, and `values`. The specializing JSON codec and dynamic
117
+ JSON codec serve different schemas; they are not interchangeable encodings.
118
+
119
+ `k-parse` and `k-print` use [textual k values](TEXTUAL_VALUES.md), rather than
120
+ the external integer/string/JSON interpretations above.
121
+
122
+ ## Browser bundling and verification
123
+
124
+ `scripts/build-repl-html.mjs` bundles a curated set of codecs as self-contained
125
+ ES modules in the virtual filesystem. The browser shim supplies pattern
126
+ derivation and disables CLI entrypoint behavior. It loads modules through Blob
127
+ URLs without exposing codec runtime helper files in the VFS.
128
+
129
+ A new codec needs explicit inclusion in that build to be available in the
130
+ standalone browser REPL.
215
131
 
216
- ## Web REPL (VFS) Bundling
217
-
218
- When `repl.html` is generated (`npm run build:repl-html`):
219
- - Codecs (`int.mjs`, `json.mjs`, `djson.mjs`, `utf8.mjs`, `unit.mjs`,
220
- `ieee.mjs`) are bundled into 100% self-contained ES modules with zero
221
- imports.
222
- - `runCodecCLI` is shimmed as a no-op, and `Value` helpers are directly
223
- inlined.
224
- - In the browser, the VFS serves these self-contained modules directly to
225
- native dynamic `import(blobUrl)`. No runtime helper files
226
- (`codecs/runtime/*`) need to be included in the VFS or exposed as
227
- globals.
228
-
229
- ## Checklist
230
-
231
- - Return an enveloped `Value` from `parse` using
232
- `withPattern(val, pattern)`.
233
- - Keep `parse` and `print` deterministic and free of side effects.
234
- - Validate shapes in `print` and throw clear errors when not
235
- representable.
236
- - Use `runCodecCLI(import.meta.url, { parse, print, doc })` for CLI
237
- execution.
238
- - No artificial `name` or `patterns` exports required.
239
- - Add `-h` and `--help` support via `runCodecCLI`.
240
-
241
- - [DOCS/FILE_FORMATS.md](./FILE_FORMATS.md) —
242
- guide to .k, .ko, .klib, and .kvm formats
243
- - [DOCS/CODEC_ARCHITECTURE.md](./CODEC_ARCHITECTURE.md) —
244
- codec architectural design
245
- - [DOCS/REPL.md](./REPL.md) — interactive interpreter and codec commands
132
+ Check valid and invalid input, round trips, shape rejection in `print`, CLI
133
+ help, and REPL loading. Existing examples are in `tests/test-codecs.mjs` and
134
+ `tests/test-repl.mjs`. Run `npm test` after changing codec behavior.