@fraczak/k 8.4.0 → 8.5.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 (113) hide show
  1. package/CHANGELOG.md +59 -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 +156 -123
  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 -371
  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/cli.mjs +0 -31
  27. package/backends/wasm/README.md +88 -66
  28. package/backends/wasm/src/cli.mjs +0 -31
  29. package/canonical-pattern.mjs +69 -35
  30. package/codecs/README.md +23 -261
  31. package/codecs/WIRE_FORMAT.md +132 -0
  32. package/core.k +5 -15
  33. package/index.mjs +5 -1
  34. package/named-patterns.mjs +55 -7
  35. package/object.mjs +28 -6
  36. package/objects/README.md +24 -109
  37. package/package.json +8 -3
  38. package/paper/Makefile +17 -0
  39. package/paper/k-paper.pdf +0 -0
  40. package/paper/k-paper.tex +435 -0
  41. package/parser.jison +0 -10
  42. package/parser.mjs +32 -43
  43. package/repl.mjs +79 -101
  44. package/scripts/benchmark-idempotency.mjs +3 -3
  45. package/scripts/run-tests.mjs +1 -1
  46. package/scripts/test-package.mjs +64 -0
  47. package/tests/README.md +66 -46
  48. package/tests/code-derivation/core.mjs +61 -0
  49. package/tests/helpers/cli.mjs +45 -0
  50. package/tests/integration.sh +2 -3
  51. package/tests/test-arithmetics.mjs +47 -237
  52. package/tests/test-djson-methods.mjs +71 -275
  53. package/tests/test-hash-normalization.mjs +22 -1
  54. package/tests/test-karatsuba.mjs +18 -126
  55. package/tests/test-named-patterns.mjs +174 -606
  56. package/tests/test-paper-examples.mjs +90 -0
  57. package/tests/test-poly.mjs +2 -2
  58. package/tests/test-repl-html.mjs +2 -2
  59. package/tests/test-repl.mjs +89 -38
  60. package/tests/test.mjs +27 -68
  61. package/AGENTS.md +0 -35
  62. package/CLAUDE.md +0 -64
  63. package/DOCS/BIG_PICTURE.md +0 -439
  64. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  65. package/DOCS/CANONICAL_PATTERNS.md +0 -349
  66. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  67. package/DOCS/CONVERGENCE.md +0 -123
  68. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  69. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  70. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  71. package/DOCS/Makefile +0 -99
  72. package/DOCS/NAMED_PATTERNS.md +0 -340
  73. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  74. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  75. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -136
  76. package/DOCS/book/01-introduction.md +0 -48
  77. package/DOCS/book/02-syntax-and-values.md +0 -110
  78. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  79. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  80. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  81. package/DOCS/book/06-values-in-memory.md +0 -1085
  82. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  83. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  84. package/DOCS/book/09-compiler-architecture.md +0 -160
  85. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  86. package/DOCS/book/14-canonical-serialization.md +0 -176
  87. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  88. package/DOCS/book/overview.txt +0 -68
  89. package/DOCS/book.md +0 -50
  90. package/Examples/bnat.k +0 -308
  91. package/Examples/buda.k +0 -66
  92. package/Examples/byte.k +0 -35
  93. package/Examples/code.k +0 -43
  94. package/Examples/vhdl_to_k.k +0 -67
  95. package/JOURNAL.md +0 -288
  96. package/TODO.md +0 -107
  97. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  98. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  99. package/backends/wasm/demo_ieee.mjs +0 -318
  100. package/browser/vfs-data.mjs +0 -21
  101. package/codecs/BINARY_FORMAT.md +0 -53
  102. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  103. package/codecs/pandoc.css +0 -71
  104. package/tests/code-derivation/blowup.mjs +0 -25
  105. package/tests/code-derivation/bnat.mjs +0 -11
  106. package/tests/code-derivation/dot.mjs +0 -37
  107. package/tests/code-derivation/index.mjs +0 -20
  108. package/tests/code-derivation/loop.mjs +0 -17
  109. package/tests/code-derivation/nat.mjs +0 -10
  110. package/tests/code-derivation/not-not.mjs +0 -14
  111. package/tests/code-derivation/product.mjs +0 -22
  112. package/tests/code-derivation/rlz.mjs +0 -13
  113. package/tests/test-fingerprint.mjs +0 -38
