Working draft · not stableSpecifications include planned features, not blanket implementation or proof claims.
Reading guide · not a second specification

Language guide

Assembled from the README and from SPEC-0001. The words in each section are those sources. Cairn scenario-link regions are omitted here and remain on the specification page. Where the specification describes a planned or illustrative feature, that status is the specification's own.

From the README. Wording unchanged.

Programs as values

Operations run from left to right on a typed stack. Literals push values; words consume values and produce results. For example, 40 2 + leaves 42. Putting code in brackets creates a program without executing its body:

40 2 quote [ + ] compose run

This also leaves 42, but builds the operation as a value first:

StepWhat happens
40 2Push two integers.
quoteCapture 2 in a program that pushes it when run.
[ + ]Construct a program that adds two integers.
composeCombine the two programs: push the captured 2, then add.
runExecute that program with 40 already on the stack.

Composition checks that the programs' stack interfaces fit together. Captured values and resolved definitions stay attached to the resulting program. reflect exposes its normalized recipe as inert Syntax data; inspecting a program does not execute its effects.

The design centers on a few properties:

  • Typed composition. The frontend infers stack types and effects. An independent kernel checks the candidate, and the backend rechecks it before emitting Wasm.
  • Stable meaning. Rebinding a name does not change programs that already refer to its previous definition.
  • Explicit effects and ownership. Effect bounds describe possible host requests. Host authorization is separate; supported component profiles track ownership and transfer of host resources.
  • Optional behavioral proofs. Contracts can describe a program's behavior and be checked using Lean. Ordinary execution does not require a proof.

Excerpt from the language specification. Wording unchanged.

3. Expression syntax and source units

3.1 Expression microprofile

This revision adopts the following expression grammar. Its concrete lexical rules are new draft decisions, not a claim that the RFC had already frozen punctuation.

body        = { expression } ;
expression  = integer | boolean | text | word | quotation ;
quotation   = "[", body, "]" ;
boolean     = "true" | "false" ;
integer     = [ "-" ], ( "0" | nonzero-digit, { digit } ) ;

Whitespace and comments may occur between tokens. Square brackets and double quotes are delimiters. A quotation is one expression; it may contain nested quotations. An empty body is valid.

A source unit is UTF-8. Outside text literals, ASCII space, tab, carriage return, and line feed separate tokens. Non-ASCII whitespace is not silently normalized.

Requirement: K-SYN-04

r[K-SYN-04]

K-SYN-04. The lexer MUST apply the following comment rules. Outside text literals, # begins a comment through the next carriage return, line feed, or end of input. It terminates a preceding token even without whitespace. Inside a text literal, # is ordinary text. This revision does not support block comments.

A word token begins with an ASCII letter, underscore, or one of + - * / = < > ? !. Its remaining characters can additionally include ASCII digits and .. The maximal token is scanned before classification. A complete integer token takes precedence over word classification. The spellings def, true, and false are reserved.

Requirement: K-SYN-05

r[K-SYN-05]

K-SYN-05. run and reflect are the standard operation names. call and reify are not compatibility aliases. // is an ordinary word token, not a comment opener. An explicit user definition can bind these nonreserved word spellings. An unbound spelling produces a resolution error. Tools can offer migration diagnostics but MUST NOT silently rewrite source meaning.

Examples of word tokens are square, fs.read, healthy?, list.case, +, and -. 1+ is not shorthand for 1 + and is rejected. A negative integer is one literal; subtraction is the separate word -.

Requirement: K-SYN-01

r[K-SYN-01]

K-SYN-01. Parsing MUST preserve the three semantic expression forms: literal, resolved word invocation, and quotation. There is no infix precedence, implicit process invocation, or shell expansion in this microprofile.

3.2 Literals

An integer literal denotes an I64 value and MUST be in the inclusive range -9223372036854775808 through 9223372036854775807. An out-of-range literal is a static diagnostic; it is not wrapped during parsing.

A text literal is delimited by double quotes. Its content is a sequence of Unicode scalar values. Raw line terminators and invalid UTF-8 are rejected. The supported escapes are \", \\, \n, \r, \t, and \u{H}, where H is one through six hexadecimal digits denoting a Unicode scalar value. Surrogate code points and values above 10FFFF are rejected. Text values are not implicitly Unicode-normalized.

This revision defines a Bytes type but does not select a source literal syntax for it. It can be supplied through typed data constructors or host bindings in a profile. Floats, arbitrary-precision numeric literals, interpolation, and raw strings are outside this microprofile.

3.3 Definitions and submissions

The following form is adopted for unannotated, nonrecursive definitions:

def square [ dup * ]

A declaration is not an expression that modifies a runtime dictionary. In this draft, a tooling submission is either one definition declaration or one expression body; a script runner may submit a sequence of units. The complete module grammar, imports, and type-annotation concrete syntax remain open.

Requirement: K-SYN-02

r[K-SYN-02]

K-SYN-02. A definition submission MUST be checked without executing the body. A tool MUST install the name mapping only after successful checking and preparation according to its environment policy.

Requirement: K-SYN-03

r[K-SYN-03]

K-SYN-03. A tool MUST determine the whole submission boundary before executing its expression body. A static error anywhere in that submission prevents execution of all of that submission's body, including effects textually preceding the error.

Previously completed submissions are not rolled back. A runner that checks a whole file as one unit must document that larger boundary.

Excerpt from the language specification. Wording unchanged.

4. Values, stacks, and type notation

4.1 Stacks

The stack top is written on the right. Juxtaposition of stack elements means ordered stack extension, not a tuple value.

stack shape S ::= empty | rho | S a
runtime stack s ::= [] | s v

Here a is a value type, v a value, and rho a stack-tail variable. A stack-tail variable stands for a finite ordered prefix of zero or more values. It is not an untyped container and cannot be inspected by a word that merely threads it onward.

A signature has the form:

S -- T ! e

S and T are input and output stack shapes. e is an effect bound. For readability, examples sometimes omit a common untouched prefix:

I64 I64 -- I64

means rho I64 I64 -- rho I64 ! {}.

Requirement: K-TYPE-01

r[K-TYPE-01]

K-TYPE-01. Input and output stack shapes MUST be checked in order and at their full arity. An unmentioned prefix MUST pass through without being implicitly read, duplicated, or discarded.

4.2 Types and schemes

The draft uses these semantic forms:

a, b ::= I64 | Bool | Bytes | Text | Unit
       | Pair<a,b> | Sum<a,b> | List<a>
       | Program<S,T,e> | Syntax
       | Resource<ResourceTypeId>
       | DeclaredType<TypeId, arguments...>
       | alpha

e, f ::= {} | {HostOpId, ...} | epsilon | union(e,f)

DeclaredType represents the single algebraic-data mechanism whose full declaration syntax remains open. Pair, Sum, and List are bootstrap data schemas, not separate expression forms or a commitment that every schema requires a compiler special case. Option and Result are ordinary variants supplied by schemas, not privileged control effects.

A named definition may have a rank-1 type scheme quantifying value-type, stack-tail, and effect variables, together with built-in eligibility constraints. First-class program values have instantiated interfaces. This revision does not introduce higher-rank polymorphism, impredicative types, a dynamic Any, general subtyping, or user-defined inference rules.

4.3 Eligibility predicates

The checker uses built-in predicates rather than an extensible trait-solving language:

PredicateMeaning
Data(a)Values of a may be duplicated and discarded.
Capture(a)Values of a are data with a defined portable semantic representation and may be embedded in a program recipe.

The scalar types, Unit, and Syntax satisfy both predicates. An algebraic type satisfies a predicate only when every possible payload permitted by its instantiated schema satisfies that predicate. List<a> inherits the predicate from a.

Every valid v0 Program<S,T,e> is data and capturable: its own environment is restricted to capturable data. This remains true when the program's input interface mentions a resource. A reusable operation that expects a resource does not itself own that resource.

No live resource type satisfies either predicate. Wrapping a resource in a pair, variant, list, or user-defined record does not remove that restriction. For example, Sum<Resource<R>,I64> is not data merely because its present value happens to select the integer alternative; elimination can expose the data branch at its narrower payload type.

Requirement: K-TYPE-02

r[K-TYPE-02]

K-TYPE-02. The checker MUST enforce eligibility recursively. A representation change or opaque wrapper MUST NOT launder a resource into capturable data.

A portable semantic representation is defined abstractly in section 11. It does not promise an interoperable binary encoding; section 12 explicitly leaves that encoding open.

4.4 Numeric semantics

Requirement: K-NUM-01

r[K-NUM-01]

K-NUM-01. In this draft, +, -, and * operate on two I64 values and wrap modulo 2^64, interpreted back as a signed 64-bit value. Operand order is the deeper value followed by the top value. The result MUST NOT depend on debug versus optimized compilation.

For a mathematical result z, the signed result is:

((z + 2^63) mod 2^64) - 2^63

= in the bootstrap numeric vocabulary compares two I64 values and returns Bool. It is not an implicit generic equality operator for every type. Division and floating point are not selected in the Core-Bootstrap profile; checked arithmetic is available only in the separate opt-in environment specified below.

