@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
package/DOCS/PATTERNS.md CHANGED
@@ -1,188 +1,205 @@
1
- # Schemas and Pattern Graphs
1
+ # Patterns and relations
2
+
3
+ k source defines relations, named patterns, and a terminal expression.
4
+ The terminal expression is the entry relation when executing a source file.
5
+ The REPL also accepts definitions on their own.
6
+
7
+ ## Core relations
8
+
9
+ Every expression denotes a first-order partial function over product/variant
10
+ values.
11
+
12
+ | Syntax | Meaning |
13
+ | --- | --- |
14
+ | `()` | Identity |
15
+ | `{}` | Constant unit |
16
+ | `<>` | Always undefined |
17
+ | `.field` | Project a product field |
18
+ | `/tag` | Extract a matching variant payload |
19
+ | `\|tag` | Wrap the input in a variant |
20
+ | `(f g)` | Apply `f`, then `g` |
21
+ | `{f a, g b}` | Apply both relations to the same input and construct fields `a` and `b` |
22
+ | `<f, g>` | Try `f`, then `g` if `f` is undefined |
23
+ | `?P` | Constrain the schema to pattern `P` without changing the payload |
24
+ | `name` or `@hash` | Reference a relation |
25
+
26
+ Composition can omit parentheses when grouping is unambiguous.
27
+ A product is undefined if a field computation is undefined. Choice preserves
28
+ source priority; an earlier nonterminating branch does not fall through.
29
+
30
+ Definitions use `name = expression;`. There are no builtin numeric or string
31
+ values in relation syntax: a numeric identifier such as `5` is a relation
32
+ name, and quoted strings in label positions are labels. Use
33
+ [codecs](../codecs/README.md) for external numbers, text, or JSON.
34
+
35
+ Relations can refer to other definitions in the same source, including recursive
36
+ references. Labels can be identifiers or quoted strings with escapes. Line
37
+ comments use `--`, `//`, `#`, or `%`; block comments use `/* ... */`.
38
+
39
+ ## Pattern syntax
40
+
41
+ Patterns describe schema constraints rather than computations:
42
+
43
+ | Pattern | Constraint |
44
+ | --- | --- |
45
+ | `(...)` or an unbound variable `X` | An unconstrained schema position |
46
+ | `{P a, Q b}` | A product with exactly the listed fields |
47
+ | `{P a, ...}` | A product with at least the listed fields |
48
+ | `<P a, Q b>` | A union with exactly the listed tags |
49
+ | `<P a, ...>` | A union allowing additional tags |
50
+ | `{}` | Empty product schema |
51
+ | `<>` | Empty union schema |
52
+ | `P = X` | Bind the pattern node as `X`, allowing recursive references |
53
+ | `name[P, Q]` | Instantiate a named pattern |
54
+
55
+ The distinction between open and closed union schemas concerns the schema's
56
+ available tags. A variant payload still selects one tag.
57
+
58
+ Repeated variables express equality of schema constraints:
2
59
 
3
- In `k`, an algebraic **schema** describes the shape of payload trees
4
- that may flow through a relation. In compiler artifacts and
5
- serialization, schemas are represented as property-list arrays of
6
- automata nodes. Schemas are used by:
7
-
8
- - the contract-derivation engine
9
- - the binary codec
10
- - runtime framed values `(schema, payload)`
11
- - filter expressions (`?schema` or `?name[...]`)
12
-
13
- ## Pattern Kinds
14
-
15
- The exported canonical pattern form is a property-list array of nodes.
16
-
17
- Each node has the form:
18
-
19
- ```text
20
- [kind, edges]
21
- ```
22
-
23
- where `kind` is one of:
24
-
25
- - `"any"`
26
- - `"open-product"`
27
- - `"open-union"`
28
- - `"closed-product"`
29
- - `"closed-union"`
30
-
31
- and `edges` is a list of:
32
-
33
- ```text
34
- [label, targetNodeId]
60
+ ```k
61
+ ?{ X first, X second }
35
62
  ```
36
63
 
37
- Example:
64
+ The two fields must have compatible shared schema constraints; their payloads
65
+ need not be equal. Anonymous wildcards do not impose that sharing:
38
66
 
39
- ```json
40
- [
41
- ["closed-union", [["nil", 1], ["cons", 2]]],
42
- ["closed-product", []],
43
- ["closed-product", [["car", 3], ["cdr", 0]]],
44
- ["closed-union", [["_", 1], ["0", 3], ["1", 3]]]
45
- ]
67
+ ```k
68
+ ?{ (...) first, (...) second }
46
69
  ```