package/JOURNAL.md DELETED
@@ -1,288 +0,0 @@
1
- # Transducer & Polymorphic Execution Journal
2
-
3
- Branch: `transducer`
4
- Repository: `@fraczak/k`
5
-
6
- ## Objective
7
-
8
- Design, specify, and implement an efficient compilation and execution
9
- model for polymorphic functions in K.
10
-
11
- The architecture bridges two fundamental physical data representations:
12
- 1. **Sequential Prefix-Free Streams** (Wire / Bitstream) operated by
13
- **Streaming Pushdown Transducers** for linear/erasing access.
14
- 2. **Random-Access Memory Tables** (Arena Nodes) operated by
15
- **Layout Witnesses** (Offset Dictionaries) and specialized
16
- monomorphic kernels (`?S F`).
17
- 3. **The Hybrid Dual-Form Pointer** (`KVal` / `KChild`), allowing values
18
- to remain compact wire slices by default, with on-demand **Spine
19
- Promotion** when non-linear (repeated / out-of-order) access occurs.
20
-
21
- ---
22
-
23
- ## Architecture Log & Decisions
24
-
25
- ### 2026-10-12: Architectural Foundations & TDD Initiation
26
-
27
- - **Core Duality Formalized**:
28
- - *Witness Approach*: Operates on indexed random-access memory tables.
29
- Static offset vector $\Omega(S, F)$ resolves field access without
30
- dynamic string lookups.
31
- - *Transducer Approach*: Operates on sequential prefix-free code
32
- streams. State transitions over choice bits navigate variants and
33
- skip unneeded product fields without materialization or re-encoding.
34
- - **Linearity vs Non-Linearity**:
35
- - Linear/affine access (erasing access: each field read $\le 1$ time in
36
- stream order) runs entirely in streaming Transducer mode in
37
- $O(\text{depth})$ stack memory with zero node allocations.
38
- - Non-linear access (duplication `{()x, ()x}`, out-of-order reads) is
39
- handled via:
40
- - Zero-copy slice duplication for independent linear readers.
41
- - Demand-driven **Spine Promotion**: materializing only the immediate
42
- outer product spine into an arena node with child pointers
43
- remaining as serialized wire slices.
44
- - **TDD Test Suite Planned & Implemented**:
45
- - Initial suite created in `tests/test-polymorphic-tdd.mjs` (all 6
46
- tests passing).
47
- - Targets 6 orthogonal polymorphic patterns:
48
- 1. Filtered Search (`search`): Opaque payload preservation &
49
- non-linear condition testing.
50
- 2. Search with Field Reordering: Varied syntax and memory ordering.
51
- 3. Boundary Cases: Empty lists, zero matches, all match.
52
- 4. Multi-Variant Dispatch (`extract_id`): Variable byte offsets
53
- across variants.
54
- 5. Dual-Stream Zip (`zip`): Concurrent independent polymorphic
55
- streams.
56
- 6. Polymorphic Reverse (`poly_rev`): Accumulator and spine
57
- reconstruction.
58
-
59
- ### 2026-10-12: State-Indexed Access Table (`access-table.mjs`)
60
-
61
- - **Algorithm Implemented (`buildAccessTable`)**:
62
- - Implemented in `access-table.mjs`.
63
- - Maps any input value schema $S$ to a function's structural access
64
- profile $P$.
65
- - Generates a state-indexed table of `NodeDescriptor` entries:
66
- - Products: maps logical field slots to physical slots, byte offsets,
67
- skip counts, and child states.
68
- - Unions: maps physical discriminators to branch indices and child
69
- states.
70
- - Zero runtime string lookups; single-array-load machine instruction
71
- dispatch.
72
- - **Unit Verification (`tests/test-access-table.mjs`)**:
73
- - All tests passing: verifies offset calculation for `search` and
74
- `extract_id`.
75
- - Simulates in-memory payload navigation with zero string comparisons.
76
-
77
- ### 2026-10-12: Formal Specification of PKIR (`DOCS/POLYMORPHIC_IR.md`)
78
-
79
- - Specified the Polymorphic K Intermediate Representation (PKIR):
80
- - Abstract state-indexed, slot-addressed instruction set.
81
- - Dual execution strategy: direct interpretation with `AccessTable`
82
- and fast monomorphic specialization.
83
- - Pure partial function semantics with failure propagation.
84
-
85
- ### 2026-10-12: PKIR Implementation & Specialization (`pkir.mjs`)
86
-
87
- - **Compiler Lowering (`compileRelationToPKIR`)**:
88
- - Traverses relational AST and produces state-indexed PKIR instructions.
89
- - Automatically derives `accessProfile` per pattern node.
90
- - **Fat-Pointer Runtime (`KVal` / `valueToKVal` / `kvalToValue`)**:
91
- - Materialized arena node simulation with dual-form support.
92
- - Lossless round-trip conversion preserving arbitrary nested payloads.
93
- - **Direct Execution (`executePKIR`)**:
94
- - Evaluates PKIR instructions using `AccessTable` descriptors.
95
- - Supports recursive relation invocation (`call_rel`) and failure
96
- backtracking across union branches.
97
- - **Monomorphic Specialization (`specializePKIR`)**:
98
- - Bakes concrete `AccessTable` into specialized instructions
99
- (`project_offset`, `match_tag_imm`).
100
- - Dead branch elimination: prunes non-matching union branches.
101
- - Direct execution of specialized artifacts without `AccessTable`.
102
- - **Test Verification (`tests/test-pkir.mjs`)**:
103
- - Comprehensive 8-test suite verifying lowering, recursive search,
104
- multi-variant dispatch, specialization, and error handling.
105
- - Full project test suite (`npm test`) passes with 100% green status.
106
-
107
- ### 2026-10-12: Performance Evaluation (Previous Work vs PKIR)
108
-
109
- - **Multi-Variant Dispatch Benchmark (`extract_id`, 200k iterations)**:
110
- - AST Interpreter (`run.mjs`): 225.98 ms (885,035 ops/s)
111
- [1.00x baseline].
112
- - kVM Interpreter (`kvm.mjs`): 78.36 ms (2,552,456 ops/s)
113
- [2.88x speedup].
114
- - PKIR Generic (`AccessTable`): 74.69 ms (2,677,615 ops/s)
115
- [3.03x speedup].
116
- - PKIR Specialized (`specializePKIR`): 62.23 ms (3,214,079 ops/s)
117
- [3.63x speedup].
118
- - **Elimination of the Envelope Tax**:
119
- - In previous work (`scripts/perf-poly.mjs`), polymorphic envelope
120
- wrapping suffered a 26x performance penalty (31.74 ms envelope-aware
121
- vs 1.21 ms envelope-free).
122
- - The Layout Witness approach eliminates envelopes completely: layout
123
- witnesses index heterogeneous physical records directly without
124
- boxing or re-encoding.
125
- - **Sub-30µs Specialization Latency**:
126
- - `buildAccessTable`: 2.28 µs per table.
127
- - `specializePKIR`: 24.87 µs per relation specialization.
128
- - Total Specialization Overhead: ~27.15 µs (compared to 100-1500 ms for
129
- traditional Wasm/LLVM AOT compilation), enabling instant runtime
130
- JIT tiering.
131
- - **Zero Payload Re-encoding in Recursive Traversals (`search_`)**:
132
- - Evaluated on 100-element lists with arbitrary heterogeneous payloads.
133
- - Throughput: 404,703 items/sec (0.247 ms per 100-item pass).
134
- - Opaque payload slices (`data: payload_i`) are forwarded by fat-pointer
135
- references without traversing, unpacking, or re-serializing them.
136
-
137
- ### 2026-10-12: WebAssembly Integration in REPL (`repl.mjs` & `repl.html`)
138
-
139
- - **PKIR-to-KVM Lowering (`lowerPKIRToKVM`)**:
140
- - Implemented and exported `lowerPKIRToKVM(pkir)` in `pkir.mjs` and
141
- `backend-api.mjs`.
142
- - Translates state-indexed PKIR instructions (`id`, `filter`,
143
- `project_slot`, `match_variant`, `make_variant`, `product`, `union`,
144
- `call_rel`) into machine-level KVM instructions for `lowerToWasm`.
145
- - Maps top-level input register and branch-local input registers to
146
- `%in`, enabling seamless integration with Wasm register allocation.
147
- - **WebAssembly Compilation Pipeline**:
148
- - Extended `compileModule`, `compileWasmArtifactFromDefs`, and
149
- `compileWasmArtifactFromObject` in `backends/wasm/src/wasm.mjs` with
150
- the `usePKIR` option.
151
- - Implemented and exported `compileWasmArtifactFromPKIR(pkirInput)`.
152
- - **REPL CLI Support (`repl.mjs`)**:
153
- - Added `pkir` engine mode: `--pkir`, `--engine=pkir`, `:pkir`,
154
- `:engine pkir`, and autocompletion in `:engine [wasm|pkir|js]`.
155
- - In `executeExpressionWithWasm`: routes compilation through PKIR when
156
- the engine is set to `pkir`.
157
- - **Browser Web REPL (`repl.html`)**:
158
- - Updated `browser/repl-browser.mjs` with a 3-way engine badge toggle
159
- (`wasm-in-process` -> `pkir-wasm` -> `js-in-process`).
160
- - Added `.engine-badge.pkir-mode` badge styling in
161
- `scripts/build-repl-html.mjs` and rebuilt `repl.html`.
162
- - **Verification**:
163
- - Verified evaluation of arithmetic, boolean logic, and lists via
164
- PKIR-generated WebAssembly.
165
- - Test suites (`tests/test-pkir.mjs`, `tests/test-repl.mjs`,
166
- `tests/test-repl-html.mjs`, and `npm test`) pass with 100% green.
167
-
168
- ### 2026-10-12: Integration into Performance Harnesses (`perf:*`)
169
-
170
- - **Benchmark Integration**:
171
- - Integrated `pkir` execution lane into:
172
- - `scripts/perf-int.mjs`: Big Integer ops and 10-step squaring scale.
173
- - `scripts/perf-ieee.mjs`: IEEE 754 float ops across 144 evaluations.
174
- - `scripts/perf-multiplication.mjs`: Multi-backend squaring benchmark.
175
- - `scripts/perf-poly.mjs`: Polymorphic list ops and macro tracing.
176
- - Generates and compiles WebAssembly artifacts via
177
- `compileWasmArtifactFromObject(rel.object, { usePKIR: true })`.
178
- - **Target Backend Selection**:
179
- - Added support for `BACKENDS=pkir`, `PKIR_ONLY=1`, and `--pkir-only`.
180
- - When unrestricted, all backends (`llvm`, `wasm`, `pkir`, `kvm`, `js`)
181
- execute concurrently for direct side-by-side comparison.
182
- - **Convenience NPM Scripts (`package.json`)**:
183
- - Added `perf:int:pkir`: `BACKENDS=pkir node scripts/perf-int.mjs`
184
- - Added `perf:ieee:pkir`: `BACKENDS=pkir node scripts/perf-ieee.mjs`
185
- - Added `perf:mult:pkir`:
186
- `node scripts/perf-multiplication.mjs --backends pkir`
187
- - Added `perf:poly:pkir`: `BACKENDS=pkir node scripts/perf-poly.mjs`
188
- - **Verification**:
189
- - All benchmarks verify 100% output conformance against native K
190
- oracle values.
191
- - Squaring benchmarks reach full 10/10 steps with matching outputs.
192
-
193
- ### 2026-10-13: LLVM Backend Integration for PKIR
194
-
195
- - **Compiler Lowering & CLI Integration**:
196
- - Implemented `compileLLVMArtifactFromPKIR` and `{ usePKIR: true }` in
197
- `backends/llvm/src/llvm.mjs` and `backends/llvm/src/executable.mjs`.
198
- - Added CLI support (`--pkir` and `.pkir` input files) for
199
- `k-llvm-compile`, `k-llvm-build`, and `k-wasm-compile`.
200
- - Exported `compilePKIRToExecutable` and `compilePKIRAndRun` from
201
- `backends/llvm/src/executable.mjs`.
202
- - **Runtime & Slot Lowering Fixes**:
203
- - Synthesized union helper `inputPattern`: resolved input pattern in
204
- `union_expr` and `union_arm` from
205
- `regPatterns.get(cleanReg(inst.src))`
206
- so field access in arm functions targets correct physical slots.
207
- - Open product field indexing in PKIR: restricted static physical slot
208
- addressing in `getFieldEdgeIndex` to closed products when `usePKIR`
209
- is active, falling back to dynamic `k_product_get_n` for polymorphic
210
- open products to prevent physical index misalignment.
211
- - Wire serialization for polymorphic outputs: implemented and exported
212
- `k_encode_wire` via `derive_pattern(value)` in `krt.h` and `krt.c`,
213
- with fallback in `executable.mjs` when static output pattern has
214
- `KP_ANY`.
215
- - Pattern graph ID 0 check: updated `compileObjectToLLVM` pattern
216
- lookups to check `!== undefined` so node ID 0 is not treated as falsy.
217
- - **Performance Harnesses & NPM Automation**:
218
- - Added `llvm-pkir` backend lane across:
219
- - `scripts/perf-multiplication.mjs` (`--backends llvm-pkir`)
220
- - `scripts/perf-int.mjs` (`BACKENDS=llvm-pkir`)
221
- - `scripts/perf-poly.mjs` (`BACKENDS=llvm-pkir`)
222
- - `scripts/perf-ieee.mjs` (`BACKENDS=llvm-pkir`)
223
- - Added npm scripts to `package.json`:
224
- - `perf:mult:llvm-pkir`
225
- - `perf:int:llvm-pkir`
226
- - `perf:poly:llvm-pkir`
227
- - `perf:ieee:llvm-pkir`
228
- - **Verification**:
229
- - Added PKIR LLVM lowering, compilation, and execution tests
230
- (Tests 10, 11, 12 in `tests/test-pkir.mjs`).
231
- - Verified 100% test pass on `npm test` and `npm run test:backends`.
232
- - Verified 100% output conformance across all `perf:*` benchmarks.
233
-
234
- ### 2026-10-13: Concurrent LLVM & LLVM-PKIR Benchmark Comparison
235
-
236
- - **Motivation**:
237
- - The previous harness integration allowed selecting either `llvm` or
238
- `llvm-pkir` via `BACKENDS=llvm-pkir`, but did not run both
239
- concurrently in default runs (`npm run perf:int`, etc.).
240
- - Users expecting direct performance comparisons between the original
241
- monomorphic LLVM backend and the new polymorphic PKIR LLVM backend
242
- now see both lanes evaluated side-by-side by default.
243
- - **Changes Across All Perf Harnesses**:
244
- - `scripts/perf-int.mjs`: Separated `runLLVM` and `runLLVMPKIR` into
245
- distinct lanes enabled by default. Both `LLVM` and `LLVM-PKIR` are
246
- compiled, warmed, timed, and reported in the main integer benchmark
247
- table and squaring scale benchmark.
248
- - `scripts/perf-ieee.mjs`: Both `LLVM` and `LLVM-PKIR` executables are
249
- compiled across specified optimization levels and reported side-by-
250
- side in the results table and conformance validation.
251
- - `scripts/perf-poly.mjs`: Both `LLVM` and `LLVM-PKIR` are benchmarked
252
- side-by-side in default runs and supported in 7-phase execution
253
- tracing (`--trace`).
254
- - `scripts/perf-multiplication.mjs`: Added `llvm-pkir` to default
255
- backend list (`llvm,llvm-pkir,wasm,pkir,kvm,js`) and respected
256
- `BACKENDS` environment variable.
257
-
258
- ---
259
-
260
- ## Work Items & Progress
261
-
262
- - [x] Branch creation (`transducer`)
263
- - [x] Execution model & duality analysis documented
264
- - [x] Initialize `JOURNAL.md`
265
- - [x] Create `tests/test-polymorphic-tdd.mjs` test harness (passing)
266
- - [x] Establish evaluator & kVM baseline passes
267
- - [x] Design & implement `buildAccessTable` algorithm (`access-table.mjs`)
268
- - [x] Create `tests/test-access-table.mjs` test suite (passing)
269
- - [x] Formal PKIR specification (`DOCS/POLYMORPHIC_IR.md`)
270
- - [x] Prototype `KVal` fat-pointer representation (`pkir.mjs`)
271
- - [x] Implement PKIR compiler lowering (`compileRelationToPKIR`)
272
- - [x] Implement PKIR execution engine (`executePKIR`)
273
- - [x] Implement Monomorphic Specializer with dead branch elimination
274
- - [x] Create `tests/test-pkir.mjs` test suite (passing)
275
- - [x] Integrate with test runner (`scripts/run-tests.mjs`) & verify
276
- - [x] Benchmark performance against previous work (AST & kVM baselines)
277
- - [x] Integrate PKIR into Wasm lowering (`lowerPKIRToKVM`)
278
- - [x] Enable PKIR in `repl.mjs` (`--pkir`, `:engine pkir`)
279
- - [x] Enable PKIR in `repl.html` (3-way engine badge toggle)
280
- - [x] Add PKIR to perf:* harnesses (perf:int, perf:ieee, perf:mult, poly)
281
- - [x] Integrate PKIR into LLVM lowering (`compileLLVMArtifactFromPKIR`)
282
- - [x] Add CLI support for PKIR in LLVM tools (`k-llvm-compile`, etc.)
283
- - [x] Standalone executable compilation (`compilePKIRToExecutable`)
284
- - [x] Integrate `llvm-pkir` into all `perf:*` benchmarks and
285
- `package.json`
286
- - [x] Fix polymorphic open product slot resolution and dynamic wire
287
- encoding
288
- - [x] Run both LLVM and LLVM-PKIR side-by-side by default in perf:* tests
package/TODO.md DELETED
@@ -1,107 +0,0 @@
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 relations (functions) over tree-like (JSON-like) documents.
21
- - [x] **Content-Addressed Identity**: Relations 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] **Grammar Categories**:
23
- 1. **Definitions (Local Aliases)**:
24
- - `name = relExpr;` &mdash; Relation alias (e.g. `swap = { . y x, . x y };`).
25
- 2. **Relation Expressions (`relExpr`)**: Functions transforming an input document to an output document:
26
- - `{ 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 `{}`).
27
- - `< rel_1, ..., rel_k >` &mdash; Union / ordered choice of arity $k$ (evaluates relations in order until one succeeds).
28
- - `( 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`).
29
- - `. label` &mdash; Field projection (extracts field `label`).
30
- - `/ tag` &mdash; Variant branch projection (extracts payload of variant `tag`).
31
- - `| tag` &mdash; Variant constructor (wraps document into variant `tag`).
32
- - `? filterExpr` &mdash; Pattern filter (asserts input matches pattern; serves as inductive termination witness).
33
- - `name` / `@hash` &mdash; Relation reference.
34
- - [x] **Simplified Intro**:
35
- - 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.
36
- - [x] **Replaced Misleading Expressions & Snippets**:
37
- - Removed phantom concepts (`10` as literal, "bit-path", `{10 int x, 5 int y} plus` in default state).
38
- - Added self-contained snippets (`{} | ok`, `not = < / true | false, / false | true >;`, `bool = ?< {} true, {} false >;`, `not = bool ?X < / true | false, {} | true > ?X;`, `swap = { . y x, . x y };`).
39
- - [x] **Command Reference Table**:
40
- - Added `:time <expr>`.
41
- - Removed obsolete commands: `:rel <name> = expr`, `:val`, `:timing [on|off]`, `:codec define n t b`.
42
- - Removed obsolete commands: `:type`, `:types`, `:code`, `:codes`.
43
- - Timing is now always enabled by default across all evaluations.
44
- - Updated `:input` documentation to note the interactive browser dialog.
45
- - Clarified `:rels` (relation aliases).
46
-
47
- ---
48
-
49
- ## 3. Codecs Modal Overhaul
50
-
51
- ### Concept Correction: External Format Adapters
52
- - [x] Reframed codecs as format adapters translating external text to/from $k$ values defined as pairs `(filter, tree)`.
53
- - [x] **Type-Specific Codecs**:
54
- - `int`: Converts decimal integers to/from `int = ?< bits '+', bits '-' >`.
55
- - `ieee`: Converts decimal floats to/from `float64` records (`sign`, `exponent`, `fraction`).
56
- - `utf8`: Converts text to/from `string` (aliased to `utf8`), a list of Unicode scalar values (`unicode`) partitioned by Unicode planes.
57
- - `unit`: Converts to/from `{}`.
58
- - [x] **Parameterized Codecs**:
59
- - `json`: JSON text is untyped; deserializing JSON requires a target $k$ type schema parameter (e.g. `:input {float64 x, string n} json`).
60
- - [x] **Custom Codec Studio**:
61
- - Updated explanation to emphasize pairs `(filter, tree)`.
62
- - Fixed `yn` preset to provide self-contained relation definition `bool = ?< {} true, {} false >;`.
63
- - Fixed `blank` preset with proper Value payload formatting.
64
-
65
- ---
66
-
67
- ## 4. 'Input' Modal Overhaul
68
-
69
- - [x] **Parameterized Codec Support**:
70
- - 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>`).
71
- - Integrated `resolveInputTypeHash(state, rawType)` into live validation and modal submit.
72
- - Marked `json` as a Parameterized Codec requiring a target type schema.
73
- - Added composite quick samples demonstrating type + JSON payload pairs (e.g. `{float64 x, string n}` with `{"x":12, "n":"Woj"}`).
74
- - Preserved CLI-specified type expressions when opening via `:input <type> [codec]`.
75
-
76
- ---
77
-
78
- ## 5. Welcome Banner
79
-
80
- - [x] Shortened initial welcome message to just the title line: `k interactive repl`.
81
- - [x] Removed secondary description and quick link lists to keep the terminal prompt clean and uncluttered.
82
-
83
- ---
84
-
85
- ## 6. Curated VFS & Navbar Examples Dropdown
86
-
87
- - [x] Added `poly.k` to `verifiedExamples` and `#example-select`.
88
- - [x] Structured Navbar Examples dropdown into self-contained basic expressions vs. library-dependent workflows.
89
- - [x] Removed `:val` from example dropdown list.
90
- - [x] Fixed `() ()` option display text.
91
-
92
- ---
93
-
94
- ## 7. Responsive Navbar & Obsolete Command Removal
95
-
96
- - [x] **Responsive Navbar on Narrow Screens**:
97
- - Changed `.navbar` from fixed `height: 48px;` to `min-height: 48px; height: auto; flex-wrap: wrap; padding: 6px 16px; gap: 8px 12px;`.
98
- - 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`).
99
- - Added comprehensive responsive media query for narrow screens ($\le 768\text{px}$) with full width wrapping and adaptable control inputs.
100
- - Verified via headless Chromium CDP automated tests that `#btn-help` is completely visible and interactable at narrow viewport widths (e.g. 600px).
101
- - [x] **Removed Obsolete Commands**:
102
- - Removed `:rel <name> = expr` and `:def` (relations are defined using native syntax `name = expr;`).
103
- - Removed `:type`, `:types`, `:code`, `:codes` commands completely on `no-codes`.
104
- - Removed `:val` completely.
105
- - Removed `:timing [on|off]` (timing reporting is now permanently enabled by default for all evaluations; `:time <expr>` remains for explicit timing).
106
- - Removed `:codec define n t b` (custom codecs are created using the browser Custom Codec Studio UI or loaded from modules via `:codec load`).
107
-
@@ -1,233 +0,0 @@
1
- # Using WebAssembly
2
-
3
- The experimental WebAssembly backend can compile a k program into a binary
4
- `.wasm` artifact and run that artifact later without loading the original k
5
- source. It uses the same binary `pattern + value` streams as the normal `k`
6
- runtime, so the existing codecs remain the pipeline boundaries.
7
-
8
- ## Install the Commands
9
-
10
- From the monorepo root:
11
-
12
- ```bash
13
- npm install
14
- cd backends/wasm
15
- npm link
16
- ```
17
-
18
- This installs three commands:
19
-
20
- | Command | Purpose |
21
- | --- | --- |
22
- | `k-wasm` | Compile k source, `.ko`, or `.kvm` input in memory and run it immediately |
23
- | `k-wasm-compile` | Compile k source, `.ko`, or `.kvm` input into a standalone `.wasm` artifact |
24
- | `k-wasm-run` | Run a previously compiled `.wasm` artifact |
25
-
26
- The same tools can be called directly from a checkout with
27
- `node ./bin/k-wasm.mjs`, `node ./bin/k-wasm-compile.mjs`, and
28
- `node ./bin/k-wasm-run.mjs`.
29
-
30
- ## Compile and Run a Source File
31
-
32
- A source file must end with the expression that becomes its entry point:
33
-
34
- ```k
35
- |ok
36
- ```
37
-
38
- Compile it:
39
-
40
- ```bash
41
- k-wasm-compile program.k program.wasm
42
- ```
43
-
44
- Run it over a binary input stream:
45
-
46
- ```bash
47
- k-unit --parse |
48
- k-wasm-run program.wasm |
49
- k-print
50
- ```
51
-
52
- Expected output:
53
-
54
- ```json
55
- "ok"
56
- ```
57
-
58
- The `.wasm` artifact is a standard WebAssembly binary module:
59
-
60
- ```bash
61
- file program.wasm
62
- ```
63
-
64
- It can be stored or transferred as one file. The runner does not need
65
- `program.k` after compilation.
66
-
67
- ## Compile an Expression
68
-
69
- For a small program, pass a k expression directly:
70
-
71
- ```bash
72
- k-wasm-compile '|ok' program.wasm
73
- ```
74
-
75
- The `k-wasm` convenience command performs compilation and execution in one
76
- process:
77
-
78
- ```bash
79
- k-unit --parse |
80
- k-wasm '|ok' |
81
- k-print
82
- ```
83
-
84
- For compile inputs, existing paths are read as files. Missing names with
85
- `.k`, `.ko`, `.kvm`, `.klib`, or `.wasm` extensions are reported as missing
86
- files; other arguments are interpreted as inline source snippets.
87
-
88
- ## Read Input from a File
89
-
90
- Both runners accept an optional binary input file:
91
-
92
- ```bash
93
- k-unit --parse > input.kv
94
- k-wasm-run program.wasm input.kv > output.kv
95
- k-print < output.kv
96
- ```
97
-
98
- The one-step command has the same input-file form:
99
-
100
- ```bash
101
- k-wasm program.k input.kv > output.kv
102
- ```
103
-
104
- ## Compile from k Objects or kVM
105
-
106
- `k-wasm-compile` can consume the object and kVM outputs produced by
107
- `k-compile`:
108
-
109
- ```bash
110
- k-compile program.k program.ko
111
- k-wasm-compile program.ko program.wasm
112
-
113
- k-compile program.k program.kvm
114
- k-wasm-compile program.kvm program.wasm
115
- ```
116
-
117
- Use `.ko` when you want to preserve the compiled object form for the normal k
118
- toolchain. Use `.kvm` when you want to inspect or cache the lowered kVM program
119
- before producing WebAssembly.
120
-
121
- ## Compile with Libraries
122
-
123
- `k-wasm-compile` and `k-wasm` accept one `--lib` option before the program.
124
- Use repeated `--export` options to bring aliases from that library into the
125
- source scope. The export spec is `name` or `libname:localname`.
126
-
127
- For a library that defines `transform`:
128
-
129
- ```bash
130
- k-compile library.k library.klib
131
- k-wasm-compile --lib library.klib --export transform 'transform' program.wasm
132
- k-parse |
133
- k-wasm-run program.wasm |
134
- k-print
135
- ```
136
-
137
- The `.klib` file is required while compiling the artifact. It is not required
138
- when running the resulting `.wasm` file.
139
-
140
- ## Profile IEEE Execution
141
-
142
- The comparative IEEE benchmark moved with the backend:
143
-
144
- ```bash
145
- npm run perf:ieee
146
- ```
147
-
148
- To isolate WebAssembly execution and report arena allocation statistics:
149
-
150
- ```bash
151
- WASM_ONLY=1 WASM_PROFILE=1 ITERATIONS=3 npm run perf:ieee
152
- ```
153
-
154
- Set `WASM_RESET=0` to reproduce retained-arena growth and
155
- `WASM_WARMUP_ITERATIONS=0` to include cold-start behavior.
156
-
157
- ## What the Artifact Contains
158
-
159
- `k-wasm-compile` produces one WebAssembly binary module. The module contains:
160
-
161
- - the bump-allocator runtime from [`runtime.wat`](../runtime.wat)
162
- - one WebAssembly function for each reachable k relation
163
- - the exported `rel___main__` entry point
164
- - a WebAssembly custom section named `k.metadata`
165
-
166
- The custom section stores runner metadata:
167
-
168
- | Field | Meaning |
169
- | --- | --- |
170
- | `format` | Artifact family, currently `k-wasm` |
171
- | `version` | Artifact format version, currently `1` |
172
- | `abi` | Runtime ABI, currently `arena-v1` |
173
- | `entry` | Exported WebAssembly function called by the runner |
174
- | `inputPattern` | Pattern graph used to serialize the input into the arena |
175
- | `outputPattern` | Pattern graph used to decode the output from the arena |
176
- | `tags` | Stable integer IDs assigned to statically known variant tags |
177
-
178
- Embedding metadata in a custom section keeps the artifact self-contained.
179
- Unknown WebAssembly engines ignore custom sections, while `k-wasm-run` reads
180
- the section with `WebAssembly.Module.customSections(...)`.
181
-
182
- ## Compilation Pipeline
183
-
184
- Compilation follows these steps:
185
-
186
- 1. Resolve the input as inline source, a source file, a `.ko` object, or a
187
- `.kvm` program.
188
- 2. For source input, parse and annotate the source, including any loaded
189
- `.klib` dependencies and `--export` aliases.
190
- 3. For `.ko` input, use the hydrated relation definitions directly.
191
- 4. For `.kvm` input, use the already-lowered kVM functions directly.
192
- 5. Lower each reachable kVM function to WebAssembly text.
193
- 6. Combine the generated functions with `runtime.wat`.
194
- 7. Use WABT to validate the text and emit a binary WebAssembly module.
195
- 8. Append the `k.metadata` custom section to the binary module.
196
-
197
- The implementation lives in [`src/wasm.mjs`](../src/wasm.mjs). The command-line
198
- wrappers are [`k-wasm-compile.mjs`](../bin/k-wasm-compile.mjs),
199
- [`k-wasm-run.mjs`](../bin/k-wasm-run.mjs), and
200
- [`k-wasm.mjs`](../bin/k-wasm.mjs).
201
-
202
- ## Execution Pipeline
203
-
204
- `k-wasm-run` performs these steps:
205
-
206
- 1. Load and compile the `.wasm` module with Node.js `WebAssembly.compile(...)`.
207
- 2. Read and validate the `k.metadata` custom section.
208
- 3. Decode the input `pattern + value` stream.
209
- 4. Serialize the input tree into the module's linear-memory arena.
210
- 5. Call the artifact entry point with the input arena pointer.
211
- 6. Decode the returned arena pointer under the stored output pattern.
212
- 7. Write the result as a binary `pattern + value` stream.
213
-
214
- The WebAssembly entry-point ABI is:
215
-
216
- ```text
217
- (param input_pointer i32) -> (result output_pointer i32, ok i32)
218
- ```
219
-
220
- An `ok` result of `1` means that the partial function produced a value. A
221
- result of `0` means that the k relation was undefined for that input.
222
-
223
- ## Current Limitations
224
-
225
- - The artifact is a WebAssembly module, not a native executable. It still needs
226
- a host runner that understands k binary streams and the `k.metadata` section.
227
- - `k-wasm-run` currently targets Node.js. A browser runner can use the same
228
- artifact contract but has not been added yet.
229
- - `.klib` files are compile-time dependencies, not standalone WebAssembly
230
- inputs. Load them with `--lib` and compile source, `.ko`, or `.kvm` input with
231
- a main relation.
232
- - The backend is experimental. Use `k` as the general-purpose runtime while
233
- WebAssembly pattern coverage and optimization continue to evolve.
@@ -1,58 +0,0 @@
1
- # Technical Debt
2
-
3
- ## Polymorphic Input Retyping for Precompiled Wasm
4
-
5
- `k-wasm` can retype a polymorphic program when it compiles and runs in one step:
6
- the CLI decodes the input stream first, intersects the program input pattern with
7
- the input value envelope, and compiles a specialized WebAssembly module for that
8
- run.
9
-
10
- `k-wasm-run` cannot currently do the same for an already compiled `.wasm`
11
- artifact. By the time the runner sees the input envelope, the k program has
12
- already been lowered to WebAssembly and the artifact only carries metadata such
13
- as the generic input/output patterns. The original source/object relation graph
14
- needed to re-run type derivation is not available.
15
-
16
- This means precompiled artifacts can execute polymorphic programs, but their
17
- output envelopes are limited to the generic artifact metadata rather than being
18
- retyped against each input envelope.
19
-
20
- One possible fix is to delay compilation for programs with polymorphic input
21
- until the input envelope is available. That could mean storing enough source,
22
- object, or typed relation data in the artifact to specialize on first run, or
23
- using a separate artifact form for deferred compilation.
24
-
25
- ## Wasm Arena Memory Management
26
-
27
- The WebAssembly backend currently uses a bump arena for all product and variant
28
- values created during execution. This keeps allocation cheap and simple, and
29
- failed union branches can roll the arena back to a checkpoint, but successful
30
- paths do not reclaim temporary values until the whole run ends.
31
-
32
- Tail-call lowering now avoids allocating replacement input products for some
33
- self-tail-recursive loops by keeping top-level product fields in Wasm locals.
34
- Furthermore, self-tail-recursive loops now incorporate threshold-based arena
35
- compaction: when arena growth within a tail loop exceeds 1 MB, live accumulator
36
- and argument graphs are compacted down to the loop entry mark using an iterative
37
- staging-and-copy mechanism in `runtime.wat`, freeing dead scratch data while
38
- preserving performance for hot short-lived loops.
39
-
40
- Additionally, linear memory exhaustion and 32-bit unsigned offset overflow are
41
- now tracked explicitly via exported flags (`oom_flag`, `oom_size`) in `runtime.wat`,
42
- which the JS runtime intercepts to throw a descriptive `OutOfMemoryError` instead
43
- of an untyped `unreachable` trap.
44
-
45
- Remaining memory-management targets:
46
-
47
- - Add allocation profiling that attributes arena growth to generated relations
48
- and static allocation sites. Large regressions should be visible without
49
- manually instrumenting `factorial:o` or similar workloads.
50
- - Extend local-loop lowering beyond top-level product fields. Hot tail loops
51
- should keep common accumulator state in locals where possible and materialize
52
- arena values only at function boundaries or observable return points.
53
- - Introduce safe lifetime boundaries for successful non-tail calls. The runtime
54
- needs a way to reclaim scratch values after a callee result has been consumed
55
- without copying large live values on every call.
56
- - Keep unsigned pointer handling explicit. Wasm arena addresses are `i32`
57
- offsets, and JavaScript sees exported `i32` values as signed numbers, so all
58
- JS-side arena offsets must be normalized before `DataView` access.