@fraczak/k 8.4.1 → 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 (109) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/DOCS/ARCHITECTURE.md +83 -0
  3. package/DOCS/CODECS.md +93 -204
  4. package/DOCS/DICTIONARY.md +42 -1241
  5. package/DOCS/FILE_FORMATS.md +170 -625
  6. package/DOCS/GETTING_STARTED.md +164 -0
  7. package/DOCS/KIR_V1.md +22 -33
  8. package/DOCS/KVM_EXECUTION_MODEL.md +88 -481
  9. package/DOCS/PATTERNS.md +155 -138
  10. package/DOCS/POLYMORPHIC_IR.md +83 -101
  11. package/DOCS/PROFILING_AND_TRACING.md +52 -166
  12. package/DOCS/README.md +35 -0
  13. package/DOCS/REPL.md +100 -377
  14. package/DOCS/TEXTUAL_VALUES.md +53 -81
  15. package/DOCS/TYPE_DERIVATION.md +95 -234
  16. package/DOCS/book-combined.md +3786 -0
  17. package/Examples/arithmetics.k +45 -59
  18. package/Examples/djson.k +102 -112
  19. package/Examples/karatsuba-mult.k +2 -3
  20. package/Examples/list.k +6 -7
  21. package/Examples/nat.k +6 -6
  22. package/Examples/poly.k +45 -45
  23. package/LICENSE +15 -0
  24. package/README.md +72 -410
  25. package/backends/llvm/README.md +75 -97
  26. package/backends/wasm/README.md +88 -66
  27. package/canonical-pattern.mjs +7 -3
  28. package/codecs/README.md +23 -261
  29. package/codecs/WIRE_FORMAT.md +132 -0
  30. package/core.k +5 -15
  31. package/named-patterns.mjs +19 -7
  32. package/objects/README.md +24 -109
  33. package/package.json +8 -3
  34. package/paper/Makefile +17 -0
  35. package/paper/k-paper.pdf +0 -0
  36. package/paper/k-paper.tex +435 -0
  37. package/parser.jison +0 -10
  38. package/parser.mjs +32 -43
  39. package/repl.mjs +74 -29
  40. package/scripts/benchmark-idempotency.mjs +3 -3
  41. package/scripts/run-tests.mjs +1 -1
  42. package/scripts/test-package.mjs +64 -0
  43. package/tests/README.md +66 -46
  44. package/tests/code-derivation/core.mjs +61 -0
  45. package/tests/helpers/cli.mjs +45 -0
  46. package/tests/integration.sh +2 -3
  47. package/tests/test-arithmetics.mjs +47 -237
  48. package/tests/test-djson-methods.mjs +71 -275
  49. package/tests/test-hash-normalization.mjs +22 -1
  50. package/tests/test-karatsuba.mjs +18 -126
  51. package/tests/test-named-patterns.mjs +174 -621
  52. package/tests/test-paper-examples.mjs +90 -0
  53. package/tests/test-poly.mjs +2 -2
  54. package/tests/test-repl-html.mjs +2 -2
  55. package/tests/test-repl.mjs +49 -41
  56. package/tests/test.mjs +27 -68
  57. package/AGENTS.md +0 -35
  58. package/CLAUDE.md +0 -64
  59. package/DOCS/BIG_PICTURE.md +0 -439
  60. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  61. package/DOCS/CANONICAL_PATTERNS.md +0 -362
  62. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  63. package/DOCS/CONVERGENCE.md +0 -123
  64. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  65. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  66. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  67. package/DOCS/Makefile +0 -99
  68. package/DOCS/NAMED_PATTERNS.md +0 -361
  69. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  70. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  71. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -134
  72. package/DOCS/book/01-introduction.md +0 -48
  73. package/DOCS/book/02-syntax-and-values.md +0 -110
  74. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  75. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  76. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  77. package/DOCS/book/06-values-in-memory.md +0 -1085
  78. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  79. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  80. package/DOCS/book/09-compiler-architecture.md +0 -160
  81. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  82. package/DOCS/book/14-canonical-serialization.md +0 -176
  83. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  84. package/DOCS/book/overview.txt +0 -68
  85. package/DOCS/book.md +0 -50
  86. package/Examples/bnat.k +0 -308
  87. package/Examples/buda.k +0 -66
  88. package/Examples/byte.k +0 -35
  89. package/Examples/code.k +0 -43
  90. package/Examples/vhdl_to_k.k +0 -67
  91. package/JOURNAL.md +0 -288
  92. package/TODO.md +0 -107
  93. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  94. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  95. package/backends/wasm/demo_ieee.mjs +0 -318
  96. package/browser/vfs-data.mjs +0 -21
  97. package/codecs/BINARY_FORMAT.md +0 -53
  98. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  99. package/codecs/pandoc.css +0 -71
  100. package/tests/code-derivation/blowup.mjs +0 -25
  101. package/tests/code-derivation/bnat.mjs +0 -11
  102. package/tests/code-derivation/dot.mjs +0 -37
  103. package/tests/code-derivation/index.mjs +0 -20
  104. package/tests/code-derivation/loop.mjs +0 -17
  105. package/tests/code-derivation/nat.mjs +0 -10
  106. package/tests/code-derivation/not-not.mjs +0 -14
  107. package/tests/code-derivation/product.mjs +0 -22
  108. package/tests/code-derivation/rlz.mjs +0 -13
  109. package/tests/test-fingerprint.mjs +0 -38
