HoldFastPlayground

HoldFast language reference

See the first-release contract for primitives, modules and ownership libraries, the synchronous core for loan and refinement rules, and the surface grammar for syntax.

How to read this reference

Status markers apply to the indicated forms.

Marker Status Owner
P Checked by the pure prototype and emitted as Gallina over Nat and bool Pure prototype
M Accepted by the opt-in mathematical elaborator, which emits CIC terms for kernel replay Mathematical elaborator
S Parsed as located syntax by the development parser Surface grammar
D Specified by a design contract. Prototype checking may cover narrower forms. The linked contract

The mathematical elaborator reads surface syntax and records solver-discharged obligations in its solver-trust ledger. See the delivery plan for production requirements.

Run python tools/run.py holdfast-parser parse --surface FILE on parsed examples. Design examples exceed the relevant prototype's scope.

Lexical structure

Element Rule Status
Source text Strict UTF-8. Identifiers are ASCII [A-Za-z_][A-Za-z0-9_]*. P
Comments // to end of line. Consecutive /// lines can attach documentation to a declaration. The surface entry also accepts nested /* ... */ comments. P (line comments), M (block comments)
Keywords Reserved or contextual according to the surface grammar and lexer S
Integer literals Decimal, 0x hexadecimal and 0b binary digits with _ separators; a representation suffix (0usize, 0byte) or the expected type selects the type P (decimal Nat), M
Other literals true, false, (), characters 'a' with escapes, strings "...", raw strings """...""" and format templates $"...{hole}...". Character and string contents may be Unicode. Bytes and text P (true, false), M

Use PascalCase for public functions, constants and user-defined types, and camelCase for locals and value parameters. Naming lints are advisory by default. Common style · Generic type parameter naming

Menhir's strict, conflict-free parser uses token shape alone. Syntax constraints In patterns, an initial uppercase letter in the final segment names a constructor. An unqualified lowercase- or underscore-prefixed name binds, except the wildcard _. In match, is and let/var (including else), Pattern as name binds the whole and its parts. The binder accepts @ grade. Mathematical elaboration permits the form in ghost or specification contexts, for copyable types and for shared in loans. Non-copyable handles bound through shared loans stay read-only. Executable patterns cannot keep a non-copyable whole while moving out a part.

Even in parentheses, the checker rejects a whole-pattern binder that differs from a visible constructor of the matched union only in initial capitalization. For Option, none would match every value. Use None for the case, _ for a permitted discard, or a distinct name to bind the whole.

Declarations

Construct Syntax Status
Module Begin each file with module Name;. The surface parser also accepts qualified names such as module Name.Path;. P (single name), M (qualified path)
Import import Module.Path; binds namespace Path (Path.Operation(...)). import Module.Path as M; binds namespace M and import Module.Path { T, F as G }; selects explicit bare names. Modules and packages M
Visibility public or private on declarations. internal grants eligible runtime helpers visibility to sibling modules in the same locked package instance. M
Constant public const T Name = expression; at module scope or const T name = expression; inside a function. The initializer must evaluate during compilation. Required-static constants P
Function public T Name(T1 a, T2 b) followed by a block or => expression; P
Constant-compatible function and static parameter public const T Name(...) may also run at runtime. In public T Name(const U config, V value), every call must supply a static config. P
Mathematical definition definition T Name(...) => expression;, with no runtime representation implied; a pure block of immutable bindings ending in return expression; is equivalent M
Theorem and lemma theorem Name(...) ensures P proof { ... }; lemma likewise. For a single postcondition, proof by e; supplies its justification. M
Record record Name(T1 Field1, ...) with optional invariant clauses and a member body (record Name { ... } without primary parameters) M (primary params/props/methods)
Distinct wrapper distinct Name = T introduces a nominal type with constructor and pattern Name(val), projection .Value, and optional invariants and members. Its Gallina carrier is the underlying type. Mathematical interpretation M
Union union Name { Case1(T x); Case2; }; nullary cases omit () in declarations, patterns, and expressions M
Property public T Name => expression; defines a total, effect-free, allocation-free property M
Interface and implementation interface ISized { ... } (This implicit), impl Nat : ISized { ... }, used through where T : ISized M
Named effect set effect Name = calls(F) | Other canceled by calls(Wrapper); M
Finite-state model machine Name invariant Property: EXPR { ... } contains initialized state fields and named transition declarations S · Finite-state model checking
Inductive and coinductive types inductive Name { Ctor(...); }, coinductive Name<T> { ... } S