47
70
 
48
- This is not the wire format. It is the canonical readable export form.
71
+ Pattern variables in a relation have relation-definition scope.
49
72
 
50
- ## Named Patterns and Templates
73
+ ## Named patterns
51
74
 
52
- Named patterns define reusable, modular regular tree grammars using
53
- square brackets `[...]`:
75
+ Square brackets distinguish reusable templates from bare variables:
54
76
 
55
77
  ```k
56
- name[ P1, P2, ... Pn ] = filter;
78
+ bit[] = < {} 0, {} 1 >;
79
+ bits[] = < {} _, B 0, B 1 > = B;
80
+ pair[A, B] = { A first, B second };
81
+ list[X] = < {} nil, { X car, Y cdr } cons > = Y;
57
82
  ```
58
83
 
59
- For 0-arity patterns (no parameters), empty brackets `[]` are used:
84
+ A filter applies a template:
60
85
 
61
86
  ```k
62
- bit[] = < {} 0, {} 1 >;
63
- bits[] = < {} _, B 0, B 1 > = B;
64
- byte[] = {
65
- bit[] 0, bit[] 1, bit[] 2, bit[] 3,
66
- bit[] 4, bit[] 5, bit[] 6, bit[] 7
67
- };
87
+ ?pair[bit[], bits[]]
68
88
  ```
69
89
 
70
- Parameterized patterns declare external ports in the bracket list:
90
+ Template applications can be nested inside patterns, including arguments such
91
+ as `list[pair[A, B]]`. Every application must resolve in scope and have the
92
+ declared arity.
71
93
 
72
- ```k
73
- list[X] = < {} nil, { X car, Y cdr } cons > = Y;
74
- pair[A, B] = { A first, B second };
75
- ```
94
+ Variables have three roles:
76
95
 
77
- Callers instantiate a named pattern:
78
- - As a standalone filter: `? list[X]` or `? bits[]`
79
- - Within relation guards: `?{ nat[] = N x, ... }`
80
- - As template arguments: `list[byte[]]` or `pair[A, B]`
96
+ - Parameters in a header such as `[X]` are supplied by callers.
97
+ - Other free variables are private existential constraints. Repeated uses share
98
+ a constraint; different instantiations receive fresh private names.
99
+ - Bound variables such as `= Y` are internal cycle knots.
81
100
 
82
- Inside a definition, knot identifiers (`= Y`) close internal recursive
83
- loops. Recursive loops are private and alpha-renamed during expansion.
84
- Direct or mutual recursion among templates (`bits[]` calling `bits[]`)
85
- is disallowed to ensure every template dependency graph is an acyclic
86
- DAG, guaranteeing finite regular tree automaton compilation.
101
+ Knots cannot be parameters. For example,
102
+ `list[X, Y] = <{} nil, {X car, Y cdr} cons> = Y;` is rejected.
103
+ Template dependency cycles are also rejected: recursion uses a knot inside a
104
+ template, rather than the template calling itself. Undefined templates and
105
+ arity mismatches are rejected even in unused definitions.
87
106
 
88
- In the interactive REPL, inspecting a pattern with `:pattern <name>` (or
89
- `:pat <name>`) displays its canonical decompiled form with newly
90
- introduced variables in discovery order (e.g.
91
- `list[X1] = <{X1 car, X0 cdr} cons, {} nil>=X0; -- @...`).
107
+ ## Filters and contracts
92
108
 