@@ -1,113 +1,85 @@
1
- # Textual k Values
1
+ # Textual k values
2
2
 
3
- `k-parse` and `k-print` work with a textual notation for k values.
3
+ `k-parse` and `k-print` translate between readable trees and the binary
4
+ [schema+payload stream](../codecs/WIRE_FORMAT.md).
4
5
 
5
- It looks like JSON because products print as JSON objects, but
6
- semantically it is not a generic JSON format. It is a readable
7
- notation for values built from the two k data constructors:
6
+ This boundary notation is separate from relation source syntax. It resembles
7
+ JSON, but its leaves and numeric-looking tokens represent structural k data;
8
+ use `k-json`, `k-int`, or the other [codecs](../codecs/README.md) for external
9
+ JSON and numeric meanings.
8
10
 
9
- - product
10
- - tagged union
11
+ ## Trees and shorthand
11
12
 
12
- ## The Value Model
13
+ Products map labels to child values; variants select one tag and its payload.
14
+ The empty product `{}` is the unit leaf.
13
15
 
14
- A k value is a tree.
15
-
16
- - A product is a mapping from field labels to child values.
17
- - A union is a single chosen tag together with its payload value.
18
-
19
- There are no primitive leaves or built-in numbers. The base leaf is
20
- the empty product (the unit):
16
+ Accepted forms include:
21
17
 
22
18
  ```text
23
19
  {}
20
+ {"x":{},"y":{}}
21
+ {"succ":{"succ":{"zero":{}}}}
24
22
  ```
25
23
 
26
- ## Textual Notation
27
-
28
- The textual notation used by `k-parse` and `k-print` is:
29
-
30
- - `{}` for the empty product
31
- - `{"field": value, ...}` for a product
32
- - `{"tag": value}` for a union
33
-
34
- The last form is why the notation only looks like JSON. Syntactically,
35
- a single-entry object is ambiguous in plain JSON, but in k it is
36
- interpreted through the inferred or supplied pattern.
37
-
38
- Examples:
24
+ An atomic label such as `zero` or `"zero"` abbreviates a unit variant.
25
+ The last tree can therefore be written:
39
26
 
40
27
  ```text
41
- {}
28
+ {"succ":{"succ":"zero"}}
42
29
  ```
43
30
 
44
- ```text
45
- {"point":{"x":{},"y":{}}}
46
- ```
31
+ Square-bracket notation such as `[a,b]` abbreviates a tree with numeric labels
32
+ `0` and `1`. It is an indexed product, not the `cons`/`nil` list representation;
33
+ a one-element array has the same singleton ambiguity described below.
47
34
 
