@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,1241 +1,42 @@
1
- # Concept Dictionary
2
-
3
- This document defines the main concepts, artifacts, values, and transformations
4
- of the k system. It is written as a standalone specification: terms are defined
5
- by their role in the language and compilation pipeline, not by any particular
6
- concrete compiler, storage encoding, or tool interface.
7
-
8
- The goal is to keep one vocabulary across source semantics, object artifacts,
9
- intermediate representations, value serialization, reference execution, and
10
- target execution.
11
-
12
- ## Naming Principles
13
-
14
- - Use semantic names for all externally visible concepts.
15
- - Distinguish a concept from its serialized representation.
16
- - Distinguish source syntax from the semantic object represented by that syntax.
17
- - Distinguish a mathematical relation from the compiler artifacts used to
18
- compile or execute it.
19
- - Use `schema` for data shapes (algebraic tree automata), `contract` for
20
- relational signatures, `filter` for partial identity guards and inductive
21
- witnesses, and `(schema, payload)` for framed runtime values.
22
-
23
- ## Source-Level Concepts
24
-
25
- ### k Source
26
-
27
- `k source` is the textual language read by the parser. It defines relations
28
- (including schemas defined as partial identities/filters) and an optional
29
- entry expression.
30
-
31
- Use this term for source text before compiler passes have resolved names,
32
- canonicalized schemas, or derived relational contracts.
33
-
34
- ### Expression
35
-
36
- An `expression` is a source-level program fragment that denotes a partial
37
- relation over framed values.
38
-
39
- Expressions include identity, composition, projection, variant introduction,
40
- product construction, ordered union, filters, and references to named
41
- relations or intrinsics.
42
-
43
- ### Partial Relation
44
-
45
- A `partial relation` maps an input framed payload to an output framed payload
46
- when it is defined. If it is not defined for the input, execution fails normally.
47
- This failure is part of the language semantics, not a system exception.
48
-
49
- Mathematically, a k program denotes a deterministic partial relation
50
- (partial function).
51
-
52
- ### Schema
53
-
54
- A `schema` describes a set of labeled tree payloads accepted by a finite tree
55
- automaton. Schemas are built from products and tagged unions. A schema can be
56
- *closed* (all constructors determined) or *open* (containing schema parameters
57
- $X, Y$).
58
-
59
- Use "schema" for the semantic concept. Avoid using "code" or "type pattern" by
60
- itself in public docs when the meaning is a schema.
61
-
62
- ### Canonical Schema
63
-
64
- A `canonical schema` is the deterministic, hashable normal form of a schema
65
- automaton. Its canonical textual syntax is its primary universal identity in the
66
- schema registry; its `@hash` is a fixed-width indexing digest.
67
-
68
- ### Filter
69
-
70
- A `filter` is an expression `?schema` that constrains the input payload
71
- to a schema and otherwise behaves like identity.
72
-
73
- In recursive relations, filters also serve as **inductive termination
74
- witnesses**, ensuring contract derivation converges.
75
-
76
- ### Named Pattern
77
-
78
- A `named pattern` is a parameterized regular tree grammar template
79
- defined using square-bracket syntax (`name[P1, ..., Pn] = filter;`).
80
- Named patterns declare external input ports in their parameter list
81
- and may contain internal unification variables and cycle knots
82
- (`= KnotName`). They are expanded statically without recursive
83
- divergence, compiling into canonical schema automata nodes.
84
-
85
- ### Canonical Content-Addressed Hash (`@hash`)
86
-
87
- A `canonical content-addressed hash` is the immutable, unique identifier
88
- derived from the normalized AST of a relation or the minimal deterministic
89
- tree automaton of a schema.
90
-
91
- In `k`, there is no global symbol namespace. Every compiled relation and
92
- schema is identified globally and uniquely by its `@hash`.
93
-
94
- ### Local Alias
95
-
96
- A `local alias` is a human-readable identifier (such as `plus`, `int`,
97
- or `5`) mapped to a canonical hash in object metadata (`relAlias`,
98
- `schemaAliases`).
99
-
100
- Aliases are local to their compilation scope. When loading libraries
101
- with `--lib`, canonical definitions are available by their `@hash`, but
102
- local aliases are not automatically exported into the consumer's scope
103
- unless explicitly mapped with `--export`.
104
-
105
- ### Relations as Values (No Built-in Numbers)
106
-
107
- In `k`, there are no primitive numerical types or built-in integer
108
- literals. Numerical identifiers such as `5` or `10` are nullary
109
- relations (constants) mapping the unit `{}` to bit trees of contract
110
- `{} -> bits`. Operations on signed integers (`int`) require
111
- converting bit trees via the `int` constructor (`5 int`).
112
-
113
- ## Values, Schemas, And Contracts
114
-
115
- ### Payload Tree (or Payload)
116
-
117
- A `payload tree` (or `payload`) is the product/variant tree part of a value during
118
- execution.
119
-
120
- By itself, a raw payload tree is not self-describing at a binary or polymorphic
121
- boundary. The same tree is meaningful only when framed by a schema.
122
-
123
- ### Schema
124
-
125
- A `schema` describes a set of possible payload trees accepted by an algebraic
126
- automaton. It is the semantic object represented by source filter syntax and by the
127
- schema graphs carried through compilation and execution.
128
-
129
- Examples of schema kinds include:
130
-
131
- - unconstrained schema parameter (`X`, `?X`);
132
- - open product;
133
- - closed product;
134
- - open union;
135
- - closed union;
136
- - closed schema derived from concrete definitions.
137
-
138
- ### Schema Graph
139
-
140
- A `schema graph` is the graph representation of a schema. Nodes describe
141
- schema kind and openness. Edges describe required product fields or union tags.
142
-
143
- Schema graph node identity matters: if two positions point to the same schema
144
- node, they share the exact same schema structure.
145
-
146
- Use "schema graph" for the representation, and "schema" for the semantic
147
- language it defines.
148
-
149
- ### Framed Value `(schema, payload)`
150
-
151
- A `framed value` (formerly called an enveloped value) is a pair:
152
-
153
- ```text
154
- (schema, payload)
155
- ```
156
-
157
- Structural operations propagate or refine the framing schema:
158
-
159
- - projection selects a subschema;
160
- - product construction builds a closed product schema from field schemas;
161
- - variant introduction builds an open union schema for the introduced tag;
162
- - filters intersect the active schema with a static schema constraint.
163
-
164
- The schema is part of the semantic value at compilation and execution
165
- boundaries. A payload tree without a framing schema is incomplete at those boundaries.
166
-
167
- ### Contract
168
-
169
- A `contract` is the derived $(input, output)$ linked schema graph attached to an
170
- expression or relation:
171
-
172
- ```text
173
- input schema -> output schema
174
- ```
175
-
176
- Contracts are compiler facts. Unlike independent types, a contract is a single
177
- connected schema graph where shared vertices ($=X$) prove structure preservation:
178
- input substructures flow through to the output without destruction or rebuilding.
179
- Contracts guide diagnostics, REPL output, binary serialization, and optimizations.
180
-
181
- ### Domain
182
-
183
- Use "domain" carefully.
184
-
185
- The input schema of a relation is a static constraint, not
186
- necessarily the exact mathematical domain of the relation. A relation may still
187
- be undefined for some payload trees that fit its input schema.
188
-
189
- Prefer:
190
-
191
- - "input schema";
192
- - "accepted schema";
193
- - "static input constraint".
194
-
195
- Use "domain" only when referring to the actual set of inputs for which the
196
- partial relation is defined.
197
-
198
- ## Serialization And Boundaries
199
-
200
- ### Wire Stream
201
-
202
- A `wire stream` is the binary transport representation of a framed value `(schema, payload)`.
203
-
204
- The active format is:
205
-
206
- ```text
207
- encoded schema, followed by payload bits encoded under that schema
208
- ```
209
-
210
- Use "wire stream" or "schema+payload wire stream" for external transport
211
- boundaries. Use "framed value" for the semantic object used during
212
- execution.
213
-
214
- ### Codec
215
-
216
- A `codec` converts between an external representation and a k wire stream.
217
-
218
- Examples include the unit, JSON, integer, IEEE, UTF-8, and UTF-16 codecs. A
219
- codec must preserve the schema/payload relationship: it either supplies a
220
- schema for parsing, decodes the schema from the stream for printing, or
221
- works with a universal representation that can infer a suitable schema.
222
-
223
- ### Input Schema
224
-
225
- An `input schema` is the schema framing the input payload at a program or
226
- execution boundary.
227
-
228
- Execution targets use the input schema to specialize or validate execution.
229
- The input schema can be provided explicitly, derived from a filter expression, or
230
- decoded from a wire stream.
231
-
232
- ### Output Schema
233
-
234
- An `output schema` is the schema attached to the output payload after execution.
235
-
236
- A correct runner must emit both the output schema and the output payload bits.
237
- Rendered values can hide schema differences, so conformance checks must compare
238
- schemas whenever schema identity matters.
239
-
240
- ## Compiler Stages
241
-
242
- ### Parsed AST
243
-
244
- The `parsed AST` is the direct parser output. It keeps source-shaped expression
245
- nodes, source names, source ranges, and filter syntax.
246
-
247
- Use this term only for the representation before schema registration,
248
- relation canonicalization, and contract derivation.
249
-
250
- ### Contract-Annotated Core
251
-
252
- `Contract-annotated core` is the first semantic compiler artifact after parsing.
253
-
254
- It keeps the expression structure close to k source, but it has:
255
-
256
- - registered canonical schemas;
257
- - resolved schema references to canonical schema names;
258
- - relation dependency information;
259
- - canonical aliases for relations;
260
- - a schema graph for each relation;
261
- - a contract on each expression;
262
- - contract-derivation convergence status.
263
-
264
- The key product is still a k-shaped core expression graph, now annotated by
265
- schema contract facts. This stage is a semantic artifact; it does not imply a
266
- particular serialized format.
267
-
268
- ### Ahead-Of-Time (AOT) Contract Checking
269
-
270
- `Ahead-of-time (AOT) contract checking` refers to the compilation phase
271
- where parsing, relation expansion, structural contract derivation, and
272
- fixed-point constraint convergence are solved in advance.
273
-
274
- The resulting compiled artifacts (`.ko`, `.klib`, `.kvm`) store fully
275
- derived principal schema contracts and interned schemas, allowing downstream
276
- execution or linking to skip cold-start derivation entirely.
277
-
278
- ### k Object
279
-
280
- A `k object` is a compiled semantic object.
281
-
282
- It stores canonical schemas, relations, aliases, metadata,
283
- schema graphs, and contract-derivation status.
284
-
285
- An executable object (`.ko`) has an execution entrypoint (`main:
286
- "__main__"`). A library object (`.klib`) contains reusable definitions
287
- but no selected main relation (`main: null`).
288
-
289
- ### File Formats in the K Universe
290
-
291
- The `k` toolchain defines four primary file formats (for comprehensive
292
- details and workflows, see [`DOCS/FILE_FORMATS.md`](FILE_FORMATS.md)):
293
-
294
- - **Source File (`.k`):** Plain UTF-8 source text defining algebraic
295
- schemas, relations, and expressions.
296
- - **Executable Object (`.ko`):** AOT contract-checked executable artifact
297
- with binary header `KOBJ\n` and JSON payload containing schemas, relations,
298
- and entrypoint `main: "__main__"`. Executable directly via `k.mjs`,
299
- WebAssembly, or LLVM.
300
- - **Library Object (`.klib`):** AOT contract-checked library container stored
301
- as plain UTF-8 JSON without an entrypoint (`main: null`). Provides
302
- reusable pre-converged relations and schema graphs for downstream linking.
303
- - **Polymorphic kVM Template (`.kvm`):** Register-IR bytecode template
304
- (`format: "k-vm"`, `layer: "KVM-P"`) carrying principal contracts.
305
- Specialized on-the-fly at runtime (`specializeKVM`) against concrete
306
- input schemas $(v, S_v)$ without re-running type inference.
307
-
308
- ### Stream Transformer vs. Closed Constant Relation
309
-
310
- - A **stream transformer** is a relation with an open input schema (e.g. `{() x,
311
- 5 int y} plus`) that consumes external data arriving from a binary
312
- stream or standard input.
313
- - A **closed constant relation** is a relation with no free inputs (such
314
- as `{10 int x, 5 int y} plus`). Its input schema is the unit `{}`,
315
- requiring an empty unit `{}` when executed as a standalone script.
316
-
317
- ### KIR-P
318
-
319
- `KIR-P` is the portable, polymorphic K Intermediate Representation.
320
-
321
- It is a stable artifact contract over k objects. It preserves schema-carrying
322
- semantics while normalizing names, expression opcodes, and schema graph node IDs
323
- so consumers do not depend on parser-shaped fields or object encoding details.
324
-
325
- Use KIR-P as the shared semantic contract between k objects and lower-level
326
- execution artifacts.
327
-
328
- ### Schema-Specialized KIR-P
329
-
330
- `Schema-specialized KIR-P` is KIR-P rebuilt for a concrete input schema.
331
-
332
- Schema-specialization:
333
-
334
- - takes a KIR-P object or k object;
335
- - takes an input schema;
336
- - re-runs contract derivation as if the entry expression were filtered by that
337
- schema;
338
- - derives the corresponding output schema;
339
- - emits ordinary KIR-P for the specialized entry relation.
340
-
341
- ### KIR-M
342
-
343
- `KIR-M` is a materialized execution layer after schema-specialized KIR-P.
344
-
345
- It should contain layout and ABI decisions such as field offsets, tag dispatch,
346
- call-site specialization, and schema-free execution assumptions.
347
-
348
- ### Lowered Execution Model
349
-
350
- A `lowered execution model` is an executable middle layer.
351
-
352
- It lowers KIR-P relation bodies into a small instruction model with
353
- explicit partial failure, filters, projections, construction, calls, and
354
- returns.
355
- It is an execution contract that a lower-level compiler or executor can
356
- consume. It is not defined by a particular byte encoding.
357
-
358
- `kVM` is the name used in this specification for such a lowered execution model.
359
-
360
- ### Lowered Execution Artifact
361
-
362
- A `lowered execution artifact` is a post-schema-specialization execution
363
- artifact.
364
-
365
- It is produced by taking a source or object program, specializing it against a
366
- concrete input schema, lowering the resulting KIR-P to a lowered execution
367
- model, and wrapping the entry metadata and relations. It is not the same thing
368
- as a general k object.
369
-
370
- ## Execution Concepts
371
-
372
- ### Schema-Aware Execution
373
-
374
- `Schema-aware execution` carries framing schemas through inner operations.
375
-
376
- This mode matches the reference execution and codec model. It is the safest
377
- semantic baseline because values keep their schema framing throughout execution.
378
-
379
- ### Schema-Free Execution
380
-
381
- `Schema-free execution` uses static layout and schema information inside the
382
- compiled relation and attaches the derived output schema only at the boundary.
383
-
384
- This is valid only when schema-specialization and contract derivation prove the
385
- needed schema contexts.
386
-
387
- ### Partial Failure
388
-
389
- `Partial failure` is the normal result when a partial relation is undefined for
390
- its input payload.
391
-
392
- In high-level execution this is represented as absence of an output value. In
393
- lower-level execution contracts it may be represented explicitly as a failed
394
- result. It is distinct from a `contract violation`, malformed artifacts, system
395
- failures, and host exceptions.
396
-
397
- ### Contract Violation (Type Error)
398
-
399
- A `contract violation` (or `type error`) is a semantic contradiction indicating
400
- that the schema of a payload or expression does not conform to the expected
401
- input schema of the relation to which it is applied.
402
-
403
- A contract violation is fundamentally distinct from `partial failure`:
404
-
405
- - `Partial failure` is a normal, valid semantic outcome representing mathematical
406
- undefinedness for an input value that nonetheless conforms to the expected
407
- input schema (for example, failing a condition in an inner branch, which in
408
- an ordered union allows subsequent branches to be evaluated).
409
- - A `contract violation` represents a contract contradiction or boundary contract
410
- violation. It is not an ordinary execution result and cannot be recovered by
411
- branching constructs like ordered union.
412
-
413
- A contract violation can occur at two distinct stages:
414
-
415
- 1. **Compilation time (Contract Derivation)**: Triggered during
416
- `contract-derivation` when an expression's schema cannot be
417
- unified with, or does not satisfy, the required input schema of a relation
418
- it is passed to (such as disjoint schemas or unsatisfiable filters).
419
- This causes compilation or contract derivation to fail with a diagnostic.
420
- 2. **Runtime (Evaluation Boundary)**: Triggered when a `framed value` carries
421
- an `input schema` that does not match or conform to the expected input
422
- schema of the relation being executed (for example, passing an incompatible
423
- schema to an entry relation or target executable). At runtime, a
424
- contract violation halts execution with a fatal diagnostic or error code (such as exit
425
- status 5 in compiled targets) rather than producing partial failure.
426
-
427
- ### Intrinsic
428
-
429
- An `intrinsic` is a predefined operation supplied by the execution environment and
430
- known to the compiler.
431
-
432
- Intrinsics need explicit schema and lowering rules. Pure identity-like intrinsics
433
- can participate in ordinary relation semantics. Effectful or host-only
434
- intrinsics require explicit ordering constraints or must be excluded from pure
435
- lowering targets.
436
-
437
- ## Transformation Graphs
438
-
439
- This section names the transformations between the concepts above.
440
-
441
- The diagrams use a Petri-net-like convention:
442
-
443
- - all nodes are rectangles;
444
- - blue nodes are artifacts or semantic concepts;
445
- - amber nodes are transformations;
446
- - green nodes are execution values or wire streams;
447
- - purple nodes are lowered execution artifacts;
448
- - every transformation is shown as an explicit node between its inputs and
449
- outputs;
450
- - a transformation with several incoming arrows needs all shown inputs.
451
-
452
- ### Whole-System Artifact Graph
453
-
454
- This graph starts with a relation definition in k syntax and an input
455
- framed value `(schema, payload)`. It ends with an output framed value. Lowering paths branch
456
- after the k object.
457
-
458
- ```mermaid
459
- %%{init: {"flowchart": {"htmlLabels": true, "nodeSpacing": 42, "rankSpacing": 58}, "themeVariables": {"fontSize": "18px"}} }%%
460
- flowchart TB
461
- classDef artifact fill:#e8f2ff,stroke:#2563eb,stroke-width:1.5px,color:#0f172a;
462
- classDef transform fill:#fff4d6,stroke:#d97706,stroke-width:1.5px,color:#3b2300;
463
- classDef value fill:#e8f7ee,stroke:#16a34a,stroke-width:1.5px,color:#052e16;
464
- classDef lowered fill:#f3e8ff,stroke:#7e22ce,stroke-width:1.5px,color:#2e1065;
465
- classDef result fill:#fff1f2,stroke:#e11d48,stroke-width:1.5px,color:#4c0519;
466
-
467
- subgraph Compile["compile source into a semantic object"]
468
- direction LR
469
- Src["k source<br/>program"]:::artifact
470
- Parse["source<br/>parsing"]:::transform
471
- AST["parsed<br/>AST"]:::artifact
472
- Annotate["contract<br/>derivation"]:::transform
473
- Core["contract-annotated<br/>core"]:::artifact
474
- Package["object<br/>packaging"]:::transform
475
- Object["k<br/>object"]:::artifact
476
- Src --> Parse --> AST --> Annotate --> Core --> Package --> Object
477
- end
478
-
479
- subgraph Input["prepare the input value"]
480
- direction LR
481
- InputValue["input framed value<br/>(schema, payload)"]:::value
482
- ExtractEnvelope["input-schema<br/>extraction"]:::transform
483
- InputEnvelope["input<br/>schema"]:::artifact
484
- InputValue --> ExtractEnvelope --> InputEnvelope
485
- end
486
-
487
- subgraph Reference["reference schema-aware execution"]
488
- direction LR
489
- Select["entry<br/>selection"]:::transform
490
- EntryFunction["entry<br/>relation"]:::artifact
491
- ReferenceRun["reference<br/>evaluation"]:::transform
492
- OutputValue["output framed value<br/>(schema, payload)"]:::result
493
- Select --> EntryFunction --> ReferenceRun --> OutputValue
494
- end
495
-
496
- subgraph KIRPrep["prepare lowered artifacts"]
497
- direction LR
498
- ExportKIR["KIR-P<br/>export"]:::transform
499
- KIRP["KIR-P"]:::artifact
500
- Specialize["schema<br/>specialization"]:::transform
501
- SpecializedKIRP["schema-specialized<br/>KIR-P"]:::artifact
502
- OutputEnvelope["output<br/>schema"]:::artifact
503
- ExportKIR --> KIRP --> Specialize --> SpecializedKIRP
504
- Specialize --> OutputEnvelope
505
- end
506
-
507
- subgraph LoweredPath["lowered execution path"]
508
- direction LR
509
- LowerModel["execution-model<br/>lowering"]:::transform
510
- LoweredArtifact["lowered execution<br/>artifact"]:::lowered
511
- ExecuteLowered["lowered<br/>evaluation"]:::transform
512
- LowerModel --> LoweredArtifact --> ExecuteLowered
513
- end
514
-
515
- subgraph TargetPath["target execution path"]
516
- direction LR
517
- TargetLowering["target<br/>lowering"]:::transform
518
- TargetArtifact["target<br/>artifact"]:::lowered
519
- TargetExecution["target<br/>execution"]:::transform
520
- TargetLowering --> TargetArtifact --> TargetExecution
521
- end
522
-
523
- Object --> Select
524
- InputValue --> ReferenceRun
525
- Object --> ExportKIR
526
- InputEnvelope --> Specialize
527
- SpecializedKIRP --> LowerModel
528
- LoweredArtifact --> TargetLowering
529
- InputValue --> ExecuteLowered
530
- InputValue --> TargetExecution
531
- ExecuteLowered --> OutputValue
532
- TargetExecution --> OutputValue
533
- ```
534
-
535
- ### Reference Execution Graph
536
-
537
- The reference path is the semantic baseline. It can run directly from source or
538
- from a loaded k object. It stays schema-aware: the value keeps its schema framing
539
- through projections, constructors, filters, and relation calls.
540
-
541
- ```mermaid
542
- %%{init: {"flowchart": {"htmlLabels": true, "nodeSpacing": 42, "rankSpacing": 50}, "themeVariables": {"fontSize": "18px"}} }%%
543
- flowchart LR
544
- classDef artifact fill:#e8f2ff,stroke:#2563eb,stroke-width:1.5px,color:#0f172a;
545
- classDef transform fill:#fff4d6,stroke:#d97706,stroke-width:1.5px,color:#3b2300;
546
- classDef value fill:#e8f7ee,stroke:#16a34a,stroke-width:1.5px,color:#052e16;
547
- classDef result fill:#fff1f2,stroke:#e11d48,stroke-width:1.5px,color:#4c0519;
548
-
549
- Source["relation<br/>definition in k syntax"]:::artifact
550
- Input["input framed value<br/>(schema, payload)"]:::value
551
- Parse["source<br/>parsing"]:::transform
552
- AST["parsed<br/>AST"]:::artifact
553
- Annotate["contract<br/>derivation"]:::transform
554
- Core["contract-annotated<br/>core"]:::artifact
555
- Select["entry<br/>selection"]:::transform
556
- Transform["relation with<br/>contract"]:::artifact
557
- Run["reference<br/>evaluation"]:::transform
558
- Output["output framed value<br/>(schema, payload)"]:::result
559
-
560
- Source --> Parse --> AST --> Annotate --> Core --> Select --> Transform
561
- Transform --> Run
562
- Input --> Run
563
- Run --> Output
564
- ```
565
-
566
- ### Lowering Preparation Graph
567
-
568
- The lowering preparation path starts from a k object and an input schema. It
569
- specializes the program for that schema, derives the output schema, lowers
570
- to a lowered execution artifact, and may then lower to a concrete execution
571
- target.
572
-
573
- ```mermaid
574
- %%{init: {"flowchart": {"htmlLabels": true, "nodeSpacing": 42, "rankSpacing": 50}, "themeVariables": {"fontSize": "18px"}} }%%
575
- flowchart LR
576
- classDef artifact fill:#e8f2ff,stroke:#2563eb,stroke-width:1.5px,color:#0f172a;
577
- classDef transform fill:#fff4d6,stroke:#d97706,stroke-width:1.5px,color:#3b2300;
578
- classDef lowered fill:#f3e8ff,stroke:#7e22ce,stroke-width:1.5px,color:#2e1065;
579
-
580
- Object["k<br/>object"]:::artifact
581
- InputEnvelope["input<br/>schema"]:::artifact
582
- Export["KIR-P<br/>export"]:::transform
583
- KIRP["KIR-P"]:::artifact
584
- Specialize["schema<br/>specialization"]:::transform
585
- Specialized["schema-specialized<br/>KIR-P"]:::artifact
586
- OutputEnvelope["output<br/>schema"]:::artifact
587
- LowerModel["execution-model<br/>lowering"]:::transform
588
- Lowered["lowered execution<br/>artifact"]:::lowered
589
- TargetLowering["target<br/>lowering"]:::transform
590
- Target["target<br/>artifact"]:::lowered
591
-
592
- Object --> Export --> KIRP
593
- KIRP --> Specialize
594
- InputEnvelope --> Specialize
595
- Specialize --> Specialized
596
- Specialize --> OutputEnvelope
597
- Specialized --> LowerModel --> Lowered
598
- Lowered --> TargetLowering --> Target
599
- ```
600
-
601
- ### Wire Boundary Graph
602
-
603
- The wire boundary is separate from program compilation. It converts between a
604
- binary schema+payload stream and the in-memory framed value that execution
605
- uses.
606
-
607
- ```mermaid
608
- %%{init: {"flowchart": {"htmlLabels": true, "nodeSpacing": 42, "rankSpacing": 50}, "themeVariables": {"fontSize": "18px"}} }%%
609
- flowchart LR
610
- classDef transform fill:#fff4d6,stroke:#d97706,stroke-width:1.5px,color:#3b2300;
611
- classDef value fill:#e8f7ee,stroke:#16a34a,stroke-width:1.5px,color:#052e16;
612
- classDef result fill:#fff1f2,stroke:#e11d48,stroke-width:1.5px,color:#4c0519;
613
-
614
- InputWire["input wire<br/>stream"]:::value
615
- Decode["wire<br/>decoding"]:::transform
616
- InputValue["input framed value<br/>(schema, payload)"]:::value
617
- Execute["reference/target<br/>execution"]:::transform
618
- OutputValue["output framed value<br/>(schema, payload)"]:::result
619
- Encode["wire<br/>encoding"]:::transform
620
- OutputWire["output wire<br/>stream"]:::result
621
-
622
- InputWire --> Decode --> InputValue
623
- InputValue --> Execute --> OutputValue
624
- OutputValue --> Encode --> OutputWire
625
- ```
626
-
627
- ### Transformation Naming Scheme
628
-
629
- Use noun phrases ending in the operation kind:
630
-
631
- - `Parsing` for syntax to AST.
632
- - `Registration` for assigning canonical identities.
633
- - `Construction` for building semantic tables from parsed material.
634
- - `Derivation` for computing schema contracts.
635
- - `Canonicalization` for stable names and hashes.
636
- - `Packaging` for serializable artifacts.
637
- - `Loading` for reconstructing semantic objects from artifacts.
638
- - `Selection` for choosing an entry object from a larger artifact.
639
- - `Evaluation` for executing a semantic or lowered execution artifact.
640
- - `Extraction` for reading a component from an artifact without changing it.
641
- - `Export` for a stable inspection or interchange view.
642
- - `Specialization` for rewriting an artifact for a concrete input schema.
643
- - `Lowering` for moving to a lower-level execution contract.
644
- - `Encoding` and `Decoding` for wire boundaries.
645
- - `Rendering` for human or external presentation.
646
-
647
- Use lowercase hyphenated identifiers for transformation contracts. These
648
- identifiers name abstract transformation boundaries, not concrete function
649
- names.
650
-
651
- ### Transformation Contract Summary
652
-
653
- | Identifier | Preferred name | Inputs | Outputs |
654
- | --- | --- | --- | --- |
655
- | `source-parsing` | Source Parsing | k source program | parsed AST |
656
- | `schema-registration` | Schema Registration | parsed AST | canonical schema table |
657
- | `relation-table-construction` | Relation Table Construction | parsed AST, canonical schema table | source relation table |
658
- | `contract-derivation` | Contract Derivation | source relation table, canonical schema table | contract-annotated core |
659
- | `relation-canonicalization` | Relation Canonicalization | contract-annotated core | canonical relation aliases |
660
- | `object-packaging` | Object Packaging | contract-annotated core, canonical relation aliases | k object |
661
- | `object-loading` | Object Loading | k object | loaded k object |
662
- | `entry-selection` | Entry Selection | contract-annotated core or loaded k object | entry relation |
663
- | `reference-evaluation` | Reference Evaluation | entry relation, input framed value | output framed value or partial failure |
664
- | `input-schema-extraction` | Input-Schema Extraction | input framed value | input schema |
665
- | `kir-p-export` | KIR-P Export | k object | KIR-P |
666
- | `schema-specialization` | Schema Specialization | KIR-P or k object, input schema | schema-specialized KIR-P, output schema |
667
- | `execution-model-lowering` | Execution-Model Lowering | schema-specialized KIR-P | lowered execution artifact |
668
- | `lowered-evaluation` | Lowered Evaluation | lowered execution artifact, input framed value | output framed value or partial failure |
669
- | `target-lowering` | Target Lowering | lowered execution artifact | target artifact |
670
- | `target-execution` | Target Execution | target artifact, input framed value or input wire stream | output framed value or output wire stream |
671
- | `wire-decoding` | Wire Decoding | input wire stream | input framed value |
672
- | `wire-encoding` | Wire Encoding | output framed value | output wire stream |
673
- | `external-rendering` | External Rendering | output wire stream or output framed value | external text, JSON, or host value |
674
-
675
- ### Abstract Transformation Contracts
676
-
677
- Each transformation should be implementable and testable as an independent
678
- contract. A concrete compiler may combine several transformations for
679
- performance or convenience, but tests should still be able to isolate these
680
- boundaries.
681
-
682
- #### Source Parsing (`source-parsing`)
683
-
684
- Inputs:
685
-
686
- - k source program.
687
-
688
- Outputs:
689
-
690
- - parsed AST.
691
-
692
- Contract:
693
-
694
- - Parse textual k syntax into source-shaped AST nodes.
695
- - Preserve source names, source ranges, and source-level filter syntax.
696
- - Do not resolve type names, derive patterns, or assign canonical hashes.
697
- - Reject malformed syntax with a diagnostic tied to the source location when
698
- available.
699
-
700
- Independent tests:
701
-
702
- - Minimal expression parses to the expected AST shape.
703
- - Type definitions and partial-function definitions remain distinct.
704
- - Source ranges survive for expressions and nested filters.
705
- - Invalid syntax fails before any later compiler transformation runs.
706
-
707
- #### Type-Code Registration (`type-code-registration`)
708
-
709
- Inputs:
710
-
711
- - parsed AST.
712
-
713
- Outputs:
714
-
715
- - canonical type-code table.
716
- - source-name to type-code alias map.
717
-
718
- Contract:
719
-
720
- - Convert source type definitions into canonical type-code identities.
721
- - Resolve structural type definitions into stable hashable representations.
722
- - Preserve enough alias information to report source names in diagnostics and
723
- metadata.
724
- - Do not derive partial-function pattern signatures or execute partial-function
725
- bodies.
726
-
727
- Independent tests:
728
-
729
- - Structurally equivalent type definitions produce the same canonical type code.
730
- - Distinct product/union structures produce distinct type codes.
731
- - Recursive type definitions produce stable identities.
732
- - Undefined type references fail at this boundary, not during later lowering.
733
-
734
- #### Partial-Function Table Construction (`partial-function-table-construction`)
735
-
736
- Inputs:
737
-
738
- - parsed AST.
739
- - canonical type-code table.
740
-
741
- Outputs:
742
-
743
- - source partial-function table.
744
-
745
- Contract:
746
-
747
- - Collect named partial-function definitions and the entry expression.
748
- - Rewrite type references in expressions to canonical type-code names where the
749
- source syntax explicitly names a type.
750
- - Preserve source partial-function names before canonicalization.
751
- - Preserve expression structure; do not add inferred boundary guards or lowering
752
- instructions.
753
-
754
- Independent tests:
755
-
756
- - Named definitions and the entry expression are both present.
757
- - References to known source types resolve through the type-code table.
758
- - References to unknown partial functions remain diagnosable.
759
- - Expression ordering in composition and ordered union is preserved.
760
-
761
- #### Pattern-Signature Derivation (`pattern-signature-derivation`)
762
-
763
- Inputs:
764
-
765
- - source partial-function table.
766
- - canonical type-code table.
767
-
768
- Outputs:
769
-
770
- - pattern-annotated core.
771
-
772
- Contract:
773
-
774
- - Build one type-pattern graph for each partial function.
775
- - Attach a pattern signature to each expression node.
776
- - Convert source filter syntax into type-pattern graph nodes.
777
- - Propagate constraints through composition, projection, product construction,
778
- ordered union, references, and type-code expressions.
779
- - Record type-derivation convergence status.
780
-
781
- Independent tests:
782
-
783
- - Identity has the same input and output pattern representative.
784
- - Composition unifies each stage output with the next stage input.
785
- - Product construction derives a closed product output pattern.
786
- - Projection derives an open product or open union input pattern as appropriate.
787
- - Pattern guards constrain input and output to the same pattern.
788
- - Recursive partial functions report converged or not-converged status
789
- deterministically.
790
-
791
- #### Partial-Function Canonicalization (`partial-function-canonicalization`)
792
-
793
- Inputs:
794
-
795
- - pattern-annotated core.
796
-
797
- Outputs:
798
-
799
- - canonical partial-function aliases.
800
- - updated canonical references.
801
-
802
- Contract:
803
-
804
- - Compute stable canonical representations for partial functions.
805
- - Assign canonical hash aliases after dependency and convergence analysis.
806
- - Keep source aliases for diagnostics, metadata, and decompilation.
807
- - Preserve semantics: canonicalization must not change evaluation results.
808
-
809
- Independent tests:
810
-
811
- - Whitespace and source alias changes do not change canonical aliases.
812
- - Semantically different bodies produce different canonical aliases.
813
- - Mutually recursive groups canonicalize deterministically.
814
- - References inside canonicalized definitions point at the intended canonical
815
- partial functions.
816
-
817
- #### Object Packaging (`object-packaging`)
818
-
819
- Inputs:
820
-
821
- - pattern-annotated core.
822
- - canonical partial-function aliases.
823
-
824
- Outputs:
825
-
826
- - k object.
827
-
828
- Contract:
829
-
830
- - Produce a k object artifact from the compiled semantic object.
831
- - Preserve canonical type codes, partial functions, aliases, metadata,
832
- type-pattern graphs, and type-derivation status.
833
- - For executable objects, preserve the entry partial function.
834
- - For library objects, preserve exported reusable definitions without an entry.
835
- - Do not require an input enveloped value.
836
-
837
- Independent tests:
838
-
839
- - Packaged executable objects retain a main entry.
840
- - Packaged libraries have no main entry.
841
- - Object round trips preserve type-pattern graph structure and aliases.
842
- - Unreachable semantic material is either intentionally pruned or intentionally
843
- preserved according to the object contract.
844
-
845
- #### Object Loading (`object-loading`)
846
-
847
- Inputs:
848
-
849
- - k object.
850
-
851
- Outputs:
852
-
853
- - loaded k object.
854
-
855
- Contract:
856
-
857
- - Reconstruct a usable semantic object from a k object artifact.
858
- - Preserve the artifact's semantic content exactly.
859
- - Make the object usable by reference evaluation, KIR-P export, and lowering
860
- preparation.
861
- - Do not re-run source parsing or type derivation.
862
-
863
- Independent tests:
864
-
865
- - Loading followed by packaging is semantically stable.
866
- - Pattern graph representatives are usable after loading.
867
- - Loaded objects evaluate the same as freshly compiled objects.
868
- - Malformed object artifacts fail at loading.
869
-
870
- #### Entry Selection (`entry-selection`)
871
-
872
- Inputs:
873
-
874
- - pattern-annotated core or loaded k object.
875
- - optional requested partial-function name.
876
-
877
- Outputs:
878
-
879
- - entry partial function.
880
-
881
- Contract:
882
-
883
- - Resolve the entry partial function to execute or specialize.
884
- - Default to the executable object's main partial function when no explicit name is
885
- provided.
886
- - Resolve source aliases to canonical names where needed.
887
- - Fail if the requested entry cannot be found or if no entry exists.
888
-
889
- Independent tests:
890
-
891
- - Executable objects select their main partial function by default.
892
- - Explicit source aliases resolve to the intended canonical partial function.
893
- - Library objects require an explicit exported partial function.
894
- - Missing entries produce targeted diagnostics.
895
-
896
- #### Reference Evaluation (`reference-evaluation`)
897
-
898
- Inputs:
899
-
900
- - entry partial function.
901
- - input enveloped value.
902
-
903
- Outputs:
904
-
905
- - output enveloped value, or partial failure.
906
-
907
- Contract:
908
-
909
- - Execute the envelope-aware reference semantics.
910
- - Intersect input envelopes with static input patterns.
911
- - Propagate subpatterns through projections.
912
- - Build output envelopes for product and variant construction.
913
- - Return partial failure when the partial function is undefined for a conforming input.
914
- - Signal a type error when an input envelope contradicts the static input pattern constraint.
915
- - Throw diagnostics only for malformed artifacts or fatal system errors.
916
-
917
- Independent tests:
918
-
919
- - Identity returns the same enveloped value.
920
- - Projection returns the correct child with the correct sub-envelope.
921
- - Product construction builds the expected output tree and envelope.
922
- - Ordered union tries later branches only after earlier partial failure.
923
- - Input envelope mismatch triggers a type error rather than partial failure.
924
- - Pattern guard failure on a conforming value is reported as partial failure.
925
-
926
- #### Input-Envelope Extraction (`input-envelope-extraction`)
927
-
928
- Inputs:
929
-
930
- - input enveloped value.
931
-
932
- Outputs:
933
-
934
- - input envelope.
935
-
936
- Contract:
937
-
938
- - Read the envelope carried by the input value.
939
- - Do not inspect or transform the value tree except as needed to validate that
940
- the envelope exists and is well formed.
941
- - Preserve the envelope representation expected by specialization and lowering
942
- transformations.
943
-
944
- Independent tests:
945
-
946
- - Extraction returns the exact pattern attached to the input value.
947
- - Missing envelopes fail when the caller requires specialization.
948
- - Malformed pattern graphs are rejected before lowering preparation.
949
-
950
- #### KIR-P Export (`kir-p-export`)
951
-
952
- Inputs:
953
-
954
- - k object.
955
-
956
- Outputs:
957
-
958
- - KIR-P.
959
-
960
- Contract:
961
-
962
- - Produce the portable polymorphic view of a k object.
963
- - Normalize expression op names into the KIR-P vocabulary.
964
- - Convert per-partial-function pattern graphs to dense local node IDs.
965
- - Preserve type codes, aliases, metadata, and type-derivation status needed by
966
- consumers.
967
- - Do not specialize for any input envelope.
968
- - Do not make consumers depend on any particular object encoding.
969
-
970
- Independent tests:
971
-
972
- - Export is deterministic for the same object.
973
- - Pattern graph IDs are dense and local to each partial function.
974
- - KIR-P expression opcodes are from the closed KIR-P vocabulary.
975
- - KIR-P export preserves enough information for reference/lowered conformance
976
- tests.
977
-
978
- #### Envelope Specialization (`envelope-specialization`)
979
-
980
- Inputs:
981
-
982
- - KIR-P or k object.
983
- - input envelope.
984
- - optional entry partial-function name.
985
-
986
- Outputs:
987
-
988
- - envelope-specialized KIR-P.
989
- - output envelope.
990
-
991
- Contract:
992
-
993
- - Specialize the entry partial function as if guarded by the input envelope.
994
- - Re-run pattern-signature derivation for the specialized entry context.
995
- - Preserve ordinary KIR-P shape in the emitted artifact.
996
- - Derive the output envelope for that invocation.
997
- - Keep call-site worklists, cache keys, and instance metadata internal unless a
998
- later artifact contract explicitly exposes them.
999
-
1000
- Independent tests:
1001
-
1002
- - Specialization of `P f` matches compiling an entry expression guarded by `P`.
1003
- - Output envelope matches reference execution for representative inputs.
1004
- - The emitted artifact remains ordinary KIR-P, not a separate wrapper format.
1005
- - A helper used under two input envelopes can specialize differently without
1006
- corrupting the unspecialized object.
1007
-
1008
- #### Execution-Model Lowering (`execution-model-lowering`)
1009
-
1010
- Inputs:
1011
-
1012
- - envelope-specialized KIR-P.
1013
-
1014
- Outputs:
1015
-
1016
- - lowered execution artifact.
1017
-
1018
- Contract:
1019
-
1020
- - Lower KIR-P partial-function bodies to an explicit execution model.
1021
- - Preserve input and output pattern metadata on the entry function.
1022
- - Represent partial failure explicitly.
1023
- - Lower pattern guards, type checks, projections, constructors, calls, ordered
1024
- unions, and sequencing according to the lowered execution semantics.
1025
- - Enforce artifact eligibility rules such as accepted input-envelope shape at
1026
- the packaging boundary.
1027
-
1028
- Independent tests:
1029
-
1030
- - Identity lowers to a return of the input.
1031
- - Pattern guards lower to guard instructions or proven redundant checks.
1032
- - Product and variant operations preserve field/tag semantics.
1033
- - Ordered union preserves branch order and rollback/failure behavior.
1034
- - Non-eligible input envelopes are rejected with a targeted diagnostic when a
1035
- lowered artifact requires a narrower envelope.
1036
-
1037
- #### Lowered Evaluation (`lowered-evaluation`)
1038
-
1039
- Inputs:
1040
-
1041
- - lowered execution artifact.
1042
- - input enveloped value.
1043
-
1044
- Outputs:
1045
-
1046
- - output enveloped value, or partial failure.
1047
-
1048
- Contract:
1049
-
1050
- - Execute the lowered execution model.
1051
- - Validate the input envelope against the artifact input pattern, signaling a runtime type error on mismatch.
1052
- - Return output values under the artifact output pattern.
1053
- - Preserve partial failure as an ordinary execution result when undefined for a conforming input.
1054
- - Match reference evaluation for the specialized artifact.
1055
-
1056
- Independent tests:
1057
-
1058
- - Lowered evaluation matches reference evaluation on conformance fixtures.
1059
- - Input envelope mismatch aborts with a runtime type error before producing output.
1060
- - Recursive or repeated calls preserve deterministic results.
1061
- - Partial failure matches reference undefinedness.
1062
-
1063
- #### Target Lowering (`target-lowering`)
1064
-
1065
- Inputs:
1066
-
1067
- - lowered execution artifact.
1068
-
1069
- Outputs:
1070
-
1071
- - target artifact.
1072
-
1073
- Contract:
1074
-
1075
- - Lower the lowered execution artifact to a concrete execution target.
1076
- - Preserve the input and output envelope contract at the target boundary.
1077
- - Emit explicit success/failure result status.
1078
- - Reject unsupported operations with diagnostics rather than silently changing
1079
- semantics.
1080
-
1081
- Independent tests:
1082
-
1083
- - Generated target artifact has the expected entry shape.
1084
- - Supported lowered operations lower without fallback to unrelated generic paths.
1085
- - Unsupported operations fail predictably.
1086
- - Target output matches reference output for supported fixtures.
1087
-
1088
- #### Target Execution (`target-execution`)
1089
-
1090
- Inputs:
1091
-
1092
- - target artifact.
1093
- - input enveloped value or input wire stream.
1094
-
1095
- Outputs:
1096
-
1097
- - output enveloped value or output wire stream.
1098
-
1099
- Contract:
1100
-
1101
- - Run the target artifact for a specialized partial function.
1102
- - Validate or decode the input envelope at the boundary, triggering a runtime type error on mismatch.
1103
- - Emit the compiled output envelope with the output value.
1104
- - Preserve partial failure according to the target execution contract.
1105
-
1106
- Independent tests:
1107
-
1108
- - Target execution matches reference output on supported fixtures.
1109
- - Input envelope mismatch triggers a runtime type error (e.g. exit code 5) rather than partial failure.
1110
- - Wire output includes the expected output envelope.
1111
- - Persistent and one-shot runners produce the same results.
1112
- - Partial failure is distinguishable from process, system, or type-error failure.
1113
-
1114
- #### Wire Decoding (`wire-decoding`)
1115
-
1116
- Inputs:
1117
-
1118
- - input wire stream.
1119
-
1120
- Outputs:
1121
-
1122
- - input enveloped value.
1123
-
1124
- Contract:
1125
-
1126
- - Decode the leading envelope representation.
1127
- - Decode the following value bits under that envelope.
1128
- - Attach the decoded envelope to the execution value.
1129
- - Reject malformed streams, invalid envelopes, and non-zero padding according to
1130
- the wire format.
1131
-
1132
- Independent tests:
1133
-
1134
- - Encoding followed by decoding returns the same enveloped value.
1135
- - Decoding rejects truncated streams.
1136
- - Decoding rejects value bits that are impossible under the decoded envelope.
1137
- - The decoded value carries the decoded envelope, not a recomputed substitute.
1138
-
1139
- #### Wire Encoding (`wire-encoding`)
1140
-
1141
- Inputs:
1142
-
1143
- - output enveloped value.
1144
- - optional explicit output envelope.
1145
-
1146
- Outputs:
1147
-
1148
- - output wire stream.
1149
-
1150
- Contract:
1151
-
1152
- - Choose the explicit envelope when supplied, otherwise use the value envelope.
1153
- - Validate or coerce the value against the chosen envelope according to the codec
1154
- contract.
1155
- - Write the encoded envelope followed by the value bits encoded under it.
1156
- - Produce deterministic bytes for the same value and envelope.
1157
-
1158
- Independent tests:
1159
-
1160
- - Decoding the encoded stream returns the original enveloped value.
1161
- - Explicit envelopes override carried envelopes only when compatible.
1162
- - Incompatible explicit envelopes fail before bytes are emitted.
1163
- - Equivalent values under equivalent envelopes produce stable byte streams.
1164
-
1165
- #### External Rendering (`external-rendering`)
1166
-
1167
- Inputs:
1168
-
1169
- - output wire stream or output enveloped value.
1170
-
1171
- Outputs:
1172
-
1173
- - external text, JSON, or host value.
1174
-
1175
- Contract:
1176
-
1177
- - Render values for humans or external systems.
1178
- - Preserve envelope visibility when debug or inspection mode requests it.
1179
- - Avoid presenting rendered tree equality as proof of envelope equality.
1180
- - Do not feed rendered output back into target parity tests unless the envelope
1181
- is also checked.
1182
-
1183
- Independent tests:
1184
-
1185
- - Rendering a known enveloped value produces expected text/JSON.
1186
- - Debug rendering includes the envelope.
1187
- - Two values with the same tree and different envelopes can be distinguished in
1188
- inspection mode.
1189
- - Rendering errors do not imply execution errors.
1190
-
1191
- ### Transformation Notes
1192
-
1193
- - Compilation transformations do not need an input value until
1194
- schema-specialization or execution.
1195
- - Reference execution can use the contract-annotated core directly; target
1196
- execution goes through KIR-P and a lowered execution artifact.
1197
- - Schema-specialization is not a new source language feature. It is a compiler
1198
- transformation driven by the input schema.
1199
- - The output schema is an artifact of execution or specialization. It must be
1200
- preserved at binary boundaries even when printed payload trees look identical.
1201
- - Partial failure is an ordinary result of execution transformations. It should
1202
- not be modeled as a malformed artifact.
1203
-
1204
- ## Recommended Pipeline Vocabulary
1205
-
1206
- Use this pipeline in high-level docs:
1207
-
1208
- ```text
1209
- k source
1210
- -> parsed AST
1211
- -> contract-annotated core
1212
- -> k object
1213
- -> KIR-P
1214
- -> schema-specialized KIR-P
1215
- -> lowered execution artifact
1216
- -> target artifact
1217
- ```
1218
-
1219
- For the execution and codec boundary:
1220
-
1221
- ```text
1222
- wire stream <-> framed value (schema, payload) <-> partial relation <-> framed value (schema, payload) <-> wire stream
1223
- ```
1224
-
1225
- ## Terminology Rules
1226
-
1227
- These rules are normative for this specification:
1228
-
1229
- - Use "relation" or "partial relation" as the dominant public term.
1230
- - Keep "contract-annotated core" as the name for the normalized,
1231
- contract-annotated AST stage.
1232
- - Use "schema-specialized KIR-P" for KIR-P rebuilt under a concrete input
1233
- schema.
1234
- - Use "canonical schema" for the deterministic representation of a schema,
1235
- and "schema" for the semantic language of payload trees.
1236
- - Use "contract" for the connected $(input, output)$ schema graph derived
1237
- for relations, capturing structural preservation ($=X$).
1238
- - Use "framed value `(schema, payload)`" for the self-describing value
1239
- at execution and wire boundaries.
1240
- - Use "filter" for the syntactic expression `?schema` that constrains
1241
- payloads and acts as inductive termination witness.
1
+ # Glossary
2
+
3
+ These terms are used throughout the [documentation](README.md).
4
+
5
+ | Term | Meaning |
6
+ | --- | --- |
7
+ | **Relation** | A first-order partial function transforming one input value into one output value, or returning undefined. |
8
+ | **Product** | A value with labeled fields. A product expression applies every field relation to the same input. |
9
+ | **Variant** | One tag and its payload. A union schema lists possible tags; `\|tag` constructs a variant. |
10
+ | **Unit** | The empty product `{}`. |
11
+ | **Ordered choice** | `<f, g, ...>` tries relations in source order, selecting the first defined result. |
12
+ | **Schema** | A structural description of products and tagged unions, possibly recursive. |
13
+ | **Pattern** | A graph of schema constraints, including open positions and shared variables. Closed, fully determined patterns describe concrete schemas. |
14
+ | **Filter** | A relation `?P` that constrains the schema and leaves the payload unchanged. |
15
+ | **Named pattern** | A template declared as `name[A, ...] = P;` and instantiated as `name[argument, ...]`. |
16
+ | **Knot** | A binding `P = X` that makes occurrences of `X` refer back to a node in a recursive pattern. |
17
+ | **Envelope** | The pattern carried with a runtime payload. An enveloped value is the pair `(pattern, payload)`. |
18
+ | **Contract** | The input/output pattern graph derived for a relation. Shared nodes express shared schema constraints; they do not alone establish payload identity. |
19
+ | **Canonical skeleton** | The normalized structure of a named pattern with a separate port for each open leaf position. |
20
+ | **Routing vector** | Arguments connecting caller parameters, repeated variables, and wildcards to a canonical skeleton's ports. |
21
+ | **Content hash** | The `@hash` of a normalized definition. Named-pattern constraints also depend on their routing arguments. |
22
+ | **Alias** | A local friendly name for a canonical relation or pattern. |
23
+ | **Wire stream** | The binary representation of an envelope followed by a payload encoded under it. |
24
+ | **Codec** | A translator between an external representation and enveloped k values. |
25
+ | **Contract derivation** | Compiler propagation and unification of pattern constraints, with fixed-point iteration for recursive relation groups. |
26
+ | **Specialization** | Adapting a relation or execution artifact to a particular input envelope. The KIR-P and kVM passes use different mechanisms. |
27
+ | **Partial failure** | Ordinary undefinedness during execution, distinct from a schema contradiction or system error. |
28
+ | **Object / library** | Stored compiled definitions: `.ko` has an entry relation; `.klib` has no main entry. |
29
+ | **KIR-P** | Portable relation and pattern export from compiled objects. |
30
+ | **kVM** | Register-based execution representation, with polymorphic templates and specialized artifacts. |
31
+ | **PKIR** | A separate experimental representation using schema states and layout witnesses for structural access. |
32
+
33
+ A contract's input pattern is a static constraint, not necessarily the exact
34
+ mathematical domain of the relation. A relation can be undefined for values
35
+ whose schemas satisfy that constraint.
36
+
37
+ Canonicalization normalizes structural graphs; the implementation does not
38
+ provide general semantic equality of programs. For patterns, distinguish the
39
+ canonical skeleton from the routing constraints of an alias.
40
+
41
+ See [patterns](PATTERNS.md), [file formats](FILE_FORMATS.md), and
42
+ [compiler architecture](ARCHITECTURE.md) for the corresponding details.