93
- ### Template Applications vs. Type Variables
109
+ A relation can combine structural guards with ordinary computation:
94
110
 
95
- Identifiers with square brackets (`name[...]`) are strictly pattern
96
- template applications. A referenced pattern template must exist in scope
97
- or in an imported library. An undefined template lookup raises an
98
- `Unknown pattern template` error immediately and is **never** silently
99
- treated as an open variable or leaf.
111
+ ```k
112
+ bool[] = < {} false, {} true >;
113
+ not = ?bool[] < /false |true, /true |false > ?bool[];
114
+ ```
100
115
 
101
- In contrast, bare identifiers without brackets in pattern positions (e.g.
102
- `X`, `T`, `Y`) represent formal parameters, cycle knots (`= Y`), or
103
- existential type variables asserting type equality across fields.
116
+ Both boundaries have the boolean schema, although the relation changes the
117
+ payload. Shared contract nodes describe schema relationships, not a separate
118
+ proof of preservation of the original data.
104
119
 
105
- Pattern definitions are validated eagerly at compile time: undefined
106
- references, cyclic template dependencies, and arity mismatches are
107
- rejected before code generation or canonical hashing.
120
+ Explicit recursive patterns can make contract derivation converge. This is a
121
+ compiler property, not a guarantee of execution termination. See
122
+ [contract derivation](TYPE_DERIVATION.md).
108
123
 
109
- ## Filters and Terminal Positions
124
+ In the envelope-aware runtime, constraints intersect the carried pattern and
125
+ contradictions raise type errors. Optimized execution may erase guards proved
126
+ by specialization. Ordinary partial failure remains distinct from a schema
127
+ contradiction.
110
128
 
111
- A k script can describe a pattern through:
129
+ ## Canonical identity and routing
112
130
 
113
- - a relation in terminal position
114
- - a filter expression in terminal position
115
- - a named pattern invocation (`? name[...]`)
131
+ Relations are hashed from normalized definitions; that does not decide general
132
+ semantic equality of programs.
116
133
 
117
- Examples:
134
+ Named patterns factor into a canonical linear skeleton and alias arguments.
135
+ Every open leaf slot of the skeleton has its own port:
118
136
 
119
137
  ```k
120
- bits[] = < {} _, B 0, B 1 > = B;
121
- list[X] = < {} nil, { X car, Y cdr } cons > = Y;
122
- list? = ? list[bits[]];
123
- list?
138
+ pair[A, B] = { A first, B second };
139
+ same_pair[T] = { T first, T second };
140
+ closed_same_pair[] = { T first, T second };
141
+ any_pair[] = { (...) first, (...) second };
124
142
  ```
125
143
 
126
- Or anonymously:
144
+ All four use the skeleton:
127
145
 
128
146
  ```k
129
- ? list[bits[]]
147
+ @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[X0, X1] = {
148
+ X0 first, X1 second
149
+ };
130
150
  ```
131
151
 
132
- In all cases, the compiler derives a root pattern from `__main__`.
133
-
134
- ## Pattern Export Helper
152
+ Their arguments retain the differences:
135
153
 
136
- `patterns/from-k.mjs` extracts that root pattern from a k script. It is a
137
- repository helper, not an installed `package.json` binary.
154
+ | Alias | Skeleton arguments |
155
+ | --- | --- |
156
+ | `pair[A, B]` | `[A, B]` |
157
+ | `same_pair[T]` | `[T, T]` |
158
+ | `closed_same_pair[]` | `[T, T]`, with a fresh private `T` per instantiation |
159
+ | `any_pair[]` | `[(...), (...)]` |
138
160
 
139
- It:
161
+ Formal parameters route to their supplied arguments. A repeated private
162
+ variable routes the same fresh variable to multiple slots. A private variable
163
+ used only once becomes a wildcard. Knots remain internal to the graph.
140
164
 