48
- ```text
49
- {"succ":{"succ":{"zero":{}}}}
50
- ```
51
-
52
- The last example is the k value usually written in native notation as:
35
+ In relation source, the corresponding constructor expression is:
53
36
 
54
37
  ```k
55
- {}|zero|succ|succ
38
+ {} |zero |succ |succ
56
39
  ```
57
40
 
58
- ## Relation to Native k Notation
59
-
60
- The native k notation is more explicit for interactive work:
61
-
62
- - product construction: `{ v field, w other }`
63
- - union introduction: `v |tag`
41
+ `k-print` emits boundary notation, with shorthand where available.
42
+ The REPL renders the relation-style value and its envelope instead.
64
43
 
65
- `k-print` does not emit that native notation. It emits the JSON-like
66
- tree notation because it is easy to pipe, inspect, and round-trip
67
- through standard text tooling.
44
+ ## Singleton ambiguity
68
45
 
69
- ## `k-parse`
46
+ A single-child tree such as `{"item":{}}` could mean either a singleton
47
+ product or a variant. Its pattern decides which.
70
48
 
71
- `k-parse`:
49
+ Without an explicit pattern, witness derivation treats:
72
50
 
73
- 1. reads textual k values
74
- 2. optionally takes an input type or input pattern
75
- 3. produces the binary `pattern + value` stream
51
+ - empty nodes as closed products;
52
+ - multiple-child nodes as closed products;
53
+ - single-child nodes as open unions.
76
54
 
77
- When no explicit pattern or type is supplied, `k-parse` derives a
78
- witness pattern from the textual tree.
55
+ Use an open product filter when you need to convert the parsed singleton into
56
+ a product. Fully closed patterns validate the existing product/variant kind
57
+ without that conversion.
79
58
 
80
- ## `k-print`
59
+ ## Commands
81
60
 
82
- `k-print`:
61
+ From the repository root:
83
62
 
84
- 1. reads the binary `pattern + value` stream
85
- 2. decodes it to a runtime value with its carried pattern
86
- 3. prints the value tree in JSON-like notation
87
-
88
- So `k-print` is not a JSON decoder in the general sense. It is a
89
- renderer from k runtime values to a JSON-shaped textual notation.
90
-
91
- ## Ambiguity and Patterns
92
-
93
- The textual tree alone does not always determine whether a single-child
94
- node is meant as a union or a singleton product. That is why patterns
95
- matter.
63
+ ```sh
64
+ printf '%s\n' '{"x":{},"y":{}}' |
65
+ node codecs/k-parse.mjs | node codecs/k-print.mjs
66
+ ```
96
67
 
97
- When `k-parse` has no explicit input pattern, it applies the current
98
- witness rule:
68
+ For a singleton product:
99
69
 
100
- - empty node => closed product
101
- - node with multiple children => closed product
102
- - node with one child => open union by default
70
+ ```sh
71
+ printf '%s\n' '{"item":{}}' |
72
+ node codecs/k-parse.mjs --input-type '?{ {} item, ... }' |
73
+ node codecs/k-print.mjs
74
+ ```
103
75
 
104
- An explicit input pattern or input type can force a different
105
- interpretation.
76
+ `--input-type` accepts a filter script or file.
77
+ `--input-pattern` accepts a property-list pattern as JSON or a file.
78
+ Choose one of those options. `k-parse` also accepts an input value filename;
79
+ otherwise it reads stdin.
106
80
 
107
- ## See Also
81
+ `k-print` decodes the carried pattern and payload before rendering.
82
+ The text by itself may not retain all envelope distinctions, so compare
83
+ patterns as well as rendered payloads when checking conformance.
108
84
 
