@fraczak/k 5.1.2 → 6.0.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 (115) hide show
  1. package/.codex +0 -0
  2. package/Code-derivation-tests/blowup.mjs +3 -3
  3. package/Code-derivation-tests/bnat.mjs +2 -2
  4. package/Code-derivation-tests/codec-witness-pattern.mjs +50 -0
  5. package/Code-derivation-tests/convergence-strategy.mjs +24 -0
  6. package/Code-derivation-tests/dot.mjs +12 -9
  7. package/Code-derivation-tests/filter-syntax.mjs +21 -0
  8. package/Code-derivation-tests/loop.mjs +8 -2
  9. package/Code-derivation-tests/nat.mjs +1 -1
  10. package/Code-derivation-tests/not-not.mjs +3 -3
  11. package/Code-derivation-tests/pattern-envelope.mjs +68 -0
  12. package/Code-derivation-tests/rlz.mjs +2 -2
  13. package/{BIG_PICTURE.md → DOCS/BIG_PICTURE.md} +103 -50
  14. package/DOCS/REPL.md +191 -0
  15. package/DOCS/a.html +398 -0
  16. package/DOCS/book/01-introduction.md +51 -0
  17. package/DOCS/book/02-syntax-and-values.md +111 -0
  18. package/DOCS/book/03-types-as-finite-automata.md +156 -0
  19. package/DOCS/book/04-partial-functions-and-composition.md +146 -0
  20. package/DOCS/book/05-typing-filters-and-normalization.md +111 -0
  21. package/DOCS/book-combined.html +3798 -0
  22. package/DOCS/book-combined.md +3745 -0
  23. package/DOCS/book-combined.pdf +0 -0
  24. package/DOCS/book-combined.tex +5682 -0
  25. package/DOCS/book.html +65 -0
  26. package/DOCS/book.md +54 -0
  27. package/DOCS/book.pdf +0 -0
  28. package/DOCS/book.tex +150 -0
  29. package/NAT.k~ +452 -0
  30. package/README.md +204 -508
  31. package/TypeGraph.mjs +43 -0
  32. package/TypePatternGraph.mjs +251 -0
  33. package/Value.mjs +192 -0
  34. package/augmentation.mjs +198 -0
  35. package/codecs/BINARY_FORMAT.html +471 -0
  36. package/codecs/BINARY_FORMAT.md +53 -0
  37. package/codecs/POLYMORPHIC_BINARY_FORMAT.html +355 -0
  38. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +303 -0
  39. package/codecs/README.md +215 -0
  40. package/codecs/example-pipeline.mjs +149 -0
  41. package/codecs/ieee.mjs +140 -0
  42. package/codecs/int.mjs +104 -0
  43. package/codecs/json-codec.mjs +215 -0
  44. package/codecs/json.mjs +40 -0
  45. package/codecs/k-parse.mjs +90 -0
  46. package/codecs/k-pattern.mjs +75 -0
  47. package/codecs/k-print.mjs +46 -0
  48. package/codecs/runtime/codec.mjs +768 -0
  49. package/codecs/runtime/ieee-pattern.mjs +30 -0
  50. package/codecs/runtime/pattern-json.mjs +96 -0
  51. package/codecs/runtime/prefix-codec.mjs +425 -0
  52. package/codecs/runtime/show-value.mjs +68 -0
  53. package/codecs/runtime/typeFromValue.mjs +34 -0
  54. package/codecs/runtime/unicode-string.mjs +220 -0
  55. package/codecs/show.mjs +41 -0
  56. package/codecs/string-codec.mjs +80 -0
  57. package/codecs/unit.mjs +51 -0
  58. package/codecs/utf16.mjs +66 -0
  59. package/codecs/utf8.mjs +37 -0
  60. package/codes.mjs +146 -44
  61. package/compiler.mjs +111 -0
  62. package/convergence.mjs +197 -0
  63. package/core.k +197 -0
  64. package/export.mjs +22 -32
  65. package/hash.mjs +29 -31
  66. package/ieee.klib +0 -0
  67. package/index.mjs +41 -15
  68. package/k-vscode/.vscode/launch.json +14 -0
  69. package/k-vscode/README.md +65 -0
  70. package/k-vscode/language-configuration.json +42 -0
  71. package/k-vscode/package-lock.json +4176 -0
  72. package/k-vscode/package.json +57 -0
  73. package/k-vscode/snippets/k.json +92 -0
  74. package/k-vscode/syntaxes/k.tmLanguage.json +243 -0
  75. package/k.mjs +56 -54
  76. package/object.mjs +517 -0
  77. package/objects/README.md +38 -0
  78. package/objects/compile-lib.mjs +42 -0
  79. package/objects/compile.mjs +42 -0
  80. package/objects/decompile.mjs +32 -0
  81. package/package.json +13 -6
  82. package/parser.jison +27 -46
  83. package/parser.mjs +68 -100
  84. package/pretty.mjs +21 -40
  85. package/repl2.mjs +662 -0
  86. package/run.mjs +264 -231
  87. package/symbol-table.mjs +3 -17
  88. package/test-fingerprint.mjs +7 -7
  89. package/test-hash-fuzz.mjs +107 -0
  90. package/test-hash-normalization.mjs +134 -0
  91. package/test-k-object.mjs +74 -0
  92. package/test-repl2.mjs +106 -0
  93. package/test.mjs +45 -70
  94. package/tests.sh +10 -1
  95. package/type_registry/registry.mjs~ +105 -0
  96. package/type_registry/typeParser.jison~ +132 -0
  97. package/typing.mjs +129 -676
  98. package/unification.mjs +157 -0
  99. package/valueIO.mjs +54 -0
  100. package/valueParser.jison +143 -0
  101. package/valueParser.mjs +713 -0
  102. package/Code-derivation-tests/built-in.mjs +0 -19
  103. package/Code-derivation-tests/vector.mjs +0 -19
  104. package/Filters/bug.k +0 -3
  105. package/Filters/composing.k +0 -15
  106. package/Filters/filter.k +0 -9
  107. package/TODO.md +0 -53
  108. package/TYPING.md +0 -365
  109. package/k-repl.cast +0 -1913
  110. package/k.cast +0 -618
  111. package/my-objects.json +0 -6
  112. package/patterns.mjs +0 -543
  113. package/repl.mjs +0 -213
  114. package/test-filters.mjs +0 -45
  115. package/typing-test.mjs +0 -40