141
- 1. reads a k script from stdin or a file argument
142
- 2. runs `k.annotate(...)`
143
- 3. resolves `__main__`
144
- 4. requires `__main__` to be either:
145
- - a filter expression
146
- - a relation name
147
- 5. exports the corresponding root pattern
148
- 6. prints it as the canonical property-list array
165
+ Consequently, the skeleton hash alone does not identify all constraints of an
166
+ alias: its routing arguments matter too. Structural canonicalization also
167
+ does not identify every graph accepting the same finite-tree language; for
168
+ example, the current implementation distinguishes different unproductive
169
+ recursive structures.
149
170
 
150
- Example:
171
+ ## Inspection and persistence
151
172
 
152
- ```bash
153
- echo '?< {} nil, { {} car, X cdr } cons > = X' | \
154
- node ./patterns/from-k.mjs
155
- ```
173
+ In the REPL, `:pats` lists aliases with parameters, skeleton hashes, and routing
174
+ arguments. `:pat name` shows the alias definition; `:pat @hash` inspects a
175
+ registered canonical pattern. Hash-addressed patterns can also be defined or
176
+ instantiated directly, with all canonical arguments supplied.
156
177
 
157
- Typical output:
178
+ Object and library containers preserve:
158
179
 
159
- ```json
160
- [
161
- ["closed-union", [["nil", 1], ["cons", 2]]],
162
- ["closed-product", []],
163
- ["closed-product", [["car", 1], ["cdr", 0]]]
164
- ]
165
- ```
180
+ - `patterns[hash]`: canonical template parameters and filter AST;
181
+ - `patternAlias[name]`: alias-to-skeleton hash;
182
+ - `meta[hash].origins[]`: original alias parameters and `aliasArgs` routing.
166
183
 
167
- ## Schemas in the Codec
184
+ Repeated existential variables must survive export and loading. The
185
+ [file-format reference](FILE_FORMATS.md) describes the complete container.
168
186
 
169
- The active wire format is:
187
+ For a host-side pattern export, use:
170
188
 