Parsed example (module, constant, functions and a static parameter):

HoldFast
module Reference.Basics;

public const Nat Limit = 16;
public const Nat Twice(Nat x) => x + x;
public Nat Scale(const Nat factor, Nat value)
{
    const Nat multiplier = Twice(factor);
    return multiplier * value;
}

Parsed example (record with a named invariant, a property and a union):

HoldFast
module Reference.Data;

public record Window(Nat Start, Nat Count)
    invariant Bounded: Start + Count <= 4096
{
    public Nat End => this.Start + this.Count;
}

public union Shape
{
    Point;
    Segment(Nat length);
}

Parsed example (interface, implementation and constrained use):

HoldFast
module Reference.Interfaces;

public interface ISized
{
    Nat Size(in This value);
}

public impl Nat : ISized
{
    Nat Size(in Nat value) => value;
}

public Nat Total<T>(in T first, in T second) where T : ISized
    => T.Size(in first) + T.Size(in second);

Call interface methods through the implementing type or a receiver. Total borrows both inputs and lends each to Size, so callers can retain ownership even when T contains owned fields. Interface resolution

Finite-state model checking

The finite-state checker interprets a machine as a transition system. Its initialized state fields form one initial state. A parameterless transition is enabled when its when guard holds, or unconditionally if it has no guard. Each enabled transition is a possible next step. A state with no enabled transition is terminal. A transition's next assignments all read the old state and take effect together. A field omitted by the transition keeps its value. A field can be assigned at most once per transition.

The host checker supports bool and u8 state fields with closed initializers. Guards and machine invariants are Boolean expressions over the state. Expressions can use Boolean logic, conditionals, equality, ordering on u8, and exact u8 addition, subtraction and multiplication. Decimal literals in this finite interpretation have type u8. Arithmetic outside the range of u8 is an evaluation error. The transition body consists of direct assignments to whole state fields. Source syntax

The checker explores the reachable states from the initial state, testing every declared invariant. Breadth-first search with exact state identity returns a shortest counterexample when an invariant fails. The checker replays the transitions from the initial state before reporting the trace. Success means the reachable set is closed under the transitions and satisfies these invariants. The result is a development diagnostic scoped to the authored finite model. A proof or a claim about deployed behavior requires its own applicable evidence. Claim status

Types

Type Meaning Status
bool, Unit Exactly false/true, and the single value (); no integer truthiness P (bool), M
Nat Unbounded mathematical natural number. Runtime use needs a selected representation and range relation P, M
u8, u16, u32, u64, i8, i16, i32, i64, byte, usize Fixed-width integers. byte is u8. usize has the target's XLEN width. Primitive semantics M (word operations)
char One Unicode scalar value M
Tuples (A, B) Products, eliminated by tuple patterns M
Option<T>, Result<T, E> Library unions with Some(v)/None and Ok(v)/Err(e); absence and failure are explicit cases M
Seq<T>, Vec<T, n> Specification sequence, and a mathematical vector of length n M
Span<byte> A byte span in the packet validator's source model M
Span<T, count> View of count initialized elements with runtime Length and erased Model : Seq<T> D (ownership libraries)
Slots<T, capacity> Vacant-slot storage with live-prefix and vacant-suffix ranges. .Capacity always has type usize. Its mathematical index is capacity, whose representability is required at construction. M
TextBuilder<capacity> Bounded text buffer for allocation-free formatting M
Generics <T>, <ghost Nat n> Type parameters and erased value indices; declaration generics are rigid M
Type, Type<n>, Prop, Fn(A a) -> B Universes, propositions and dependent function types M
Fn(Nat n @ NatExact(q)) -> B and NatBound(q) Natural computation grades with separately reconstructed type uses. Supported grade fragment M (pure definitions), D
ghost T Erased, duplicable specification data with no computation use M
tracked T Erased resource evidence that cannot be copied S
Fn, FnMut, FnOnce with captures C Shared-call, exclusive-call and consuming-call function types with their capture sets S