package/DOCS/REPL.md ADDED
@@ -0,0 +1,191 @@
1
+ # k Interpreter
2
+
3
+ ## Overview
4
+
5
+ `repl2.mjs` is the interactive k interpreter. It uses the `.klib` format as
6
+ its internal state: definitions accumulate incrementally, expressions compile
7
+ in the context of the current library state, and the session can be exported as
8
+ either a reusable `.klib` library or an executable `.ko` object.
9
+
10
+ `k-repl` and `k-repl2` both start this interpreter. The primary interface is
11
+ command-based: commands start with `:`, and raw k input remains available as a
12
+ short form for quick interactive work.
13
+
14
+ ## State Model
15
+
16
+ ```
17
+ ┌─────────────────────────────────────────────────┐
18
+ │ codes: { hash → code definition } │ ← registered types
19
+ │ rels: { @hash → typed relation } │ ← compiled relations
20
+ │ aliases: { name → @hash } │ ← human names
21
+ │ value: current value (with .pattern) │ ← last result
22
+ │ lastMain: last relation/expression │ ← default .ko main
23
+ └─────────────────────────────────────────────────┘
24
+ ```
25
+
26
+ - `codes` and `rels` are the live .klib content.
27
+ - `aliases` maps human names to canonical hashes. Redefining a name updates
28
+ the alias; the old definition remains in `rels` (content-addressed, no conflict).
29
+ - `value` is the current pipeline value, initially `{}`.
30
+
31
+ ## Commands
32
+
33
+ Each line is a command. Multiline commands can be continued with a trailing
34
+ `\`.
35
+
36
+ Tab completion is available for command names, file paths in file-taking
37
+ commands such as `:load` and `:export`, and canonical names that start with
38
+ `@`.
39
+
40
+ | Command | Description |
41
+ |---------|-------------|
42
+ | `:type name = <...>` | Define a type |
43
+ | `:rel name = expr` | Define a relation |
44
+ | `:def name = expr` | Alias for `:rel` |
45
+ | `:run expr` | Run an expression on the current value |
46
+ | `:t name` | Show type signature of a relation |
47
+ | `:d name` | Show definition of a relation |
48
+ | `:type name` | Show definition of a type |
49
+ | `:codes` | List type aliases |
50
+ | `:rels` | List relation aliases |
51
+ | `:save file` | Save current state as `.klib` |
52
+ | `:klib file` | Export current state as `.klib` |
53
+ | `:ko file [expr]` | Export executable `.ko`; uses `expr` or the last relation/expression as main |
54
+ | `:export file [expr]` | Export by extension: `.klib` or `.ko` |
55
+ | `:load file` | Load `.k` source or `.klib` into state |
56
+ | `:val` | Print current value with full detail |
57
+ | `:reset` | Clear all state |
58
+ | `:help` | Show available commands |
59
+ | `:quit` | Exit |
60
+
61
+ The `/` character is never treated as a command prefix, because it is part of
62
+ k expression syntax.
63
+
64
+ ## Shorthand Input
65
+
66
+ Raw k input is still accepted:
67
+
68
+ - `$ name = <...>;` is treated like `:type name = <...>`.
69
+ - `name = expr;` is treated like `:rel name = expr`.
70
+ - Any other non-command input is treated like `:run expr`.
71
+
72
+ For command-based use, semicolons are optional in `:type` and `:rel`.
73
+
74
+ ## Input Handling
75
+
76
+ ### Type Definition: `:type name = <...>`
77
+
78
+ - Parse and register the code via `codes.register`.
79
+ - Store canonical hash in `aliases[name]`.
80
+ - Print: `$ name = @hash`
81
+
82
+ ### Relation Definition: `:rel name = expr`
83
+
84
+ - Build source: alias preamble + definition + `name` as main expression.
85
+ - Compile with current `{codes, rels}` as library context.
86
+ - Store compiled rel in `rels[@hash]`.
87
+ - Update `aliases[name] → @hash`.
88
+ - Print: `name = @hash`
89
+
90
+ ### Expression Evaluation: `:run expr`
91
+
92
+ - Build source: alias preamble + expression as main.
93
+ - Compile with current library context.
94
+ - Run on current `value`.
95
+ - Update `value` with result.
96
+ - Print result with envelope (see Output Format).
97
+
98
+ ## Alias Preamble
99
+
100
+ Before compiling any user input, the REPL prepends alias definitions so that
101
+ human names resolve to library relations:
102
+
103
+ ```k
104
+ add = @mKEA...; succ = @Swjz...; nat = @w8iS...;
105
+ <user input>
106
+ ```
107
+
108
+ For type aliases, the preamble uses `$ name = @hash;` syntax (referencing
109
+ an existing canonical code by hash).
110
+
111
+ This reuses the existing parser and compiler without modification.
112
+
113
+ ## Output Format
114
+
115
+ Values are printed as:
116
+
117
+ ```
118
+ <value-in-k-syntax> ?<pattern-as-filter>
119
+ ```
120
+
121
+ Examples:
122
+
123
+ ```
124
+ > {}|zero|succ|succ
125
+ {succ: {succ: {zero: {}}}} ?<{} zero, X succ>=X
126
+
127
+ > {{}|1 car, {}|nil cdr}|cons
128
+ {{{}|1 car, {}|nil cdr}|cons} ?<{} nil, {<{} 0, {} 1> car, X cdr} cons>=X
129
+ ```
130
+
131
+ Uses `valueToK` and `propertyListToFilter` from
132
+ `codecs/runtime/show-value.mjs`.
133
+
134
+ When the result is `undefined`, print:
135
+
136
+ ```
137
+ ... undefined
138
+ ```
139
+
140
+ ## Loading Files
141
+
142
+ ### `:load file.k`
143
+
144
+ - Parse and compile the source as a library in the current context.
145
+ - Merge resulting codes and rels into state.
146
+ - Update aliases from `relAlias` (source name → hash).
147
+
148
+ ### `:load file.klib`
149
+
150
+ - Decode the .klib file.
151
+ - Merge codes and rels into state.
152
+ - Update aliases from `meta` (recover source names from origins).
153
+
154
+ ## Exporting
155
+
156
+ ### `:save file.klib`
157
+
158
+ - Serialize current `{codes, rels, meta, main: null}` as a .klib.
159
+ - `meta` is built from the alias table (each alias → origin entry).
160
+
161
+ ### `:klib file.klib`
162
+
163
+ - Alias for saving the current state as a `.klib`.
164
+
165
+ ### `:ko file.ko [expr]`
166
+
167
+ - Compile `expr` as the executable object's main expression.
168
+ - If `expr` is omitted, reuse the last relation definition or expression that
169
+ was evaluated in the interpreter.
170
+ - The current `.klib` state is passed as the compilation library context.
171
+
172
+ ### `:export file [expr]`
173
+
174
+ - If `file` ends in `.klib`, save the current library state.
175
+ - If `file` ends in `.ko`, compile an executable object using `expr` or the
176
+ last main expression.
177
+
178
+ ## Example
179
+
180
+ ```
181
+ > :type nat = <{} zero, nat succ>
182
+ $ nat = @...
183
+ > :rel succ = |succ
184
+ succ = @...
185
+ > :run succ
186
+ {}|succ ?<{} succ, ...>
187
+ > :klib nat.klib
188
+ saved nat.klib
189
+ > :ko succ.ko succ
190
+ saved succ.ko (succ)
191
+ ```
package/DOCS/a.html ADDED
@@ -0,0 +1,398 @@
1
+ <h1 id="patterns-and-typed-values">Patterns And Typed Values</h1>
2
+ <h2 id="abstract">Abstract</h2>
3
+ <p>This note proposes a semantic foundation for <code>k</code> patterns,
4
+ types, typed values, and polymorphic values. The central point is that a
5
+ value in <code>k</code> is not a bare tree: it exists only in the
6
+ context of a type. Accordingly, a pattern denotes a set of types, and
7
+ therefore also a set of <strong>typed</strong> values, not a set of raw
8
+ trees. This distinction is essential for reasoning about equality,
9
+ polymorphism, and binary serialization with DAG compression.</p>
10
+ <h2 id="introduction">1. Introduction</h2>
11
+ <p>The <code>k</code> language manipulates algebraic values built from
12
+ products and unions. At first sight one may be tempted to define a value
13
+ simply as a rooted labeled tree and then define types as sets of such
14
+ trees. For <code>k</code>, this is not the right semantic level.</p>
15
+ <p>Two trees with the same shape but belonging to different types are
16
+ different values. Type is part of value identity.</p>
17
+ <p>This leads to the following semantic ladder:</p>
18
+ <ul>
19
+ <li>a <strong>type</strong> denotes a set of typed values,</li>
20
+ <li>a <strong>pattern</strong> denotes a set of types,</li>
21
+ <li>therefore a <strong>pattern</strong> also denotes a set of typed
22
+ values,</li>
23
+ <li>a <strong>polymorphic value</strong> is a pattern together with a
24
+ typed value compatible with that pattern.</li>
25
+ </ul>
26
+ <p>The rest of this note makes these notions precise.</p>
27
+ <h2 id="types">2. Types</h2>
28
+ <p>A <strong>type graph</strong> is a finite rooted directed graph with
29
+ labeled edges. Each node is one of:</p>
30
+ <ul>
31
+ <li><code>product</code>,</li>
32
+ <li><code>union</code>.</li>
33
+ </ul>
34
+ <p>For a product node, outgoing edge labels are field names. For a union
35
+ node, outgoing edge labels are tags. Edges are locally unique by
36
+ label.</p>
37
+ <p>The graph may be cyclic, which allows recursive types.</p>
38
+ <p>Two type graphs that are equivalent as regular tree languages may be
39
+ identified. For types, minimization by bisimulation is appropriate.</p>
40
+ <h3 id="trees-accepted-by-a-type">2.1. Trees accepted by a type</h3>
41
+ <p>Let <code>Tree(T)</code> denote the set of rooted value trees
42
+ accepted by a type graph <code>T</code>. Acceptance is defined in the
43
+ standard way:</p>
44
+ <ul>
45
+ <li>a product tree is accepted by a product node when its fields match
46
+ the outgoing labels of that node and each child tree is accepted by the
47
+ corresponding target node,</li>
48
+ <li>a union tree is accepted by a union node when it chooses exactly one
49
+ outgoing tag and the child tree is accepted by the corresponding target
50
+ node.</li>
51
+ </ul>
52
+ <h2 id="typed-values">3. Typed Values</h2>
53
+ <p>A <strong>typed value</strong> is a pair</p>
54
+ <pre class="text"><code>(T, t)</code></pre>
55
+ <p>where:</p>
56
+ <ul>
57
+ <li><code>T</code> is a type graph,</li>
58
+ <li><code>t ∈ Tree(T)</code>.</li>
59
+ </ul>
60
+ <p>Thus a value is intrinsically typed. The tree <code>t</code> is only
61
+ a representation of the value; it is not, by itself, a semantic value of
62
+ the language.</p>
63
+ <p>We write:</p>
64
+ <pre class="text"><code>Val(T) = { (T, t) : t ∈ Tree(T) }.</code></pre>
65
+ <h3 id="identity-of-typed-values">3.1. Identity of typed values</h3>
66
+ <p>Typed values are intensional with respect to the type:</p>
67
+ <pre class="text"><code>(T, t) ≠ (U, t) whenever T ≠ U.</code></pre>
68
+ <p>Even when the same raw tree <code>t</code> is accepted by both
69
+ <code>T</code> and <code>U</code>, the two typed values are
70
+ different.</p>
71
+ <p>This point is essential for serialization: the identity of a value
72
+ cannot be recovered from the raw tree alone.</p>
73
+ <h2 id="patterns">4. Patterns</h2>
74
+ <p>A <strong>pattern graph</strong> is a finite rooted directed graph
75
+ with labeled edges. Each node carries:</p>
76
+ <ul>
77
+ <li>a node kind:
78
+ <ul>
79
+ <li><code>unknown</code>,</li>
80
+ <li><code>product</code>,</li>
81
+ <li><code>union</code>,</li>
82
+ </ul></li>
83
+ <li>an openness flag:
84
+ <ul>
85
+ <li><code>open</code>,</li>
86
+ <li><code>closed</code>.</li>
87
+ </ul></li>
88
+ </ul>
89
+ <p>For product and union nodes, outgoing edges are labeled by field
90
+ names or tags. Edges are locally unique by label.</p>
91
+ <p>Unlike the case of types, <strong>node identity in a pattern graph is
92
+ semantic</strong>. If two edges point to the same pattern node, this
93
+ means that the corresponding positions must be inhabited by the very
94
+ same type.</p>
95
+ <p>Therefore patterns are not quotiented by bisimulation in general.</p>
96
+ <h2 id="filters-as-syntax">5. Filters As Syntax</h2>
97
+ <p>A filter expression is a textual way of describing a pattern
98
+ graph.</p>
99
+ <p>Variables appearing in filters are not the semantic object itself.
100
+ They are a device for serializing and reusing pattern graph nodes in
101
+ syntax.</p>
102
+ <p>For example, the two filters</p>
103
+ <pre class="k"><code>{ (...) x, (...) y, ... }
104
+ { X x, X y, ... }</code></pre>
105
+ <p>describe different pattern graphs:</p>
106
+ <ul>
107
+ <li>the first has two distinct target nodes for <code>x</code> and
108
+ <code>y</code>,</li>
109
+ <li>the second has one shared target node reached from both
110
+ <code>x</code> and <code>y</code>.</li>
111
+ </ul>
112
+ <p>These two patterns are semantically different.</p>
113
+ <h2 id="matching-a-type-against-a-pattern">6. Matching A Type Against A
114
+ Pattern</h2>
115
+ <p>Let <code>P</code> be a pattern graph and <code>T</code> a type
116
+ graph. We say that <code>T</code> <strong>matches</strong>
117
+ <code>P</code>, written</p>
118
+ <pre class="text"><code>T ⊨ P,</code></pre>
119
+ <p>if there exists a root-preserving graph morphism</p>
120
+ <pre class="text"><code>h : nodes(P) → nodes(T)</code></pre>
121
+ <p>such that:</p>
122
+ <ol type="1">
123
+ <li><p>if <code>p</code> is <code>unknown</code>, then <code>h(p)</code>
124
+ may be any type node,</p></li>
125
+ <li><p>if <code>p</code> is <code>product</code>, then <code>h(p)</code>
126
+ is a product node,</p></li>
127
+ <li><p>if <code>p</code> is <code>union</code>, then <code>h(p)</code>
128
+ is a union node,</p></li>
129
+ <li><p>if <code>p</code> is <code>closed</code>, then the outgoing
130
+ labels of <code>h(p)</code> are exactly the outgoing labels of
131
+ <code>p</code>,</p></li>
132
+ <li><p>if <code>p</code> is <code>open</code>, then the outgoing labels
133
+ of <code>h(p)</code> contain at least the outgoing labels of
134
+ <code>p</code>,</p></li>
135
+ <li><p>for every pattern edge</p>
136
+ <pre class="text"><code>p --l--&gt; q</code></pre>
137
+ <p>there is a corresponding type edge</p>
138
+ <pre class="text"><code>h(p) --l--&gt; h(q).</code></pre></li>
139
+ </ol>
140
+ <p>Condition 6 is the crucial one: if two edges of <code>P</code> point
141
+ to the same node <code>q</code>, then the corresponding edges of
142
+ <code>T</code> must point to the same type node <code>h(q)</code>. This
143
+ is how the graph structure of the pattern expresses “the same type”.</p>
144
+ <p>We define:</p>
145
+ <pre class="text"><code>Types(P) = { T : T ⊨ P }.</code></pre>
146
+ <h3 id="proposition-0">Proposition 0</h3>
147
+ <p>If <code>T ⊨ P</code>, then:</p>
148
+ <ul>
149
+ <li>the root kind of <code>T</code> is compatible with the root kind of
150
+ <code>P</code>,</li>
151
+ <li>every label explicitly present at the root of <code>P</code> is
152
+ present at the root of <code>T</code>,</li>
153
+ <li>if the root of <code>P</code> is closed, then <code>T</code> has no
154
+ additional root labels.</li>
155
+ </ul>
156
+ <h4 id="proof">Proof</h4>
157
+ <p>All three statements are immediate from the definition of the
158
+ root-preserving morphism <code>h</code> and conditions 1-5 above,
159
+ applied at the root node of <code>P</code>.</p>
160
+ <h2 id="singleton-patterns-and-types">7. Singleton Patterns And
161
+ Types</h2>
162
+ <p>Every type graph <code>T</code> determines a closed pattern
163
+ <code>Pat(T)</code> obtained by forgetting that it is a type and viewing
164
+ it as a closed pattern graph.</p>
165
+ <p>This gives the following proposition.</p>
166
+ <h3 id="proposition-1">Proposition 1</h3>
167
+ <p>For every type <code>T</code>, the pattern <code>Pat(T)</code> is
168
+ singleton:</p>
169
+ <pre class="text"><code>Types(Pat(T)) = { T }</code></pre>
170
+ <p>up to the chosen notion of type equivalence.</p>
171
+ <h4 id="proof-1">Proof</h4>
172
+ <p>The identity map from <code>nodes(Pat(T))</code> to
173
+ <code>nodes(T)</code> witnesses <code>T ⊨ Pat(T)</code>. Conversely,
174
+ suppose <code>U ⊨ Pat(T)</code> via a root-preserving morphism
175
+ <code>h</code>. Because every node of <code>Pat(T)</code> is either
176
+ product or union, every node kind is preserved. Because every node is
177
+ closed, the outgoing labels at each image node are exactly the outgoing
178
+ labels of the corresponding node of <code>T</code>. Because every
179
+ pattern edge must be respected by <code>h</code>, all target-sharing
180
+ constraints are preserved as well. Therefore <code>h</code> is a graph
181
+ isomorphism modulo the chosen equivalence on type graphs, and hence
182
+ <code>U</code> is equivalent to <code>T</code>.</p>
183
+ <h3 id="proposition-2">Proposition 2</h3>
184
+ <p>Conversely, every singleton pattern determines a unique type up to
185
+ type equivalence.</p>
186
+ <h4 id="proof-2">Proof</h4>
187
+ <p>Let <code>P</code> be singleton. By definition, <code>Types(P)</code>
188
+ contains exactly one type up to equivalence. Choose any representative
189
+ <code>T ∈ Types(P)</code>. Then <code>T</code> is the unique type
190
+ determined by <code>P</code>, again up to the chosen equivalence
191
+ relation.</p>
192
+ <p>Thus types can be regarded as a special case of patterns.</p>
193
+ <h2 id="polymorphic-values">8. Polymorphic Values</h2>
194
+ <p>A <strong>polymorphic value</strong> is a pair</p>
195
+ <pre class="text"><code>(P, v)</code></pre>
196
+ <p>where:</p>
197
+ <ul>
198
+ <li><code>P</code> is a pattern graph,</li>
199
+ <li><code>v</code> is a typed value <code>(T, t)</code>,</li>
200
+ <li><code>T ⊨ P</code>.</li>
201
+ </ul>
202
+ <p>Equivalently:</p>
203
+ <pre class="text"><code>PolyVal(P) = { (P, (T, t)) : T ⊨ P and t ∈ Tree(T) }.</code></pre>
204
+ <p>So a pattern does not denote a set of raw trees. It denotes a set of
205
+ typed values:</p>
206
+ <pre class="text"><code>Val(P) = { (T, t) : T ⊨ P and t ∈ Tree(T) }.</code></pre>
207
+ <p>This is a disjoint union over matching types, not an ordinary union
208
+ of raw tree sets.</p>
209
+ <h3 id="proposition-3">Proposition 3</h3>
210
+ <p>For every type <code>T</code>,</p>
211
+ <pre class="text"><code>Val(Pat(T)) = Val(T).</code></pre>
212
+ <h4 id="proof-3">Proof</h4>
213
+ <p>By Proposition 1, <code>Types(Pat(T)) = { T }</code> up to
214
+ equivalence. Substituting this into the definition of
215
+ <code>Val(P)</code> yields exactly the set of typed values whose type is
216
+ <code>T</code>.</p>
217
+ <h2 id="examples">9. Examples</h2>
218
+ <h3 id="distinct-pattern-graphs">9.1. Distinct pattern graphs</h3>
219
+ <p>Consider:</p>
220
+ <pre class="k"><code>P1 = { (...) x, (...) y, ... }
221
+ P2 = { X x, X y, ... }</code></pre>
222
+ <p>Then <code>P1</code> and <code>P2</code> are different patterns.</p>
223
+ <ul>
224
+ <li><code>P1</code> allows the types at <code>x</code> and
225
+ <code>y</code> to differ.</li>
226
+ <li><code>P2</code> requires the types at <code>x</code> and
227
+ <code>y</code> to be the same.</li>
228
+ </ul>
229
+ <p>Hence:</p>
230
+ <pre class="text"><code>Types(P2) ⊊ Types(P1).</code></pre>
231
+ <h4 id="proof-sketch">Proof sketch</h4>
232
+ <p>Every type matching <code>P2</code> also matches <code>P1</code>,
233
+ because identifying the target types of <code>x</code> and
234
+ <code>y</code> is stronger than leaving them unrelated. The inclusion is
235
+ strict because a product type with distinct types at <code>x</code> and
236
+ <code>y</code> matches <code>P1</code> but not <code>P2</code>.</p>
237
+ <h3 id="same-tree-different-typed-values">9.2. Same tree, different
238
+ typed values</h3>
239
+ <p>Let <code>t = {}|x</code>. Suppose <code>t</code> is accepted both
240
+ by</p>
241
+ <pre class="k"><code>T1 = &lt; {} x &gt;
242
+ T2 = &lt; {} x, {} y &gt;</code></pre>
243
+ <p>Then <code>(T1, t)</code> and <code>(T2, t)</code> are different
244
+ typed values.</p>
245
+ <p>The raw tree is the same, but the type is different.</p>
246
+ <h3 id="proposition-4">Proposition 4</h3>
247
+ <p>If <code>T ≠ U</code>, then:</p>
248
+ <pre class="text"><code>Val(T) ∩ Val(U) = ∅.</code></pre>
249
+ <h4 id="proof-4">Proof</h4>
250
+ <p>An element of <code>Val(T)</code> has the form <code>(T, t)</code>.
251
+ An element of <code>Val(U)</code> has the form <code>(U, u)</code>. If
252
+ <code>(T, t) = (U, u)</code>, then necessarily <code>T = U</code>.
253
+ Hence, when <code>T ≠ U</code>, the two sets are disjoint.</p>
254
+ <h2 id="consequences-for-equality-and-compression">10. Consequences For
255
+ Equality And Compression</h2>
256
+ <p>Since values are intrinsically typed, raw tree equality is not
257
+ sufficient for semantic equality.</p>
258
+ <p>This has an immediate consequence for DAG compression. Suppose we
259
+ have the raw tree</p>
260
+ <pre class="k"><code>{{}|x a, {}|x b, {}|x c}</code></pre>
261
+ <p>and consider two patterns:</p>
262
+ <pre class="k"><code>P1 = { (...) a, (...) b, (...) c, ... }
263
+ P2 = { X a, X b, X c, ... }</code></pre>
264
+ <p>If only the raw tree is considered, the three occurrences of
265
+ <code>{}|x</code> appear identical and a naive compressor may merge
266
+ them. But semantically this is not always justified.</p>
267
+ <ul>
268
+ <li>Under <code>P1</code>, the three occurrences need not belong to the
269
+ same type.</li>
270
+ <li>Under <code>P2</code>, they must belong to the same type.</li>
271
+ </ul>
272
+ <p>Therefore canonical value sharing, when used as an optimization, must
273
+ be relative to the typing information supplied by the pattern and the
274
+ witness type. One must not collapse raw subtrees merely because they
275
+ look the same as trees.</p>
276
+ <h3 id="proposition-5">Proposition 5</h3>
277
+ <p>There is, in general, no canonical DAG compression procedure that
278
+ depends only on the raw value tree and is correct for all polymorphic
279
+ values.</p>
280
+ <h4 id="proof-5">Proof</h4>
281
+ <p>Consider the raw tree</p>
282
+ <pre class="text"><code>{{}|x a, {}|x b, {}|x c}.</code></pre>
283
+ <p>As a raw tree, the three subtrees under <code>a</code>,
284
+ <code>b</code>, and <code>c</code> are isomorphic. Hence any tree-only
285
+ compressor cannot distinguish their occurrences by local tree structure
286
+ alone. Now compare the two valid pattern contexts:</p>
287
+ <pre class="text"><code>P1 = { (...) a, (...) b, (...) c, ... }
288
+ P2 = { X a, X b, X c, ... }.</code></pre>
289
+ <p>Under <code>P1</code>, the three occurrences are not forced to have
290
+ the same type. Under <code>P2</code>, they are forced to have the same
291
+ type because all three edges land in the same pattern node. So a
292
+ compressor that always merges these subtrees is unsound for
293
+ <code>P1</code>, while a compressor that never merges them fails to
294
+ capture the canonical sharing justified by <code>P2</code>. Therefore no
295
+ canonical sharing rule can be defined from the raw tree alone; typing
296
+ information from the pattern and witness type is required.</p>
297
+ <h3 id="proposition-6">Proposition 6</h3>
298
+ <p>For a fixed polymorphic value <code>(P, (T, t))</code>, any canonical
299
+ DAG compression of <code>t</code> must be invariant under equality of
300
+ <strong>typed occurrences</strong>, not merely equality of raw
301
+ subtrees.</p>
302
+ <h4 id="proof-sketch-1">Proof sketch</h4>
303
+ <p>By Proposition 4, typed values of different types are distinct even
304
+ when represented by the same raw tree. Within a fixed witness type
305
+ <code>T</code>, the pattern graph still matters because distinct
306
+ positions of <code>P</code> may or may not be identified. Therefore the
307
+ only semantically defensible sharing criterion is one that respects the
308
+ typing/decorated occurrence information carried by <code>(P, T)</code>,
309
+ not the undecorated tree <code>t</code> alone.</p>
310
+ <h2 id="topological-remark">11. Topological Remark</h2>
311
+ <p>There is a topology-like intuition behind patterns, but only for a
312
+ fragment.</p>
313
+ <p>If one looks only at open positive patterns, they behave like
314
+ observable structural properties of types and suggest a topology or,
315
+ more precisely, an Alexandrov-style structure on the class of types
316
+ ordered by refinement.</p>
317
+ <p>However, the full pattern formalism is richer than topology because
318
+ it includes:</p>
319
+ <ul>
320
+ <li>closedness constraints,</li>
321
+ <li>explicit graph sharing, which expresses sameness of type at
322
+ different positions.</li>
323
+ </ul>
324
+ <p>These two features go beyond ordinary open-set semantics.</p>
325
+ <h3 id="proposition-7">Proposition 7</h3>
326
+ <p>The class of patterns is strictly richer than the open positive
327
+ fragment.</p>
328
+ <h4 id="proof-sketch-2">Proof sketch</h4>
329
+ <p>The open positive fragment can describe only monotone structural
330
+ requirements such as “at least these labels” and “these positions have
331
+ these subpatterns”. It cannot express exact closedness, because
332
+ closedness is not monotone under refinement. It also cannot express
333
+ identification of two positions as “the same type” without preserving
334
+ explicit graph sharing. Since full patterns include both closedness and
335
+ shared-node identity, they strictly extend the open positive
336
+ fragment.</p>
337
+ <h2 id="summary">12. Summary</h2>
338
+ <ul>
339
+ <li>A type is a regular rooted graph denoting a set of accepted
340
+ trees.</li>
341
+ <li>A typed value is a pair <code>(T, t)</code> with
342
+ <code>t ∈ Tree(T)</code>.</li>
343
+ <li>A pattern is a rooted graph with node kind, openness, and semantic
344
+ node identity.</li>
345
+ <li>A filter is only syntax for serializing a pattern graph.</li>
346
+ <li>A type matches a pattern via a root-preserving morphism respecting
347
+ node kind, openness, labels, and shared targets.</li>
348
+ <li>A pattern denotes a set of types, and therefore a set of typed
349
+ values, not a set of raw trees.</li>
350
+ <li>A polymorphic value is a pair <code>(P, (T, t))</code> with
351
+ <code>T ⊨ P</code>.</li>
352
+ <li>Types are exactly the singleton-pattern case.</li>
353
+ <li>DAG compression of values is a representation optimization only and
354
+ must respect typing information.</li>
355
+ </ul>
356
+ <h2 id="corollaries-for-binary-serialization">13. Corollaries For Binary
357
+ Serialization</h2>
358
+ <p>The previous propositions impose strong constraints on any correct
359
+ binary format.</p>
360
+ <h3 id="corollary-1">Corollary 1</h3>
361
+ <p>The semantic payload of a serialized polymorphic value must
362
+ determine:</p>
363
+ <ul>
364
+ <li>a pattern graph <code>P</code>,</li>
365
+ <li>a witness typed value <code>(T, t)</code>,</li>
366
+ </ul>
367
+ <p>with <code>T ⊨ P</code>.</p>
368
+ <p>It is not sufficient to serialize only a raw tree.</p>
369
+ <h4 id="justification">Justification</h4>
370
+ <p>By Proposition 4, type is part of value identity. By Proposition 5,
371
+ the raw tree alone is insufficient to determine correct canonical
372
+ sharing behavior.</p>
373
+ <h3 id="corollary-2">Corollary 2</h3>
374
+ <p>A closed monomorphic typed value is the special case where the
375
+ serialized pattern is singleton.</p>
376
+ <h4 id="justification-1">Justification</h4>
377
+ <p>This is Proposition 1 together with Proposition 3.</p>
378
+ <h3 id="corollary-3">Corollary 3</h3>
379
+ <p>Any canonical DAG representation of the witness value must be
380
+ computed from the decorated object <code>(P, T, t)</code>, not from
381
+ <code>t</code> alone.</p>
382
+ <h4 id="justification-2">Justification</h4>
383
+ <p>This is exactly the content of Propositions 5 and 6.</p>
384
+ <h3 id="corollary-4">Corollary 4</h3>
385
+ <p>Pattern serialization must preserve explicit pattern-node
386
+ identity.</p>
387
+ <h4 id="justification-3">Justification</h4>
388
+ <p>Pattern node sharing expresses sameness of type at different
389
+ positions. Replacing a pattern graph by any representation that forgets
390
+ this identity changes its denotation.</p>
391
+ <h3 id="corollary-5">Corollary 5</h3>
392
+ <p>For singleton patterns, one may replace the explicit serialized
393
+ pattern graph by a canonical type reference as a compact optimization,
394
+ provided that the decoding semantics is unchanged.</p>
395
+ <h4 id="justification-4">Justification</h4>
396
+ <p>By Proposition 2, a singleton pattern determines a unique type up to
397
+ equivalence. Therefore the explicit graph may be recoverable from a
398
+ canonical type identifier.</p>
@@ -0,0 +1,51 @@
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 language constructs: no *variables* and no *control statements*.
37
+ It has only:
38
+
39
+ 1. **types** (which describe tree shapes), and
40
+ 2. **partial functions** (which transform one tree into another).
41
+
42
+ These two ingredients are sufficient and powerful enough to express structured
43
+ computation in a concise and understandable way.
44
+
45
+ There is another concept in the language, called **filters**.
46
+ Filters play a role in the process of reasoning about types of partial functions.
47
+ Filters have been added to the syntax of the language as they allow explicit annotations
48
+ of "polymorphic" expressions, i.e., expressions which make sense in different contexts.
49
+ Filters are similar to *type classes* in other languages.
50
+
51
+ ---