109
- - [DOCS/FILE_FORMATS.md](./FILE_FORMATS.md) — guide to
110
- .k, .ko, .klib, and .kvm formats
111
- - [codecs/README.md](../codecs/README.md)
112
- - [DOCS/PATTERNS.md](./PATTERNS.md)
113
- - [DOCS/OBJECT_FILE_AND_PATTERN.md](./OBJECT_FILE_AND_PATTERN.md)
85
+ For source programs and compiled artifacts, see [file formats](FILE_FORMATS.md).
@@ -1,270 +1,131 @@
1
- # Type Derivation Algorithm
2
-
3
- ## 1. Overview
4
-
5
- This algorithm infers type constraints for programs consisting of
6
- mutually recursive partial functions over algebraic data types
7
- (products and unions).
8
-
9
- **Input:** AST of a `k` program, consisting of function definitions
10
- (expressions), which can be seen as a set of recursive equations.
11
- **Output:** Annotated AST with type patterns (also called filters).
12
-
13
- All types and relations are canonically identified by immutable
14
- content-addressed hashes (`@hash`). Human-readable names are local
15
- aliases.
16
-
17
- ## 2. Patterns
18
-
19
- A **pattern** represents a set of types:
20
-
21
- | Notation | Meaning | Fields |
22
- |----------|---------|--------|
23
- | `(...)` | Open unknown | Any |
24
- | `{...}` | Open product | At least specified |
25
- | `<...>` | Open union | At least specified |
26
- | `{}` | Closed product | Exactly specified |
27
- | `<>` | Closed union | Exactly specified |
28
- | `T` | Named type | From type definition |
29
-
30
- **Fields:** Each pattern has associated field labels. For open patterns,
31
- additional fields may exist. For closed patterns, the field set is exact.
32
- Unknown-kind patterns have only the open form `(...)`; a closed filter
33
- must choose product `{...}`/`{}` or union `<...>`/`<>`.
34
-
35
- A type pattern is a singleton pattern, i.e., only one type is captured
36
- by such a pattern.
37
-
38
- ## 3. Pattern Graph - A Data Structure Used During Type Derivation
39
-
40
- **Nodes:** Patterns organized in a "reps" (representatives) forest,
41
- similar to union-find. However, a union of two (or more) different trees
42
- always produces a new "rep" (root) node, joining the trees.
43
- **Edges:** Labeled by field names, pointing to other patterns.
44
- **Representatives:** Root nodes (called reps) represent equivalence
45
- classes.
46
-
47
- **Operations:**
48
-
49
- - `find(p)` - get representative of pattern `p`
50
- - `unify(p₁, ..., pₙ)` - merge patterns into equivalence class,
51
- potentially adding a new rep (root); the rep gathers all edges of
52
- their children
53
- - `clone(p₁, ..., pₙ)` - generate a copy of the pattern graph connected
54
- to the patterns
55
- - `compact()` - discovers all singleton patterns and replaces them by
56
- named canonical types
57
-
58
- ## 4. Unification
59
-
60
- `unify(p₁, ..., pₙ)` computes the least upper bound (most specific
61
- common pattern); it may add a new node (rep) into the reps forest, but
62
- it does not modify any existing pattern node.
63
-
64
- **Rules:**
65
-
66
- - **Open + Open:** Merge field sets, stay open
67
- - **Open + Closed:** Check field inclusion, then become closed
68
- - **Closed + Closed:** Check field equality, then stay closed
69
- - **Product ⊥ Union:** Error (incompatible)
70
- - **Type T:** Unique (canonical `@hash` name)
71
-
72
- **Algorithm:**
73
-
74
- ```text
75
- 1. Find representatives of all patterns
76
- 2. If the set of reps is a singleton, return it as the result
77
- 3. Compute merged pattern descriptor
78
- 4. Create new representative node
79
- 5. Migrate edges from old representatives
80
- 6. Recursively unify edge destinations for each field name
81
- ```
82
-
83
- ## 5. Local Typing Rules
84
-
85
- For each expression type, define input/output pattern constraints:
1
+ # Contract derivation
86
2
 