Use explicit T.From(x) for infallible widening and T.TryFrom(x) for a range-checked Result. The language excludes null, T? and automatic T/Option<T> conversion. Exclusions

Parsed example (generic and dependent signatures):

HoldFast
module Reference.Types;

public definition T Identity<T>(T value) => value;
public definition Nat Length<T, ghost Nat n>(Vec<T, n> items) => n;

Bindings

Construct Syntax Status
Immutable local let name = e; or let T name = e; P
Mutable local var name = e; or var T name = e; M
Local constant const T name = e;, required-static P
Pattern binding let (owner, receipt) = pair;, let Ready(buffer) = outcome; M
Early-exit guard let Some(v) = e else { return ...; }, whose else block must leave the scope M
Expression-local binding let name = e in body M

An immutable let still permits writes through its exclusive loan. With let and var, mutability and type annotation are independent. Binding table

Parsed example (typed and inferred locals):

HoldFast
module Reference.Bindings;

public Nat Sum(Option<Nat> maybe, Nat base)
{
    let Some(extra) = maybe else { return base; }
    var Nat total = base;
    total += extra;
    return total;
}

Expressions and operators

Operators run from weakest to strongest binding. Parser

Level Operators and forms Associativity Status
1 Lambdas x => e, quantifiers forall (T x) [when G] => P and exists (T x) [when G] => P, let ... in, if (c) a else b Extend right M
2 Implication ==>, equivalence <==> Right M
3 || Left P
4 && Left P
5 ==, !=, <, <=, >, >=, e is Pattern Monotonic chains (==, <, <=, >, >=); none (!=, is) P (single comparison), M (chains and is)
6 lhs |> rhs Left M
7 Range a..b None M
8 Bitwise | Left M
9 Bitwise ^ Left M
10 Bitwise & Left M
11 +, - Left P
12 *, /, % Left P
13 Record update e with { Field = v, ... } Left M
14 Prefix !, -, ~, *p, &place, move, in, ref, out Right P (!), M (-, ~, move, in, ref, out), S (rest)
15 Postfix call f(...), member .Name, index e[i], generic F<T>, propagation e? Left P (calls), M
16 Literals, names, $, (e), tuples, match, holes ?name, operator values (+) n/a P (literals, names, grouping), M

Comparison chains are monotonic (0 <= i < len, hi >= mid > lo, a == b == c). They short-circuit like && and evaluate each middle operand once, including effects, loans and affine expressions. Mixed directions (a < b > c) and chained != require explicit parentheses. Both && and || evaluate the right operand only as needed. The token after the full angle list selects generic application in expressions such as Foo<T>.Bar. Token-only rule

For represented integers, ordinary +, -, * and signed division require representable results. Both / and % require a nonzero divisor. Checks and diagnostics use the operand type's limits. Named Checked*, Wrapping* and Saturating* have separate primitive semantics.

For Nat, prove b <= a for a - b and b != 0 for a / b or a % b. Nat.SaturatingSub(a, b) returns zero when b > a. Quantification covers all naturals. Closed evaluation remains subject to elaborator resource limits. Pure arithmetic checks · Mathematical elaboration

Form Meaning Status
Labeled call Copy(in source, target: ref dst) A positional prefix followed by labels matching parameter names in declaration order (unnamed callable parameters accept no labels) P (named pure functions), M (including loan arguments and methods)
Member call x.Method(a) Supplies the declaration's receiver loan; other arguments repeat their modes M
Conditional if (c) a else b Mandatory else; the same join as a two-arm match M
Match expression match (e) { Pattern [when cond] => value, ... }, exhaustive, optional final comma; == expr pins an outer value and Pattern as name binds whole plus parts M
Negated pattern test e is not P Complement of a nonbinding pattern test; introduces no bindings M
Alternative pattern P or Q Nonbinding alternatives in one unguarded match arm over a copyable scrutinee; each alternative retains its own coverage and resource checks M
Pattern test e is P A successful pattern (including Pattern as name) binds its variables in later && operands, the then branch of an if guard and the consequent of ==>. Pattern test scope M
Record update move base with { F = v } Declaration-order update; linear or affine records require move. A copyable record can use nonoverlapping nested field paths, as in base with { F.G = v } M (copyable nested paths; direct fields)
Pipeline e |> f($, y) Evaluates the LHS once by value and binds $ across the RHS (supporting calls, labeled args, expressions, move $, and in $; linear values allow at most one move $) M
Formatting builder.Write($"n={n}") The mathematical builder model returns an updated TextBuilder observed through .Fits, .Written and .WrittenBytes. A failed append preserves the bytes present before the call. The represented buffer API returns Result<usize, CapacityError>. M (builder model), D (represented result)

