@fraczak/k 8.4.1 → 8.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/DOCS/ARCHITECTURE.md +83 -0
  3. package/DOCS/CODECS.md +93 -204
  4. package/DOCS/DICTIONARY.md +42 -1241
  5. package/DOCS/FILE_FORMATS.md +170 -625
  6. package/DOCS/GETTING_STARTED.md +164 -0
  7. package/DOCS/KIR_V1.md +22 -33
  8. package/DOCS/KVM_EXECUTION_MODEL.md +88 -481
  9. package/DOCS/PATTERNS.md +155 -138
  10. package/DOCS/POLYMORPHIC_IR.md +83 -101
  11. package/DOCS/PROFILING_AND_TRACING.md +52 -166
  12. package/DOCS/README.md +35 -0
  13. package/DOCS/REPL.md +100 -377
  14. package/DOCS/TEXTUAL_VALUES.md +53 -81
  15. package/DOCS/TYPE_DERIVATION.md +95 -234
  16. package/DOCS/book-combined.md +3786 -0
  17. package/Examples/arithmetics.k +45 -59
  18. package/Examples/djson.k +102 -112
  19. package/Examples/karatsuba-mult.k +2 -3
  20. package/Examples/list.k +6 -7
  21. package/Examples/nat.k +6 -6
  22. package/Examples/poly.k +45 -45
  23. package/LICENSE +15 -0
  24. package/README.md +72 -410
  25. package/backends/llvm/README.md +75 -97
  26. package/backends/wasm/README.md +88 -66
  27. package/canonical-pattern.mjs +7 -3
  28. package/codecs/README.md +23 -261
  29. package/codecs/WIRE_FORMAT.md +132 -0
  30. package/core.k +5 -15
  31. package/named-patterns.mjs +19 -7
  32. package/objects/README.md +24 -109
  33. package/package.json +8 -3
  34. package/paper/Makefile +17 -0
  35. package/paper/k-paper.pdf +0 -0
  36. package/paper/k-paper.tex +435 -0
  37. package/parser.jison +0 -10
  38. package/parser.mjs +32 -43
  39. package/repl.mjs +74 -29
  40. package/scripts/benchmark-idempotency.mjs +3 -3
  41. package/scripts/run-tests.mjs +1 -1
  42. package/scripts/test-package.mjs +64 -0
  43. package/tests/README.md +66 -46
  44. package/tests/code-derivation/core.mjs +61 -0
  45. package/tests/helpers/cli.mjs +45 -0
  46. package/tests/integration.sh +2 -3
  47. package/tests/test-arithmetics.mjs +47 -237
  48. package/tests/test-djson-methods.mjs +71 -275
  49. package/tests/test-hash-normalization.mjs +22 -1
  50. package/tests/test-karatsuba.mjs +18 -126
  51. package/tests/test-named-patterns.mjs +174 -621
  52. package/tests/test-paper-examples.mjs +90 -0
  53. package/tests/test-poly.mjs +2 -2
  54. package/tests/test-repl-html.mjs +2 -2
  55. package/tests/test-repl.mjs +49 -41
  56. package/tests/test.mjs +27 -68
  57. package/AGENTS.md +0 -35
  58. package/CLAUDE.md +0 -64
  59. package/DOCS/BIG_PICTURE.md +0 -439
  60. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  61. package/DOCS/CANONICAL_PATTERNS.md +0 -362
  62. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  63. package/DOCS/CONVERGENCE.md +0 -123
  64. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  65. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  66. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  67. package/DOCS/Makefile +0 -99
  68. package/DOCS/NAMED_PATTERNS.md +0 -361
  69. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  70. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  71. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -134
  72. package/DOCS/book/01-introduction.md +0 -48
  73. package/DOCS/book/02-syntax-and-values.md +0 -110
  74. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  75. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  76. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  77. package/DOCS/book/06-values-in-memory.md +0 -1085
  78. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  79. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  80. package/DOCS/book/09-compiler-architecture.md +0 -160
  81. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  82. package/DOCS/book/14-canonical-serialization.md +0 -176
  83. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  84. package/DOCS/book/overview.txt +0 -68
  85. package/DOCS/book.md +0 -50
  86. package/Examples/bnat.k +0 -308
  87. package/Examples/buda.k +0 -66
  88. package/Examples/byte.k +0 -35
  89. package/Examples/code.k +0 -43
  90. package/Examples/vhdl_to_k.k +0 -67
  91. package/JOURNAL.md +0 -288
  92. package/TODO.md +0 -107
  93. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  94. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  95. package/backends/wasm/demo_ieee.mjs +0 -318
  96. package/browser/vfs-data.mjs +0 -21
  97. package/codecs/BINARY_FORMAT.md +0 -53
  98. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  99. package/codecs/pandoc.css +0 -71
  100. package/tests/code-derivation/blowup.mjs +0 -25
  101. package/tests/code-derivation/bnat.mjs +0 -11
  102. package/tests/code-derivation/dot.mjs +0 -37
  103. package/tests/code-derivation/index.mjs +0 -20
  104. package/tests/code-derivation/loop.mjs +0 -17
  105. package/tests/code-derivation/nat.mjs +0 -10
  106. package/tests/code-derivation/not-not.mjs +0 -14
  107. package/tests/code-derivation/product.mjs +0 -22
  108. package/tests/code-derivation/rlz.mjs +0 -13
  109. package/tests/test-fingerprint.mjs +0 -38
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fraczak/k",
3
- "version": "8.4.1",
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