@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
package/objects/README.md CHANGED
@@ -1,112 +1,27 @@
1
- # objects/
2
-
3
- CLI tools for compiling and inspecting k object files (`.ko`), library
4
- files (`.klib`), and polymorphic kVM template files (`.kvm`).
5
-
6
- ## Tools
7
-
8
- ### `k-compile`
9
-
10
- Compiles `.k` source into an executable object file (`.ko`), library
11
- file (`.klib`), or polymorphic kVM backend artifact (`.kvm`). Output
12
- format is inferred from the output extension, or from `--format`.
13
-
14
- ```bash
15
- k-compile [--lib lib-file] [--export spec]... \
16
- [--format ko|klib|kvm] [source-snippet | input-file [output-file]]
17
- ```
18
-
19
- Existing input paths are read as files. A non-existing input with `.k`,
20
- `.ko`, or `.klib` extension is reported as a missing file; otherwise it
21
- is compiled as inline k source, in the same style as `k.mjs`.
22
-
23
- `.kvm` is a polymorphic kVM template artifact (`layer: "KVM-P"`). It
24
- carries relational function definitions, principal pattern graphs,
25
- and lowered kVM instruction streams ready for runtime specialization
26
- when enveloped values arrive (`specializeKVM`).
27
-
28
- When linking a `--lib` dependency, all relations are loaded under their
29
- canonical content-addressed hashes (`@hash`). To use human-readable
30
- alias names in an expression or script, explicitly map them into the
31
- local scope using `--export <alias>` or
32
- `--export <libAlias>:<localAlias>`.
33
- Alternatively, canonical `@hash` names may always be referenced directly.
34
-
35
- ### `k-decompile`
36
-
37
- Decompiles a `.ko` or `.klib` back into human-readable k source.
38
-
39
- ```bash
40
- k-decompile [object-file [k-file]]
41
- ```
42
-
43
- ### `k-extract-aliases`
44
-
45
- Extracts metadata aliases from a `.ko` or `.klib` as a valid k
46
- definition snippet. Output is grouped by metadata type (`code`, then
47
- `rel`), then sorted by alias name and `compiledAt`.
48
-
49
- ```bash
50
- k-extract-aliases [object-file [k-file]]
51
- ```
52
-
53
- ### `k-inspect-object`
54
-
55
- Inspects a `.ko` or `.klib`. By default it prints a compact object
56
- summary. With `--kir`, it prints the current KIR-P export used by
57
- backend experiments.
58
-
59
- ```bash
60
- k-inspect-object [--summary | --kir] [object-file]
61
- ```
62
-
63
- For scripts that only need KIR-P export, `k-kir [object-file]` is the
64
- direct exporter backed by `kir.mjs`.
65
-
66
- ### `k-validate-object`
67
-
68
- Validates a `.ko` or `.klib` object and its derived KIR-P export. With
69
- `--kir`, it validates an already exported KIR-P artifact.
70
-
71
- ```bash
72
- k-validate-object [--kir] [input-file]
1
+ # Object tools
2
+
3
+ Run these modules with `node` from a checkout, or use the installed names after
4
+ `npm link`.
5
+
6
+ | Command | Purpose |
7
+ | --- | --- |
8
+ | `k-compile` | Compile source into `.ko`, `.klib`, or `.kvm`; infer output format from the extension |
9
+ | `k-decompile` | Render object/library definitions as k source |
10
+ | `k-extract-aliases` | Recover aliases as source definitions |
11
+ | `k-inspect-object` | Inspect a summary, or export KIR-P with `--kir` |
12
+ | `k-validate-object` | Validate an object, library, or exported KIR-P (`--kir`) |
13
+ | `k-kir` | Export KIR-P directly |
14
+
15
+ ```sh
16
+ node objects/compile.mjs '{} |ok' /tmp/k-ok.ko
17
+ node objects/inspect.mjs /tmp/k-ok.ko
18
+ node objects/validate.mjs /tmp/k-ok.ko
73
19
  ```
74
20
 
75
- The installed names are `k-` plus the source basename without `.mjs`.
76
- Every installed object binary supports `-h` and `--help`.
77
-
78
- ## Current Format Notes
79
-
80
- - For full specifications, see
81
- [`DOCS/FILE_FORMATS.md`](../DOCS/FILE_FORMATS.md).
82
- - Both `.ko` and `.klib` are ahead-of-time (AOT) type-checked artifacts.
83
- Parsing, relation expansion, type derivation, and constraint
84
- convergence are completed in advance.
85
- - `.klib` files are plain UTF-8 JSON, not binary containers
86
- (`main: null`).
87
- - `.ko` files use the `KOBJ\n` binary header followed by a JSON payload
88
- (`main: "__main__"`).
89
- - There is no object payload version field in either format.
90
- - `typeDerivation` belongs only to relations and currently stores only
91
- `status`.
92
- - Source `start` / `end` ranges live on `meta[hash].origins[]` entries.
93
- - Origin entries do not have `kind`; the metadata entry has `type: "code"`
94
- or `type: "rel"`.
95
- - Stored relation bodies do not include generated input/output filters.
96
- - KIR-P is available as an inspection/export contract; it does not change
97
- the stored `.ko` or `.klib` payload.
98
- - `.kvm` is a polymorphic backend template artifact (`layer: "KVM-P"`),
99
- lowered from KIR-P for runtime execution and JIT specialization.
100
-
101
- ## Further reading
21
+ `--lib` loads a dependency. It does not select library output; use a `.klib`
22
+ output filename or `--format klib`. Friendly library names need explicit
23
+ `--export` mappings.
102
24
 
103
- - [DOCS/FILE_FORMATS.md](../DOCS/FILE_FORMATS.md) — guide to
104
- .k, .ko, .klib, and .kvm formats
105
- - [DOCS/OBJECT_FILE_AND_PATTERN.md](../DOCS/OBJECT_FILE_AND_PATTERN.md) —
106
- object file format and pattern encoding
107
- - [DOCS/KIR_V1.md](../DOCS/KIR_V1.md) — KIR-P inspection/export contract
108
- for backends
109
- - [DOCS/TYPE_DERIVATION.md](../DOCS/TYPE_DERIVATION.md) — type
110
- derivation (what compilation skips when loading a `.ko`/`.klib`)
111
- - [DOCS/CONVERGENCE.md](../DOCS/CONVERGENCE.md) — convergence strategies
112
- for type inference
25
+ The [file-format reference](../DOCS/FILE_FORMATS.md) is the source for container
26
+ fields, executable/library distinctions, aliases, and complete workflows.
27
+ [KIR-P](../DOCS/KIR_V1.md) documents the portable backend export.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fraczak/k",
3
- "version": "8.4.0",
3
+ "version": "8.5.0",
4
4
  "description": "k — a language for content-addressable schemas and data transformations over algebraic data types (products and tagged unions); includes runtime, contract derivation, REPL, and codec toolchain",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -11,7 +11,7 @@
11
11
  "./*": "./*"
12
12
  },
13
13
  "scripts": {
14
- "prepare": "jiwson -m es6 parser.jison -o parser.mjs; jiwson -m es6 valueParser.jison -o valueParser.mjs; ",
14
+ "prepare": "jiwson -m es6 parser.jison -o parser.mjs && jiwson -m es6 valueParser.jison -o valueParser.mjs",
15
15
  "test": "node scripts/run-tests.mjs",
16
16
  "test:backends": "node backends/llvm/scripts/run-tests.mjs && node backends/wasm/scripts/run-tests.mjs",
17
17
  "test:llvm": "node backends/llvm/scripts/run-tests.mjs",
@@ -36,7 +36,9 @@
36
36
  "perf:idempotency": "node scripts/benchmark-idempotency.mjs",
37
37
  "deps:graph": "node scripts/generate-dependency-graph.mjs",
38
38
  "compare": "node harness/cli.mjs",
39
- "build:repl-html": "node scripts/build-repl-html.mjs"
39
+ "build:repl-html": "node scripts/build-repl-html.mjs",
40
+ "prepublishOnly": "npm test",
41
+ "test:package": "node scripts/test-package.mjs"
40
42
  },
41
43
  "repository": {
42
44
  "type": "git",
@@ -77,5 +79,8 @@
77
79
  "devDependencies": {
78
80
  "esbuild": "^0.28.2",
79
81
  "jiwson": "^0.1.2"
82
+ },
83
+ "engines": {
84
+ "node": ">=18"
80
85
  }
81
86
  }
package/paper/Makefile ADDED
@@ -0,0 +1,17 @@
1
+ PAPER = k-paper
2
+ TEX = pdflatex -interaction=nonstopmode
3
+
4
+ .PHONY: all pdf clean arxiv
5
+
6
+ all: pdf
7
+
8
+ pdf: $(PAPER).tex
9
+ $(TEX) $(PAPER).tex
10
+ $(TEX) $(PAPER).tex
11
+
12
+ arxiv: pdf
13
+ tar -czvf arxiv-submission.tar.gz $(PAPER).tex
14
+ @echo "Created arxiv-submission.tar.gz for arXiv upload"
15
+
16
+ clean:
17
+ rm -f $(PAPER).aux $(PAPER).log $(PAPER).out $(PAPER).toc $(PAPER).pdf arxiv-submission.tar.gz
Binary file
@@ -0,0 +1,435 @@
1
+ \documentclass[11pt,a4paper]{article}
2
+
3
+ % --- Packages ---
4
+ \usepackage[margin=1in]{geometry}
5
+ \usepackage[T1]{fontenc}
6
+ \usepackage[utf8]{inputenc}
7
+ \usepackage{lmodern}
8
+ \usepackage{amsmath,amssymb,amsthm}
9
+ \usepackage{microtype}
10
+ \usepackage{booktabs}
11
+ \usepackage{xcolor}
12
+ \usepackage{listings}
13
+ \usepackage{cite}
14
+ \usepackage[colorlinks=true,
15
+ linkcolor=blue!70!black,
16
+ citecolor=blue!70!black,
17
+ urlcolor=blue!70!black]{hyperref}
18
+
19
+ % --- Theorem Environments ---
20
+ \newtheorem{theorem}{Theorem}[section]
21
+ \newtheorem{definition}[theorem]{Definition}
22
+ \newtheorem{invariant}[theorem]{Invariant}
23
+
24
+ % --- Code Listings Configuration ---
25
+ \lstdefinelanguage{k}{
26
+ morecomment=[l]{--},
27
+ morekeywords={bit, bits, pair, list, same_pair, closed_same_pair, any_pair, peel, peel_bad, half_add, not, edge, edges, node, pattern, string, unicode},
28
+ sensitive=true,
29
+ basicstyle=\ttfamily\small,
30
+ keywordstyle=\bfseries\color{blue!75!black},
31
+ commentstyle=\itshape\color{gray!75!black},
32
+ stringstyle=\color{green!50!black},
33
+ breaklines=true,
34
+ tabsize=2,
35
+ columns=fullflexible,
36
+ keepspaces=true,
37
+ frame=single,
38
+ rulecolor=\color{gray!30},
39
+ backgroundcolor=\color{gray!5},
40
+ aboveskip=0.8em,
41
+ belowskip=0.8em
42
+ }
43
+
44
+ \lstset{language=k}
45
+
46
+ % --- Metadata ---
47
+ \title{\textbf{K: the programming language}}
48
+ \author{
49
+ \textbf{Wojciech Fraczak}\\
50
+ \texttt{fraczak@gmail.com}
51
+ }
52
+ \date{October 2026}
53
+
54
+ \begin{document}
55
+
56
+ \maketitle
57
+
58
+ \begin{abstract}
59
+ K is a minimalist programming language inspired by the algebraic principles of Milner's CCS and Hoare's CSP. Computation is modeled as partial functions (called \emph{relations}) over rooted, edge-labeled trees, built from three fundamental combinators: sequential composition, concurrent choice, and parallel composition. Together with elementary tree navigation and construction, these combinators replace the control-flow constructs, variable bindings, and built-in primitive types of traditional programming languages.
60
+
61
+ In K, both partial functions (relations) and their types (called \emph{patterns}) are content-addressable. Because K is Turing-complete, semantic function equality is undecidable; however, patterns denote regular tree languages, which admit an effective canonical representation. Through parameterized \emph{Named Patterns}, K factors schemas into canonical linear skeletons and parameter routing vectors, enabling exact structural type equivalence, global cryptographic deduplication, and static verification with zero runtime overhead.
62
+ \end{abstract}
63
+
64
+ \vspace{0.5em}
65
+ \noindent\textbf{Keywords:} Relational programming, Process calculi, Content-addressable code, Regular tree languages, Type systems.
66
+
67
+ \vspace{1em}
68
+
69
+ % ============================================================================
70
+ \section{Introduction}
71
+ % ============================================================================
72
+
73
+ K is a relational programming language inspired by the algebraic principles of Milner's Calculus of Communicating Systems (CCS)~\cite{milner1989ccs} and Hoare's Communicating Sequential Processes (CSP)~\cite{hoare1985csp}. Computation in K is modeled as first-order partial functions (called \emph{relations}) over \textbf{rooted, edge-labeled trees}, structured around three fundamental algebraic composition modes:
74
+
75
+ \begin{enumerate}
76
+ \item \textbf{Transformation Chaining}: feeding the output tree of one relation as the input to the next (sequential composition).
77
+ \item \textbf{Concurrent Choice}: evaluating alternative relations and selecting the first one defined on the input (alternative composition).
78
+ \item \textbf{Parallel Composition}: evaluating multiple relations in parallel on the same input tree and assembling their results under distinct labeled branches of a new tree.
79
+ \end{enumerate}
80
+
81
+ Together with elementary tree navigation and construction, these three combinators replace the disparate mechanisms of traditional programming languages---such as conditional branching, local variable bindings, argument passing, and built-in primitive types---within a single uniform algebra.
82
+
83
+ Within this framework, types (called \emph{patterns}) are regular tree languages that can be embedded directly into relations as domain-restricting identity filters. The compiler verifies these structural contracts statically and uses them as inductive witnesses to ensure type derivation converges, leaving execution free of runtime type checks.
84
+
85
+ This work presents the K relational calculus (Section~2), its static pattern and type system (Section~3), \textbf{Named Patterns} and the Linear Canonical Theorem for global cryptographic content-addressing (Sections~4--6), and K's self-describing binary serialization format (Appendix~A).
86
+
87
+ % ============================================================================
88
+ \section{The Core Calculus: Schemas, Documents, and Relations}
89
+ % ============================================================================
90
+
91
+ \subsection{Documents and Schemas}
92
+
93
+ K programs compute over \textbf{documents}, mathematically defined as finite, rooted, edge-labeled trees. Crucially, \emph{a document is always interpreted in the context of a schema} (called a \emph{pattern} in K)---a deterministic regular tree automaton~\cite{comon2007tree} defining the language of admissible trees.
94
+
95
+ Schemas and documents are built from two dual structural constructors:
96
+ \begin{itemize}
97
+ \item \textbf{Products}: In the context of a product schema $\{ S_1 \;\text{label}_1, S_2 \;\text{label}_2, \dots \}$, a product document consists of labeled outgoing edges pointing to sub-documents, each conforming to its respective sub-schema $S_i$. The empty product \lstinline|{}| corresponds to the unique \textbf{unit document}.
98
+ \item \textbf{Variants (Unions)}: In the context of a union schema $\langle S_1 \;\text{tag}_1, S_2 \;\text{tag}_2, \dots \rangle$, a variant document selects a tag $\text{tag}_k$ and carries a payload document conforming to sub-schema $S_k$. A variant document only has meaning within a union schema specifying its admissible alternatives.
99
+ \end{itemize}
100
+
101
+ At system boundaries, every value is a self-describing pair of $(\text{schema}, \text{document})$.
102
+
103
+ \subsection{Relations: Three Combinators}
104
+
105
+ Computation in K is expressed as first-order partial relations that transform an incoming document into an outgoing document under their respective schemas. In addition to transformation chaining (functional composition), K adopts from process calculi (Milner's CCS and Hoare's CSP) two structural constructions: concurrent choice and parallel composition. In the following, $f_1, f_2, \dots, f_n$ denote K relations, $\text{label}_1, \text{label}_2, \dots$ denote outgoing edge labels, and $P_1, P_2, \dots$ denote the analogous process expressions in CCS and CSP:
106
+
107
+ \begin{enumerate}
108
+ \item \textbf{Transformation Chaining \texttt{(f1 f2 ...)}}: Chains relations such that the output document of $f_1$ is passed as input to $f_2$, and so on ($f_n \circ \dots \circ f_1$, corresponding to \emph{Sequential Composition} $P_1 ; P_2 ; \dots$ in CSP). An empty composition \lstinline|()| denotes the identity relation.
109
+
110
+ \item \textbf{Concurrent Choice \texttt{< f1, f2, ... >}}: Evaluates alternative relations (corresponding to \emph{Alternative Composition} $P_1 + P_2 + \dots$ in CCS, or $P_1 \Box P_2 \Box \dots$ in CSP): if $f_1$ is defined on the incoming document, its output is produced; otherwise, computation proceeds to $f_2$. An empty choice \lstinline|<>| is undefined everywhere.
111
+
112
+ \item \textbf{Parallel Composition \texttt{\{ f1 label1, f2 label2, ... \}}}: Evaluates relations in parallel (corresponding to \emph{Parallel Composition} $P_1 \mid P_2 \mid \dots$ in CCS, or $P_1 \parallel P_2 \parallel \dots$ in CSP) on the same incoming document $x$, constructing a product document whose labeled edges $\text{label}_1, \text{label}_2, \dots$ point to the respective results $f_1(x), f_2(x), \dots$. If any branch $f_i$ is undefined, the entire product relation is undefined.
113
+ \end{enumerate}
114
+
115
+ Elementary relations navigate and construct document trees:
116
+ \begin{itemize}
117
+ \item \textbf{Product projection \texttt{.label}}: traverses edge \lstinline|label|, returning the sub-document.
118
+ \item \textbf{Variant projection \texttt{/tag}}: traverses variant \lstinline|tag|, returning its payload document if the tag matches.
119
+ \item \textbf{Variant constructor \texttt{|tag}}: constructs a variant document by tagging the incoming document with \lstinline|tag|.
120
+ \end{itemize}
121
+
122
+ Under these combinators:
123
+ \begin{itemize}
124
+ \item The empty product \lstinline|{}| is a relation that transforms any input into the unit document.
125
+ \item Constant relations combine \lstinline|{}| with constructor relations: for example, \lstinline!{} |true! produces the boolean true document, and \lstinline!{} |zero! produces the Peano zero document.
126
+ \end{itemize}
127
+
128
+ % ============================================================================
129
+ \section{Patterns: Compile-Time Prototypes and Inductive Witnesses}
130
+ % ============================================================================
131
+
132
+ A \textbf{pattern} defines a regular tree language accepted by a deterministic tree automaton~\cite{hosoya2003regular}. Syntactically, a pattern $P$ is constructed from:
133
+ \begin{itemize}
134
+ \item \textbf{Product and union patterns}: $\{ P_1 \; l_1, \dots, P_n \; l_n \}$ and $\langle P_1 \; t_1, \dots, P_n \; t_n \rangle$, which may optionally include a literal ellipsis \lstinline|...| (e.g., \lstinline|< P1 t1, ... >|) to denote an \emph{open} product or union permitting additional unlisted fields or tags;
135
+ \item \textbf{Wildcards and pattern variables}: bare identifiers \lstinline|X|, which act as polymorphic pattern variables unifying all occurrences of \lstinline|X|, and the wildcard \lstinline|(...)|, which acts as an anonymous pattern variable;
136
+ \item \textbf{Recursive bindings}: \lstinline|P = X|, which binds the pattern node $P$ to \lstinline|X| so that occurrences of \lstinline|X| inside $P$ form cycles in the automaton.
137
+ \end{itemize}
138
+
139
+ For example, the pattern
140
+ \begin{lstlisting}[language=k]
141
+ < {} nil, { (...) car, List cdr } cons > = List
142
+ \end{lstlisting}
143
+ describes a linked list: a list is a variant that is either \lstinline|nil| (carrying the empty product \lstinline|{}|) or \lstinline|cons| (carrying a product with a head element under label \lstinline|car| and a recursive tail list \lstinline|List| under label \lstinline|cdr|). Because the cycle returns to the same \lstinline|cons| node, all elements of the list share the same type.
144
+
145
+ \subsection{Filters as Static Prototypes}
146
+
147
+ In languages like ML, a first-order function $f$ is typed via a separate signature $f : \text{In} \to \text{Out}$. In K, a pattern $P$ is embedded directly into relation syntax as a filter \lstinline|?P|---an identity relation whose domain and codomain are restricted to $P$---so a full signature is written simply as \lstinline|(?In f ?Out)|. This uniform notation is particularly convenient for partial inline annotations: for example, in \lstinline|(f1 f2 ?P f3)|, the filter \lstinline|?P| witnesses only the output of \lstinline|f2| and the input of \lstinline|f3|. Because the compiler verifies all filter constraints statically, \lstinline|?P| is a pure no-op at runtime, incurring zero execution overhead.
148
+
149
+ \subsection{Inductive Witnesses in Contract Derivation}
150
+
151
+ The K compiler derives a contract $P_{\text{in}} \to P_{\text{out}}$ for every relation via fixed-point iteration. Because elementary projections such as \lstinline|/0| and \lstinline|/+1| only infer \emph{open} variant patterns (\lstinline|< ... >|), and open nodes at different depths cannot be merged automatically by state minimization, an unannotated recursive definition such as
152
+ \begin{lstlisting}[language=k]
153
+ peel_bad = < /+1 peel_bad, /0 |0 >;
154
+ \end{lstlisting}
155
+ fails to converge, unrolling an infinite chain of nested open unions \lstinline|< X1 0, < X1 0, < ... > +1, ... > +1, ... >|.
156
+
157
+ By inserting inline filter annotations sharing a pattern variable \lstinline|X|:
158
+ \begin{lstlisting}[language=k]
159
+ peel = ?X < /+1 ?X peel, /0 |0 >;
160
+ \end{lstlisting}
161
+ the two occurrences of \lstinline|?X| unify the relation's input domain with the payload of \lstinline|/+1|. This explicitly witnesses the inductive cycle and allows type derivation to converge immediately to the polymorphic contract:
162
+ \begin{lstlisting}[language=k]
163
+ ?< X1 0, X0 +1, ... > = X0 --> ?< X1 0, ... >
164
+ \end{lstlisting}
165
+
166
+ % ============================================================================
167
+ \section{Named Patterns and Parameterized Schemas}
168
+ % ============================================================================
169
+
170
+ K provides named patterns as parameterized regular tree templates:
171
+
172
+ \begin{lstlisting}[language=k]
173
+ -- Arity-0 leaf patterns:
174
+ bit[] = < {} 0, {} 1 >;
175
+ bits[] = < {} _, B 0, B 1 > = B;
176
+
177
+ -- Parameterized product:
178
+ pair[A, B] = { A first, B second };
179
+
180
+ -- Inductive linked list:
181
+ list[X] = < {} nil, { X car, Y cdr } cons > = Y;
182
+ \end{lstlisting}
183
+
184
+ Square brackets \lstinline|[...]| provide deterministic lexical disambiguation: a bare identifier (\lstinline|X|) represents a variable, whereas a bracketed identifier (\lstinline|bit[]| or \lstinline|list[X]|) represents a pattern template application.
185
+
186
+ % ============================================================================
187
+ \section{Linear Canonical Normalization}
188
+ % ============================================================================
189
+
190
+ In a content-addressed system~\cite{merkle1987sig}, every entity is identified by its cryptographic hash \lstinline|@hash|. A major problem arises when parameterized patterns enforce equality constraints:
191
+
192
+ \begin{lstlisting}[language=k]
193
+ pair[A, B] = { A first, B second };
194
+ same_pair[T] = { T first, T second };
195
+ closed_same_pair[] = { T first, T second };
196
+ any_pair[] = { (...) first, (...) second };
197
+ \end{lstlisting}
198
+
199
+ All four patterns describe a binary record with fields \lstinline|first| and \lstinline|second|. If equality constraints were baked into the canonical graph, the compiler would produce four distinct graphs, fracturing global deduplication.
200
+
201
+ \subsection{The Linear Canonical Theorem}
202
+
203
+ K solves this by factoring every pattern into two independent parts:
204
+
205
+ \begin{equation}
206
+ \text{Pattern} = \bigl(\mathcal{S}_{\text{canonical}},\, \vec{\rho}\bigr)
207
+ \end{equation}
208
+
209
+ \begin{enumerate}
210
+ \item \textbf{Linear Canonical Skeleton ($\mathcal{S}_{\text{canonical}}$)}: Leaves are \textbf{separated linearly}. Every open slot is assigned a distinct port $X_0, X_1, \dots$ in depth-first order.
211
+ \item \textbf{Parameter Routing Vector ($\vec{\rho}$)}: An external vector routing caller parameters, diagonalized equalities, and wildcards.
212
+ \end{enumerate}
213
+
214
+ The canonical skeleton for all four pair variations is identical:
215
+ \begin{lstlisting}[language=k]
216
+ @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[X0, X1] = {
217
+ X0 first, X1 second
218
+ };
219
+ \end{lstlisting}
220
+
221
+ Their routing vectors capture their specific constraints:
222
+ \begin{lstlisting}[basicstyle=\ttfamily\small]
223
+ pair[A, B] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[A, B]
224
+ same_pair[T] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T, T]
225
+ closed_same_pair[] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[T, T]
226
+ any_pair[] = @KqTBNkznjWWwync2Mm94XjCez63neJBJtgYcJJEE5kEm[(...), (...)]
227
+ \end{lstlisting}
228
+
229
+ \subsection{Benefits of Linear Decomposition}
230
+
231
+ \begin{itemize}
232
+ \item \textbf{Global Deduplication}: Structurally isomorphic shapes share the exact same \lstinline|@hash| across all libraries and programs.
233
+ \item \textbf{Affine Multi-Hole Functors}: Skeletons act as pure multi-hole functors $\text{Type}^n \to \text{Type}$.
234
+ \item \textbf{Zero Loss of Type Safety}: When \lstinline|same_pair[bit[]]| is instantiated, the parameter $T$ routes to both ports, enforcing equality at the call site while preserving the shared linear canonical graph.
235
+ \end{itemize}
236
+
237
+ % ============================================================================
238
+ \section{Variables: Ports, Knots, and Inductive Integrity}
239
+ % ============================================================================
240
+
241
+ Within any pattern template, variables are classified into three orthogonal categories:
242
+
243
+ \begin{enumerate}
244
+ \item \textbf{External Ports ($\forall$)}: Variables declared in header \lstinline|[P1, ..., Pn]|, representing open slots supplied by caller arguments.
245
+ \item \textbf{Internal Existential Variables ($\exists$)}: Free variables within the template body asserting structural equality across multiple fields.
246
+ \item \textbf{Cycle Knots ($\mu$)}: Variables bound via \lstinline|= KnotName|, forming directed back-edges that define recursive fixed points.
247
+ \end{enumerate}
248
+
249
+ \subsection{Knot Encapsulation and Inductive Integrity}
250
+
251
+ Cycle knots represent the internal topology of recursive definitions. In:
252
+ \begin{lstlisting}[language=k]
253
+ list[X] = < {} nil, { X car, Y cdr } cons > = Y;
254
+ \end{lstlisting}
255
+ \lstinline|= Y| binds the root union, and \lstinline|Y| in field \lstinline|cdr| refers back to this node, closing the inductive cycle.
256
+
257
+ To preserve inductive integrity, knots are strictly encapsulated as internal fixed points. Parameter substitution operates exclusively on external ports (\lstinline|X|), ensuring that recursive cycles remain structurally intact across all instantiations.
258
+
259
+ \subsection{The Knot Invariant}
260
+
261
+ \begin{invariant}[Knot Invariant]
262
+ Formal parameters and cycle knots occupy disjoint namespaces: parameters and knots remain strictly segregated, guaranteeing that internal recursive wiring remains permanently intact.
263
+ \end{invariant}
264
+
265
+ % ============================================================================
266
+ \section{A Complete Example: Bit Arithmetic}
267
+ % ============================================================================
268
+
269
+ The following self-contained K program illustrates the interplay of documents, relations, and compile-time patterns:
270
+
271
+ \begin{lstlisting}[language=k]
272
+ -- 1. Patterns (compile-time prototypes)
273
+ bit[] = < {} 0, {} 1 >;
274
+
275
+ -- 2. Constructors
276
+ 0 = {} |0 ?bit[];
277
+ 1 = {} |1 ?bit[];
278
+ not = < /0 1, 0 >;
279
+
280
+ -- 3. Half adder: prototype ?{ bit[] a, bit[] b }
281
+ half_add = ?{ bit[] a, bit[] b }
282
+ <
283
+ { .a /0 if, { .b sum, 0 carry } then } .then,
284
+ { .b not sum, .b carry }
285
+ >;
286
+ \end{lstlisting}
287
+
288
+ Here, \lstinline|?{ bit[] a, bit[] b }| establishes the static input prototype. The two rules concisely handle both cases of \lstinline|a|:
289
+ \begin{enumerate}
290
+ \item When \lstinline|a| is \lstinline|0|: \lstinline|{ .a /0 if, ... } .then| succeeds, producing sum \lstinline|b| and carry \lstinline|0|.
291
+ \item When \lstinline|a| is \lstinline|1|: choice selects the second branch, producing sum \lstinline|.b not| and carry \lstinline|b|.
292
+ \end{enumerate}
293
+
294
+ % ============================================================================
295
+ \section{Conclusion}
296
+ % ============================================================================
297
+
298
+ K unifies data, computation, and types into a minimal, content-addressed framework inspired by algebraic process calculi:
299
+ \begin{itemize}
300
+ \item \textbf{Documents} are rooted, edge-labeled trees interpreted in the context of schemas.
301
+ \item \textbf{Computation} is partial relations formed by transformation chaining \lstinline|(f1 f2 ...)|, concurrent choice \lstinline|< f1, f2, ... >|, and parallel composition \lstinline|{ f1 label1, f2 label2, ... }|.
302
+ \item \textbf{Types} are patterns acting as static compile-time prototypes and inductive witnesses, with zero runtime overhead.
303
+ \end{itemize}
304
+
305
+ By decomposing named patterns into pure linear canonical skeletons and parameter routing vectors, K achieves maximal cross-codebase deduplication while preserving author-intended equality constraints. The result is a rigorous, expressive, and elegantly minimal foundation for content-addressed programming. An implementation of K is available on GitHub~\cite{k2026github}.
306
+
307
+ % ============================================================================
308
+ \appendix
309
+ \section{Data Serialization and Enveloped Values}
310
+ % ============================================================================
311
+
312
+ \subsection{The Enveloped Value}
313
+
314
+ In K, documents are abstract rooted trees whose structure and interpretation are defined relative to a schema. At execution and transport boundaries, data is represented as an \textbf{enveloped value} (or \emph{framed value}): a self-describing pair
315
+
316
+ \begin{equation}
317
+ (S,\, d)
318
+ \end{equation}
319
+
320
+ \noindent where:
321
+ \begin{itemize}
322
+ \item $S$ is a rooted regular pattern graph defining the schema.
323
+ \item $d$ is a document tree conforming to $S$.
324
+ \end{itemize}
325
+
326
+ The schema $S$ serves as the structural authority for the document $d$. During relation execution, elementary operations propagate and refine this envelope:
327
+ \begin{itemize}
328
+ \item \textbf{Product projection \texttt{.label}}: extracts the target sub-document and advances the schema to the corresponding field sub-schema.
329
+ \item \textbf{Variant projection \texttt{/tag}}: matches the variant tag and advances the schema to the payload sub-schema.
330
+ \item \textbf{Parallel composition \texttt{\{ f1 l1, ... \}}}: constructs a product document paired with the product schema of its branches.
331
+ \item \textbf{Variant constructor \texttt{|tag}}: constructs a tagged variant document paired with the union schema containing that tag.
332
+ \end{itemize}
333
+
334
+ \subsection{Self-Hosted Schema Representation}
335
+
336
+ Schemas in K are first-class documents defined directly within the language. The standard core library \texttt{core.k} defines the canonical schema for patterns:
337
+
338
+ \begin{lstlisting}[language=k]
339
+ edge[] = { string[] label, bits[] target };
340
+ edges[] = < {} nil, { edge[] car, E cdr } cons > = E;
341
+ node[] = <
342
+ {} any,
343
+ edges[] open-product,
344
+ edges[] open-union,
345
+ edges[] closed-product,
346
+ edges[] closed-union
347
+ >;
348
+ pattern[] = < {} nil, { node[] car, P cdr } cons > = P;
349
+ \end{lstlisting}
350
+
351
+ A schema is represented as an inductive list of canonical nodes:
352
+ \begin{itemize}
353
+ \item Node 0 designates the root of the schema automaton.
354
+ \item Edges specify labeled transitions to target node indices, encoded as bit paths (\lstinline|bits[]|).
355
+ \item Nodes distinguish between products and unions, as well as open and closed structural contracts.
356
+ \end{itemize}
357
+
358
+ Because \lstinline|pattern[]| is a fixed, universally agreed-upon schema constant, it provides the inductive anchor for all K binary serialization.
359
+
360
+ \subsection{The Canonical Wire Stream}
361
+
362
+ The binary wire representation of an enveloped value $(S, d)$ is a two-stage prefix-free bitstream:
363
+
364
+ \begin{equation}
365
+ \text{Stream} = \text{encode}\bigl(S : \text{pattern}[]\bigr) \; \text{encode}(d : S)
366
+ \end{equation}
367
+
368
+ \begin{enumerate}
369
+ \item \textbf{Schema Header}: The schema $S$ is serialized as a regular K document under the universal singleton schema \lstinline|pattern[]|.
370
+ \item \textbf{Document Payload}: The document $d$ is serialized as a prefix-free bitstream interpreted strictly relative to the decoded schema $S$.
371
+ \end{enumerate}
372
+
373
+ Decoding operates deterministically: the recipient first decodes $S$ using the universal \lstinline|pattern[]| specification, and then uses $S$ to decode the subsequent payload bitstream $d$.
374
+
375
+ \subsection{Prefix-Free Payload Encoding}
376
+
377
+ Given the decoded schema $S$, the document payload $d$ is encoded with maximal compactness:
378
+
379
+ \begin{itemize}
380
+ \item \textbf{Products}: Field values are encoded sequentially in canonical sorted label order:
381
+ \begin{equation}
382
+ \text{encode}(d_1) \; \text{encode}(d_2) \dots \text{encode}(d_k)
383
+ \end{equation}
384
+ Because the schema specifies field identities and ordering, the payload consists exclusively of contiguous field value bits.
385
+ \item \textbf{Variants}: A union alternative is identified by its tag ordinal, encoded in minimal fixed-width bits:
386
+ \begin{equation}
387
+ w = \lceil \log_2(n) \rceil
388
+ \end{equation}
389
+ where $n$ is the union cardinality, followed immediately by the payload document conforming to the selected alternative.
390
+ \item \textbf{Compact Base Cases}:
391
+ \begin{itemize}
392
+ \item The empty product \lstinline|{}| consumes 0 bits.
393
+ \item A singleton variant ($n = 1$) consumes 0 bits.
394
+ \item A boolean choice ($n = 2$, e.g., \lstinline|< {} 0, {} 1 >|) consumes exactly 1 bit.
395
+ \end{itemize}
396
+ \end{itemize}
397
+
398
+ The resulting binary wire format is strictly prefix-free, self-delimiting, and structurally transparent, enabling direct stream processing and lazy sub-document projection.
399
+
400
+ % ============================================================================
401
+ % References
402
+ % ============================================================================
403
+ \begin{thebibliography}{9}
404
+
405
+ \bibitem{milner1989ccs}
406
+ R.~Milner.
407
+ \newblock \emph{Communication and Concurrency}.
408
+ \newblock Prentice Hall, 1989.
409
+
410
+ \bibitem{hoare1985csp}
411
+ C.~A.~R. Hoare.
412
+ \newblock \emph{Communicating Sequential Processes}.
413
+ \newblock Prentice Hall, 1985.
414
+
415
+ \bibitem{hosoya2003regular}
416
+ H.~Hosoya and B.~C. Pierce.
417
+ \newblock Regular expression pattern matching for {XML}.
418
+ \newblock \emph{ACM Transactions on Programming Languages and Systems (TOPLAS)}, 25(2):194--232, 2003.
419
+
420
+ \bibitem{merkle1987sig}
421
+ R.~C. Merkle.
422
+ \newblock A digital signature based on a conventional encryption function.
423
+ \newblock In \emph{Advances in Cryptology --- CRYPTO '87}, pages 369--378. Springer, 1987.
424
+
425
+ \bibitem{comon2007tree}
426
+ H.~Comon, M.~Dauchet, R.~Gilleron, C.~L{\"o}ding, F.~Jacquemard, D.~Lugiez, S.~Tison, and M.~Tommasi.
427
+ \newblock \emph{Tree Automata Techniques and Applications}.
428
+ \newblock Available online: \url{https://tata.gforge.inria.fr/}, 2007.
429
+
430
+ \bibitem{k2026github}
431
+ An implementation of K can be found at GitHub: \url{https://github.com/fraczak/k}.
432
+
433
+ \end{thebibliography}
434
+
435
+ \end{document}
package/parser.jison CHANGED
@@ -215,16 +215,6 @@ filter_
215
215
  end: $5.end
216
216
  };
217
217
  }
218
- | at name
219
- {
220
- $$ = {
221
- type: "pattern_apply",
222
- pattern: "@" + $2.value,
223
- args: [],
224
- start: $1.start,
225
- end: $2.end
226
- };
227
- }
228
218
  ;
229
219
 
230
220
  pattern_args