Parsed example (operators, a conditional expression and a match):

HoldFast
module Reference.Expressions;

public Nat Clamp(Nat value, Nat limit)
    => if (value <= limit) value else limit;
public bool InRange(Nat value, Nat low, Nat high)
    => low <= value < high;
public Nat Headroom(Option<Nat> used, Nat capacity)
    => match (used) {
        Some(count) => Nat.SaturatingSub(capacity, count),
        None => capacity,
    };
public Nat Groups(Nat count, Nat size)
    requires size != 0
    => count / size;

Statements and control flow

Construct Syntax Status
Block and return { ...; return e; }; an expression body checks as one return P
Conditional statement if (c) { ... } else { ... } P (final statement, both branches return), M
Match statement match (e) { Pattern [when cond] => { ... }, ... }, exhaustive; == expr pins an outer value and Pattern as name binds whole plus parts M
Range loop foreach (let i in low..high) invariant P { ... } M
Collection loop foreach (let x in xs), foreach (in x in xs), foreach (ref x in xs) select value, shared-read, and exclusive element iteration M (selected models), D (represented iteration)
While loop while (c) invariant P decreases m { ... } M
Scoped disposal using let h = init; invokes IDispose.Dispose(in h) returning Unit on fallthrough, return, and ? for the rest of the enclosing block (skipping disposal if ? exits from init) M
Local effect confinement effect (!writes(x), !RawIO) { ... } enforces tighter positive or negative (!) effect bounds over the block M
break, continue Leave or restart the innermost loop, closing local loans M
Assignment x = e;, x += e; and the other compound forms, on var locals, fields and indexed elements M
Propagation e? yields the payload of Ok or Some. On Err or None, it returns the failure from the enclosing function. M

A range loop supplies bounds, a representable increment and a decreasing measure. Author only its functional invariant. Each exit closes the iteration's loans. Loans and control flow

A scoped using (let h = init) { ... } is equivalent to a nested block starting with using let h = init; (M). The resource is not visible outside that block. A using resource and its loans must stay in scope through the enclosing block. Mathematical elaboration rejects break and continue across that boundary. Nested cleanup runs in reverse declaration order before exit.

Parsed example (statement match with a nullary case, pin pattern, and when guard):

HoldFast
module Reference.Control;

public const Nat Magic = 42;

public Nat CountSome(Option<Nat> first, Option<Nat> second, Nat expected)
{
    var Nat count = 0;
    match (first)
    {
        Some(== Magic) => { count += 10; },
        Some(value) when value == expected => { count += 2; },
        Some(_) => { count += 1; },
        None => { },
    }
    if (second is Some(other) && other > 0) { count += 1; }
    return count;
}

Parsed example (a bounded loop with its invariant):

HoldFast
module Reference.Loops;

public Nat CountTo(Nat limit)
{
    var Nat count = 0;
    foreach (let index in 0..limit)
        invariant count == index
    {
        count += 1;
    }
    return count;
}

Loans and parameter modes

