HoldFast development surface grammar
For supported subsets and semantics, see the language reference and first-release scope, primitives and modules. The parser supports required-static constants. Generic static binders, derivation registration and quotation/splicing are metaprogramming designs.
Entry points
One authored Menhir grammar provides two public entries. file emits schema 1
for the pure prototype and parser comparison. holdfast-parser parse --surface SOURCE
selects surface_file, emitting schema 2 with a module name and declarations
in a surface_file node. Its generic-argument productions also serve the
internal application probe. Surface parsing has no translation fallback, and
pure translation rejects wider constructs.
Both entries retain half-open original-byte spans for nodes and names and
preserve numeric spellings, including underscores. Only digits count toward
the literal bound. Separator and suffix rules
Both enforce UTF-8, source-byte, literal-digit, delimiter, syntax-depth, duration
and output limits and reject an initial byte-order mark at line 1, column 1.
Both skip // comments. Only the surface entry skips nested /* ... */ comments,
subject to the nesting limit.
Required syntax
machine, hardware, state, register, transition, rule, next,
schedule and cycle can name parameters, locals, expressions and members.
when is reserved for guards. In a hardware update, next precedes a storage
name with optional field and index projections.
import Storage.Blocks as Blocks; aliases a module namespace.
import Storage.Blocks { Block, Empty as Free }; selects public names and
permits per-name aliases. The selection list is nonempty and accepts a trailing
comma. Aliases are located identifiers. Import scope
Grammar actions construct located syntax. Consumers check meaning and well-formedness.
| Area | Syntax acceptance |
|---|---|
| Modules and abstraction | Qualified module names, imports, aliases, namespaces, public, private and internal declarations, typed constants, interfaces and implementations, abstract signatures and definitions |
| Data and dependency | Records, tagged unions, nominal distinct wrappers, fields, constructors, named views, generic types and applications, typed ghost indices, region and capture parameters, grade parameters and annotations |
| Types and resources | Qualified and applied types, ownership, shared/exclusive loans and place-named lifetimes, ghost/tracked/scoped modifiers, function types with captures and effects, dependent binders and universe syntax |
| Contracts | Requires, ensures, restores, effects (including negative ! prohibitions and canceled by effect sets), unnamed and named (invariant Clause: EXPR) invariants, selective invariant opening (open (ref target) lifts Clause, ... { ... }), and decreasing measures. where T : IBound constrains a generic type parameter. old and final are ordinary calls. |
| Expressions | Literal spellings (including multi-quote raw strings and interpolated format templates) and representation suffixes, qualified access, nested calls, indexing and ranges, explicit-placeholder pipelines (|>, $), unary/arithmetic/comparison/logical operators, implication, pattern tests, explicit generic application, tuples, lambdas and named holes |
| Control | Immutable/mutable and typed locals, required-static local constants, scoped using disposal (using let | var h = init;), local effect confinement blocks (effect (...) { ... }), assignments, blocks, returns, if/else, bounded-loop syntax, exhaustive-match syntax, break/continue and explicit propagation |
| Grades | Domain carrier/zero/one/add/mul/admits/interpret/laws declarations and parameter use grades |
| Effects and tasks | Effect operations and resumption bounds, deep/shallow handlers, return/operation clauses, resume/dispose/rehandle, async functions, structured task scopes (scope (...) { ... })/spawn/await/commit and on-cancel cleanup |
| Mathematical proofs | Definitions, theorems and lemmas, proof blocks, proof by expressions, assertions with optional by justifications, quantifiers, inductive and coinductive declarations, constructors, universes and typed holes |
| Architecture and hardware | Machine/hardware containers, state/register declarations, transitions/rules, guards, next-state assignments and explicit schedules/cycles |
Declarations are type-first and containers and loop bodies use braces.
Generic expressions such as F<T>(arguments) and Foo<T>.Bar follow the
token-only angle-argument rule.
Each nested argument list closes with one >. Arguments can be values or
lifetimes. Parenthesize relational value arguments and use named shift operations.
Parenthesize callable return types that are themselves callable. Lambdas and
quantifiers use =>, and quantifiers require typed binders. Function types use
->. End a bare assertion or an expression justification with a semicolon,
as in assert P; or assert P by e;. A block justification ends at its
closing brace. Architecture and hardware consumers must supply transition or
circuit interpretations.
Bounded, token-only lookahead distinguishes type-first local and callback annotations (qualified, applied or parenthesized type followed by a binder) from expressions. It preserves lexeme positions and pure-entry tokenization.
Type<u> names a universe-indexed type.
rehandle shares the body and clause syntax of handle.
Inductive and coinductive constructors omit () when nullary and can specify
result indices with : TYPE, as in Nil : Vec<T, 0>;.
module Syntax.Examples;
universe u;
public definition Nat Twice(Nat x) => x + x;
public Nat Increment(Nat x)
requires x > 0
ensures result > x
=> x + 1;
public inductive Natural { Zero; Succ(Natural predecessor); }
public coinductive Stream<T> { More(T head, Stream<T> tail); }
public lemma Reflexive(Nat n)
ensures n == n
proof { assert n == n; }
public theorem Witness() ensures exists (Nat n) => n == 0;
public machine Counter invariant Bounded: value <= 10 {
state u8 value = 0;
transition Step() when (value < 10) { next value = value + 1; }
}
public hardware RegisterCounter {
register u64 count = 0;
rule Tick() when (count < 10) { next count = count + 1; }
schedule Main { Tick; }
cycle 1;
}
Reflexive includes its proof. The declaration of Witness gives only a
statement, so parsing it supplies no proof. The finite-state checker can
explore Counter from zero through ten. The
whole-file fixture combines dependent
data, contracts, loans and task cleanup. Independent fixtures cover every row.
Syntax and fixtures
Finite-state machines
Use machine with named invariant clauses before its body for a finite model.
Declare each state with a type and initializer. A transition has a name, an
empty parameter list, an optional parenthesized when guard, and a block of
next assignments. The arena example models cancellation with a live grant,
quiescence, release before reissue, and a late completion across two generations.
Arena lifecycle source ·
State and transition semantics
Composable type and resource syntax
These forms serve both the graded foundation and borrow rules.
- Callable types use the declaration parameter telescope, including optional
names, grades and nested ownership modifiers (
Fn(Nat n, byte x @ q) -> Vec<byte, n>). Locatedparameternodes carryname,typeandgrade. Omitted names are null. Lambdas also accept use grades ((byte x @ q) => x). The checker infers type-use demands. Unithas value(). Products such as(T, U)and(x, y)may nest and need at least two components. Single-component parentheses group. Unit nodes aretype,unitandunit_pattern, and product nodes aretuple_type,tupleandtuple_pattern. Use(owner, receipt) => ...in a match andlet (owner, receipt) = value;orvarfor an explicit local pattern._is awildcard_patternwhose discard permission requires elaboration. In generic arguments, parentheses alone denote a value expression. Prefix structural types withtype, as inResult<type (owned Packet, tracked Receipt), Error>. The prefix works with other type forms and is optional forResult<Unit, Error>.- Parametric aliases use the generic telescope, as in
alias Callback<grade q : NatExact> = Fn(byte x @ q) -> byte;. Dependent records supply pairs and indexed unions supply outcome-dependent resources.Box,Result,Option, cells, guards and protocol tokens use ordinary library types and operations without implicit disposal.
Compose these forms with place-named loans, captures, restoration, nested reborrows, typestate, dynamic-borrow conflicts and cleanup. Independent AST assertions distinguish parameters from dependent result indices, check grade binding and preserve nested pattern/type roles and original byte spans. Reject incomplete binders or grades, malformed products or patterns and nesting exhaustion. Leave duplication, tracked-token loss, stale snapshots and loans across suspension to semantic checking.
Dependent elimination and library interfaces
The foundation's dependent elimination uses the existing record, union and pattern forms. A nonempty expression match has comma-separated expression arms, with one optional trailing comma, under the match arm grammar:
definition Vec<byte, packet.Length> Contents(Packed<byte> packet) =>
match (packet) as whole : Vec<byte, whole.Length> {
Packed(length, bytes) => bytes,
};
Both match forms accept as NAME : TYPE, binding the scrutinee in the motive.
The located match_motive has name and type. An omitted motive is null.
The checker handles branch substitution and resource compatibility.
Expression matches use match_expression and expression_case with
pattern, optional guard and value. They work with calls, operators,
lambdas, proofs and nested matches. Statement matches emit a match node
with one case node per arm. Write PATTERN [when EXPR] => followed by a
statement or block. Guards use
s_contract_expression and require bool without loan mutation. A guarded
arm contributes neither to exhaustiveness nor to coverage of later arms.
Fields and record or constructor parameters accept @ GRADE before any
initializer and store null for an omitted grade. Records can represent
graded boxes and retained callback environments.
Implementations use the declaration generics and contracts nodes, as in
impl<T, grade q : NatExact> Box<T, q> : IDup where T : IRepeatable<q> { ... }.
Elaboration checks generic binding, coherence and laws. Parenthesize a callable
target to delimit its effects, as in
impl (Fn() -> Nat ~> Read) : ICallable requires Law() { ... }.
Generic interface constraints
Give each constrained parameter a where clause, as in
where T : ISized, IOrdered where U : ISized. Bounds name interfaces, optionally
qualified, without a final comma. The parameter supplies This and <...>
instantiates remaining types, grades or indices. Use requires for preconditions.
A located type_constraint in contracts stores a located parameter and
nonempty bounds array. Binding and witness resolution
Callable types and contracts
Use ~> after a signature to introduce its effect bound. A declaration takes
comma-separated entries, as in ~> reads(src), writes(dst). Use ~> none for
an explicit empty bound. Eligible helpers can omit the clause and let the
checker infer their effects. Package effect contracts
A callable type puts ~> after its result and optional captures. Write one
effect as Fn() -> Nat ~> Read and group several as Fn() -> Nat ~> (Read, Log).
The parentheses keep commas in the effect list distinct from the surrounding
parameter or type arguments. Fn() -> Unit takes no arguments.
Fn(Unit) -> Unit takes one, whose value is ().
effect Name { ... } declares a family of operations. With an equals sign,
effect Name = ...; names a reusable set. Inside a function,
effect (!RawIO) { ... } confines the enclosed code. In a generic parameter
list, effect E binds an effect parameter. The plural spelling effects is
reserved so an old set declaration cannot be mistaken for a field declaration.
Named sets and confinement
Callable types reuse the telescope and put optional contracts after the effect bound.
alias Update<T> = Fn<region 'loan>(scoped ref<'loan> T value) -> Unit
with { requires Valid(value); restores Valid(value); };
Each declaration contract in with ends in a semicolon. This delimiter
distinguishes callback and enclosing contracts without name resolution.
function_type stores generics and contracts, empty when omitted.
Elaboration checks binders, loan ancestry, escape, invocation and disposal.
Independent fixtures distinguish motive and branch binders and check dependent indices, field grades, local regions, contract ownership and original UTF-8 byte spans. Include malformed neighbors and syntax-valid incompatible branches, escaping loans and incorrect grade or resource use.
Resource contracts and lexical handler capabilities
Effect operations put declaration contracts after any resumption bound and
before the semicolon. An effect_operation stores reply type, parameter grades,
resumption allowance and resource transitions separately. Its contracts array
is empty when omitted.
effect Exchange<T> {
owned T Replace(owned T replacement @ NatExact(1)) resumes(0..1)
requires Available(replacement)
ensures Returned(result)
restores Closed(result)
~> writes(Storage);
}
Record, interface, machine and hardware declarations store their own
contracts between the generic telescope and opening brace, as in
interface IRepeatable<grade q : NatExact> requires Admits(This, q) { ... } and
record LocalCell<T> invariant Closed(this) { ... }. Interface and module
callable signatures use bodyless functions
(T Read() requires Readable(this) ensures Stable(result);). Interface laws
use bodyless lemma or theorem declarations
(lemma ReadLaw(Handle target) ensures Owns(target);). Lemmas and theorems
place requires, decreases and any where before one or more ensures in
contracts. End with proof { ... } for a proof block, proof by e; for a
single postcondition, or ; for a statement alone. The surface reserves trait, operation,
handle, open and lifts. In the pure entry, trait, operation,
open and lifts are identifiers.
invariant InitializedPrefix: LivePrefix(this.slots, 0usize, this.length)
adds a located name to its contract. Unnamed clauses omit the field.
open (ref this) lifts InitializedPrefix, VacantSuffix { ... } temporarily
opens a nonempty list of named conjuncts and permits a trailing comma.
The open_invariant node holds resources, located identifiers in lifts
and a body. The structured task scope (...) { ... } node holds only
resources and body. Elaboration checks preservation, conjunct
independence, grade laws and operation effects.
handle (body()) as chosen { ... } names a lexical perform capability.
as NAME also follows the expression in handle shallow and rehandle.
The handle or rehandle node stores the located name in capability or null
when omitted. chosen.Choose() uses ordinary call/member syntax.
The capability scopes over the handled expression only. Nesting, shadowing,
outer forwarding and rehandling preserve distinct syntax identities.
Checking resolves binding, frame identity, escape, resumption, capture across
open invariants, Dup, Dispose and restoration.
Handler lookup rules
Independent fixtures must assert operation/container/member contract ownership,
named and unnamed invariant clauses, selective open (...) lifts ... clause
lists (including trailing commas) beside task scope blocks,
dependent reply indices, parameter-grade and resumption-bound attachment, named
and unnamed handler associations, and original UTF-8 byte spans. Compose these
forms with loans, guarded updates, two-step bulk relocation (CopyRepresentation
and TransferType), indexed outcomes, shallow rehandling and explicit
disposal. Refuse incomplete contract expressions, malformed named invariants
(invariant : expr, invariant Clause:), named requires/ensures clauses,
empty or malformed lifts lists (lifts {}, lifts , Clause, lifts A,, B),
open without lifts, scope (...) lifts ..., open or lifts used as a
surface identifier, and incomplete capability binders without
publishing an AST. Syntactically valid violations of capability scope or resource
rules must still parse.
Type-valued computations and uniform library laws
Type parameters may state a kind using the existing type syntax:
Box<T : Type<u>, grade q : NatExact>. A type-mode generic_parameter
keeps its type field null for a bare binder and records the kind when supplied.
Associated types likewise accept an optional : TYPE kind before contracts and
their optional definition; associated_type.kind_annotation is null when absent.
Universe formation, conversion and dependent substitution remain checking duties.
Parenthesize a callable kind so its effects stay distinct from declaration contracts.
Explicit type TYPE expressions inject structural types into ordinary definitions,
calls and dependent matches. A type_expression has a type field containing the
located type node. For example, an ordinary type family can return
match (flag) { true => type (T, T), false => type Unit, }.
Like lambdas and quantifiers, these forms occupy a complete expression; group them
when used as operator operands. Parenthesize a callable payload, as in
type (Fn(T value) -> T ~> Read), to delimit its effects.
This reuses callable, product and library types
instead of introducing separate type-level function or box primitives.
Bare Boolean, string, character and named-hole generic arguments use their existing
expression nodes, alongside numbers, lifetimes and parenthesized expressions.
Named arguments remain unresolved syntax; this introduces no stable-value judgment.
A callable value may reuse the complete callable type before =>:
FnOnce<region 'loan>(scoped ref<'loan> T value @ NatExact(1)) -> T
captures Environment ~> Read
with { requires Open(value); restores Closed(value); }
=> Read(in value)
The typed_lambda node contains signature (the existing function_type) and
body; its parameters, grades, local regions, captures, effects and contracts
therefore have the same syntax as a callable annotation. Existing inferred lambdas
retain their current nodes. Naming parameters, capture completeness, repeatability,
loan escape and per-call resource transitions require elaboration.
Union, inductive and coinductive declarations accept ordinary declaration contracts
between their generic telescope and body. Constructors accept them after the
optional result type. Pure definition declarations accept them after their parameter telescope and before =>. Associated types accept them before an optional = definition.
Each of these nodes exposes a contracts array, empty when omitted. Thus domain
laws, graded storage, indexed outcomes and type families share the existing
contract language; their laws do not acquire parser authority.
Effects following a bare callable constructor result still belong to that callable;
parenthesize the result to attach an effects contract to the constructor itself.
Independent fixtures must compose kinded binders, type-valued matches, explicit callable signatures, scoped loans and graded library resources. Assert contract ownership, signature/body roles, dependent indices, literal spellings and original UTF-8 byte spans. Refuse incomplete kinds, type expressions, callable signatures and contracts without an AST; syntax-valid erasure, ownership and grade violations must still parse.
Local grades, domain members and disposal clauses
Local value bindings reuse the parameter and field use-grade annotation:
let value @ q = Make();, let T value @ q = Make(); and
var T value @ q = Make(); (bare T value @ q = Make(); without let or var
is refused as syntax). The let and var nodes
expose a nullable grade field alongside type and value. Both inferred and
explicitly typed bindings accept the same grade expression. Product-pattern
bindings retain their existing form; component modalities belong in their data
types. Checking the binding's allowance, evaluation effects and subsequent uses
remains subject to the graded foundation.
In particular, zero demand does not erase an effectful initializer.
Named function or method parameters supply call-site argument labels directly
from their declared parameter names (Nat offset allows Read(offset: 3) or
Read(3)). Parameter names in one telescope must be distinct. An interface
supplies the parameter names used as caller labels (impl declarations may
choose their own local parameter names without breaking interface callers).
The domain roles carrier, zero, one, add, mul, admits, interpret
and laws introduce entries inside a domain. In value positions they are ordinary
identifiers, including parameter names and member names after a dot. Ordinary paths, type paths
and member expressions can therefore refer to a domain dictionary without new
operator or projection primitives:
definition NatExact.carrier AddZero(NatExact.carrier value) =>
NatExact.add(value, NatExact.zero);
These names preserve the existing located path/member AST forms. For example, definition Nat add(Nat zero, Nat one) => zero + one; uses three role names as ordinary values.
Domains also reuse the existing generic telescope and declaration contracts,
for example domain Product<A : GradeDomain, B : GradeDomain> requires Compatible(A, B) { carrier (A.carrier, B.carrier); ... }.
Their generics and contracts arrays are empty when omitted. Compatible product
domains therefore need no separate grammar primitive or assumed algebraic law.
Handlers accept an explicit disposal clause, using the same expression or block body as their operation and return clauses:
handle (Run()) as chosen {
Choose() with k => resume k(true),
return value => value,
dispose reason => { Cleanup(reason); return (); },
}
A disposal_clause has a located name for the disposal-reason binder and a
body. It composes with deep/shallow handlers and rehandlers, sharing their
comma-delimited clause list. The handler lifecycle
owns its intended resource context and lexical restrictions: the handler's own
perform capability is absent in its clauses. A disposal clause describes the
declared disposal graph; capture and ordinary return do not invoke it. Parsing neither
invokes cleanup nor supplies a resource-restoration proof; duplicate clauses,
unbound capabilities and invalid disposal bodies still parse as semantic errors.
The existing dispose continuation computation retains its separate syntax.
Annotation lookahead must accept callable types inside generic local and lambda annotations, including nested results, loan modifiers, grades and effects. Arrows in these types must not close generic argument lists. Independent fixtures must distinguish local allowance, initializer and lambda-parameter grades, domain member/path spans, and operation/return/disposal clause ownership. Include nested handlers, syntax-valid resource violations, malformed neighboring spellings and bounded-lookahead exhaustion.
Computed types and uniform elimination
The stable type-valued computations of the graded foundation
can appear wherever a type is expected, through type[EXPR]. A computed_type
node stores the ordinary expression in its value field. This delimited form
reuses calls, dependent matches, local indices and library operations:
definition Type<u> Select<T : Type<u>>(bool pair) =>
match (pair) { true => type (T, T), false => type T, };
alias Selected<T : Type<u>, ghost bool pair> requires Stable(pair) =
type[Select<T>(pair)];
type[Select<T>(pair)] Read<T : Type<u>>(bool pair);
Computed types also work directly as generic arguments, as in
Box<type[Select<T>(flag)]>, and in fields, parameters, callable signatures,
local annotations and lambda annotations. The existing type TYPE expression
injects structural types into values; type[EXPR] uses a type-valued expression
as a type. The checker establishes stability, purity, universe formation,
conversion, erasure, and resource availability. Effectful or ill-kinded type
expressions can still parse.
Aliases accept existing declaration contracts after their generic telescope and
before =. Effect families accept them before their opening brace. Their
contracts arrays are empty when omitted and distinct from operation or callable
contracts. Grade-domain laws, capture requirements and family invariants therefore
reuse the same contract language as records and other library definitions.
An empty sum's value eliminator uses match (impossible) as whole : T {}.
Its match_expression node has an empty cases array and the existing optional
motive. Like lambdas and type injection, an empty value match occupies a complete
expression; group it when applying operators or postfix operations. A semicolon
distinguishes an empty-match expression statement from the retained bare empty
statement match. Nonempty expression matches use the comma-separated arms above.
Whether the scrutinee has an empty type and which resources can
reach that branch are checking obligations; syntax supplies no inhabitant or
proof. String and character literal patterns reuse their lexical spelling in
string_pattern and character_pattern nodes, with the same value field as
their expression literals; they introduce no decoding or equality operation.
Independent fixtures must compose computed types with kinded parameters, dependent results, scoped loans, local grades and callable contracts. Assert expression/type roles, alias/family/member contract ownership, empty-match motive and statement/expression boundaries, literal pattern spellings and original UTF-8 byte spans. Include malformed neighbors, bounded nesting and syntactically valid semantic errors.
Shared operators and local elimination
Parenthesized symbolic arithmetic, bitwise, comparison, and Boolean operators
are ordinary expression atoms. Unary ! and ~ also accept this form.
Examples include (+), (%), (&), (==>) and (!). A located operator
node retains its located name; its span includes parentheses while the name's
span covers only the symbol. Unary and binary uses share (-), (*) and (&);
elaboration determines the selected operation and arity under the pointer/loan
rules below and applies the natural arithmetic boundary.
Operator values compose with calls,
members, generic application, tuples, lambdas, computed types and ordinary
declaration contracts. Grade-domain entries use these same expressions, including
their existing (+) and (*) spellings, without a separate domain-value grammar.
Assignment, range, propagation and keyword computations are not operator values.
Local elimination reuses constructor and recursive patterns:
let Some(value) = optional; and
var Ready((owner, receipt)) = outcome;. Qualified constructors are
accepted. A single parenthesized pattern groups
it, producing group_pattern with a pattern child; products still require at
least two components. Grouping works in local elimination, match arms and pattern
tests. Local pattern bindings retain let_pattern/var_pattern with pattern
and value fields. A bare lowercase local name retains the existing inferred binding form;
a local nullary constructor pattern uses a qualified uppercase path, as in let Result.Empty = outcome;.
Union and inductive constructor declarations start with an uppercase letter.
An unqualified name starting with a lowercase letter or _ binds, except for
the wildcard _. A final segment starting with an uppercase letter identifies
a constructor. Write a nullary case such as None without parentheses in a
pattern. Component grades remain in their data types. Refutability, constructor arity,
exhaustiveness, ownership and resource disposal are elaboration obligations, so
syntactically valid mistakes still parse.
The grammar shares operator productions between binary expressions and operator values, and shares recursive type-modifier construction across ordinary, callable, generic and local-annotation types. Preserve precedence, associativity, contract ownership, every child in syntax-depth accounting and the pure entry's schema. Independent fixtures must assert operator and nested pattern roles, original UTF-8 byte spans, higher-order application and domain compatibility; exercise every operator spelling and malformed neighboring forms, syntax-valid resource mistakes and nesting limits.
Typed local initializers share fields and children across contexts. The enclosing statement or expression binding supplies the node kind and span. Local annotations use lexical disambiguation, and literal patterns have their own node kinds. The native fixtures cover these roles alongside nested types, generic binders, quantifiers, and lambda boundaries.
Pattern test scope
A successful e is P introduces P's bindings on its true path. In L && R,
the right operand runs only if the left is true and sees its true-path bindings.
When both operands succeed, the conjunction carries the bindings from both.
Parentheses preserve this flow. An if condition makes its true-path bindings
visible only in the then branch. A direct pattern guard refines the scrutinee
to the pattern in then and to its complement in else.
In A ==> B, check B with the bindings available on A's true path, just
as in the then branch of if (A) B else true. For Boolean implication, a
false antecedent yields true without evaluating B. Thus in
ensures result is Ok(slot) ==> slot == expected, slot is in scope throughout
the consequent. A conjunction in the antecedent can introduce more bindings,
as in (left is Some(x) && right is Some(y)) ==> x == y.
Only a direct is test, grouping and && forward bindings to a containing
guard's true path. In particular, || carries no new bindings between its
operands or out to a containing guard. An implication exports no bindings to a
surrounding expression or branch. Names already in scope remain visible inside
nested expressions, so item is Some(n) ==> (n == 0 || n >= limit) can use n
in both disjuncts. For independently well-scoped Boolean operands, !A || B
gives the same truth value as A ==> B. Resolve names using the authored
operator before applying the Boolean identity.
Quantifier guards
Both forall and exists accept an optional when after the parameter
list. The parameters are in scope in the guard and the body. Check the body
assuming the guard succeeded, including any bindings introduced on its
true path.
For example, ensures (forall (usize i) when 0 < i && i < items.Length => items[i - 1] <= items[i])
states that each adjacent pair is ordered. For a property of the elements
alone, write ensures items.Model.All(item => Valid(item)).
Sequence models
A guarded forall holds if every value selected by the guard satisfies
the body. It is true when the guard selects no values. A guarded exists
requires a witness satisfying both the guard and the body, so it is false
when the guard selects no values. For example,
assert exists (Nat n) when n < 3 => n == 2 by witness(2);.
Expression-local bindings
An ordinary expression may bind a shared subexpression with
let NAME = EXPR in EXPR, including the existing optional type and use-grade
annotations. Recursive local patterns use the same constructor/product/group
forms as statement elimination. For example, a type family can compute
let chosen = Select(flag) in chosen; a computed type can use
type[let chosen = Select(flag) in chosen]. A contract or match arm can bind a
library result without a new type-family, borrow or protocol primitive.
A located let_expression contains a binding (the existing let or
let_pattern node) and a body. The binding covers let through its initializer;
the outer node includes the body. The binder's scope is the body, not the
initializer; name resolution, refutability, grades, effects and resource disposal
remain checking obligations. Bindings associate to the right and occupy a full
expression, like lambdas and quantifiers. Group them for postfix/operator use.
Statement bindings end in a semicolon. Expression-local bindings belong to the
surface entry point.
Independent fixtures must compose nested bindings with dependent types, callable contracts, grades, constructor patterns, matches and lambdas; distinguish initializer/body and binder scopes in the AST and preserve UTF-8 byte spans. Refuse missing initializers, delimiters and bodies; keep syntax-valid resource errors accepted. Preserve nesting limits, strict conflict-free generation and every existing surface and pure qualification case.
Explicit values, loans and absence
The parser records explicit parameter modes and absence cases. Elaboration checks conversions, exhaustiveness, and authority. Language exclusions
Ordinary type-first parameters pass values. The surface entry parses in,
ref and out as modified_type nodes in types and unary nodes in
expressions, with an optional place-named lifetime on the type. The pure
entry diagnoses loan modes as unsupported. Prefix * dereferences and prefix
& derives an address or loan. Multiplication, bitwise conjunction, and
parenthesized operator values use distinct AST forms. Prefixes associate right.
Postfix indexing and calls bind
more tightly. Pointer arithmetic uses the existing additive and indexing forms.
Named library types carry pointer representations; no C declarator or T* type
suffix is introduced. -> remains a function-type arrow.
Member calls retain ordinary member/call syntax. The
receiver rule supplies
the selected declaration's receiver loan, including a named view such as
ref this.Tail; other arguments retain explicit loan modifiers. Resolution,
once-only receiver evaluation, argument order and overlap remain semantic
obligations. A call rejected for an overlapping argument or an ineligible receiver
still parses; the parser neither chooses a view nor delays a loan.
let and var locals have distinct AST roles. A nonconstant local with a type
annotation starts with let T or var T. Option<T>, Some(value), None
and their constructor patterns use ordinary library syntax. The surface entry
rejects bare null, T? annotations, null-forgiving postfix !, ?? and ?..
Postfix ? denotes explicit propagation. Prefix ?name denotes a named hole.
Propagation followed by member access uses (Read()?).Value.
The contiguous spelling Read()?.Value is refused with a diagnostic explaining
that ? is early-return propagation rather than C# null-conditional ?. and
offering (Read()?).Value (to propagate) or a match skeleton (to handle
locally) under the assist-don't-coerce tooling.
The parser still accepts incomplete option matches, immutable writes, mistyped
arithmetic, missing/mismatched loan modifiers and forbidden sharing as located
syntax for the semantic consumer to report the appropriate obligation.
Use the symbol families consistently:
| Symbols | Syntax roles |
|---|---|
(...) |
Calls, parameter telescopes, grouping, products and parenthesized operator values; grammar context fixes the role |
{...} |
Declaration/statement/proof bodies, match arms, handler clauses and explicitly introduced callable contracts |
[...] |
Indexing; type[...] explicitly introduces a computed type |
<...> |
Generic parameters and arguments. Expression <...> follows the token-only rule. |
->, =>, ==>, <==> |
Callable result, lambda/operation/quantifier/match/handler body, implication and equivalence respectively |
|, ||, &, &&, ^, ~ |
Bitwise and Boolean operators with separate fixed precedence; prefix & derives an address/loan |
*, +, - |
Multiplication and additive operators; prefix * dereferences a pointer and prefix - negates |
@, 'place, ?, ?name |
Use grade, lifetime identity, propagation and named hole respectively |
|>, $ |
Explicit-placeholder pipeline operator (weaker than range/bitwise/arithmetic, tighter than comparisons/is) and LHS placeholder |
Independent fixtures must check default/explicit binding roles, nested
Option<Option<T>> and exhaustive constructor matches, value/in/ref/out/
owned signatures and arguments, out lifetime annotations, unary versus binary
*/&, pointer arithmetic/indexing, operator values and original UTF-8 spans.
Refuse malformed adjacent forms, C pointer declarators, nullable/null-forgiving
spellings, missing unary operands and non-monotonic or != chained comparisons.
Keep semantically invalid neighbors as positive syntax fixtures, including
partial matches, implicit conversion attempts, immutable reassignment and
overlapping/shared-mutation attempts. Their acceptance is no semantic verdict.
Concise authoring syntax
- Unit. The type is
Unitand the value and pattern are(). AUnit-returning block function can omit the finalreturn ();. - Receiver name. Declarations, contracts, views, captures, and lifetimes
can refer to the receiver as
this, as inref this.Tailand'this.text. Access follows the receiver rule. - Range loops.
foreach (let index in lower..upper) { ... }binds an immutable index over the half-open range. It accepts the ordinary loop contracts. Loop and exit rules - Labeled calls. Write a positional prefix followed by labeled arguments
in declaration order, as in
Copy(in source, target: ref destination, count: length). Each label must name the next parameter. An unnamed parameter accepts positional arguments only. Eachargumentnode contains a nullablelabeland avalue. Both pure routes and mathematical elaboration validate labels. Either spelling evaluates arguments once, left to right, under the same loan, grade, dependency, capture, effect, and exit rules. - Output locals.
out var nameproduces anout_variablenode spanning both keywords and the binder. The mathematical elaborator accepts it, including after a label, in a standaloneUnitcall with a checked output. Each name must be fresh in the environment and within the call. The new names enter scope together after the call and last until block exit. - Inferred lambda parameters.
value => value + 1,(value) => value + 1, and(left, right) => left + rightomit parameter types. Thelambda_parameternode records a null annotation. Elaboration uses the expected type or reports an unresolved parameter type. - Expression function bodies.
Nat F(Nat x) requires x > 0 => x;has anexpression_bodyspanning the arrow through the semicolon. It checks like a single return under the same effect and resource rules. - Contract expressions. Parenthesize an outer lambda, quantifier,
expression-local binding, or type value in an ordinary contract clause,
for example
requires (forall (Nat n) => Valid(n)). This distinguishes the inner arrow from a function body. Nested forms such asrequires items.Model.All(x => x > 0)need no extra parentheses. Theorem and lemma clauses accept outer quantifiers directly. - Trailing commas. Nonempty parameter, argument, generic, callable, constructor, and pattern lists permit one trailing comma. A tuple must still have at least two elements.
- Pattern bindings. Token shape separates
bindings and constructors.
== EXPRmakes apin_patternwhose expression has bitwise-or precedence. It is available inmatch,is, andletorvarguards withelse. The comparison uses the outer environment, without sibling pattern bindings or mutation.Pattern as nameforms a left-associativeas_patternwith an unqualified lowercase or underscore-prefixed non-wildcard binder and an optional@ grade. - Comparison chains.
0 <= i < len,hi >= mid > lo, anda == b == cproduce acomparison_chainwithoperandsandoperators. A single comparison staysbinary. Chains reject!=and direction changes. - Nominal wrappers.
distinct Name<...> = TYPEaccepts record-style invariant clauses and a semicolon or member body. It emits adistinctnode. Wrapper semantics - Pipelines.
lhs |> rhsis left-associative and binds$within its right operand. It binds more tightly than comparisons andis, and more loosely than ranges and bitwise or arithmetic operators. The AST usespipeandpipe_placeholder. Unarymove $andin $retain their ordinary roles. - Scoped disposal.
using let h = init;orusing var h = init;emits ausingnode containing the local binding. The declaration can include the ordinary type and grade annotations. Its scope is the remainder of the enclosing block. Disposal rules
Qualification compares labeled and positional calls with dependent parameters, callable values, generic arguments, shadowing, and loans. It checks chained comparisons for single evaluation of reached operands and compares expression bodies with single-return blocks modulo source provenance. Exercise malformed labels, mixed-direction chains, loop exits, rebinding versus loan writes, and lambdas that need an expected type, including graded loan callbacks. Editor hints
Bindings, match arms, and generic calls
Local bindings use let [T] name = value; or var [T] name = value;.
Both pure routes accept typed immutable Nat and bool locals, whose
schema-1 type field is null when omitted. An annotation must match the
initializer. The formatter preserves the authored form.
Match arms begin with Pattern [when EXPR] =>. In an expression match,
separate the arm values with commas and optionally add a trailing comma.
In a statement match, each arm contains one statement or block and may end
with a comma.
Mathematical definition bodies use definition ... => EXPR; or the pure
block form described in concise syntax refinements. Initializers,
constants, type aliases, associated-type aliases, and grade-domain equations
use =.
In an expression, a postfix < starts generic application when a complete
nonempty argument list ends in > and the next token is one of the following.
( ) ] } : ; , . ? == != | |> ^ && || & [ => ~> < <= >= is as
Otherwise < is a binary operator. The lexer matches longer tokens first.
In F<T>>=x it reads the closing > and then >=. Use spaces in
F<T> == x to keep the closing angle and equality tokens separate. ?name
is a single named-hole token, distinct from postfix ?.
Related C# rule
Type positions accept angle lists directly. Generic arguments can include dependent values, lifetimes, structural and computed types, and parenthesized expressions, with an optional final comma.
| Expression | Parse |
|---|---|
Outer(F<A, B>(7)) |
One argument, a generic call |
Outer(F < A, B > 7) |
Two comparison arguments |
Outer(F < A, B > &value) |
One argument, a bitwise expression. Write Outer((F < A), B > &value) to get two comparisons. |
(f < n) > x |
Two explicitly grouped comparisons |
Choose<(a < b)>(value) |
A generic call with a grouped comparison argument |
Library.F<T>(value), factory()<T>(value) |
Generic calls on a qualified or computed callee |
Foo<T>.Bar, Apply(Identity<Nat>, value) |
Generic application before member access or an argument separator |
(F<T>) > x |
A grouped generic application before comparison |
Probes share the source, delimiter, depth, and duration limits and inspect at most 200,000 tokens in aggregate per parse. Budget exhaustion refuses the parse. A successful syntax decision stands even when semantic checking later fails.
Qualification covers local binding roles, shadowing and reassignment, alias identity and range conversions, empty and nonempty match arms, nested patterns and motives, and the body delimiters. Generic fixtures cover grouping, nested applications, higher-order values, loan modes, comments, newlines, UTF-8 spans, incomplete delimiters, and probe exhaustion.
Ergonomic authoring and bounded collection iteration
The parser preserves unsuffixed literals for contextual inference. Contextual inference
Collection loops accept value, shared-read, and exclusive element modes and an optional element type or use grade.
foreach (let item in values) { ConsumeValue(item); }
foreach (let byte item in values) { ConsumeByte(item); }
foreach (in item in values) { Inspect(in item); }
foreach (ref byte item in values) { Update(ref item); }
An untyped value binder over a range, including a parenthesized range, emits
foreach with name, range, contracts, and body. Other forms emit
foreach_collection with name, nullable type, mode (value, in, or
ref), collection, contracts, and body. Both nodes include grade when
authored. Contracts precede the body. An explicit type or loan mode on a range
is kept for semantic checking. Value iteration requires copy permission and
in and ref grant scoped element loans. Iterator laws and release qualification
Sequence model expressions such as items.Model.All(x => x > 0) reuse
ordinary member, call, and lambda syntax in contracts.
Sequence models
Raw strings. An opening run of at least three double quotes pairs with
a closing run of the same length. A multiline literal starts with a newline
after the opening delimiter and ends on a separate closing line. Each
nonblank content line keeps at least the closing line's indentation. The
string and string_pattern nodes preserve spelling and source span.
Text semantics
Format templates. $"..." emits interpolated_string with the original
spelling in value. Holes use {expr} or {expr:spec}. An expression may
nest within the delimiter budget. A format specifier must be nonempty and
contain no whitespace or quotes. Write {{ and }} for literal braces.
The lexer refuses unterminated templates, empty holes or specifiers, and
unescaped closing braces. A template is an expression, and a pattern cannot
contain one. The represented API checks templates inside calls such as
builder.Write($"..."), using a static IFormat<T> for each hole and
returning Result<usize, CapacityError>. Formatting contract
Assertions. The forms assert EXPR;, assert EXPR by EXPR;, and
assert EXPR by { ... } emit assert with value and a by field
that is null, an expression, or a block. A justification block contains
let and assert steps and ends at its closing brace.
Conditional expressions. if (COND) THEN else ELSE emits
if_expression with condition, then, and else. The final branch is
required. At statement start, group the expression to distinguish it from
a statement if.
Constructor-pattern labels and record updates. A constructor pattern can
start with positional subpatterns and continue with label: pattern.
The parser emits a labeled_pattern with label and pattern. Checking
matches labels in declaration order. A postfix BASE with { Field = EXPR, ... }
produces a with_expression with value and a nonempty array of
field_update children. It accepts a trailing comma and binds at unary
precedence, so move base with { ... } updates a moved value. Linear or
affine records require the explicit move. Update expressions evaluate
left to right in declaration order.
Early-exit bindings. A let or var constructor pattern followed by
= EXPR else { ... } emits let_else or var_else with pattern,
value, and else. The else block ends at its closing brace and must
leave the scope, accounting for the unmatched resources. On success the
bindings remain in scope. Pattern scope
Expression properties. A module, record, union, or implementation can
declare [visibility] [ghost] T Name [contracts] => EXPR;. The property
node carries name, type, contracts, value, and declaration
modifiers. Property syntax omits parameters, effects, and setters and
refuses async and const. Elaboration checks totality and the absence of
effects and allocation. Properties
Qualification covers all collection modes, grouped ranges, nested loops, contracts, and exits. It checks raw literals with embedded quotes and backslashes, format specifiers and escaped braces, and syntax-valid errors in formatting and loan checking. Check both AST roles and malformed neighbors for conditional expressions, labeled patterns, updates, guards, and properties, along with missing binders and loop delimiters. Represented inference and iterator qualification require cases through their actual semantic consumers. Native qualification
Concise syntax refinements
These forms shorten existing constructs rather than adding authority, proof rules or runtime primitives. Their checking and tooling coverage is recorded in the language reference. A consumer that does not support a form must refuse it, not approximate its meaning.
Negated and alternative patterns. value is not None means
!(value is None). An alternative pattern, such as None or Invalid,
uses a single match arm for either case. The initial forms admit only
nonbinding patterns, including wildcards whose discard is independently
legal. Negation binds no names, evaluates the subject once, and does not
discard or move it. An alternative uses the same scrutinee and tests
alternatives in source order; coverage, reachability, discards, loans,
grades and branch obligations must be valid for every alternative
individually. Initially alternative arms require a copyable scrutinee
and omit guards; the scrutinee cannot carry a pending result-verdict
obligation. A shared arm is not a permission to join distinct resources
or to duplicate the subject. Binding patterns (including as binders)
inside either form are refused.
Pattern test scope ·
Resource joins
Immutable output locals. InitBounds(10, out let low, out let high);
has the initialization and freshness rules of out var. The standalone
call must return Unit; its callee must initialize each output on every
normal return. No output name is visible during argument evaluation.
After a successful call, the new names enter scope together and are
immutable bindings. This does not relax the ordinary loan or ownership
rules (including writes through an exclusive loan).
Loan modes
Unchanged-value contracts. As the complete predicate of an ensures clause,
unchanged(dst.Base, dst.Length) abbreviates
(dst.Base == old(dst.Base) && dst.Length == old(dst.Length)).
The name is contextual in this position; elsewhere it remains an ordinary
identifier. Parenthesize an ordinary call to a callable named
unchanged to distinguish it from the clause shorthand. The nonempty
argument list uses the authored order. Every argument must
be an admissible pure value expression of the same equality-capable type
at entry and exit, and individually support the existing old checks.
An exit-only variable, including result, cannot make its entry snapshot
well formed. This syntax states equality of observed values only. Temporary
writes that restore the value still count as writes; no footprint,
restoration, no-write, access or authority promise is inferred.
Contract and effect rules
Pure definition blocks. A mathematical definition may use a block of immutable local bindings followed by exactly one final value return:
definition Nat Calculate(Nat x)
{
let doubled = x + x;
let adjusted = doubled + 1;
return adjusted * adjusted;
}
This elaborates as
let doubled = x + x in let adjusted = doubled + 1 in adjusted * adjusted
with the existing annotation, scope, dependency, grade, purity and
termination checks. It is not an imperative function body: assignment,
var, control-flow statements, cleanup, effects and early returns are not
admitted. The expression-body form remains available.
Expression-local bindings
Concise proofs. A sole theorem or lemma postcondition can be discharged with its ordinary checked justification:
lemma AddZero(Nat n)
ensures n + 0 == n
proof by AddZeroRight(n);
The proof means proof { assert n + 0 == n by AddZeroRight(n); }.
Multiple postconditions keep the explicit proof block. The ordinary
premises, termination, proof checking, obligations and replay remain
unchanged. A proof assertion of an existential can directly supply a
witness, for example assert exists (Nat n) => n + 1 == 2 by witness(1);.
For a single existential binder this checks the witness against the
binder's type and discharges the optional guard and
the body with capture-avoiding substitution of that witness. A wrong
witness, unresolved proof or unsupported goal
cannot become an assumption. The witness name is contextual in a direct
by witness(e) justification
(including a short declaration proof). Elsewhere it is an ordinary identifier;
parenthesize an ordinary call to distinguish it from witness introduction.
Proof mode
Nested record updates. table with { First.Count = count } updates
the selected field of a copyable record without repeating its receiver.
Resolve every segment as a declared instance field of a copyable record;
non-copyable records along the updated paths, computed properties and
duplicate or overlapping ancestor/descendant paths are refused. Evaluate
the receiver once and each initializer once, in recursive declaration
order. Paths must be authored in that order, which shares common prefixes
without reading or evaluating a receiver again. Construct the completed
nested records with all existing field-type, dependent-index and invariant
checks. This is a value update, not mutation or a new form of loan.
Record update syntax
Scoped using blocks. using (let h = Open()?) { Work(in h); }
is equivalent to { using let h = Open()?; Work(in h); }.
The existing initializer, lexical scope, cleanup and effect rules apply;
an initializer that propagates failure does not establish a cleanup
obligation. On success the resource is disposed at the end of this block,
including supported early exits, in reverse establishment order with
nested resources. The shorter spelling does not admit any exit that
the ordinary using declaration would reject.
Disposal rules
Contextual literals. Prefer buffer[0], value == 42 or
0..buffer.Length when their checked context uniquely determines the
representation. Keep explicit widths for unresolved or deliberately
represented values. This uses existing inference, not new default widths,
numeric conversions or relaxed bounds.
Contextual inference
The schema-2 parser retains the authored forms: not_pattern contains a
pattern; or_pattern contains alternatives; out_variable has an
immutable: true field for out let; using_block contains its binding
and body; dotted field-update names retain the full path span. A contextual
unchanged node contains its values; a block definition retains its block;
proof_by and witness contain the authored justification value.
Lowering these forms does not rewrite the authenticated source envelope.
The parser qualification must retain exact authored tokens and source spans. Semantic consumers compare each shorter form with its existing equivalent, including invalid neighbors, and prove the same obligations. Formatting preserves authored spellings rather than rewriting either direction.
Required-static constants
const has three uses.
- On a function, it marks a pure body for symbolic checking and compile-time evaluation. The function also accepts runtime calls. Ordinary pure functions remain eligible when called with static arguments.
- On a parameter, it requires a static argument at every call, including labeled, generic, partial and higher-order calls. A function can forward that parameter to another static parameter.
- On a value declaration, it requires an explicit type and an initializer
that can be evaluated at compile time. Use the resulting value by name.
For example,
Limitcan indexVec<Nat, Limit>. WritingLimit()would attempt to call a value.
module StaticExample;
public const Nat Square(Nat value) => value * value;
public const Nat Limit = Square(4);
public Nat Scale(const Nat factor, Nat value) {
const Nat multiplier = Square(factor);
return multiplier * value;
}
public Nat Runtime(Nat value) => Scale(factor: Limit, value: value);
Runtime supplies the static value Limit to Scale, so multiplier
evaluates to 256 while value is still a runtime input. Passing that same
runtime input as factor would fail. Runtime arguments retain their
call-by-value evaluation order. Erasure from the executable requires its
own evidence.
Constant declarations at module, container or local scope can refer to earlier constants and pure calls with static arguments. A reference to a surrounding runtime local or unmarked ghost or generic parameter fails, even in a dead branch. Forward references, cycles, mutation, unsupported effects or resources, and opaque calls also fail. Locals inside a pure call with static arguments are available during that evaluation.
The evaluator checks work, reduction, numeric and output limits. Exhaustion
fails the static check. The evaluator works on typed expressions independently
of the host's word width, without host eval or parsing emitted Gallina.
Evaluation grants no ownership, duplication, implicit conversion or proof.
The pure prototype evaluates Nat and bool. The
mathematical prototype also evaluates Unit, char, represented words and
bounded static vectors. Its static table evaluator
can freeze string literal bytes. Image placement determines whether a table
initializes static storage or is copied into a local value.
Both Menhir schemas preserve declaration order and the optional Boolean
const flag on functions and parameters. A constant or constant_local
node carries the name, type and initializer. Mathematical callable types,
lambdas and substitutions preserve static parameter requirements. Editor
navigation, hover and symbol queries use the checked declarations and
invalidate stale snapshots after an invalid edit.
Qualification covers both static and runtime calls, specialization, forwarding, dependent indices and higher-order calls. Refusal cases include ill-typed or missing initializers, reassignment, invalid static dependencies and resource exhaustion. Editor tests check signatures, navigation and source spans after token, UTF-8 and mixed-newline edits. Pure evaluation · Parser qualification
Native qualification
menhir --strict --infer --explain with zero unresolved conflicts, no unchecked runtime dependency, locked generator/compiler checks, fresh-generation comparison, full AST/precedence/span/error/budget/comment/literal fixtures, and holdfast-parser qualify binding all inputs with separate pure and surface verdicts (parser qualification).