87
- ### Composition `(e₁ e₂ ... eₙ)`
88
-
89
- ```text
90
- in((e₁ e₂ ... eₙ)) = in(e₁)
91
- out(eᵢ) = in(eᵢ₊₁) for i = 1..n-1
92
- out((e₁ e₂ ... eₙ)) = out(eₙ)
93
- ```
3
+ The compiler derives an input/output pattern graph for each relation.
4
+ The graph constrains schemas accepted and produced by an expression; shared
5
+ nodes express equality of schema constraints across positions.
94
6
 
95
- When `n=0`, the composition is the identity, `()`.
7
+ A contract does not prove execution termination or that a shared-schema output
8
+ is the same payload as an input.
96
9
 
97
- ```text
98
- in(()) = out(())
99
- ```
100
-
101
- ### Product `{e₁ l₁, ..., eₙ lₙ}`
102
-
103
- ```text
104
- in(e₁) = ... = in(eₙ) = in({e₁ l₁, ..., eₙ lₙ})
105
- out({e₁ l₁, ..., eₙ lₙ}) = {} with edges lᵢ → out(eᵢ)
106
- ```
10
+ ## Pattern representation
107
11
 
108
- ### Variant constructor `|l`
12
+ During derivation, `TypePatternGraph` uses representative nodes and labeled
13
+ edges. Patterns can be unconstrained, open/closed products, open/closed unions,
14
+ or references to canonical closed schemas.
109
15
 
110
- ```text
111
- out(|l) = <...> with edge l → in(|l)
112
- ```
113
-
114
- ### Union `<e₁, ..., eₙ>`
115
-
116
- ```text
117
- in(e₁) = ... = in(eₙ) = in(<e₁, ..., eₙ>)
118
- out(e₁) = ... = out(eₙ) = out(<e₁, ..., eₙ>)
119
- ```
120
-
121
- ### Projection
122
-
123
- #### Dot `.l`
124
-
125
- ```text
126
- in(.l) = {...} with edge l → out(.l)
127
- ```
16
+ `find` resolves representatives; `unify` combines compatible constraints;
17
+ `clone` imports a callee's input/output graph together, retaining sharing;
18
+ `compact` reduces the graph and registers fully determined schemas.
128
19
 
129
- #### Div `/t`
20
+ Unification refines constraints:
130
21
 
131
- ```text
132
- in(/t) = <...> with edge t → out(/t)
133
- ```
22
+ - two open structures combine their required labels;
23
+ - an open structure can unify with a closed one only when its requirements
24
+ fit the closed structure;
25
+ - closed structures must agree on their fields/tags and child constraints;
26
+ - product and union kinds are incompatible;
27
+ - a free variable can be constrained to a compatible structure.
134
28
 
135
- ### Function reference `f`
29
+ Schema variables and recursive knots must retain their shared-node meaning.
30
+ Canonicalizing a closed schema and linearizing a named-pattern skeleton have
31
+ different purposes; see [patterns](PATTERNS.md).
136
32
 
137
- ```text
138
- in(f) = LOOKUP(in(f))
139
- out(f) = LOOKUP(out(f))
140
- ```
33
+ ## Local constraints
141
34
 
142
- Once the type derivation for the defining expression for `f` is done, the
143
- input and output patterns are stored and will be used.
35
+ For expression `e`, write `in(e)` and `out(e)` for its pattern roots.
144
36
 
145
- ### Filter `? F`
37
+ | Expression | Constraints |
38
+ | --- | --- |
39
+ | `()` | Input and output are the same node |
40
+ | `{}` | Output is unit; input is unconstrained |
41
+ | `(f g)` | `out(f)` unifies with `in(g)` |
42
+ | `{f a, g b}` | Both branches share the input; output is a product of branch outputs |
43
+ | `\|tag` | Output union has `tag` leading to the input |
44
+ | `.field` | Input product requires `field` leading to the output |
45
+ | `/tag` | Input union requires `tag` leading to the output |
46
+ | `<f, g>` | Branch input constraints unify, as do branch output constraints |
47
+ | `?P` | Input and output unify with `P` |
48
+ | Relation reference | Clone the callee boundary graph and unify with the reference boundaries |
146
49
 