Construct Meaning Status
Value parameter T x Passes a value where its resource rules permit copying. An unconstrained type parameter may contain owned fields. Use owned T and an explicit move for a generic transfer. P (Nat and bool), M
owned T x / move x Consuming transfer; the moved-from binding is unusable M
in T x / in place Shared-read loan M
ref T x / ref place Initialized exclusive loan M
out T x / out place Initialization loan: no read before initialization, initialized on every normal return M
out var x, out let x Declares a fresh output local in a standalone Unit call. Its type comes from the out parameter and its scope begins after the call; let prevents subsequent rebinding M (checked callee output)
Receiver this, ref this.Payload, in this.Payload The receiver and a receiver loan limited to a named fixed-field view M (fixed fields)
Named view view Payload = Left, Right; A record's selected fixed-field footprint available for a receiver loan M
Named view view Tail = slots[length], length grows; A part of a record a signature can lend separately S
Place-named loan 'input, 'this.text, or declared region 'r A loan tied to a parameter, field, or declared region M (selected forms)
Returned loan ref<'a> T or Result<ref<'table> V, E> The caller inherits the loan and its restoration duty. The mathematical replay checks selected exclusive returns. The synchronous fixture returns a shared view. M (selected forms), D (deferred contracts)
*p, &place, p + n, p[i] Typed pointer and place operations under access contracts S

Executable calls with potentially affine arguments or results require a constructor or an ownership-checked body. Specifications may use mathematical definitions on those values.

Repeat the mode of each ordinary loan argument at the call site. The loan diagnostic proposes path-specific ends from explicit flow facts. The synchronous core defines restoration, iteration boundaries and escapes. An implicit ref receiver reserves before argument evaluation and becomes exclusive at the call. Receiver rule · Source acceptance evidence

Design example (a place-named result view, after the primary design):

HoldFast
module Reference.Loans;

public record PacketView<region 'source>(
    usize Consumed,
    in<'source> Span<byte> Payload,
    ghost Header Header)
    invariant Encodes(Header, Payload.Model);

public Result<PacketView<'input>, ParseError> ParsePrefix(in Span<byte> input)
    ~> reads(input)
    ensures result.Model == Format.ParsePrefix(input.Model);

Contracts

Clause Meaning Status
requires P Entry condition the caller proves M
ensures P Exit condition; result names the returned value and old(e) evaluates e at entry M
ensures unchanged(x, y) Conjunction of exit-to-entry equalities, x == old(x) && y == old(y); not a no-write or effect guarantee M
where T : ISized, IOrdered Interface implementations required for the generic type parameter T M
restores P Predicate over the lender that holds when a returned loan ends. final(x) is the value the loan leaves behind. Restoration contracts S (authored clause), D
invariant Name: P Named record or loop invariant conjunct M
decreases m Termination measure of a recursive definition or loop M
~> reads(a), writes(b), calls(f) Closed upper bound on reads, writes and calls, including transitive callees and captures; supports named effect sets, | unions, canceled by encapsulation, and ! prohibitions M
open (ref this, ref d) lifts A, B { ... } Opens only the listed invariant conjuncts. Unlifted conjuncts stay in force. The block re-establishes the lifted ones at its closing brace and forbids early exits. M

Lending a span by ref preserves its base, length and permissions. A contract can describe how its contents change. Under every assurance preset, callers establish each exported requires clause, and the implementation establishes each ensures clause for inputs satisfying those requirements. Exported contracts

Effects union reads, writes and named calls and charge the bound at each call, mapping callee parameters to actual places. Passing a named loan or receiver to a checked helper that never accesses it contributes no read. Assigning a fresh value to a scalar place counts as a write. A compound assignment also reads the previous value, and restoring a value still counts as a write. Package exports publish a closed bound. Record methods may inherit a receiver read or write, an empty bound, or a named effect set from their enclosing record. A method with its own clause uses that bound. Private helpers and methods can infer receiver, parameter and callback effects. Package-internal helpers carry their checked footprints across sibling modules. Package effect contracts

In the following example, each Ok(slot) test binds slot in the consequent of its own clause. Pattern test scope

Design example (a returned exclusive loan with restores and final):

HoldFast
module Reference.Contracts;

public Result<ref<'table> Value, TableFull> FindOrInsert<ghost Nat capacity>(
    ref Table<Key, Value, capacity> table, Key key)
    ~> writes(table)
    ensures result is Ok(slot) ==> slot == old(table.Model).GetOr(key, Value.Default)
    restores result is Ok(slot) ==> table.Model == old(table.Model).Set(key, final(slot))
    ensures result is Err(_) ==> table.Model == old(table.Model);

Parsed example (selective invariant lifting):