171
- ```text
172
- encode(schema_value : schema) encode(payload : decoded_schema)
189
+ ```sh
190
+ printf '%s\n' '?< {} nil, { {} car, X cdr } cons > = X' |
191
+ node patterns/from-k.mjs
173
192
  ```
174
193
 
175
- So the property-list array printed by `patterns/from-k.mjs` is a
176
- readable externalization of the same schema information carried in the
177
- wire stream.
194
+ Run this from the repository root. The canonical property-list result is:
178
195
 
179
- `k-parse --input-pattern ...` produces the root schema used to interpret
180
- textual values.
181
-
182
- ## See Also
196
+ ```json
197
+ [
198
+ ["closed-union", [["cons", 1], ["nil", 2]]],
199
+ ["closed-product", [["car", 2], ["cdr", 0]]],
200
+ ["closed-product", []]
201
+ ]
202
+ ```
183
203
 
184
- - [DOCS/FILE_FORMATS.md](./FILE_FORMATS.md) — guide to
185
- .k, .ko, .klib, and .kvm formats
186
- - [DOCS/TEXTUAL_VALUES.md](./TEXTUAL_VALUES.md)
187
- - [codecs/README.md](../codecs/README.md)
188
- - [DOCS/OBJECT_FILE_AND_PATTERN.md](./OBJECT_FILE_AND_PATTERN.md)
204
+ This is an inspection representation. The [wire format](../codecs/WIRE_FORMAT.md)
205
+ encodes the graph as an ordinary value under the fixed `pattern[]` schema.
@@ -1,104 +1,86 @@
1
- # Polymorphic K Intermediate Representation (PKIR)
2
-
3
- ## 1. Overview
4
-
5
- PKIR (Polymorphic K Intermediate Representation) is the target execution
6
- contract for polymorphic `k` relations.
7
-
8
- Unlike the high-level relational AST or traditional bytecode that
9
- relies on runtime string lookups for field names and variant tags, PKIR
10
- is a **state-indexed, slot-addressed intermediate representation**.
11
-
12
- PKIR operates in two cooperating execution modes:
13
- 1. **Generic Polymorphic Mode**: Instructions execute against a
14
- precomputed `AccessTable` (Layout Witness), accessing fields and
15
- variants via static slot numbers and array lookups with zero string
16
- comparisons.
17
- 2. **Specialized Monomorphic Mode**: Given an `AccessTable`, a fast linear
18
- pass (`specializePKIR`) inlines offsets directly into immediate machine
19
- instructions, pruning unreachable union branches for peak LLVM/Wasm
20
- performance.
21
-
22
- ---
23
-
24
- ## 2. Core Concepts
25
-
26
- ### 2.1 The Structural Access Profile
27
-
28
- Every PKIR relation is accompanied by an **Access Profile** derived from
29
- its pattern graph:
30
- - For every product pattern node $u$: a list of accessed field labels
31
- defining dense, zero-based **logical slots**:
32
- $$\text{fields}(u) = [ f_0, f_1, \dots, f_{k-1} ]$$
33
- where slot $i$ corresponds to field $f_i$.
34
- - For every union pattern node $u$: a list of matched variant tags
35
- defining dense **branch targets**:
36
- $$\text{variants}(u) = [ v_0, v_1, \dots, v_{m-1} ]$$
37
- where branch $j$ corresponds to variant $v_j$.
38
-
39
- ### 2.2 Dual-Form Values (`KVal`)
40
-
41
- Values in PKIR conform to the hybrid representation:
42
- - **Serialized (Wire Slice)**: A pointer into an immutable prefix-free
43
- bitstream, carrying a bit offset and schema state.
44
- - **Materialized (Arena Node)**: An allocated record in memory containing
45
- word-aligned pointers to child values.
46
-
47
- ---
48
-
49
- ## 3. Instruction Set
50
-
51
- PKIR instructions operate over a register file (`%v0`, `%v1`, ...):
52
-
53
- ### 3.1 Field & Variant Operations
54
-
55
- - **`project_slot dest, src, state, slot`**:
56
- Projects field at logical `slot` of pattern `state` from `src`.
57
- At runtime with `AccessTable`:
58
- ```c
59
- dest.ptr = src.ptr + table[src.state].slotToByteOffset[slot];
60
- dest.state = table[src.state].slotToChildState[slot];
61
- ```
62
- - **`match_tag src, state, branches`**:
63
- Evaluates variant discriminator of `src` against pattern `state`.
64
- At runtime with `AccessTable`:
65
- ```c
66
- branch_idx = table[src.state].branchMap[src.tag];
67
- dest.state = table[src.state].childStateMap[src.tag];
68
- jump branches[branch_idx];
69
- ```
70
- - **`make_variant dest, src, tag_id`**:
71
- Wraps `src` into a tagged union with discriminator `tag_id`.
72
- - **`make_product dest, [src0, src1, ...]`**:
73
- Allocates a product node whose fields are registers `[src0, src1, ...]`.
74
-
75
- ### 3.2 Memory & Control Operations
76
-
77
- - **`promote_spine dest, src`**:
78
- If `src` is in serialized wire form, materializes only its immediate
79
- outer record in the arena; children remain serialized wire slices.
80
- If `src` is already materialized, acts as identity.
81
- - **`dup dest1, dest2, src`**:
82
- Zero-copy duplication of a value handle.
83
- - **`call_rel dest, rel_name, src`**:
84
- Invokes relation `rel_name` with input `src`.
85
- - **`id dest, src`**:
86
- Identity move.
87
- - **`fail`**:
88
- Signals partial function failure (backtracking or branch exit).
89
-
90
- ---
91
-
92
- ## 4. Execution Pipeline
1
+ # Polymorphic IR (PKIR)
2
+
3
+ PKIR is an experimental execution representation in [pkir.mjs](../pkir.mjs).
4
+ It uses schema states and structural access profiles to navigate values through
5
+ layout witnesses.
6
+
7
+ It is separate from [KIR-P](KIR_V1.md), the portable object export, and from
8
+ [kVM](KVM_EXECUTION_MODEL.md), the register execution representation used by
9
+ the backends.
10
+
11
+ ## Relation artifact
12
+
13
+ `compileRelationToPKIR(relDef, name)` creates:
93
14
 
94
15
  ```text