Draft decision D-03. Wrapping arithmetic selects a candidate from the RFC for Core-Bootstrap. The checked library complement is selected only for the opt-in checked-i64 environment below; it does not change the bootstrap operators, other profiles, or saved program identities.

For the checked-i64 environment only, select version noble-checked-i64/v1. Its exact words and stack signatures (where S is an untouched stack prefix and binary operands are deeper then top) are:

WordSignatureSuccessful value
i64.checked-addS I64 I64 → S Sum<I64,I64>exact mathematical sum in inl
i64.checked-subS I64 I64 → S Sum<I64,I64>exact deeper-minus-top difference in inl
i64.checked-mulS I64 I64 → S Sum<I64,I64>exact mathematical product in inl
i64.checked-negS I64 → S Sum<I64,I64>exact mathematical negation in inl
i64.checked-absS I64 → S Sum<I64,I64>exact mathematical absolute value in inl
i64.ltS I64 I64 → S Boolsigned deeper-operand < top-operand comparison
i64.checked-div-remS I64 I64 → S Sum<Pair<I64,I64>,I64>(quotient, remainder) in inl, quotient first

The right I64 alternative is an error code: 1 = Overflow, 2 = DivisionByZero; code 0 is reserved. The Sum tag distinguishes success from failure. Checked add/subtract/multiply return inr(1) exactly when the mathematical result is outside [-2^63, 2^63). Checked negation and absolute value return inr(1) for MIN. i64.checked-div-rem returns inr(2) for a zero divisor, inr(1) for MIN / -1, and no partial quotient or remainder on either failure. It truncates toward zero and, for nonzero divisors, satisfies a = b*q + r, |r| < |b|, and r has the sign of a when nonzero. No remainder-only or Euclidean/floor-division word is selected.

i64.lt is signed. ≤, min, and max are derived library definitions and do not add numeric builtins. The implementation checks divisor zero and MIN / -1 before Wasm i64.div_s/i64.rem_s. Arithmetic-domain errors are ordinary result values; deterministic resource exhaustion remains a distinct runtime outcome.

Requirement: K-EVAL-01

r[K-EVAL-01]

K-EVAL-01. An expression body MUST execute left to right. A literal pushes its value. Invoking a word performs its declared stack transformation. A quotation pushes a program value without executing its enclosed body.

Requirement: K-EVAL-02

r[K-EVAL-02]

K-EVAL-02. A run MUST use the resolved references in its program. It MUST NOT perform a fresh lookup of source names in a mutable namespace.

Requirement: K-EVAL-03

r[K-EVAL-03]

K-EVAL-03. Evaluation of one word MUST finish normally before the next sequential word begins. Suspending in an explicitly asynchronous host operation does not authorize reordering subsequent words in the same sequential computation.

5.2 Abstract operational model

The following rules define behavior, not an interpreter implementation. Let:

<C ; s ; H ; t>

be a configuration with pending code C, data stack s, host state H, and observable host-event trace t. Let D be the immutable store of resolved definitions. A semicolon inside C denotes the remaining sequence.

Representative steps are:

<Literal(v); C ; s ; H ; t>
    -> <C ; s v ; H ; t>

<Quotation(B); C ; s ; H ; t>
    -> <C ; s program(B) ; H ; t>

<Invoke(d); C ; s ; H ; t>
    -> <D[d].body; C ; s ; H ; t>

<run; C ; s p ; H ; t>
    -> <recipe(p); C ; s ; H ; t>

<compose; C ; s p q ; H ; t>
    -> <C ; s composed(p,q) ; H ; t>

<quote; C ; s v ; H ; t>
    -> <C ; s push-program(v) ; H ; t>

The checker has already verified the interfaces and constraints for these steps. Recipe expansion in this mathematical notation does not require an AST evaluator in production; a compiled Wasm call must have the same specified behavior.

A host step consumes the arguments specified by its declared interface, makes the authorized request, and returns its declared results, possibly with a changed host state and an appended event trace. Exact host event formats belong to the host contract. A host's nondeterministic response is not silently treated as a pure function result.

5.3 Outcomes and sequencing laws

Normal execution yields an output stack and a host trace. Execution may instead diverge or terminate abnormally. Ordinary domain failures represented as Result values are normal execution, not automatic traps.

Requirement: K-EVAL-04

r[K-EVAL-04]

K-EVAL-04. If p terminates abnormally, the second program q in compose(p,q) MUST NOT start. Earlier host effects are not rolled back by the language.

The composition laws use failure-propagating sequencing:

run(empty, s) = success(s)
run(compose(p,q), s) = run(p,s) then-on-success run(q)
run(quote(v), s) = success(s v)

Host traces concatenate in order. Where both executions terminate normally under the same host responses, composition is associative and the empty program is an identity. These laws do not equate elapsed time, allocation strategy, or behavior under different resource quotas. Recipe associativity is separately specified in section 11.

5.4 Errors and limits

Requirement: K-ERROR-01

r[K-ERROR-01]

K-ERROR-01. A static rejection MUST prevent execution of the rejected submission. At minimum, tools MUST distinguish parsing, resolution, stack/type incompatibility, eligibility/resource-use violations, and effect-bound violations in their diagnostics. Exact wording and numeric diagnostic codes are not frozen.

Requirement: K-ERROR-02

r[K-ERROR-02]

K-ERROR-02. A well-checked invocation with conforming host bindings MUST NOT encounter a language-level stack underflow, wrong operand type, or use of a consumed resource on a normal path. Those outcomes indicate an implementation or binding defect, not a permitted fallback to dynamic typing.

Requirement: K-ERROR-03

r[K-ERROR-03]

K-ERROR-03. Empty effect bounds do not guarantee termination or freedom from allocation failure, quotas, traps, or side channels. Such failures MUST NOT be misreported as ordinary successful results.

A host/execution profile specifies handling of traps, cancellation, and resource exhaustion. This draft does not specify recoverable exceptions or user-defined continuation handlers.

Excerpt from the language specification. Wording unchanged.

6. Program construction and execution

6.1 Program interface

A program has type Program<S,T,e>. S and T describe the stack at invocation; they do not describe the current stack on which the program value is constructed. e is latent until invocation.

Requirement: K-PROG-01

r[K-PROG-01]

K-PROG-01. A checked program MUST carry or be associated with sufficient trusted type and executable information to support its interface, and sufficient recipe information for reflection. These need not be stored redundantly or in a particular memory layout.

6.2 Quotation literal

If body B checks as S -- T ! e, the expression [ B ] has effect-free construction behavior:

R -- R Program<S,T,e> ! {}

R is the surrounding construction stack. It is independent of the body's invocation stack.

Requirement: K-PROG-02

r[K-PROG-02]

K-PROG-02. Quotation literals MUST NOT capture the current data stack implicitly. Missing inputs in a quotation body become requirements of its program interface; they are not obtained from values underneath the quotation during construction.

Requirement: K-PROG-03

r[K-PROG-03]

K-PROG-03. The entire quotation body MUST check even when the quotation is never called or is later discarded. Unchecked code is represented as Syntax, not as a quotation literal accepted without checking.

6.3 run

run : S Program<S,T,e> -- T ! e

run consumes the program value and invokes it against the remaining stack. Consuming a reusable data value does not invalidate any independently duplicated copy of it.

Requirement: K-PROG-04

r[K-PROG-04]

K-PROG-04. run MUST invoke an already prepared executable program. It MUST NOT implicitly compile source, fetch code, install interfaces, acquire capabilities, or reinterpret arbitrary data as instructions. An implementation may use its Wasm engine's ordinary execution preparation internally; that is not a hidden call to the language's code.prepare service.

6.4 compose

compose : R Program<A,B,e> Program<B,C,f>
          -- R Program<A,C,union(e,f)> ! {}

The deeper program runs first, then the top program. compose produces a new program value. It does not run either operand.

Requirement: K-PROG-05

r[K-PROG-05]

K-PROG-05. The shared intermediate stack B MUST unify completely, including resource types and positions. An incompatible pair is rejected statically, not converted to a runtime compatibility test.

Requirement: K-PROG-06

r[K-PROG-06]

K-PROG-06. Composing values selected or constructed at runtime MUST work over their statically known interfaces without a source compiler service. A literal-only implementation does not conform.

6.5 quote

quote : R a -- R Program<S,S a,{}> ! {}
        where Capture(a)

quote captures the top value explicitly and produces a program that pushes that value when called. The fresh invocation prefix S is unrelated to the construction prefix R unless later type constraints relate them.

Requirement: K-PROG-07

r[K-PROG-07]

K-PROG-07. quote MUST accept only capturable data, MUST preserve the captured value immutably, and MUST NOT publish or otherwise export it. A program may contain private data, including secrets represented as ordinary text; capturability is not a confidentiality guarantee.

Requirement: K-PROG-08

r[K-PROG-08]

K-PROG-08. A live resource MUST NOT be captured, including through a containing value or a program environment. A quotation may instead require that resource as an invocation input.

6.6 Ordinary higher-order definitions