HoldFast
module Reference.Lifting;

public record Buffer<ghost Nat capacity>
{
    private usize length;
    private Slots<byte, capacity> slots;
    invariant InitializedPrefix: LivePrefix(this.slots, this.length);
    invariant VacantSuffix: VacantRange(this.slots, this.length, capacity);

    public Unit Push(ref this, byte item)
        requires this.length < capacity
    {
        open (ref this) lifts InitializedPrefix, VacantSuffix
        {
            this.slots = Slots.Write(this.slots, this.length, item);
            this.length += 1;
        }
    }
}

Proof mode

Construct Meaning Status
proof { ... } Proof block whose steps elaborate to checked obligations and erase from runtime code M
proof by e; Single-postcondition theorem or lemma proof, equivalent to asserting the sole postcondition with justification e M
assert exists (T x) => P(x) by witness(e); Explicit existential introduction; check the witness type and prove the instantiated proposition P(e) M (single binder)
assert P;, assert P by e;, assert P by (h1, h2, ...);, assert P by { ... } Intermediate fact, optionally justified by a lemma call, a multi-fact tuple of justifications, or a nested proof block M
forall (T x) [when G] => P, exists (T x) [when G] => P The optional quantifier guard selects the values for which the body is checked. Parenthesize a quantifier at the root of an ordinary contract clause. Theorem and lemma clauses accept it without parentheses. M
Named hole ?name Each occurrence reports its available expected type or proposition and local context. An open goal blocks the build. Mathematical diagnostics M

See concise syntax refinements for the exact elaboration and restrictions on these shorter forms.

Checking tries conversion, resource rules, linear arithmetic, domain lemmas, then explicit proof. Timeouts and unsupported formulas leave open goals. Refinement rules · Typed holes and invalidation

Parsed example (a lemma with an explicit proof):

HoldFast
module Reference.Proofs;

public lemma AddZero(Nat n)
    ensures n + 0 == n
    proof
    {
        assert n + 0 == n;
    }

Errors and failure

Executable failure uses an explicit Result or union case. Operations prove freedom from unexpected traps under their entry conditions. The target classifies environmental faults. R-05-100 · Loans and control flow Checked arithmetic returns Result<T, ArithmeticError>. Widening with T.From(x) returns T directly. T.TryFrom(x) checks the range and returns Result<T, ConversionError>. Propagating Err or None with e? preserves out initialization and cleanup duties. Examine every Result, including Result<Unit, E>, and account for every tracked resource. An executable function that owns a record or tuple owes each verdict separately. Exhaustive matches transfer obligations to the selected payload bindings. Returning the aggregate forwards them. The prototype accepts transfers to constructors and executable parameters of checked verdict type. Abstract type parameters need a resource constraint outside the current fragment.

Parsed example (propagation and a checked operation):

HoldFast
module Reference.Errors;

public Result<u32, ArithmeticError> AddTwice(u32 a, u32 b)
{
    let sum = CheckedAdd(a, b)?;
    return CheckedAdd(sum, b);
}

Extensions outside the first release

See the extension index for deferred designs and the first-release grading contract for natural domains and separate type-use accounting. Additional domains and grade-directed tools follow the graded selection protocol.

Construct Extension Status
User-defined domain declarations and grade parameters over those domains Graded foundation S
effect, handle, resume, dispose, rehandle, shallow Handlers S
async, scope, spawn, await, commit, on cancel Structured tasks S
Cells, snapshots and local aliases Interior mutability M (local cells with deeply immutable, authority-free payloads), D (concurrent protocols)
Descriptors, derivation and generated declarations Metaprogramming D
captures, mode-crossing lattice, mode m / effect E 2LTT staging Modal and staged polymorphism D
quotient, AdapTT/Trocq transfer, relational ensures, declassify, session choreographies Quotients, IFC, and sessions D
Linear resource/time credits in Delta, guarded ITree, bit-level layout lenses Credits, ITrees, and layouts D
Slotted e-graph saturation and independent minimal-CIC dual checking Slotted e-graphs and kernel diversity D
machine, hardware, state, register, transition, rule, schedule Whole-system authorship S

scope names only a structured task scope; invariant lifting uses open.