95
- [AOT Phase]
96
- k source -> AST -> Type Pattern Graph -> PKIR Relation
97
-
98
- [Runtime Invocation with (Schema S, Payload V)]
99
- 1. AccessTable = buildAccessTable(S, PKIR.patternGraph)
100
- 2. Choose execution tier:
101
- - Tier 0 (Interpreter): executePKIR(PKIR, V, AccessTable)
102
- - Tier 1 (Specialized AOT/JIT): specializePKIR(PKIR, AccessTable)
103
- -> direct emission to LLVM / WebAssembly
16
+ format: "pk-ir"
17
+ version: 1
18
+ name
19
+ inputReg / outputReg
20
+ inputPattern / outputPattern
21
+ patternGraph
22
+ accessProfile
23
+ instructions
104
24
  ```
25
+
26
+ The pattern graph supplies relation constraints; the access profile records
27
+ which fields and variants each state uses. `.pkir` is the JSON artifact
28
+ extension accepted by target tools.
29
+
30
+ ## Access tables and values
31
+
32
+ `buildAccessTable(schema, pattern)` in
33
+ [access-table.mjs](../access-table.mjs) connects an input schema to the relation's
34
+ pattern graph. Descriptors map structural accesses to physical slots, child
35
+ states, tag identities, and offsets.
36
+
37
+ The JavaScript adapter `valueToKVal` creates materialized records with
38
+ `repr`, `state`, `tag`, and `words`; product records also retain field names.
39
+ `kvalToValue` converts these records back to `Value`. The execution code also
40
+ has support for serialized representations; use the adapter/codec contracts
41
+ rather than assuming that every PKIR value is a native pointer.
42
+
43
+ ## Current instructions
44
+
45
+ | Instruction | Role |
46
+ | --- | --- |
47
+ | `id` | Forward a register |
48
+ | `fail` | Partial failure |
49
+ | `project_slot` | Project a product field through schema/layout information |
50
+ | `match_variant` | Extract a matching variant payload |
51
+ | `make_variant` | Construct a tagged value |
52
+ | `product` | Construct fields through nested instruction streams |
53
+ | `union` | Ordered branch selection |
54
+ | `call_rel` | Relation call, including recursion |
55
+ | `project_offset` | Specialized product access with a resolved offset |
56
+ | `match_tag_imm` | Specialized tag match with resolved discriminator information |
57
+
58
+ Instruction records retain labels/tags where needed for generic adapters.
59
+ Do not assume that generic execution universally eliminates string operations.
60
+
61
+ ## Specialization and target lowering
62
+
63
+ `specializePKIR(pkir, table)` resolves product accesses to `project_offset`,
64
+ resolves variant matches to `match_tag_imm`, and removes branches whose
65
+ leading operation is known to fail. It returns an artifact with
66
+ `isSpecialized: true`.
67
+
68
+ `executePKIR` interprets generic or specialized instructions with the required
69
+ access table and relation context. `lowerPKIRToKVM` adapts instructions for
70
+ backend lowering. The shared [backend API](../backend-api.mjs) exports these
71
+ functions plus `compileWasmArtifactFromPKIR` and
72
+ `compileLLVMArtifactFromPKIR`.
73
+
74
+ The target CLIs accept `.pkir` files or `--pkir` for compiling source through
75
+ this path. See [WebAssembly](../backends/wasm/README.md) and
76
+ [LLVM](../backends/llvm/README.md).
77
+
78
+ Performance depends on the workload, adapter, and execution target. Use the
79
+ [benchmark guide](PROFILING_AND_TRACING.md) for measurements rather than
80
+ treating historical timings as interface guarantees.
81
+
82
+ ## Verification
83
+
84
+ `tests/test-access-table.mjs` exercises descriptors and layout mapping.
85
+ `tests/test-pkir.mjs` checks execution, specialization, opaque payloads,
86
+ partial failure, and target integration. Both are registered in `npm test`.