147
- ```text
148
- in(? F) = out(? F) = pattern(F)
149
- ```
50
+ An empty union is undefined. Ordered choice retains its source order at runtime;
51
+ contract unification does not change that ordering.
150
52
 
151
- A filter expression `? F` describes pattern graphs, acting as an identity filter that constrains inputs and outputs to pattern `F`.
53
+ ## Dependency groups and convergence
152
54
 
153
- ## 6. Global Algorithm
55
+ `compiler.mjs` initializes constraints and builds a graph of relation references.
56
+ It processes strongly connected components (SCCs) in dependency order.
154
57
 
155
- ### Phase 1: Initialization
58
+ - An acyclic singleton uses `single_pass`: import already derived callee
59
+ boundaries and compact once.
60
+ - A recursive component uses `fixed_point`: clone/unify callee boundaries,
61
+ compact, and compare signatures until they stabilize or the budget is exhausted.
156
62
 
157
- ```text
158
- For each function definition:
159
- 1. Create empty pattern graph
160
- 2. Traverse expression AST
161
- 3. Create [input, output] pattern pair per node of the AST
162
- 4. Apply local typing rules
163
- ```
63
+ The default fixed-point budget is `2 + SCC size`. A relation that does not
64
+ converge can retain a `not-converged` status and produce a warning; optimized
65
+ execution paths have their own eligibility checks.
164
66
 
165
- ### Phase 2: Dependency Analysis
67
+ A recursive structural witness can make derivation converge:
166
68
 
167
- ```text
168
- 1. Build dependency graph (function → referenced functions)
169
- 2. Compute strongly connected components (SCCs)
170
- 3. Topologically sort SCCs (bottom-up)
69
+ ```k
70
+ peel = ?X < /+1 ?X peel, /0 |0 >;
71
+ peel
171
72
  ```
172
73
 
173
- ### Phase 3: Fixed-Point Iteration
74
+ The repeated `X` connects the input to the recursively processed payload.
75
+ Without that connection the engine can keep expanding an open union chain.
174
76
 
175
- ```text
176
- For each SCC (in topological order):
177
- Repeat until convergence (max 10 iterations):
178
- For each function `f` in SCC:
179
- 1. Compact `f`'s pattern graph
180
- 2. For each occurrence `o` of `g` in `f`, clone(in(g), out(g))
181
- and unify input and output patterns of `o` with the
182
- corresponding cloned patterns
77
+ Convergence is a property of these constraints. For example, derivation can
78
+ converge for a self-calling relation even though execution never returns.
183
79
 
184
- If pattern graphs unchanged: break
185
- ```
80
+ ## API options and statistics
186
81
 
187
- ## 7. Compaction
82
+ `annotate`, `compile`, and `run` from `index.mjs` accept:
188
83
 
189
- **Purpose:** Replace all pattern nodes with their reps and replace all
190
- singleton patterns with types.
191
-
192
- **Algorithm:**
193
-
194
- ```text
195
- 1. Build a new graph only on reps (keep the mappings from pattern
196
- node to its rep)
197
- 2. Identify singleton patterns (closed patterns with no open ancestors)
198
- 3. Register singletons as named types and use them as type pattern nodes
84
+ ```js
85
+ {
86
+ convergence: {
87
+ strategy: "auto", // "auto", "single_pass", or "fixed_point"
88
+ maxIterations: 20
89
+ }
90
+ }
199
91
  ```
200
92
 
201
- ## 8. Convergence
202
-
203
- **Criterion:** Pattern graph structure unchanged between iterations
204
-
205
- **Measured by:**
206
- 1. Representative forest structure (parent pointers)
207
- 2. Edge sets for each representative
208
- 3. Pattern descriptors for each representative
93
+ `auto` selects the strategy by SCC shape. Explicit `single_pass` is intended
94
+ for acyclic relations and rejects multi-member components. `annotate` exposes
95
+ statistics:
209
96
 