def twice [ dup compose ]

Its schematic scheme is:

forall S e R.
R Program<S,S,e> -- R Program<S,S,e> ! {}

The resulting program runs its input twice; its effect bound remains e because sets are idempotent. An effect bound records possible kinds of operations, not the number of occurrences.

Example. 20 [ 1 + ] twice run yields 22. This definition is not applicable to every program; it requires matching input and output stack shapes.

6.7 Runtime-selected interfaces and transition libraries

Requirement: K-PROG-09

r[K-PROG-09]

K-PROG-09. A runtime-selected program MUST retain one statically established, instantiated interface. Selection MUST NOT erase stack arity, schema identity, resource obligations, or effect bounds. Heterogeneous programs require explicit typed adapters or exhaustive variants before they share a collection or dispatch interface.

Under the separately opted Worker Program v2 boundary, a runtime Program handle MUST retain the source-checked ordered instantiated input/output/effect witness and nominal identities of its retained session. A package row or guest-reported handle MUST NOT substitute a checked Program. Runtime lists and selection require one exact common witness, established through explicit checked adaptation rather than erasure.

Scenario: v2 runtime list rejects nominal lookalikes

  • GIVEN two independently source-checked Programs with equal data layout but different nominal schema identities, and an explicit common list witness from the host-selected session
  • WHEN an opted Worker Program v2 guest tries to insert both without an adapter
  • THEN the incompatible insertion is refused before invocation or protected operation; the previously admitted Program remains unchanged

Requirement: K-PROG-10

r[K-PROG-10]

K-PROG-10. An adapter MUST obey ordinary checking and ownership rules. Representation equality MUST NOT establish schema compatibility. A failed interface match MUST NOT trigger argument guessing, an implicit conversion, or an Any fallback.

A library can describe a pure transition with this schematic interface:

State Event -- State List<Action> ! {}

State, Event, and Action denote application-owned, resolved data schemas. They are not kernel types or new syntax. The shell supplies each event and retains the explicit state between invocations. Repeated shell invocation does not require guest recursion or a captured continuation.

For this resource-free example, all three schemas satisfy Data and Capture. An action is an inert request description, not a capability or an execution receipt. The shell admits each action under its own authority policy. Time, model responses, and other external observations enter as explicit inputs.

Resource-bearing programs remain possible through explicit resource inputs and ownership-preserving results. This example does not permit a live resource inside a capturable worker environment. Worker conformance defines a bounded application of these existing mechanisms.

Excerpt from the language specification. Wording unchanged.

Appendix A — Worked examples (informative)

A.1 Construction is not invocation

41 [ 1 + ]

The resulting stack contains 41 and a program requiring an integer input. No addition has run. Appending run yields 42.

[ "audit" test.emit ] drop

In a test environment declaring test.emit : Text -- ! {test.emit}, the quotation is checked and discarded without issuing the event. The declaration being available is distinct from executing its body.

A.2 Composition order

20 [ 1 + ] [ 2 * ] compose run

This yields 42. Reversing the two programs yields 41 for input 20, demonstrating that composition is ordered even though effect summaries use set union.

A.3 Runtime capture

Suppose a compiled word receives a runtime integer n on top of its construction stack:

quote [ + ] compose

It returns a program that adds n to a later integer input. Choosing n = 2 after compilation and invoking the returned program on 40 yields 42. This operation does not need code.prepare.

A.4 Program returned by an ordinary word

Install the separate declaration:

def twice [ dup compose ]

Then submit:

20 [ 1 + ] twice run

The result is 22. twice is an ordinary checked definition, not a parser feature.

A.5 Program stored in a list

20 nil [ 1 + ] swap cons [ ] [ drop run ] list.case

The nonempty branch receives the program followed by the empty tail. It drops the data-only tail and calls the program on 20, yielding 21. A conformance harness must also test a list assembled or selected after compilation.

A.6 Resource input without resource capture

Given the illustrative fs.read contract, this is a reusable program:

[ "main.rs" fs.read ]

It requires a directory input and returns that directory plus a result. The same kind of program can be used with different authorized directory inputs. Quoting the directory itself is rejected.

A.7 Invalid code cannot hide in a discarded quotation

[ "wrong" 1 + ] drop

The quotation body is ill-typed and the whole submission is rejected. Representing that text as inert Syntax would be allowed, but calling the syntax directly would still be rejected.

A.8 Reflection and editing

[ 1 + ] dup reflect

The stack retains the program and an inert resolved syntax value. A transform of that syntax may produce a new candidate. It cannot mutate the retained program; preparing the candidate must check it anew against an expected interface.