@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
@@ -1,136 +0,0 @@
1
- # Web REPL Requirements & Architecture Specification
2
-
3
- **Branch**: `web-repl`
4
- **Status**: Approved Specification
5
- **Target Area**: Web REPL UI (`browser/repl-browser.mjs`), Build Pipeline (`scripts/build-repl-html.mjs`), and REPL Engine (`repl.mjs`, `repl-codecs.mjs`)
6
-
7
- ---
8
-
9
- ## 1. Context & Objectives
10
-
11
- The goal of this initiative is to improve the user experience, robustness, and out-of-the-box readiness of the K Web REPL.
12
-
13
- The scope encompasses four primary objectives:
14
- 1. **Console Text Selection**: Ensure all output in the terminal console is smoothly selectable and copyable across all desktop and mobile browsers without focus-stealing interference.
15
- 2. **Prioritize `core.k`**: Make `core.k` the default first choice for loading, examples, dropdowns, and quick exploration.
16
- 3. **Curate VFS Files**: Restrict the bundled Virtual File System (VFS) to verified, useful `.k` files (`core.k`, `Examples/arithmetics.k`, `Examples/ieee.k`, `Examples/poly.k`), auditing and verifying types used by REPL codecs.
17
- 4. **Automatic Dependency Loading & Type Aliasing for Codecs**:
18
- - Automatically load the required `.k` source file whenever a codec is loaded, ensuring that necessary type aliases, canonical codes, and operational relations are present before the user attempts `:input` or evaluations.
19
- - Establish bidirectional type alias naming so codec names are direct aliases to the underlying type hashes (e.g. `ieee` and `float64` both point to `@AR4s...`, `utf8` and `string` both point to `@Pt3Mw...`, and `int` points to `@Nws3v...`).
20
-
21
- ---
22
-
23
- ## 2. Detailed Requirements & Architectural Decisions
24
-
25
- ### Objective 1: Selectable Console Output
26
-
27
- #### Current Problem
28
- - When users highlight and copy output text from `#terminal-output`:
29
- 1. A global click event listener on `document` listens for clicks to focus `#repl-input`:
30
- ```js
31
- document.addEventListener("click", (e) => {
32
- if (!e.target.closest("button, select, input, textarea, .modal, .quick-link, .btn-copy-entry")) {
33
- inputEl.focus();
34
- }
35
- });
36
- ```
37
- 2. Clicking or releasing a drag selection within `#terminal-output` does not match the excluded selector list.
38
- 3. Consequently, `inputEl.focus()` is called immediately upon `mouseup`/`click`.
39
- 4. In modern browsers (Chromium, Firefox, Safari), focusing a text input field collapses the window's text selection, destroying the active selection.
40
- 5. In addition, double-clicking or triple-clicking a word or line in the terminal is aborted.
41
-
42
- #### Requirements
43
- 1. **Selection Preservation**: Users must be able to click, drag-select, double-click, and triple-click any text inside the terminal output without losing selection.
44
- 2. **Clipboard Compatibility**: Standard copy shortcuts (`Ctrl+C`, `Cmd+C`) must copy the selected text, not the input buffer.
45
- 3. **Styling & Presentation**:
46
- - Terminal entries (`.terminal-entry`, `.entry-command`, `.entry-line`, `.line-output`, `.line-error`, `.line-warning`, `.system-msg`) must have explicit `user-select: text; -webkit-user-select: text;`.
47
- - Prompt decorations (`.entry-prompt`, `.entry-meta`, `.prompt-label`) retain `user-select: none;` to avoid cluttering copied text with prompt symbols (`> `).
48
- 4. **Smart Focus Restoration**:
49
- - If `window.getSelection() && !window.getSelection().isCollapsed && window.getSelection().toString().trim().length > 0`, the click handler must **never** steal focus to `#repl-input`.
50
- - Clicking directly inside `#terminal-output` on text content should allow text cursor placement and selection without snapping focus away.
51
- - Only clicking on empty dead space or background when no text is selected should optionally focus the input.
52
-
53
- ---
54
-
55
- ### Objective 2: Prioritize `core.k` as the First Choice
56
-
57
- #### Requirements
58
- 1. **Dropdown Ordering**: In `#example-select`, `core.k` must be the top-most option under standard examples.
59
- 2. **Onboarding Banner**: The welcome message and quick-start hints in `browser/repl-browser.mjs` must showcase `:load core.k` as the primary recommended action.
60
- 3. **Quick Expressions**: Ensure the quick expressions section provides expressions compatible with `core.k` out-of-the-box (e.g. `1 succ`, `10`, `bits`, `string`).
61
-
62
- ---
63
-
64
- ### Objective 3: Verified Useful Files in VFS & Codec Type Audit
65
-
66
- #### Curated File Set
67
- The bundled VFS and UI examples must include only verified useful files:
68
- - `core.k` — The foundational standard library (bits, arithmetic on bits, Unicode `unicode`, `string`, `pattern`).
69
- - `Examples/arithmetics.k` — Arbitrary-precision signed integers (`int`), rationals (`rat`), GCD/LCM, factorial, Fibonacci.
70
- - `Examples/ieee.k` — IEEE-754 double-precision floating point type (`float64`) and arithmetic operations.
71
- - `Examples/poly.k` — Polymorphic list functions (`concat`, `reverse`, `length`, `get_nth`, `split_by`, `take`, `drop`, `zip`).
72
-
73
- #### Dependency Management for `poly.k`
74
- - `Examples/poly.k` depends on `dec`, `nat`, and `zero_int?` from `Examples/arithmetics.k`.
75
- - Loading `Examples/poly.k` on a fresh session will automatically ensure `Examples/arithmetics.k` is loaded first if not already loaded in the session.
76
-
77
- ---
78
-
79
- ### Objective 4: Auto-Loading `.k` Files on Codec Load & Code Aliasing
80
-
81
- #### Requirements
82
- 1. **Codec-to-File Auto-Loading**:
83
- When a codec is registered or loaded (via `:codec load <name>`, REPL initialization, or UI action):
84
- - Check if the required `.k` file is already loaded in `state.loadedFiles`.
85
- - If not loaded, automatically load and evaluate the corresponding `.k` file before completing codec registration:
86
- - `int` -> auto-loads `Examples/arithmetics.k`
87
- - `utf8` -> auto-loads `core.k`
88
- - `json` -> auto-loads `core.k`
89
- - `ieee` -> auto-loads `Examples/ieee.k`
90
- - Print an informative message, e.g.: `(auto-loaded Examples/arithmetics.k for codec 'int')`.
91
-
92
- 2. **Bidirectional Code Aliasing**:
93
- Establish code aliasing so that codec names and their standard type names are both valid aliases pointing to the same canonical type hash:
94
- - **IEEE / Float64**:
95
- - Canonical Hash: `@AR4sFGMwXgjj5p7dhi8sJKDWNbrXxLefQUCBRNm5fP6t`
96
- - Aliases: `float64` and `ieee`
97
- - **UTF-8 / String**:
98
- - Canonical Hash: `@Pt3MwQwzUPxQKu58zXR3qUBHWTzfycx5bSZGzcK6EZQK`
99
- - Aliases: `string` and `utf8`
100
- - **Int**:
101
- - Canonical Hash: `@Nws3vysWqC9PznraTP4kWPp44Rd77NAqrx9dgbtHAjGA`
102
- - Alias: `int`
103
- This guarantees that both `:input utf8` and `:input string`, as well as `:input ieee` and `:input float64`, work seamlessly.
104
-
105
- 3. **Idempotence**:
106
- - `state.loadedFiles = new Set()` tracks loaded file paths (normalized).
107
- - Re-running `:codec load` or loading multiple codecs referencing the same file (`utf8` and `json` both referencing `core.k`) will not recompile or reload the file redundantly.
108
-
109
- ---
110
-
111
- ### Phase 2: Curated VFS, Browser Buffer & Selection Persistence
112
-
113
- #### 1. Curated Files Explorer
114
- In the Web REPL "Files" (VFS) explorer, the visible files are strictly curated to verified examples and codecs:
115
- - **k-codes**: `core.k`, `arithmetics.k`, `ieee.k`, `djson.k`
116
- - **codecs**: `json.mjs`, `djson.mjs`, `utf8.mjs`, `int.mjs`, `unit.mjs`,
117
- `ieee.mjs`
118
- - User-created or uploaded files remain visible.
119
- - Internal runtime artifacts (`backends/wasm/runtime.wat`) and redundant directory prefixes (`Examples/`, `codecs/`) are kept accessible internally but hidden from the default file listing.
120
- - Clicking "Load" on a `.mjs` file automatically executes `:codec load <filename>`.
121
-
122
- #### 2. Browser Buffer 64-bit Float & Int Methods
123
- `browser/shims/buffer.mjs` implements:
124
- - `writeDoubleBE`, `readDoubleBE`, `writeDoubleLE`, `readDoubleLE`
125
- - `writeFloatBE`, `readFloatBE`, `writeFloatLE`, `readFloatLE`
126
- - `writeBigUInt64BE`, `readBigUInt64BE`, `writeBigUInt64LE`, `readBigUInt64LE`
127
- - `writeBigInt64BE`, `readBigInt64BE`, `writeBigInt64LE`, `readBigInt64LE`
128
- - Complete integer read/write methods (`UInt32`, `Int32`, `UInt16`, `Int16`, `UInt8`, `Int8`).
129
- - `globalThis.Buffer = Buffer` set unconditionally in the browser environment.
130
- This fixes `:input {string a, float64 n}` number parsing in JSON and IEEE codecs in browser runtime.
131
-
132
- #### 3. Persistent Console Selection
133
- - Replaced the global document click focus-stealer with:
134
- - Click listener on `.terminal-input-bar` (clicking prompt line focuses input).
135
- - Keydown typing handler on `window` (typing printable characters outside modals/inputs focuses input).
136
- - Mouse selection in `.terminal-output` never collapses on click/mouseup.
@@ -1,48 +0,0 @@
1
- # Chapter 1 — Introduction
2
-
3
- ## **1.1 The purpose of this book**
4
-
5
- This book describes a small programming language called **k**.
6
- It is meant to show how data can be represented and transformed in a uniform, precise way.
7
-
8
- ---
9
-
10
- ## **1.2 Data as trees**
11
-
12
- All information in `k` is treated as a **tree**.
13
- A tree has:
14
-
15
- * a single root,
16
- * labeled edges (field names or tags),
17
- * and possibly subtrees.
18
-
19
- Both JSON objects and XML documents are trees in this sense.
20
- Every `k` value is such a finite labeled tree.
21
-
22
- ---
23
-
24
- ## **1.3 Functions that may fail**
25
-
26
- In ordinary mathematics a function always returns a result.
27
- In `k`, a function may be **undefined** for some inputs.
28
- For example, asking for the field `age` in a record that has no `age` is undefined.
29
-
30
- We call such mappings **partial functions**.
31
-
32
- ---
33
-
34
- ## **1.4 Simplicity over features**
35
-
36
- `k` avoids most traditional language constructs: no *variables*, no *loops*, and no *control flow keywords*.
37
- In `k`, programs are built from:
38
-
39
- 1. **schemas** (finite tree automata describing acceptable tree payloads), and
40
- 2. **relations** (partial mappings that transform one tree into another).
41
-
42
- Schemas and transformations share the exact same syntax: a schema definition is simply a relation acting as a partial identity.
43
-
44
- The language also provides **filters** (`?schema`). Syntactically, a filter acts as a partial identity relation on payloads conforming to the schema. Semantically, filters act as **inductive termination witnesses** during contract derivation for recursive relations, while also enabling polymorphic generic programming.
45
-
46
- When analyzing a relation, the compiler derives its **contract**: a connected $(input, output)$ schema graph where shared vertices ($=X$) prove structure preservation from input through to output.
47
-
48
- ---
@@ -1,110 +0,0 @@
1
- # Chapter 2 — Syntax and Values
2
-
3
- ## **2.1 Language fragments**
4
-
5
- The `k` language has only one kind of program element: a **definition**.
6
- A program is a sequence of definitions:
7
-
8
- ```k-lang
9
- relation_name = ...expression... ;
10
- ```
11
-
12
- The definitions are followed in the file by the *main expression*, which represents the partial function defined by the program as a whole.
13
- There is no separate syntax for type declarations. Data shapes are defined by the relations and pattern filters (`? ...`) that manipulate them.
14
-
15
- There is no syntax for values.
16
- Every syntactic form in an expression describes a **function** -- possibly a constant function that always returns the same value.
17
-
18
- ---
19
-
20
- ## **2.2 Schemas**
21
-
22
- A schema describes the possible **tree shapes** of payload values.
23
- Schemas are formed from two constructors:
24
-
25
- 1. **Product** – written `{ S₁ l₁, S₂ l₂, … }`
26
- represents records with fixed labeled fields.
27
-
28
- 2. **Union** – written `< S₁ l₁, S₂ l₂, … >`
29
- represents a choice between labeled alternatives.
30
-
31
- Both are finite and fully explicit.
32
- Every schema denotes a finite tree automaton whose accepted trees are the possible payload values of that schema.
33
-
34
- ---
35
-
36
- ## **2.3 Special and limiting cases**
37
-
38
- 1. **Empty product**
39
- `{}` has no fields.
40
- It represents the unit schema that admits exactly one value, called *unit*.
41
- There is nothing exceptional about the unit schema and its value; it is simply the degenerate case of a product with zero fields.
42
-
43
- 2. **Empty union**
44
- `<>` has no variants.
45
- It represents a schema with no possible values.
46
-
47
- ---
48
-
49
- ## **2.4 Projections**
50
-
51
- **Dot** notation, e.g.,
52
-
53
- ```k
54
- . field_name
55
- ```
56
-
57
- is used for extracting the value of a field from a record (product type value).
58
- **Div** notation, e.g.,
59
-
60
- ```k
61
- / variant_name
62
- ```
63
-
64
- is used for asserting a particular variant of a union and extracting its value.
65
- A product type `{ T₁ l₁, T₂ l₂, … , Tₙ lₙ }` naturally defines `n` partial functions: `.l₁, .l₂, … , .lₙ`,
66
- and a union type `< T₁ l₁, T₂ l₂, … , Tₙ lₙ >` naturally defines `n` partial functions `/l₁, /l₂, … , /lₙ`.
67
- Those partial functions are called **projections** and they constitute the basis for the definition
68
- of all other partial functions in the `k` language.
69
-
70
- ---
71
-
72
- ## **2.5 Functions**
73
-
74
- Expressions combine partial functions using the following operators:
75
-
76
- 1. **Composition** `(f₁ f₂ …)` — sequential application.
77
- 2. **Union** `< f₁, f₂, … >` — try each in order, first defined wins.
78
- 3. **Product (parallel)** `{ f₁ l₁, f₂ l₂, … }` — apply all to the same input, succeed only if all succeed.
79
- 4. **Variant construction** `| tag` — lift the input as a variant `tag` of a union type.
80
-
81
- Parentheses around a composition may be omitted except for the empty composition `()` — the identity function.
82
- Empty product, `{ }`, defines a constant function (ignoring its input) returning *unit*.
83
-
84
- It is important to notice that after the three markers `dot (.)`, `div (/)`, or `pipe (|)`, there must be a constant label literal. For that reason, it is possible and recommended not to leave any blanks after the marker, e.g.:
85
-
86
- ```k-lang
87
- .field /'a-tag' |"strange and long tag name ✅"
88
- ```
89
-
90
- ---
91
-
92
- ## **2.6 Example**
93
-
94
- ```k-lang
95
- true = {} |true;
96
- false = {} |false;
97
- neg = < /true false, /false true >;
98
- ```
99
-
100
- This defines three relations: two constants and one transformation exchanging the variants `/true` and `/false`. The contracts of their inputs and outputs are derived automatically by the compiler.
101
-
102
- ---
103
-
104
- ## **2.7 Summary**
105
-
106
- * All schemas describe payload tree shapes.
107
- * As an expression, `{}` is the empty product (with one value, called *unit*).
108
- * Relations, not values, are the only expressions in `k`.
109
-
110
- ---
@@ -1,155 +0,0 @@
1
- # Chapter 3 — Schemas as Finite Automata
2
-
3
- ## **3.1 Motivation**
4
-
5
- A schema in `k` describes a set of finite labeled trees, which can be recognized by a finite tree automaton (FTA). Equivalently, a schema definition can be seen as a context-free grammar (CFG), where the payloads of the schema are the derivation trees of the grammar.
6
-
7
- For example, the recursive schema of a `list`:
8
-
9
- ```k-lang
10
- bool? = ?< {} true, {} false >;
11
- list? = ?< {} nil, { < {} true, {} false > head, L tail } cons > = L;
12
- ```
13
-
14
- corresponds to the following 4-rule grammar:
15
-
16
- ```bnf
17
- 1: <bool> ::= {} |true
18
- 2: <bool> ::= {} |false
19
- 3: <list> ::= {} |nil
20
- 4: <list> ::= { <bool> head, <list> tail } |cons
21
- ```
22
-
23
- A payload of schema `list` is a derivation tree of this grammar. For instance, a list containing a single boolean value `true` can be represented by the following derivation:
24
-
25
- ```
26
- <list>
27
- -- (rule 4) --> { <bool> head, <list> tail } |cons
28
- | |
29
- | -- (rule 3) --> {} |nil
30
- |
31
- -- (rule 1) --> {} |true
32
- ```
33
-
34
- This derivation tree corresponds to the payload generated by the constant relation `{ {} |true head, {} |nil tail } |cons`.
35
-
36
- Representing schemas as automata (or CFGs) provides each schema with a well-defined structure, independent of the names used in the source code. This allows for canonical normal forms and for comparing schemas for equality by structure alone.
37
-
38
- ---
39
-
40
- ## **3.2 States and Transitions**
41
-
42
- Each schema structure introduces one or more *states* in the automaton. A union or a product schema corresponds to a state, and the variants or fields correspond to transitions to other states.
43
-
44
- For example, consider the `bool` schema:
45
-
46
- ```k-lang
47
- bool? = ?< {} true, {} false >;
48
- ```
49
-
50
- This schema translates to an automaton with two states:
51
-
52
- - A root state, let's call it `C0`, representing the `bool` schema itself (a union).
53
- - A state `C1` representing the empty product `{}`.
54
-
55
- From the root state `C0`, there are two transitions:
56
-
57
- - A transition labeled `true` to state `C1`.
58
- - A transition labeled `false` to state `C1`.
59
-
60
- `C0` is the root state of the schema, and `C1` is a leaf state, representing an empty unit value.
61
-
62
- ---
63
-
64
- ## **3.3 Canonical Form**
65
-
66
- Different schema expressions can describe the same automaton. For example:
67
-
68
- ```k-lang
69
- pair = ?{ < {} false, {} true > x, < {} false, {} true > y };
70
- pair2 = ?{ < {} true, {} false > x, < {} true, {} false > y };
71
- ```
72
-
73
- The schemas `pair` and `pair2` are structurally equivalent because the choice order in a union does not alter the underlying accepted set of trees. Canonicalization is the process of removing these superficial differences by erasing local names and renumbering states to produce a single stable representation for each unique schema structure.
74
-
75
- The canonical form is generated by traversing the schema's graph structure starting from its root state. The process ensures a unique representation by following a consistent ordering:
76
-
77
- 1. **Start at the Root**: Assign the number `C0` to the root state of the schema.
78
- 2. **Explore Neighbors**: Visit all states reachable from `C0`. Sort the transitions alphabetically by their labels (field or variant names) and assign consecutive numbers (`C1`, `C2`, ...) to the destination states in that order.
79
- 3. **Iterate**: Move to the next state in the numbered sequence (`C1`, then `C2`, etc.) and repeat the process for any of its neighbors that have not yet been numbered.
80
- 4. **Complete**: Continue until all reachable states have been assigned a unique number.
81
-
82
- This traversal produces a unique and deterministic numbering for any finite directed graph, ensuring that any two structurally identical schemas will have the exact same canonical representation.
83
-
84
- ---
85
-
86
- ## **3.4 Examples**
87
-
88
- For a schema representing binary natural numbers:
89
-
90
- ```k-lang
91
- bnat? = ?< Bnat 0, Bnat 1, {} _ > = Bnat;
92
- ```
93
-
94
- the canonical automaton form is:
95
-
96
- ```text
97
- C0 = < C0 "0", C0 "1", C1 "_" >;
98
- C1 = {};
99
- ```
100
-
101
- The automaton has two states. `C0` is a recursive state that recognizes sequences of "0"s and "1"s, while `C1` is the terminal state, marked by the "_" transition.
102
-
103
- ---
104
-
105
- ## **3.5 Normalization Process**
106
-
107
- When compiling a program, the following steps are taken to normalize schemas:
108
-
109
- 1. **Collect**: Gather all schema structures and filters from the program.
110
- 2. **Expand**: Recursively replace named relation references with their underlying schema structures until only products and unions remain.
111
- 3. **Deduplicate**: Eliminate duplicate schema structures by comparing them structurally.
112
- 4. **Canonicalize**: Assign stable state numbers to the unique schemas to produce their canonical text representation.
113
-
114
- This process is deterministic, ensuring that the same schema structure always produces the exact same canonical form.
115
-
116
- ---
117
-
118
- ## **3.6 Hash-Based Naming**
119
-
120
- To create a globally unique and stable index for each schema, the compiler computes a digest of its canonical automaton representation. This hash becomes a fixed-width content address for the schema in the registry.
121
-
122
- For example:
123
-
124
- ```text
125
- Canonical Automaton: C0=<C0"0",C0"1",C1"_">;C1={}
126
- ↓
127
- Hash
128
- ↓
129
- Identifier: @VtPHxGf5GNMzzyVFxtv7gegFfJRYapBGtCeyV56bs5Zb
130
- ```
131
-
132
- Program objects and contracts can refer to schemas by their hash-based identifiers (prefixed with `@`) without ambiguity.
133
-
134
- ---
135
-
136
- ## **3.7 Interpretation**
137
-
138
- The canonical representation of a schema can be interpreted as:
139
-
140
- - A finite set of states, `C0…Cn`.
141
- - Each state is either a product (a record with named fields) or a union (a set of variants).
142
- - Transitions between states are labeled with strings (field or variant names).
143
-
144
- Every payload tree of a given schema is a finite tree that is accepted by this automaton.
145
-
146
- ---
147
-
148
- ## **3.8 Summary**
149
-
150
- - Schemas in `k` denote sets of finite, labeled trees.
151
- - Every schema can be expressed as a finite tree automaton or a context-free grammar.
152
- - The canonical form eliminates naming differences, providing a single representation for structurally identical schemas.
153
- - Hash-based naming gives each unique schema a stable and globally unique content-addressable identifier.
154
-
155
- ---
@@ -1,145 +0,0 @@
1
- # Chapter 4 — Partial Functions and Composition
2
-
3
- ## **4.1 Partial functions**
4
-
5
- A **partial function** is a mapping that may be undefined for some inputs.
6
- In `k`, every expression denotes such a function.
7
- If a function is undefined for a given input, the evaluation process halts at that point, producing no result.
8
-
9
- There is no notion of error or exception.
10
- Undefined means simply “no output”.
11
-
12
- ---
13
-
14
- ## **4.2 Composition**
15
-
16
- Composition combines two or more partial functions sequentially.
17
- If `f` and `g` are functions, `(f g)` means “apply `f`, then apply `g` to the result”.
18
-
19
- A composition `(f g)` is defined on a value `x` if and only if:
20
-
21
- * `f` is defined on `x`, and
22
- * `g` is defined on the result of `f(x)`.
23
-
24
- Otherwise, the composition is undefined.
25
-
26
- Composition is **associative**:
27
-
28
- ```math
29
- (f (g h)) ≡ ((f g) h)
30
- ```
31
-
32
- Therefore, parentheses are unnecessary, except for the special case of the **empty composition**, written `()`, which is the identity function:
33
-
34
- ```math
35
- () x = x () = x
36
- ```
37
-
38
- ---
39
-
40
- ## **4.3 Product composition**
41
-
42
- Product composition creates a function that applies several subfunctions in parallel to the same input and gathers their results into a product value.
43
-
44
- Syntax:
45
-
46
- ```math
47
- { f₁ l₁, f₂ l₂, …, fₙ lₙ }
48
- ```
49
-
50
- This expression is defined on an input value if all component functions are defined on that input.
51
- Its result is a product with fields labeled `l₁ … lₙ`, each containing the result of the corresponding function.
52
-
53
- ---
54
-
55
- ## **4.4 Union composition**
56
-
57
- Union composition represents concurrent evaluation with fallback:
58
-
59
- ```k-lang
60
- < f₁, f₂, …, fₙ >
61
- ```
62
-
63
- The result is defined for an input `x` if at least one subfunction is defined.
64
- Evaluation proceeds left to right; the first defined result is used.
65
- If none are defined, the result is undefined.
66
-
67
- Example:
68
-
69
- ```k-lang
70
- < /x, /y >
71
- ```
72
-
73
- extracts variant `x` if present; otherwise `y` if present.
74
-
75
- ---
76
-
77
- ## **4.5 Constants**
78
-
79
- A constant function is one that always returns the same value, regardless of its input.
80
- Since `k` lacks a direct syntax for literal values, constants are created using functions that produce them.
81
-
82
- For example, we can define functions that return `true` and `false`:
83
-
84
- ```k-lang
85
- true_bool = {} |true;
86
- false_bool = {} |false;
87
- ```
88
-
89
- Here, `true_bool` and `false_bool` are constant functions. They are also **total functions**, meaning they are defined for all inputs. Each function ignores its input and produces a fixed boolean value.
90
-
91
- ---
92
-
93
- ## **4.6 Projection and variant value constructors**
94
-
95
- Projection selects a field or a variant from a product or union.
96
- It is written with a leading dot `.` or a leading slash `/`, respectively:
97
-
98
- ```k-lang
99
- .x // Selects field 'x' from a product: { T x, ... }
100
- /x // Extracts the value from a union variant 'x': < T x, ... >
101
- ```
102
-
103
- If the input is a product, `.x` returns the value of field `x`. If the input is a union, `/x` returns the value of variant `x`. In all other cases, the projection is undefined.
104
-
105
- Variant value constructors for a given union type `T = <T₁ tag₁, T₂ tag₂, … >` are written as `|tag₁`, `|tag₂`, ….
106
-
107
- ```k-lang
108
- |tag₁ // lift a value of type T₁ into a value of type T
109
- ```
110
-
111
- Projections and variant constructors are the most basic partial functions.
112
-
113
- ---
114
-
115
- ## **4.7 Derived combinations**
116
-
117
- Complex functions are built by nesting compositions.
118
- For example:
119
-
120
- ```k-lang
121
- { .x field1, .y |tag field2 }
122
- ```
123
-
124
- ---
125
-
126
- ## **4.8 Identity and emptiness**
127
-
128
- The empty composition `()` is the identity function.
129
- The empty union `<>` is the always-undefined function.
130
- The empty product `{}` is the constant function returning the unit value.
131
-
132
- ---
133
-
134
- ## **4.9 Summary**
135
-
136
- * In `k`, all expressions denote **partial functions**.
137
- * An undefined result simply means “no output,” not an error.
138
- * **Composition** `(f g)` applies functions sequentially and is associative, so parentheses are often optional.
139
- * The empty composition `()` is the **identity function**.
140
- * **Product composition** `{...}` runs functions in parallel and gathers their results.
141
- * **Union composition** `<...>` tries functions in order, returning the first successful result.
142
- * **Projections** (`.x`, `/x`) are fundamental building blocks for accessing data structures.
143
- * **Variant constructors** (`|tag`) allow lifting a value into a variant type value.
144
-
145
- ---