210
- **Algorithm:**
211
- ```text
212
- For each function f in SCC:
213
- 1. Serialize reps forest: {nodeId → parentId}
214
- 2. Serialize edge structure: {repId → {label → [targetReps]}}
215
- 3. Serialize pattern info: {repId → {pattern, fields, type}}
216
- 4. Combine into canonical form
97
+ ```js
98
+ import { annotate } from "@fraczak/k";
217
99
 
218
- Converged = (current_state == previous_state)
100
+ const result = annotate("f = .x; f");
101
+ console.log(result.compileStats.sccCount);
102
+ console.log(result.compileStats.sccs);
219
103
  ```
220
104
 
221
- **Guarantee:** Monotonic refinement + iteration bound ensures
222
- termination.
223
-
224
- ## 9. Error Handling
225
-
226
- **Unification errors include:**
227
-
228
- - Product vs Union
229
- - Closed pattern field mismatch
230
- - Two distinct type patterns (types with different canonical `@hash`
231
- names) are always incompatible
232
-
233
- **Other errors:**
234
-
235
- - Undefined function reference
236
- - Iteration limit exceeded
237
-
238
- **Error reporting should include:**
239
-
240
- - Source location
241
- - Expression type
242
- - Conflicting patterns
243
- - Unification trace
244
-
245
- ## 10. Implementation Notes
105
+ Each SCC entry records its members, selected strategy, iteration count, and
106
+ whether it converged.
246
107
 
247
- - Use reps forest for performing and tracing unification
248
- - Compact only at the end of an iteration to keep unification reasons
249
- for error messages
108
+ ## Stored and specialized contracts
250
109
 
251
- ## 11. Role in Ahead-Of-Time (AOT) Compilation
110
+ Objects store derivation status on each relation as
111
+ `typeDerivation: { status }`. Loading uses the stored graphs rather than
112
+ rederiving source contracts.
252
113
 
253
- This type derivation algorithm forms the core of Ahead-Of-Time (AOT)
254
- type checking in `k`.
114
+ KIR-P envelope specialization can deliberately run derivation again under an
115
+ input constraint. kVM specialization instead uses the lowered template and
116
+ principal patterns. See [architecture](ARCHITECTURE.md) and
117
+ [KIR-P](KIR_V1.md).
255
118
 
256
- When compiling `.k` source code into an executable object (`.ko`),
257
- a library (`.klib`), or a polymorphic kVM template (`.kvm`), type
258
- derivation converges all principal type graphs beforehand. The resulting
259
- artifacts store fully derived principal pattern graphs, allowing
260
- downstream execution and linking to bypass cold-start type derivation
261
- entirely.
119
+ ## Implementation and verification
262
120
 
263
- ## Further Reading
121
+ | File | Responsibility |
122
+ | --- | --- |
123
+ | [augmentation.mjs](../augmentation.mjs) | Local expression constraints |
124
+ | [TypePatternGraph.mjs](../TypePatternGraph.mjs), [typing.mjs](../typing.mjs) | Graph operations and unification |
125
+ | [compiler.mjs](../compiler.mjs) | Relation dependencies, SCC processing, and naming |
126
+ | [convergence.mjs](../convergence.mjs) | Strategy choice, fixed points, signatures, and budgets |
127
+ | [codes.mjs](../codes.mjs) | Closed schema normalization |
264
128
 
265
- - [DOCS/FILE_FORMATS.md](./FILE_FORMATS.md) — guide to
266
- .k, .ko, .klib, and .kvm formats
267
- - [DOCS/CONVERGENCE.md](./CONVERGENCE.md) — convergence strategies
268
- - [DOCS/OBJECT_FILE_AND_PATTERN.md](./OBJECT_FILE_AND_PATTERN.md) —
269
- object format and pattern encoding
270
- - [DOCS/DICTIONARY.md](./DICTIONARY.md) — concept names and terminology
129
+ [tests/code-derivation/](../tests/code-derivation/) covers syntax, convergence
130
+ strategies, recursive constraints, and envelopes. Named-pattern tests cover
131
+ template validation and routing. Run `npm test` from the repository root.