Skip to content

Language guide

Gale is a statically typed language that compiles to readable Elixir for the BEAM. The compiler checks types, pattern exhaustiveness and contract formulas before emitting modules with honest @specs. A separate verification run proves contracts. Gale interoperates with ordinary Elixir and OTP.

This is the compact language specification, including the type system. Library APIs are documented separately; the rules for writing Gale are here. gale guide prints the copy embedded in your compiler; the website loads this same file. The toolchain is Elixir 1.20 on OTP 28 or newer. Sources use the .gale or .🌀 extension; a project picks one and never mixes both for the same module.

Hello, World!

mod hello
@moduledoc "A greeting."
pub fn greet(name: String) -> String {
"Hello, #{name}!"
}

Each file declares exactly one module. Compile with gale compile (or mix compile in a Mix project with mix_gale); output is ordinary Elixir sidecars named *.g.ex / *.g.exs, marked # Generated by Gale, do not edit. Never edit sidecars: edit the .gale source and recompile.

Module structure

mod shop.orders
@moduledoc "Order operations."
alias gale_std.result
pub type Status = Pending | Paid | Cancelled(reason: String)
pub fn label(status: Status) -> String {
case status {
Pending -> "pending"
Paid -> "paid"
Cancelled(reason: reason) -> reason
}
}

The mod declaration comes first. Aliases, behaviour declarations or implementations (declares / implements), the optional named struct or exception declaration, types, and functions may follow in any order. Names are collected for the whole module before bodies are checked, so declarations can refer forward. Documentation attaches to its following declaration; @moduledoc describes the whole module. Everything is private unless marked pub. Library module names must equal the Mix app name or begin with that name and a dot (shop.orders in app shop).

Module forms at a glance:

Form Purpose
mod path.name The file’s module
alias path.name [as short] Refer to the module as name / short
[pub] fn name(...) -> Type { ... } Function
[pub] type Name = ... Alias or algebraic data type
struct Name<A> { ... } / exception Name { ... } One module-owned struct or exception
[pub] opaque type Name = ... Type hidden outside its module
[pub] extern "Module.fun" name(...) -> Type Typed foreign function
[pub] extern type Name / extern struct "M" N {..} / extern exception "M" N {..} Foreign types
[pub] extern mod "Module" name [implements B<...>] Native module value
declares B<...> / extern "M" declares B<...> Behaviour (Gale / existing BEAM)
implements B<...> as Name Implement a behaviour, name the capability
callback name(...) -> Type / optional callback ... Behaviour callback declaration
predicate name(...) { ... } / lemma name(...) Erased proof declarations

Naming: snake case for modules, functions, and bindings; UpperPascalCase for type names (no underscores); constructor names start uppercase; predicates may end in ?. Comments start with #. @moduledoc, @typedoc, and @doc document the declaration that follows.

Lexical rules and grammar

Source is UTF-8. Lowercase identifiers match [a-z][a-z0-9_]* with an optional final ?; _ alone is a wildcard, not an identifier prefix. Types use UpperPascalCase; constructors start uppercase. Module paths join snake_case identifiers with dots; module segments cannot end in ?. mod also names a function in function declarations and expressions, as in integer.mod(a, b); at declaration scope it still introduces a module. Atom literals use :name (including uppercase names and a final ? or !). @ may appear after the first character, as in :foo@bar. A name cannot start with @. Quoted atoms are unsupported. true, false, and nil are atoms with special spellings. Comments run from # to the end of the line. Whitespace separates tokens; there are no semicolons.

The grammar below uses ? for optional, * for repetition, and capitalized metavariables for syntax described in the corresponding sections. Literal punctuation is quoted. Comma-separated lists may have a trailing comma.

Module = "mod" Path ModuleDoc? Alias* DeclarationHeader? Implementation*
StructureHeader? Declaration*
StructureHeader = ("struct" TypeName TypeParams? | "exception" TypeName) "{" TypedFields? "}"
Alias = "alias" Path ("as" Name)?
TypeParams = "<" Param ("," Param)* ">"
Param = TypeName (":" ("Type" ("->" "Type")+ | ClosedType ("|" ClosedType)*))?
Signature = Name TypeParams? "(" ClauseParams? ")" ("receives" Type)? "->" Type
ClauseParams = Pattern (":" Type)? ("," Pattern (":" Type)?)* ("when" Expression)?
FnParams = (Name ":")? Type ("," (Name ":")? Type)*
Function = "pub"? Qualifier* "fn" Signature Contract* (Block | ImplementationClause+)
ImplementationClause = "fn" Name "(" Patterns? ")" ("when" Guard)? Block
Qualifier = "pure"
Contract = ("requires" | "ensures" | "decreases") Block
CallableContract = ("requires" | "ensures") Block
Type = PrimaryType ("|" PrimaryType)*
PrimaryType = TypeName ("<" Types ">")? | QualifiedType | ParamName
| Atom | "true" | "false" | "nil" | "(" Type ")"
| "{" Types? "}" | "%{" TypedFields? "}"
| Qualifier* "fn" "(" FnParams? ")" ("receives" Type)? "->" Type CallableContract*
| "mod" Path ("<" Types ">")?
Block = "{" Statement* Expression "}"
Statement = Pattern (":" Type)? "=" Expression | Expression
| "assert" Block | "ghost" Block
LambdaParams = (Name | "_") (":" Type)? ("," (Name | "_") (":" Type)?)*
Lambda = "fn" "(" LambdaParams? ")" ("receives" Type)? "->" (Expression | Block)
Arm = Pattern ("when" Expression)? "->" (Expression | Block)

Function types may name parameters (fn(value: Integer) -> Integer); calls remain positional. Parentheses group expressions and types. {} is the empty tuple; tuples otherwise need at least two elements. Blocks execute statements in order and return their final expression. A newline before ( after a complete expression starts a new expression; chained calls stay on one line. There is no executable code at module scope.

Use one input type for a function that accepts several related alternatives. An ADT or tuple union can retain a relationship between fields; pass that value as a whole, or match its alternatives before calling separately named functions. Destructured fields do not establish a relationship between independent arguments.

Resolution. Aliases can name modules or namespace prefixes. In Gale source, alias the submodule you use (alias gale_std.list gives list). For a top-level Gale package, drop the gale_ prefix explicitly (alias gale_req as req). Prefer float over std_float; rename local values that would shadow the alias. Use an explicit, descriptive alias when needed to keep names clear. An unqualified function resolves locally, then through built-ins; qualified names resolve through aliases or full module paths. Local values can shadow module aliases. Functions resolve by name and arity, with one shared signature and contract per identity. References use a uniquely identifying expected function arity; without that context, write an explicit lambda making the intended call. There are no distinct-signature overload families. Types and constructors have their own namespaces. Constructors may be qualified as module.Type.Constructor or Type.Constructor. For a bare constructor, an already known expected nominal type filters visible candidates; otherwise exactly one visible candidate is required. An unannotated binding, Term, or ambiguous union cannot disambiguate constructor names. Context never imports a constructor or comes from trying its arguments. Prelude constructors are visible without an alias and follow the same rules. Option.Some and Result.Ok qualify builtin constructors unless those type names are shadowed. Dot calls invoke modules or module capabilities, not instance methods; call a closure as f.(args). File paths mirror module paths below lib/ or test/; a library module belongs to its Mix app’s namespace.

Reserved Gale words:

mod declares implements opaque pub alias as fn with else when case receive
receives after type struct if cond true false nil not and or extern exception
raises requires ensures invariant decreases in

Target-language words also rejected as identifiers:

do end catch rescue module match for import quote require super try unquote
unquote_splicing def defp defmodule defstruct defexception defmacro defmacrop
defguard defguardp defdelegate defimpl defprotocol defoverridable

callback, optional, pure, predicate, lemma, assert, ghost, and proof-only forall are contextual forms. Old spec / proof fn declarations, proof { } blocks, and lemma fn are unsupported.

Types

Built in:

Type Meaning
Integer, Float Separate numerics; operators never mix them
String UTF-8 text (a Binary)
Binary Byte-aligned bits (a Bitstring)
Bitstring Any immutable bit length
Atom, :ready Any atom, or one literal atom
Boolean true | false
Term Any BEAM value; decode or refine before use
Never No possible value
List<A>, Map<K, V> Linked list, dictionary
Range Native integer range struct
{A, B}, {} Tuples, empty tuple
%{name: String} Exact record with fixed atom keys
fn(A) -> B, fn() receives M -> A Function value, with optional mailbox
AnyPid Untyped process reference
Reference Raw BEAM reference; no monitor or timer provenance
ChildSpec<A> Opaque native child specification for supervisors
Nilable<A>, Timeout A | nil, Integer | :infinity
Order Less | Equal | Greater
Option<A> Some(A) | None
Result<A, E> Ok(A) | Error(E)

Never has no normally returned values. A branch that calls a Never-returning function can fit any result type; proofs must still establish that the branch cannot produce a value. This says nothing about process survival or termination.

ChildSpec<A> is an opaque native value; its service parameter constrains typed startup interfaces, not a stored field. Proofs can transport and compare a child specification without assuming its fields or a running child. Even ChildSpec<Never> is not an empty type.

Pid<M> in the rules below denotes gale_std.process.Pid<M>; unlike AnyPid, it requires that module qualification or a local type alias. Other OTP handles likewise come from gale_std, not the builtin type namespace. Native declarations specify their runtime shape with a versioned representation(1) clause. The stdlib declares typed PIDs as pid and monitor and timer capabilities as reference; gale_std.process.Ref aliases the raw Reference primitive. A typed PID may widen to AnyPid, and a reference-shaped capability may widen to Reference. These forgetful conversions preserve no mailbox, service, monitor or timer authority. Runtime shape tests cannot recover such nominal capabilities. Their type arguments remain invariant.

Join alternatives with | (:open | :closed). Generic parameters use angle brackets. nil is the atom :nil; absence is Option, failure is Result.

Core type names are reserved: Integer, Float, String, Binary, Atom, Boolean, Term, Never, List, Map, AnyPid, Reference, ChildSpec, Nilable, Timeout and Range. Declarations and generic parameters cannot replace them. The ordinary prelude ADTs Option, Result and Order may be shadowed by local types. Constructor names have a separate namespace, so Integer(Integer) can still declare a constructor with an integer field.

Algebraic data types declare a closed set of constructors:

pub type UserId = Integer
pub type Tree<A> =
| Leaf
| Node(A, Tree<A>, Tree<A>)

Fieldless constructors (Leaf) are values; constructors with fields are constructed directly (Node(1, Leaf, Leaf)). Payload constructors are not function values: write fn(value) -> Some(value) for a callback. Constructors are namespaced by their ADT. Named declarations require labels (Cancelled(reason: r)) and defaults (C3(f: T, g: U = default); defaulted fields come last). Labeled constructor calls can be nested inside other expressions. Constructors may fix their result instance for reply-indexed protocols:

pub type Request<Reply> =
| Count : Request<Integer>
| Rename(name: String) : Request<:ok>

Matching a Request<R> refines R per branch. Indexed types are invariant; incompatible constructors are unreachable for a concrete index. Constructor constraints apply across the whole pattern before checking its literals: {Count, 1} and {1, Count} can both refine the corresponding R position to Integer. Guards and literal comparisons do not create type equalities.

Constructor indices are first-order types (including tuples and injective nominal type applications). A bare parameter of kind Type -> Type can be an index of the matching kind; an abstract application such as F<A> cannot. Keep uniform generic payloads and closed indexed payloads. Each constructor parameter must occur as a whole result index; compound indices are allowed when closed, or when their parameters also have a whole-index occurrence. A known subject type is required. Reject Pack(A): Family<List<A>> and other nonuniform forms that would introduce existential payload witnesses. Pattern facts remain local to the successful branch and cannot escape into sibling branches.

Transparent aliases cannot contain recursive alias cycles; ADTs and structs can be recursive. A constructor’s defaults must be trailing and effect-free; they cannot refer to other fields. Omitted defaults are evaluated at the call site after supplied expressions, once in declaration order; explicitly supplied fields skip their defaults. Defaults must terminate. Pattern omission means wildcard and never evaluates a default. Labels do not create ordinary function keyword arguments. The default expression is part of the constructor’s proof interface. Proofs retain its checked computation and obligations; a public function called by that expression still exposes only its own declared contract.

Records are structural and exact: extra fields make a different type:

user: %{name: String, age: Integer} = %{name: "Ada", age: 36}
older = %{user | age: user.age + 1}
name = user.name

Unannotated fields keep their precise types: %{age: 36} has field type 36. Declare age: Integer when updates should accept other integers. Updates check against the established base type; later result context cannot widen its fields.

An exact record fits Map<K, V> when its fields fit. Maps with runtime keys use %{key => value}.

Structs declare an explicit type name and are owned by their module; they emit real Elixir structs:

mod shop.user
struct User {
name: String,
active: Boolean = true
}
pub fn new(name: String) -> User {
%User{name: name}
}

A module can declare at most one struct Name { ... } or exception Name { ... }. The type name conventionally matches the module’s final segment in UpperPascalCase, but may differ: mod shop.storage with struct Entry { ... } exports shop.storage.Entry in Gale and emits %Shop.Storage{...} in Elixir. The Gale type name never introduces a nested BEAM module. Declarations require a name; unnamed struct blocks are unsupported. Module-owned structs and exceptions are public.

A generic struct writes struct Box<A> { value: A } and is used as Box<A>. Omitted fields use their declared defaults.

Defaults are checked even if every use supplies the field. They resolve names in the declaring module and cannot read other fields or caller locals. Explicit fields evaluate once in source order, then omitted defaults evaluate in declaration order on each construction. Constructor function values keep their full arity; only direct constructor calls and struct literals can omit defaults.

Struct fields use the same contextual checking as constructor arguments. Without an annotation, %Box{value: 1} retains Box<1>; checking it against Box<Integer> establishes an integer field that can later be updated with another integer. Matching uses that established field type. The native Elixir type is the owning module’s t(...), with the struct’s type parameters.

Exceptions are named, module-owned structs with native Elixir exception behaviour. Construction, field access, updates and patterns use the same syntax as ordinary structs. Creating an exception or returning it inside Error never raises it or captures a stack trace:

mod shop.errors
exception EncodingError {
issues: List<String>
}
pub fn message(error: EncodingError) -> String {
"Encoding failed"
}
pub fn reject(issue: String) -> Result<Integer, EncodingError> {
Error(%EncodingError{issues: [issue]})
}
pub fn issues(result: Result<Integer, EncodingError>) -> List<String> {
case result {
Ok(_) -> []
Error(%EncodingError{issues: issues}) -> issues
}
}

This emits Shop.Errors with defexception; reject("invalid") returns {:error, %Shop.Errors{issues: ["invalid"]}}. Other modules refer to the Gale type as errors.EncodingError after alias shop.errors.

Exceptions can declare defaults but cannot have type parameters. Provide either message: String (with an optional default), which generates the native message callback, or pub fn message(error: EncodingError) -> String. A custom callback takes precedence over a message field, has no type parameters or mailbox requirement, and is checked as ordinary Gale code. __struct__ and __exception__ are compiler-owned fields and cannot be declared or updated. Exception types remain distinct nominal types in error unions; matching their structs and fields follows the ordinary exhaustiveness rules. Result accepts ordinary structs and variants as well as exceptions. Raising remains an explicit foreign operation; an exception declaration adds no implicit control flow.

Opaque types hide their representation behind a nominal boundary: pub opaque type AccountId = Integer. Only the defining module may explicitly construct AccountId(raw) or open AccountId(raw) in a pattern. Each operation erases to the raw BEAM value. A plain binding keeps its opaque type, including inside the owner; raw fields and operators become available after opening it.

pub opaque type AccountId = Integer
pub fn new(raw: Integer) -> AccountId { AccountId(raw) }
pub fn value(AccountId(raw): AccountId) -> Integer { raw }

Opaque constructors and patterns take one positional representation argument; they use the declared type name and are unavailable outside its module. The constructor may be captured as a function, with a function annotation to fix generic parameters; invocation still owes the invariant of its result. Nested opaque boundaries require a constructor or pattern for each layer. A raw value cannot implicitly become opaque through a return annotation, call argument, equality, generic inference, or container context. Construct collection elements explicitly: [AccountId(1), AccountId(2)].

An invariant(value) { ... } requires verification at every explicit construction, including discarded values. Its binder has the raw representation type. Opening a typed value preserves its established invariant. Compile and check do not prove invariants. Optional runtime checks validate them on concrete values; validate untrusted inputs in the public constructor or decoder. opaque type Marker without a representation is uninhabited and has no value constructor or opening pattern. It may distinguish type arguments such as Handle<Marker>, whose native values remain inhabited. Marker parameters remain invariant, empty marker union alternatives are removed, and invariants require a representation.

Opaque names add no runtime tag. Use a public ADT or tagged tuple when callers need to distinguish outcomes, and expose an accessor when they need to inspect a value. Matching external data against the representation cannot establish an opaque identity; its module must supply a constructor or decoder.

Type system

Inference and annotations. Named functions annotate results and parameters in an inline definition or one shared signature header; implementation heads contain patterns. Local bindings and lambdas are inferred or checked against their expected type. Declare generic parameters explicitly (fn identity<A>(value: A) -> A). Each call instantiates a named generic function afresh. Local bindings are not implicitly generalized into generic functions. A type parameter means the function must work for every permitted instantiation; it is not dynamic Term.

Literal types. Integers, non-interpolated strings and atoms can name exact values: type ErrorCode = 1 | 2, type Status = "ok" | "error", or :ready | :waiting. Integer and string literals retain these precise types unless an annotation widens them. Inferred alternatives within the same scalar family retain a finite union; mixed families need an explicit common type. Arithmetic returns its declared numeric type, so 1 + 1 has type Integer. Float literal types are not supported. Finite Float literals are supported in patterns and dictionary pattern keys. They observe strict runtime identity, including distinct 0.0 and -0.0 on the supported BEAM runtime. Bindings retain Float; a literal pattern does not cover its open domain, so matching a Float requires a fallback.

Compatibility. Subtyping passes the same BEAM value without conversion:

Rule Consequence
Never fits every type; every type fits Term Never has no values; Term needs narrowing before use
:ready fits Atom; String <: Binary <: Bitstring Subtyping views the same native value
Integer does not fit Float Convert explicitly; arithmetic never widens numbers
A member fits its union Integer fits Integer | :infinity
Records require the same field set A record with extra fields does not fit a smaller record
Aliases are transparent; ADTs, structs, opaques, and extern types are nominal Similar representations do not make distinct declarations interchangeable

Record fields and tuple components may widen without changing shape. An exact record also fits Map<K, V> if all its keys and values fit. A struct does not implicitly become a record; construct the record explicitly.

Generic compatibility (variance). List<A>, Option<A>, both Result parameters, and dictionary values can widen with their contents (covariance). Map<K,V> keys are invariant; widening never changes native entries. Function results may widen, but a replacement function must accept at least the original parameter types (contravariance). A transparent data parameter is covariant only when it is used positively and never negatively or through an invariant type argument. Negative-only, mixed, and unused parameters are invariant. Recursive declarations are analyzed together before checking function bodies. Opaque and extern parameters, behaviour arguments, typed PIDs, server handles, and mailbox types require the same type arguments (invariance). In particular, Pid<Integer> cannot become Pid<Term>.

An operation can still declare that it combines independent domains. map_set.union accepts MapSet<A> and MapSet<B> and returns MapSet<A | B>; map.merge combines both key and value domains. These operations construct new results with the declared combined domains.

Narrowing and coverage. case and receive narrow values with patterns and guard type tests. is_binary proves Binary, not valid UTF-8 String; use a decoder for that. Every possible case input must be covered; selective receive may handle only part of its mailbox. Pins and guards can fail and generally need fallbacks. Bindings and <- need patterns that cannot fail. Result<A, Never> needs only an Ok arm.

Finite integer and string unions are exhaustive when every member is covered:

type ErrorCode = 1 | 2
fn describe(code: ErrorCode) -> String {
case code { 1 -> "missing" 2 -> "invalid" }
}

Removing the 2 arm reports a missing value. Changing the parameter to Integer requires a fallback. An annotation keeps its whole domain even when the initializer is a singleton: code: ErrorCode = 1 still requires both arms. The case result type never narrows the scrutinee. Unknown guards may fail and do not remove values from coverage. String patterns compare decoded bytes; equivalent escapes match, but Unicode normalization is not implicit.

Tuple coverage preserves combinations: matching {1, 1} and {2, 2} is exhaustive for {1, 1} | {2, 2}, but leaves {1, 2} and {2, 1} uncovered for {1 | 2, 1 | 2}. Nested patterns retain the same distinction. A tuple binding such as {code, message} = response must cover every value of the established type. A literal component is safe only when that component is already known to have that exact value; otherwise use case.

Constructor payloads follow the same rule. For type Box<A> = Wrap(A), Wrap(1) and Wrap(2) exhaust Box<1 | 2>. A Box<Integer> also needs a pattern such as Wrap(_) for the other integers. Patterns use the same constructor qualification and expected-type rules as constructor values.

Unions and representation. A union adds no runtime tag. Gale flattens unions, removes redundant members, and rejects ambiguous constructor tags. Use {:value, Integer | String}, not two tuple members sharing the same tag and arity. Two ADTs with the same lowered constructor tag and arity cannot be joined into a union. These checks matter because fieldless ADT constructors emit snake-case atoms and constructors with fields emit tagged tuples: None is :none, Some(1) is {:some, 1}, and Ok(1) is {:ok, 1}.

Capabilities. mod B<...> exposes a declared behaviour’s callbacks; a module must implement it to be passed. receives M is a function capability checked at call sites, not just documentation. Functions without a mailbox requirement may run in any mailbox context. Indexed constructors such as Count: Request<Integer> refine the reply type when matched. Behaviour parameters may abstract over a type constructor (Call: Type -> Type), as in gale_std.gen_server.Server; this is not unrestricted higher-rank typing.

Kinds and equality. Ordinary parameters have kind Type. A parameter F: Type -> Type takes one type argument; more arrows set a fixed arity. For example, type Box<F: Type -> Type, A> = Box(F<A>) accepts List as F. Generic declarations are rank one: functions cannot take a polymorphic function parameter. Strict equality compares complete runtime values of related types, including Term and a single generic parameter. Literals from the same scalar family also compare inside matching tuples, records and covariant data: [1] != [2] is valid. Invariant resource arguments must still agree. Either operand can supply an established type to a literal or callback that needs context; equality does not invent a mixed-family union or widen existing bindings. There is no Eq bound or custom equality implementation; use explicit comparators for ordering.

Inference procedure. Expected types flow into function/lambda bodies, annotated bindings, call arguments, collection components, and branch results. Named calls infer generic arguments; explicit call-site type arguments are excluded. Independently established result context guides parameter inference. For example, wide: Integer = choose(1, 2) establishes Integer, while an unannotated value = choose(1, 2) retains 1 | 2.

The checker collects subtype bounds from all arguments before choosing an inferred parameter. It can use an established operand type, a finite union of literals from one scalar family, or a structural combination through covariant components. Invariant components must agree. It does not invent a mixed-family union, widen literals to a primitive type, or guess Term to reconcile arguments. A broad expected result does not widen an existing invariant input: get<A>(Key<A>, A) -> A called with Key<Integer> and 0 infers Integer, even when returned as Term. Callback input constraints follow the same rule. The result must still fit its annotation; Key<Term> requires a compatible invariant input. Nested construction can consume result context when its type cannot be established independently.

Explicit callback input annotations and already typed function values also supply candidates. For wrap<A>(fn(A) -> Integer), a callback accepting Integer can establish A = Integer; an unannotated callback cannot supply its own missing input type. Candidates must satisfy every argument. Inputs 1 | 2 and 2 | 3 do not invent the intersection 2, while an independent argument of type 2 can establish that candidate.

A match uses the scrutinee type established by these rules. A 1 | 2 binding needs both literal cases even if initialized with 1; an Integer binding needs a fallback. Match arms cannot choose a smaller generic instantiation.

Ambiguous parameters require an annotation. There is no blanket Never default. Bottom defaults are limited to specified empty covariant values and adaptation of an explicitly mailbox-free callback to a mailbox parameter. Unrelated phantom parameters remain ambiguous. Declared parameters are rigid, and finalized local bindings cannot be inferred again at later uses. An independently typed invariant input can constrain a union with one unresolved bare parameter: matching Box<nil | T> against Box<nil | Integer> supplies Integer as T’s lower bound. Other operands may add bounds, and the completed substitution must still match the entire invariant input. Several unresolved union parameters remain ambiguous; return context alone does not choose their assignments. An empty residual in such an independently typed input supplies the absent payload’s Never default, without defaulting unrelated generic parameters. Without context supplying their payload types, None has type Option<Never> and Ok(1) has type Result<1, Never>. Context can widen these payloads; it cannot turn an incorrect payload into a valid one.

A literal can also establish a payload-free union arm. For example, gale_std.option.from_nil(nil) infers Option<Never>, so matching None is exhaustive. Real payload evidence or an explicit Option<Integer> context takes precedence. This default requires covariant data occurrences; it cannot choose an unknown callback input, invariant resource type, or unrelated parameter.

Transparent parameters used only positively are covariant; used only negatively, in both, or in neither position they are invariant. Contravariance arises only structurally, in function argument positions. Function subtyping also requires equal arity and compatible mailbox capability: a mailbox-free function fits one requiring a mailbox, but not conversely; two present mailbox types must be identical.

Union normalization flattens nested unions, drops Never, duplicates, and members already covered by another member (Term covers all). It does not distribute unions through containers. Besides ADT tag/arity collisions, ambiguous unions include an ADT and an atom/tuple alternative accepting its tag, distinct foreign exceptions for the same native module, and an opaque value overlapping its exposed runtime shape. Structural unions can overlap; pattern matching narrows all compatible members without inventing nominal identity. Struct identity and distinct outer tags can distinguish alternatives. For example, an opaque integer can appear beside :missing; after matching :missing, the remaining value keeps its opaque type. It cannot appear beside Integer, since both alternatives admit the same runtime values. Matching a hidden value’s representation does not grant access to it; use its public API.

Boundary of the guarantee. Extern signatures are trusted. Decode external Term values rather than claiming a type through an unchecked extern. --runtime-typechecks (or the Mix option) adds checks at supported function boundaries; it does not validate all foreign process messages or prove contracts. Typing does not establish termination, delivery, liveness, or absence of native exceptions. Contracts require a separate verification run.

Functions and bindings

Every function has one annotated signature and contract per name/arity. Keep inline typed single-body definitions, or a contiguous shared header followed by pattern heads. The first matching head wins; the family must cover every valid typed input. Clauses do not repeat independent contracts or signatures. Different arities are separate functions. There are no ordinary default parameters.

mod counter
pub fn count(items: List<Integer>) -> Integer
ensures { result >= 0 }
fn count([]) { 0 }
fn count([_ | tail]) { 1 + count(tail) }

The header describes the callable input domain. Patterns select values within it; they do not shrink the signature to make coverage succeed. Header argument names denote whole inputs in the shared contracts, independently of head binders:

pub fn sum(items: List<Integer>) -> Integer
fn sum([]) { 0 }
fn sum([head | tail]) { head + sum(tail) }

Coverage considers all argument positions together. Clauses for (1, 1) and (2, 2) leave (1, 2) and (2, 1) uncovered when both parameters have type 1 | 2. An unknown guard leaves its failure path for later clauses. Preconditions do not discharge missing head coverage. The header owns visibility, generic parameters, the result type, mailbox and contracts. Each head proves that shared contract under its pattern and guard facts. Head-local names do not enter the header’s contracts.

pub fn add<A>(item: A, items: List<A>) -> List<A> {
[item | items]
}
pub fn twice() -> Integer {
count: Integer = 3
doubled = fn(value: Integer) -> value * 2
doubled.(count)
}

Values are immutable and bindings are lexically scoped. Rebinding a name creates a new binding identity; old captures, pins and contracts retain the version they resolved. Nested branches/functions may shadow outer names. Annotate a binding with : Type before = when inference needs help. Lambdas capture by value and may omit parameter types when an expected function type supplies them. _ discards a parameter without introducing a binding. The lambda body uses its own receives annotation; neither the surrounding function nor an expected type grants it a mailbox capability.

Generic calls collect independent argument types before checking callbacks that need them. A list with element type 1 | 2 supplies that finite callback input; a list annotated List<Integer> supplies Integer. This also works when the callback appears before the data argument. Runtime arguments still evaluate in the order written.

For accumulator callbacks, the initial value can seed inference and the callback result can enlarge the domain. An integer addition supplies Integer, so ordinary numeric folds need no accumulator annotation. The compiler rechecks callbacks against the final domain, including match exhaustiveness. Explicit annotations remain authoritative. If no domain can be established, add a parameter or result annotation. A nested generic call such as map_set.new() can receive its type from another argument to the enclosing call. A generic factory with inputs can also wait for sibling context. For a factory that returns a function, established function inputs provide context while the factory’s own arguments establish its result. Checking order never changes runtime evaluation order, and an unrelated unresolved parameter still requires an annotation.

Expected union types can supply generic result context through a unique tagged tuple alternative with the same literal tag and arity. Multiple alternatives with that tag remain ambiguous; the completed call must still fit the entire expected type.

f(x) calls a named function; f.(x) calls a function value. A closure call evaluates its callee once, then its arguments from left to right. A named function can be used as a value: callback: fn(Integer) -> Integer = identity. Qualified references follow the same visibility and alias rules as calls. An expected function type selects the arity of a name with several arities. The reference retains that arity’s one signature and the original ordered clauses. An expected arrow may restrict its input through ordinary function subtyping; its output remains the declared result type. A narrower argument does not select a different result signature. Without an expected arrow, a name with several arities needs a wrapper lambda. Creating a reference does not execute the function or require its mailbox; calling it checks that capability. Local function values are monomorphic.

fn classify(value: Integer | String) -> Integer
fn classify(value) when is_integer(value) { 1 }
fn classify(value) when is_binary(value) { 2 }
pub fn classifier() -> fn(Integer | String) -> Integer { classify }

Pipelines pass the value as the first argument. That value is evaluated before the callee and the remaining arguments, including for a closure target:

items |> list.map(transform) |> list.take(10)

Function contracts and purity

Named function aliases may bind argument names and carry contracts:

mod steps
pub type Next = pure fn(value: Integer) -> Integer
requires { value >= 0 }
ensures { result == value + 1 }
pub fn next(value: Integer) -> Integer { value + 1 }
pub fn run(step: Next, value: Integer) -> Integer
requires { value >= 0 }
ensures { result == value + 1 }
{
step.(value)
}

The alias contract belongs to every invocation. Captures, stored/returned callbacks and behaviour dispatch preserve their established interface facts. Implementations accept at least the interface’s domain and establish its guarantees. A plain function type cannot silently erase an unmet precondition. Global aliases reference invocation arguments, not captured runtime variables.

pure fn supplies deterministic, effect-free, terminating logical application on the stated domain. Pure externs/callbacks are explicit; named Gale helpers establish eligibility through bodies/dependencies. Ordinary recursion may diverge; contracts hold on normal return. Spec helpers/defaults/lemmas need proved decreasing measures, including mutual recursion. A server loop may run forever while every completed transition preserves its invariant.

Optional pure requests logical-call eligibility: determinism from arguments and immutable captures, no observable effects, and normal termination on the domain allowed by the parameter types and requires conditions. Returning an Error(...) value is a normal return. Source declarations and supplied callback implementations owe separate effect and termination checks; writing pure never proves either property. The compiler checks effects; gale verify must discharge termination obligations. Named source helpers can establish the same eligibility from their bodies without a qualifier. An extern pure declaration explicitly trusts both properties because Gale cannot inspect its implementation. There is no public total qualifier or termination-trust annotation.

call_requires(callback, arguments...) and call_ensures(callback, arguments..., output) are proof-only observations of a callback’s invocation contract. Arguments appear individually in the callback’s declared order; a zero-argument callback uses call_requires(callback) and call_ensures(callback, output). Both return Boolean formulas and may occur in contracts, predicates, assertions and ghost code, never runtime code or guards. They require a statically known function interface without a mailbox. The input and output expressions must have the declared argument/result types. Observing a contract does not call the callback, establish termination, or prove that an invocation happened. Requires observes admitted inputs; ensures relates admitted inputs to outputs permitted by the established contract. A weak postcondition permits multiple outputs and does not make a callback deterministic.

After a real callback invocation, its returned value satisfies call_ensures. Generic higher-order functions can publish that relation without requiring pure callbacks. Checked construction and function-interface conversions retain only justified contract facts; they cannot strengthen an unknown callback. Captures are immutable Gale values. Effects may still observe changing process state or external resources; these observations do not model those resources’ transitions.

A lambda created in a predicate, specification or ghost block can return a callback-contract observation and pass it to a pure logical helper. This observes the callback’s permitted inputs/results; it does not invoke the callback or require that callback to be pure. The lambda and its captured proof values stay erased. A helper that actually invokes an unknown callback in logic still requires that callback’s checked logical-call eligibility.

Collection selection predicates and ordering comparators require pure fn. Mapping, accumulation and action callbacks remain ordinary fn, permitting effects and normal-return contracts. Native pure declarations explicitly trust logical eligibility; native effectful declarations can publish callback result relations without acquiring logical-call eligibility. There is no pure when syntax.

Logical eligibility and body visibility are separate. A contracted source helper can supply its checked contract to proofs while its implementation is verified separately. Ordinary calls also carry the implicit guarantees of their argument and result types. Small eligible private helpers without postconditions retain bounded checked body summaries, with or without a pure annotation; an imported interface never discharges its implementation. Passing a known pure callback to an eligible contracted helper keeps that contract boundary. Its body is not specialized into each caller merely because the callback is known. Put the callback/result relation consumers need in the helper’s contract; its implementation and callback conformance still prove independently.

Finite-choice generic parameters such as <N: Integer | Float> admit one listed closed type per instantiation, not the union. Bodies are checked and proved for every choice. This general user-accessible facility preserves the numeric kind for Kernel abs/min/max; it adds no trait search or general subtype-bound solver. Ordinary generics keep contextual/unification inference. Ordering two values of the same finite-choice parameter is allowed when every choice supports that ordering. Numeric negation preserves that parameter when every choice is Integer or Float. Separate parameters remain independent even when they list the same choices. Choices may also be closed compound types, such as <C: List<Integer> | List<String>>. A mixed List<Integer | String> does not select either choice. A single choice fixes the type in the body; an implementation may accept more choices than its callback interface requires.

A direct call to an implementation may use its callback’s promised results only when the actual type arguments satisfy the callback’s choices and its value preconditions hold. That proof depends on the provider’s conformance proof. Calls outside the callback’s type domain retain the implementation’s own contract.

Values and literals

Integers are arbitrary precision and accept decimal, 0xFF, 0o755, and 0b1010; underscores occur only between valid digits. Floats use finite binary64 (3.14, 1.0e3); scientific notation requires the decimal point. Preserve signed zeros, native rounding and underflow; reject nonfinite literals. Triple-quoted expression heredocs support multiline text and remove closing-delimiter indentation. Strings support interpolation and ordinary Elixir escapes: quote/backslash, \n, \t, \r, \0, \a, \b, \v, \f, \e, \s, \uNNNN, \u{...}, \xNN, and escaped interpolation (\#{...}). Validate the complete decoded static fragment as UTF-8; adjacent byte escapes may form text; interpolation accepts String, numbers, booleans, and atoms (convert raw bytes with gale_std.string.from_binary first). Embedded expressions evaluate once from left to right; an exception stops evaluation. Interpolation always produces String, even when its pieces are literals. Conversion follows native Elixir string conversion: booleans become "true"/"false", atoms omit the colon, and nil becomes an empty string. Nested strings and heredocs use the same rules. List cons is [head | tail]. timeout: 5_000 in a list is the tuple {:timeout, 5_000}. Lists must have proper list tails. An empty list without context has type List<Never>; List<A> context supplies A directly. Nonempty lists collect all element types before choosing a common type: [1, 2] infers List<1 | 2>, while [1, "one"] needs explicit context such as List<Integer | String>. List construction evaluates elements in order, then an authored tail. Keyword items keep their order and duplicates. %{} without context has type Map<Never, Never> and fits any dictionary type; %{key => value} constructs a map with arbitrary typed keys. %{field: value} constructs an exact atom-keyed record when all entries use named fields. Mixed named and arbitrary-key entries construct a dictionary. Dictionary entries evaluate key then value, in source order; the last duplicate key wins. Duplicate record fields are errors. map_put(key, value, map) inserts or replaces an entry and returns Map<K | Key, V | Value> for a Map<K, V> input. map_delete(key, map) removes an entry if present and retains Map<K, V>. Both leave the input unchanged and evaluate arguments once, from left to right. Exact records may be widened to dictionaries for these operations; native structs are not dictionaries. These are ordinary total operations available in bodies and contracts, and are not permitted in guards. Map<K, V> specifies key and value types; it does not fix a map’s size or fields. Use an explicit size observation for a particular value. Exact record types specify their fixed field shape. Library functions use ordinary type inference and contracts; no library function receives special inference rules.

Strings use Unicode scalar escapes of one to six hex digits; surrogates and values above U+10FFFF are rejected. Heredocs start with a newline after the opening delimiter. Documentation heredocs contain raw text.

Expressions evaluate eagerly in source order, except short-circuit and / or and the selected branches of control-flow forms. Values are immutable; record/struct updates preserve the original value and require existing fields. A field read on a union requires that field on every member and joins its types. Updates on unions preserve each alternative’s field types and tag/payload correlations. No update can combine a tag with another variant’s payload. Each replacement must fit its field in every alternative; otherwise match the alternative before updating.

Bitstrings

Use <<...>> for construction and parsing. Integer segments default to unsigned, big endian, 8 bits; value::8, integer, signed/unsigned, big/little and size(nonnegative_literal) are supported. Encoding keeps the native low bits, including for out-of-range integers. Width zero is valid. Complete binary/bytes and bitstring/bits payloads may be concatenated.

mod packet
pub fn frame(size: Integer, payload: Binary) -> Binary {
<<size::16, payload::binary>>
}
pub fn payload(packet: Binary) -> Option<Binary> {
case packet {
<<size::16, data::binary-size(size)>> -> Some(data)
_ -> None
}
}

Patterns may use a constant or previously bound Integer for payload size, including an earlier segment binding. Binary sizes count bytes; bitstring sizes count bits. A negative dynamic size fails the match. Only a trailing payload may omit size. <<rest::binary>> covers Binary; its bitstring form covers Bitstring. Prefix/content/length constraints generally need a fallback. Binary matching on Bitstring additionally needs alignment. A pinned or repeated payload compares the whole extracted value, including its length. An explicitly sized match succeeds only when that length also agrees.

Construction excludes sized payload extraction; use a fallible pattern. Float/UTF/native-endian segments, custom units, runtime integer widths and general computed sizes are excluded. String literals contribute decoded UTF-8 bytes. bit_size observes bits; byte_size observes bytes. Proofs model length, concatenation, alignment, integer encoding and match facts.

Control flow

Every form is an expression and returns a value.

if ready {
"ready"
} else {
"waiting"
}
cond {
count == 0 -> "empty"
count < 10 -> "few"
true -> "many"
}
case result {
Ok(value) -> value
Error(:missing) -> fallback
Error(:invalid) -> fallback
}
with {
user <- load_user(id)
email <- validate_email(user.email)
email
}

if always has an else; conditions are Boolean. The final cond condition must be the literal true. cond evaluates conditions once in order and evaluates only the first selected body. Conditions may call ordinary functions; exceptions propagate. Each body receives the type facts from its successful condition, and later arms receive facts from earlier conditions being false. Combine conditions with and or or; cond does not take when guards. case checks arms top to bottom; the compiler rejects missing cases and unreachable arms. with chains Results: each <- unwraps Ok, the first Error returns, and the final expression wraps in Ok. Ordinary = bindings may appear between steps. Both binding forms require infallible patterns; an annotation on <- describes its success payload. The error type joins all step errors without erasing their distinctions. An else matches unwrapped error payloads and every arm must return a Result. It sees the scope from before the with, and must handle every possible error. Step bindings stay inside the successful path. Verification follows this same order: later steps and recovery owe their contracts only on paths that execute them. Exceptions still propagate normally:

with {
value <- read_value()
value
} else {
:missing -> Ok(0)
:invalid -> Error(:bad_input)
}

Prefer with to nested case expressions when each successful Result feeds the next operation. Adapt errors at the step that produces them when stages need different error meanings. Use named helpers for distinct branch behavior, and match tuple or list shapes directly when possible. Keep independent validation accumulating all failures; replacing it with with would stop at the first error.

Patterns

Patterns appear in bindings, case, with, and receive:

_ # ignore
name # bind
^expected # compare with an existing binding
{left, right} # tuple
[head | tail] # non-empty list
%{name: name} # record
%{"name" => name} # dictionary subset
{same, same} # bind once, then compare by strict equality
whole = Some(value) # bind the whole value and a nested field
Some(value) # ADT constructor
"GET " <> rest # non-empty string prefix

With a new name, an alias pattern whole = pattern gives whole the matched type while binding the fields inside pattern. It covers exactly the values that the nested pattern covers. For example, whole = {:ok, value} retains the matched tuple for passing to another function. Aliases can be nested and used in function heads or inside binding patterns; the nested binding pattern must still be infallible. The left side must be a binding name or _. If the name already occurs in the pattern, it adds a strict-equality check against that first binding instead of introducing another binding.

| in a pattern is only the list-tail marker; use separate arms for alternatives. Bindings and with require infallible patterns; refutable patterns belong in case or receive.

For List<A>, [] and [head | tail] cover every value. The head has type A and the tail has type List<A>. Fixed-length patterns such as [one] leave longer lists uncovered. Finite element types remain precise: matching List<1 | 2> with [], [1 | _], and [2 | _] is exhaustive. List<Never> contains only []. An annotation such as List<Integer> retains its full domain even when initialized with [].

When inspecting Term, a cons pattern leaves an unknown tail as Term: the runtime value may have an improper tail. A fixed-length pattern such as [_] establishes a proper list. A fallback is still needed for other terms.

Record patterns may name a subset of fields; the matched value keeps its full exact shape. A pattern requesting a missing key cannot match that exact record alternative. Nested field patterns preserve correlations between union members. For example, %{a: 1, b: 1} | %{a: 2, b: 2} has only two alternatives; %{a: 1 | 2, b: 1 | 2} has four combinations.

Dictionary subset patterns require literal keys or previously bound pinned keys. A successful partial match on Map<K, V> or Term does not establish an exact record: additional keys may exist. Dictionary fields start with V, and fields from Term start with Term, before nested pattern refinement. Nonempty subset patterns can fail on an empty dictionary. The empty pattern %{} matches every map, including nonempty maps; on Term, other runtime shapes still need coverage. Duplicate keys in one pattern are errors, including equivalent label/literal spellings such as a: and :a =>.

Arms may add guards:

value when is_integer(value) -> value
level when level in [:debug, :info] -> level

Guards allow scalar, tuple, list, record and dictionary literals, variables, field access, comparisons, boolean operators, literal-list and range-syntax in / not in, and the guard-safe built-ins: is_atom, is_binary, is_bitstring, is_boolean, is_float, is_integer, is_list, is_map, is_nil, is_number, is_pid, is_reference, is_tuple, is_function, byte_size, bit_size, map_size, is_map_key, map_get, length, hd, tl, tuple_size, elem, min, max, round, trunc, abs. No arbitrary function calls in guards. is_function accepts a value and optional Integer arity. A negative arity raises outside guards and rejects the arm inside a guard; the arity form grants no callable signature or exhaustiveness fact. byte_size accepts Binary (including String), length accepts a proper List<A>, and bit_size accepts Bitstring. All three return Integer. map_size accepts maps, records and structs and returns Integer. Dictionary observers preserve their established key and value domains. The standard library exposes list element count as gale_std.list.size(items), with the same result as builtin length(items). map_get(key, dictionary) has the dictionary value type and requires a present key. In a guard, an absent key rejects the arm; in a specification, proving key presence is an obligation. These operations are available in bodies, guards and contracts. Narrow unknown values before using them; is_list alone does not establish a proper list. is_map_key(key, map) accepts an arbitrary key and an established map shape, returning Boolean with strict key equality (for example, 1 and 1.0 are different keys). It follows Erlang’s key-first argument order. Size comparisons and map-key tests do not establish exhaustive coverage.

hd, tl, map_get, and elem are executable only in guards; use checked accessors or patterns in a body. hd and tl require a nonempty proper list; elem(tuple, index) uses a zero-based Integer index. Empty lists and indices outside the tuple reject a guard arm, including inside nested expressions. In specifications these accesses create validity obligations. A literal tuple index retains the selected field type; a dynamic index returns the union of field types. round and trunc accept numbers and return Integer. Integer inputs are modeled exactly in proofs; Float rounding currently reports an unsupported proof model, as Float arithmetic does. abs accepts Integer, Float, or their union and preserves the numeric family. Its Integer proof model is exact; Float absolute value remains an unsupported proof model. min and max accept two Integers and return Integer. Type tests refine Term or unions inside the arm and in if branches; and, or, and not combine recognized narrowing facts. Short-circuit operands use the facts established by the path that reaches them. These facts come from builtin operations: an authored function with the same name and arity shadows the builtin and supplies no automatic narrowing. Literal atom-list membership can refine atom unions. An arbitrary predicate or comparison does not establish exhaustive coverage. Total type tests can cover closed variants. is_list cannot turn arbitrary Term into a proper List (BEAM permits improper lists); is_tuple and is_function similarly cannot supply unknown components or a callable signature. Guard failures from partial native guard operations reject the arm.

A repeated variable in a pattern compares with its first occurrence using strict equality. An alias pattern whole = Some(value) binds both the whole value and its parts. A pin compares against an enclosing binding, never a binder introduced by the same pattern. Dictionary subset patterns use literal or pinned keys, such as %{"name" => name}.

In {x, ^x}, the first position introduces a new x; the pin reads the enclosing x from before the pattern. Repeated names share one scope across all arguments of a function clause. Equality patterns normally need a fallback. An equality known to succeed, such as {x, x} over {1, 1} or the alias x = x, can contribute full coverage. If equality analysis cannot establish coverage, the diagnostic asks for a fallback. Patterns requiring a finite value to contain itself, such as whole = [whole | _], cannot match.

Literals (including negative numbers), empty/fixed lists, struct patterns, and labeled constructor patterns are also supported. Record/struct patterns may select a subset of fields. Prefix patterns require a nonempty literal followed by a variable or _; the remainder is String for text, otherwise Binary. Finite string literal domains retain their exact suffix alternatives. Prefix coverage on established text or binary domains detects contained or repeated prefixes; a broad String or Binary still needs a fallback. Coverage for dynamic Term retains an unknown remainder and may not detect redundant prefixes. A prefix binding is allowed when every possible literal starts with that prefix and any repeated binding is known to agree. Bindings permit only irrefutable destructuring (including a single-constructor ADT with irrefutable fields). Matching a dynamic Term can expose structural components as Term, but does not certify an ADT by its tag. An empty case value {} is valid only for an uninhabited type.

Operators

Operators Use
+ - * Integer arithmetic
unary - Integer or Float negation
first..last, first..last//step, .. Native inclusive integer range construction
<> String or binary concatenation
++ List concatenation
-- List subtraction, removing one left occurrence per right element
== != Strict equality between related types
< <= > >= Ordering between two Integers, two Floats, or compatible String/Binary values
and / &&, or / ||, not / ! Boolean-only, short-circuit logic
in, not in Typed list or integer range membership; guards require literal lists or range syntax
|> Pass a value as the first function argument

List membership uses strict equality and the same query/element compatibility rules as ==, including finite literal alternatives. It evaluates the query once, then the proper list once, in that order. It does not invoke enumeration protocols. List membership in a guard requires a closed list of scalar literals; computed elements, list variables, and explicit tails are not guard-safe. An empty list is not allowed in a guard: Elixir would not evaluate the query. A partial operation rejects the arm when the guard evaluates it, as in is_function(value, arity) or true.

Precedence, lowest to highest: or / ||; and / &&; == !=; < <= > >=; |>; in / not in; range step //; .. <> ++ --; + -; * /; unary not ! -; field access and calls. .., //, <>, ++, and -- associate right; other binary operators associate left. / is parsed but rejected by the typechecker. === and !== are not Gale operators. Equality requires types assignable in at least one direction (two different singleton atoms are also comparable). Binary concatenation yields String only when both operands are String.

Numeric operators never mix Integer and Float, and there is no widening. Integer division, remainder and Float arithmetic use checked library calls; see the standard library’s package instructions for the available operations. Equality is strict and works for related types, including one generic parameter and Term; unrelated types need an explicit comparison boundary. There is no ordering of arbitrary terms. Range is a native struct with integer first, last, and step fields.

Range expressions follow Elixir’s inclusive integer range notation. first..last infers step 1 when first <= last, otherwise -1. Prefer an explicit negative step for descending ranges, as in Elixir. first..last//step supplies the step. All operands must be Integer and evaluate once, from left to right. Arithmetic binds inside endpoints and steps. A step pointing away from the endpoint produces an empty range; the last endpoint belongs only when reached exactly. Bare .. is the full-slice range 0..-1//1, an empty collection.

pub fn odd_range() -> Range { 1..9//2 }
pub fn countdown() -> Range { 3..1//-1 }
pub fn contains(value: Integer) -> Boolean { value in 1..9//2 }
pub fn endpoints(value: Range) -> {Integer, Integer} { {value.first, value.last} }

Range is available without a library dependency. It uses the existing native struct representation %Range{first: ..., last: ..., step: ...}; generated Elixir specs describe the native struct and its integer fields. Its fields can be read, matched, constructed and updated using ordinary struct syntax. Prefer range notation to manual struct construction so Elixir validates the step. in and not in accept an Integer query and a Range, including a stored range outside guards. Guards require range syntax with guard-safe endpoints and, when present, a nonzero literal step; range variables and dynamic steps are excluded there.

Range syntax rejects a literal zero step. Dynamic zero steps raise Elixir’s ArgumentError; verification retains a nonzero-step obligation. Range membership also requires a valid nonzero step. Use the checked gale_std.list.range(first, last, step) API when a possibly zero step should produce Result<List<Integer>, :invalid_step> instead. These operations add no generic Enumerable/protocol abstraction.

Numerical Float proof models are excluded from v1. Proofs retain Float identity, transport and stable comparison observations without numerical ordering or arithmetic laws. Strict == maps to Elixir ===, so signed zeros are distinct.

Processes and mailboxes

A function that uses receive declares its mailbox with receives. Typed PIDs carry the message type accepted by process.send:

alias gale_std.process
pub type Message = Ping(process.Pid<:pong>) | Stop
fn loop() receives Message -> :ok {
receive {
Ping(reply_to) -> {
process.send(reply_to, :pong)
loop()
}
Stop -> :ok
}
}

receive is selective: unhandled messages remain queued. An explicit _ consumes unmatched messages. after accepts the native bounded nonnegative millisecond domain or :infinity; 0 polls. Dynamic timeouts need ordinary validation or proved preconditions. Declare standard messages in the mailbox alongside application messages and match their ordinary native tuples:

receive {
Reply(value) -> value
{:DOWN, ^monitor, :process, worker, reason} -> handle_down(worker, reason)
{:EXIT, worker, reason} -> handle_exit(worker, reason)
after 5_000 -> fallback
}

The same receives M annotation is needed for process.self and calls that require M; mailbox types must agree. A lambda must declare its own mailbox; an expected type does not insert the annotation. Pid<M> fits AnyPid, but an AnyPid cannot be used for typed sending. Spawning a mailbox-free function can produce Pid<Never>.

process.sleep(timeout) requires :infinity or a nonnegative Integer. Unlike receive, it accepts integers above 4,294,967,295 because Elixir chunks long sleeps. Its ordinary precondition must be proved for dynamic arguments; neither successful verification nor :infinity promises termination.

Use stdlib Down and ExitEvent mailbox types. process.flag(:trap_exit, true) returns the previous setting; no TrapExit witness or special receive arm is needed. spawn_monitor creates/monitors atomically. Matching a DOWN/EXIT shape does not authenticate a message or prove liveness. Process references, monitor capabilities, and timers are distinct nominal values, even when their native representation is a reference. process.send_after(pid, message, delay) returns Result<Timer, TimerError>; TimerError is :invalid_argument for a native-invalid delay or a nonlocal target. A dead local PID is valid. cancel_timer(timer) returns Option<Integer> with the remaining milliseconds, including zero. Neither result proves message delivery. demonitor(monitor) returns Result<Boolean, MonitorError>, where MonitorError is :invalid_argument. It uses native default options; its second arity accepts :flush and :info. Default true need not mean a monitor was active. Flush removes at most one matching DOWN message, including a forged one, without authenticating it.

Elixir and library interop

Declare foreign functions at a typed boundary with extern. The compiler trusts the signature:

pub extern "String.trim" trim(value: String) -> String
pub extern exception "ArgumentError" ArgumentError {
message: String
}
pub extern raises "String.to_integer" to_integer(value: String) -> Result<Integer, ArgumentError>

extern raises requires a Result<Success, E> return type and converts the declared exception types to Error; other failures keep their native behaviour. extern type is nominal, extern struct "URI" Uri { ... } binds a native Elixir struct, extern exception "Exception" E { ... } models an Elixir exception, and extern mod "Enum" enum is a module value whose surface is exactly its implements clauses. Erlang remotes use :erlang.send spelling. An ordinary extern call goes straight to its native target, including from another Gale module. extern raises converts declared exceptions at the call site, and optional runtime typechecks validate arguments and results there. An extern emits no Gale-module function; write a private extern and a public fn when you want to expose your own wrapper.

A Gale module name is also a value with singleton type mod path.name. A value of that type exposes the module’s public functions, including declared externs; calling an extern this way still uses its native target and exception adaptation. extern mod ":lists" lists binds an Erlang module value. Module values preserve their static identity when passed through generic functions or matched; ordinary atoms cannot be used in their place.

An extern type Handle<A> keeps its identity and has invariant type arguments: Handle<1> does not become Handle<Integer>. An unknown native representation cannot be inspected with patterns, even in its declaring module. Use a surrounding tag or ADT to distinguish outcomes, such as {:ok, Handle<Integer>} | {:error, String}, and bind the handle as a whole. Handle<Never> may still contain a native value; it is not an empty type. Unknown native types project to term() in Elixir specs.

Native interface version 1 supports declared PID and reference shapes and hidden native struct fields:

pub extern type Worker<Message> representation(1) pid
pub extern type Token<Tag> representation(1) reference
pub extern type Box<A> representation(1) struct "Native.Box" { value: A }

The representation is a trusted correspondence with the foreign implementation. It supplies honest Elixir specs, runtime boundary descriptors and shape observations. Hidden struct fields carry generic runtime checks without allowing Gale construction, access or pattern inspection. Use extern struct when the fields should be accessible in Gale. Unsupported interface versions, duplicate or reserved fields and field defaults are rejected. Names such as Pid and MapSet have no special compiler privileges.

Raw Reference values can be recognized by is_reference independently of any stdlib declaration. This test grants only the raw shape. Native functions and their contracts remain explicit trust boundaries, recorded by verification.

New native bindings use ordinary Gale declarations. A simple extern contract can state its result directly; richer contracts may refer to regular checked pure Gale functions that describe the result. No WhyML implementation or compiler registration is required. The foreign implementation’s agreement with that contract is trusted; Gale proves the surrounding wrappers and consumers. Verification reports the native target, declared purity and totality, representation version when present, and source revision of each assumption. Runtime correspondence checks test the Elixir implementation separately.

An extern struct keeps its native Elixir module and declares the fields Gale can use. Construction must supply every declared field; undeclared fields use the native struct’s defaults. Access, updates and %Name{field: pattern} matching preserve its nominal identity. A raw record or Term cannot establish that identity or the declared field types just by carrying the same module tag.

Named foreign resources are also trust boundaries: ets.named_unchecked, registry.named_unchecked, persistent_term.named_key_unchecked, and gen_server.named_unchecked assert caller-selected types without checking the native resource. Publish a single typed accessor for each resource; independent annotations of the same native name are not checked for agreement. The same rule applies to gen_server.global_unchecked, remote_unchecked, and named_unchecked in supervisor, dynamic_supervisor and task_supervisor. None performs lookup or validation; all writers and replacement registrations must obey the asserted contract. Supply a result or function annotation when the caller chooses an otherwise unconstrained resource identity.

otp.Name and registry.name describe untyped routing data. Acquiring a typed server from a local, global or via route uses gen_server.named_unchecked. Typed child-spec overrides exclude :start, which could replace the service. Typed ETS options exclude :keypos: {K, V} objects always use key position one.

Foreign structs have declared fields but may contain additional native fields; foreign struct declarations cannot have generic parameters or defaults. Construction supplies every declared field. Foreign exceptions also support construction, inspection, updates and matching. Their literals construct the native struct directly, preserving undeclared native defaults; they do not call a customized native exception/1 callback. Bind such a factory explicitly with extern if the native API requires normalization. Updates retain undeclared fields. extern raises accepts Gale-defined and foreign exceptions. extern raises wraps normal results in Ok, catches only declared exception types as Error, and reraises other exceptions with their stack; throws and exits remain native failures. A plain atom is not evidence of a module capability.

Arguments are evaluated once, in source order, before entering the rescue boundary. An exception from evaluating an argument therefore propagates normally. Pipelines and function references use the same adaptation; capturing an extern does not call it until the returned function is invoked. These declarations are trusted native API contracts: the compiler cannot distinguish an expected ArgumentError from an internal bug that raises the same exception class.

At runtime, aliases and type parameters erase. Modules use Elixir CamelCase (shop.orders becomes Shop.Orders); structs are native structs; records are maps; lists, tuples, functions, PIDs, and atoms use their BEAM representations. Generated nominal types use snake_case Elixir type names. If a name and arity conflict with a BEAM builtin type, the emitted name gains __gale_type_ (for example, Gale Number emits __gale_type_number()). The same escape protects an authored T from a struct’s t() at the same arity. Definitions and remote references use the same name; constructor tags and runtime values are unchanged.

Generated function specs preserve relationships between repeated type parameters with named variables. A parameter occurring only once emits term() because Elixir rejects single-use spec variables; erased parameters emit no variable. Never emits none(). Specs approximate runtime representations and do not replace Gale’s type checks. Indexed relationships that BEAM types cannot express widen to term(). For example, Pack(A): Family<List<A>> keeps its constructor tag but emits a term() payload. If an erased index can refine a function’s type parameter, that parameter widens throughout the emitted function spec. Gale still checks the precise indexed relationship. Optional runtime checks validate supported input/output representations, including UTF-8 and exact record fields. They also evaluate executable contracts, assertions and opaque invariants. Checks validate function arity and values at checked invocation sites. Quantified postconditions describing returned functions attach checks to those functions, including functions in record fields. These returned functions are wrapped and can have different native function identity. Phantom parameters and protocol indices are erased; runtime checks do not validate mailbox payloads or establish nominal provenance. Recursive types use lazy descriptors, so nested values are checked without unrolling recursive definitions during compilation. Extern arguments are checked before the native call; adapted Result values are checked after any declared exception handling. Checks validate concrete literal membership, including finite strings and integers. Callback arguments passed across native or source dependency boundaries can be wrapped to validate their actual inputs and outputs and record results for postcondition evaluation. These wrappers can change native function identity. Postconditions reuse recorded callback results rather than repeating the corresponding calls. Representation failures raise Gale.Check.TypeError; false proof conditions raise Gale.Check.ContractError, including the Gale source file, line and condition. Preconditions run before the operation; postconditions check its actual normal return after any declared exception adaptation. Native operations are invoked once; evaluating specification helpers can perform additional pure computation. Callback contracts are checked at invocation sites and on source behaviour implementations. Checked callers carry the specification helpers and interface evaluators needed for contracts declared in dependencies, including source functions and callbacks compiled without checks. Checks can add stack frames and runtime work, including when evaluating recursive specification helpers.

Generated modules provide the internal __gale_runtime_type__/2 function even when boundary checks are disabled, allowing checked consumers to use their type descriptors. That function name and arity are reserved for the compiler.

Behaviours

mod storage
declares Store<K, V>
callback get(data: Map<K, V>, key: K) -> Option<V>
optional callback close() -> :ok

Behaviour parameters are in scope for callbacks only. A callback can declare its own generic parameters; these shadow same-named behaviour parameters. Required callbacks contain signatures without bodies. Optional callbacks may include a default body, as in optional callback close() -> :ok { :ok }. Callbacks have no guards. All signatures and default bodies are checked even when no module implements them. Callbacks may declare requires / ensures over their parameters; result names the return value in ensures:

mod counters
declares Counter
callback step(value: Integer) -> Integer
requires { value >= 0 }
ensures { result > value }

gale verify proves every implementation against the instantiated callback contracts: the callback’s requires is assumed, and the body must establish the callback’s ensures. An implementation may add its own contracts; its requires must follow from the callback’s, and the body still owes the callback’s ensures. Callbacks take no decreases: termination is proved at each implementation.

A Gale behaviour emits Elixir callback declarations and optional-callback metadata. An extern behaviour names an existing native contract and emits no duplicate callbacks. The generated behaviour_info/1 belongs to the behaviour; an ordinary function in the declaring module cannot redefine it.

Implement in another module:

implements storage.Store<String, Integer> as Store

Every required callback needs a pub fn with a Gale body of the same name and arity, checked as a subtype of the instantiated callback; optional callbacks may be omitted. An extern fn binding emits no Gale function, so implement a native operation through a public wrapper. Gale emits @behaviour for each implemented contract and names that behaviour explicitly in each callback’s @impl. OTP behaviours (GenServer, Supervisor, Application, …) come this way through gale_std, e.g. extern "GenServer" declares Server<...>. There is no global implementation lookup: pass a mod B<...> value or a function when generic code needs an implementation.

A module declares at most one behaviour and may implement several distinct behaviours. One public function may satisfy overlapping name/arity callbacks when it meets each interface independently, including its contract. Callback generics must agree up to parameter renaming, and function subtyping includes the mailbox capability: a mailbox-free function can satisfy a callback that permits a mailbox, while two declared mailboxes must agree. as Name introduces a local capability alias; expose an alias explicitly with pub type if callers need it. An abstract mod B value exposes required and default-backed callbacks. An optional callback without a body may remain absent and is callable only when concrete presence is known. An optional callback with a default emits a real function when omitted; an override must prove the same contract. Conflicting defaults need an explicit implementation. Default names resolve in their defining scope. Native module declarations acquire only the capabilities explicitly listed in their implements clauses.

Contracts and proofs

State what must hold; then prove it. Contracts sit between the return type and the body:

pub opaque type State = %{reserved: Integer, capacity: Integer}
invariant(state) {
state.reserved >= 0 and state.reserved <= state.capacity
}
pub fn available(State(state): State) -> Integer
ensures { result >= 0 }
{
state.capacity - state.reserved
}
pub fn increment(x: Integer) -> Integer
requires { x >= 0 }
ensures { result == x + 1 }
{
x + 1
}
  • requires { ... } is a caller obligation and an assumption in the body. Arguments are evaluated before checking the enclosing call’s preconditions; a nested call establishes its result guarantees first.
  • ensures { ... } holds on every normal return; result is the return value. Inside this clause it shadows any parameter named result.
  • invariant(value) { ... } on an opaque type must hold at every explicit construction, including construction from an updated representation. Its binder has the raw representation type. Inside the defining module, intermediate raw values may violate the invariant while being repaired. Verification may rely on the invariant for typed inputs and requires it for typed results, including values stored inside records, tuples and data constructors. A constructed opaque value must satisfy its invariant even when it is subsequently discarded.
  • assert { ... } and ghost { ... } are erased when runtime checks are disabled. With runtime checks enabled, assertions raise on established false conditions and ghost statements run in a separate scope. Inconclusive checks are skipped.
  • predicate name(params) { formula } names a formula for use in specs.
  • Predicates and lemmas accept ordinary generic parameters. Each use substitutes its type arguments; the generic definition and its call-admission duties remain checked independently.
  • lemma name(params) requires { ... } ensures { ... } names a theorem (optional body); cite it inside ghost { ... }.
  • decreases { integer_expression } supplies an explicit numeric termination measure. Structural recursion over list tails and ADT children infers a size measure, including mutually recursive traversals with different parameter positions. Such a group may forward an unchanged value through finitely many helpers before descending: inferred finite phases decrease on forwarding calls, and every cycle must contain structural descent. The verifier proves every recursive decrease; typing alone does not establish termination. Runtime checks validate explicit well-founded lexicographic descent on recursive re-entry. Dynamic Term traversals can descend through cons cells and the native Map.to_list contents view of Map<Term, Term>. The finite-map size correspondence is recorded as a native model assumption; recursive descent and the generated list/product measures are still checked.

Predicates and lemmas are not ordinary functions and cannot be called or captured from executable code. They emit runtime evaluation helpers only when runtime checks are enabled; a computable helper a spec may name is an ordinary fn, with optional requires and ensures. Defaults and spec helpers must be effect-free and terminating on their domain. pure fn callback interfaces and explicit extern pure declarations support logical calls, including contracted passed/returned/stored pure closures. An ensures clause alone proves neither purity nor termination. Effectful callbacks remain executable with normal-return contracts. Ordinary helper bodies are checked recursively for effects. Predicates cannot recurse; recursive executable functions need a decreasing integer measure for termination proofs. A predicate or lemma has typed parameters but no result annotation or mailbox. Lemmas may omit their body; the stated theorem still needs proof. Ghost code cannot supply executable results. forall(value: Type) { formula } is normally erased quantified logic. Runtime checks can exhaustively enumerate finite literal unions, tuples of finite domains and non-generic fieldless ADTs (up to 1024 values per domain). Membership and occurrence formulas can also be evaluated over their concrete lists, tuple projections, map keys, map entries and native MapSet contents when the compiler establishes that the formula is true outside that finite support. String concatenation formulas describing prefixes, suffixes and substrings use exact byte matching at UTF-8 boundaries. Integer quantifiers guarded by a concrete lower bound and exclusive upper bound enumerate that complete interval. A quantified postcondition describing a returned function is checked when that function is invoked: its actual arguments instantiate the quantified parameters, and its actual result is reused while evaluating the property. This also works for functions in record fields and through simple source invocation helpers. The quantified parameters must correspond to the called function’s arguments. Quantified variables in runtime contracts can use the current values of their types, including generic variables. They are instantiated with the concrete values supplied to that call, including collection elements and actual callback arguments and results. These bindings are local to the current call and are discarded on return or failure. Generic callback laws therefore check the current inputs; gale verify proves their universal form. Loop-invariant formulas over arbitrary predicates can use actual callback transitions as an induction certificate without running hypothetical predicates. Quantified requirements on callback parameters attach checks to each actual invocation. The checks reuse that invocation’s result, respect the quantified input type, and travel with the callback if it is returned. Existential list formulas can check concrete accumulator witnesses built from actual callback results by running their emitted predicate. These checks validate executed calls; they do not prove the property for inputs that have never been supplied. Other unbounded quantification and abstract callback-contract observations requiring an inferred closure model cannot be evaluated generally. Runtime proof checks are best effort. Unsupported or inconclusive formulas are skipped without blocking compilation or raising at runtime. Skipping a check does not establish its truth. Independent supported clauses and conjuncts still run; known false conditions raise Gale.Check.ContractError, and representation failures raise Gale.Check.TypeError. Ordinary conditions over actual arguments and results do not require quantifier enumeration. Callback outcome observations can reuse recorded results for the supplied arguments in the current execution. Quantified properties of callbacks used or returned by executable code monitor actual invocations, even for finite input types. Pure callable parameters used only as proof predicates can run on current concrete data; a finite input type alone does not supply additional callback arguments. An inconclusive guard can leave a dependent branch unchecked. Optional branch evaluation does not probe an unobserved callback or foreign binding. Actual operations and known-selected checks retain their normal errors. Runtime evaluation distinguishes these cases:

Formula Runtime meaning
Executable condition or complete finite-domain/support reduction An ordinary Boolean, including under negation or as a premise.
Unbounded generic/callback forall over current inputs Checks this execution’s inputs. A falsifying input refutes the universal claim; passing observations leave universal truth unknown. Negations and premises retain that distinction.
Validated existential witness or induction certificate Establishes truth. Failure to find a certificate is inconclusive and skips that check; it does not establish falsity.
Other quantified compositions Skipped when they cannot be evaluated conclusively; they do not disable independent checks.

Declared callback-contract observations evaluate the permitted input/output relation even after an invocation; the recorded output does not restrict a weak contract to one permitted result. Pure logical callbacks additionally require their deterministic application result; a weak postcondition cannot compute it.

Executable specification helpers check their input types, prerequisites, postconditions and explicit descent measures. Calls made while executing a helper body validate their own contracts. References inside a contract evaluate an already active function’s mathematical body, with domain/type/descent checks, without recursively expanding its postcondition. This applies to direct and mutual references; it does not exempt invocations inside those model bodies. Nested specification evaluation shares a temporary cache of pure call results, which is discarded on return or failure. Declared callable-interface observations evaluate their preconditions and postconditions without invoking the callback; pure outcome observations still require an executable outcome model. Quantified names stay inside the formula and range over their declared type domains. Calls inside the formula owe their preconditions for every value and path that reaches them. A quantified formula may be bound in ghost code and never contributes a runtime value. There is no assume/admit, source exists or SMT trigger syntax. Numerical Float models are excluded from v1; unsupported/unknown/timeout obligations never count as success.

Public declarations expose proof information according to their existing kind:

Declaration Facts available to callers
pub fn Parameter/result types and declared contracts
pub pure fn The same facts, with checked deterministic, effect-free, terminating logical application
pub predicate Its formula definition
pub lemma Its proved theorem, with its preconditions

A public function without postconditions exposes its typed result, not an inferred implementation equation. Public function bodies and lemma proof bodies are checked independently. This boundary applies within packages as well as between them. Private helpers can retain bounded checked body inference; a private helper used by an exported predicate remains part of that formula. An eligible private helper with an authored postcondition can use that checked contract as a local proof boundary. Stating a useful shape or preservation property avoids requiring callers to reflect its implementation. Known callbacks and private implementation dispatch do not reopen public bodies.

A callback already known to be pure can pass through an ordinary callback parameter while retaining its established logical application facts at that value. The conversion still checks invocation-contract compatibility. It does not strengthen an unrelated unknown ordinary callback. Purity checking follows the callbacks actually invoked by ordinary source helpers. A pure caller may use an ordinary helper with a pure callback; the same helper remains available to effectful callers. Recursive helpers propagate these callback requirements, but purity alone never proves termination. Specifications and field defaults apply the same check to actual callbacks; an ordinary helper’s callback parameter does not require a redundant public qualifier when the supplied implementation establishes the needed guarantee. Public validators used in specifications publish their useful relations through contracts or predicates. Private reflection copies at most 128 expression nodes per helper (body and contracts together), with at most 16 nested helpers. Larger executable helpers use their program contracts; a specification that requires an unsupported logical body receives a diagnostic. These limits bound proof construction and do not weaken an obligation or establish termination by themselves. Concrete numerical recursive calls can also use bounded instances of their checked equations. Each instance retains its preconditions; proving a concrete result never excuses an unmet call requirement or an unproved implementation.

Project verification checks reachable source implementations independently; their contracts are not foreign assumptions. Passing an Integer or Float through Term preserves its native numeric kind. An Integer type test recovers the original integer; a Float type test recovers the original Float identity. These conversion facts introduce no numerical Float arithmetic model and no assumption about an unrelated untrusted Term. Known scalar values widened to Term also retain native category distinctions: Integers, Floats, atoms, references, PIDs and bitstrings are separate categories. Booleans are atoms, and String/Binary share the bitstring category; source type names alone never imply different native values. Ordinary Term comparisons use the same native identity facts as dictionary keys. Arbitrary Terms remain open. Equality on proper lists, tuples and Gale constructor values compares their components using those components’ native equality. A union’s proof encoding does not introduce a native tag, including when stored inside another value. Native identity of a component need not mean equality of its WhyML encoding; enclosing comparisons must preserve that distinction, including recursively. An ordinary function dependency does not select unrelated callbacks in its module. Passing a concrete module capability selects that provider’s callback conformance obligations. Public APIs have separate caller and implementation proof inputs. A body refactoring preserves the caller input when its contract stays unchanged. Predicates, invariants and helper definitions exposed by the contract remain part of that input. A failed implementation blocks project success even when the caller has reusable proof evidence. Recursive components retain joint termination checks.

Reflected helpers check each call’s admission conditions at that expression. A recursive call must establish its result contract before that result is used as another call’s argument; reflection does not erase either check.

Library combinators can describe callback results through call_ensures and ordinary exported predicates. This preserves each invocation’s contract without re-invoking an effectful callback in logic. Intermediate values may be erased proof witnesses; they need not be runtime allocations. Read the library’s contracts for the exact relation and proof scope of each operation.

A small lambda with checked purity and termination can carry a checked body summary without an authored callable postcondition or a pure annotation. Its implementation must prove that summary, including captured-value and call-admission duties. A reflected helper accepting plain fn parameters has a conditional logical copy: it requires these checked callback facts. Ordinary calls with unknown or effectful callbacks retain their executable contracts and do not acquire that condition. Direct lambdas, small checked Gale function captures, and their immutable bindings can supply the facts at a call site. Native captures still need explicit effect and totality declarations; a target name never supplies them. Explicit pure interfaces also preserve their checked summaries through stored fields. Checked factories returning bare callbacks can carry inferred summaries into records and later calls without strengthening unknown callbacks of the same type. Matching results do not imply matching runtime function identities.

For example, ordinary list callbacks can prove this result without separate callback contracts or a parallel formal implementation. Intermediate assertions let the solver establish each collection result before proving the next step:

alias gale_std.list
pub fn pipeline() -> Integer
ensures { result == 10 }
{
selected = list.filter([1, 2, 3], fn(value) -> value >= 2)
assert { selected == [2, 3] }
mapped = list.map(selected, fn(value) -> value * 2)
assert { mapped == [4, 6] }
list.reduce(mapped, 0, fn(value, sum) -> value + sum)
}

When a pipeline still times out, give a helper an ensures clause describing the intermediate result. Gale checks that helper separately and lets its caller use the contract without reopening the implementation. This is particularly useful when a pipeline combines different collection models, such as mapping a list of pairs and then building a dictionary. The helper’s implementation must prove its contract; a caller remains conditional if that proof fails.

Captures with checked purity and termination can also reuse the declared contracts of an ordered clause family. Its heads and guards select the applicable contract; each generated closure must prove its summary before exporting it.

Named Gale captures retain their BEAM target and capture kind. A local capture and an external module-qualified capture of the same function are different BEAM function values. Capturing an ordered clause family names its one emitted function with the family’s shared signature. Native captures keep open identities: source aliases can share a native function, and exception or runtime-check wrappers can introduce different function values. A binding name does not prove equality or inequality of native captures.

Allocating a closure or capture introduces a proof dependency without executing the callback. Invoking a known local callback participates in recursion and structural-descent analysis. Cyclic creation of a proof-callable function currently reports G2599; this unsupported proof cannot establish termination. A cycle in proof declarations likewise reports a source diagnostic before invoking Why3. Source union alternatives add no runtime tags, including when stored in lists, tuples, records or ADTs. Native types may overlap at runtime; their different source encodings cannot establish inequality. The verifier keeps these identity questions open when no runtime distinction has been established.

Struct proofs use the full finite runtime map, including the __struct__ module key. A Gale-defined struct has exactly its declared fields and module key. An extern struct or hidden native struct representation guarantees its declared fields but can contain additional native fields. Construction, field access, updates and patterns preserve stored-value domains; updates retain undeclared native fields. Equal declared fields do not establish equality of two native structs. Native layout and constructor-default correspondence are reported trusted assumptions tied to their source declarations.

String and Binary proofs share an ordered byte representation. String boundaries require strict UTF-8; Binary boundaries allow arbitrary byte values. Literal content, strict equality, <> and byte_size use the same representation in logical and executable proof code. Byte counts include all UTF-8 encoding bytes and do not count Unicode scalars or graphemes. Equality performs no normalization. string.length counts native graphemes: its result is nonnegative and is zero exactly for the empty string. No additive grapheme-length law is assumed. String prefix, suffix and substring observations describe exact UTF-8 bytes. string.starts_with?(text, prefix) holds exactly when some String remainder satisfies text == prefix <> remainder; ends_with? uses the corresponding leading remainder. contains? holds exactly when text decomposes into a leading String, the substring, and a trailing String. Empty patterns match. These native contracts perform no Unicode normalization or grapheme comparison. Concatenation preserves byte order and adds byte lengths. Why3 proves the UTF-8 preservation and String-to-Binary correspondence laws as model duties. Native String.valid? has an audited correspondence with this UTF-8 domain, selected by its native target and binary-to-Boolean signature. The stdlib’s checked string.from_binary succeeds exactly for valid bytes and preserves them; a String converted to Binary and validated again is unchanged.

Constrained lists retain the validity of every stored element and tail at typed boundaries, including abstract generic elements. List append uses proved length, right-nil, membership and domain-preservation laws. Subtraction removes first strict occurrences in order and preserves stored-element validity. Applications can reuse these facts through ordinary contracts without supplying induction proofs.

A predicate body must produce Boolean and define a total formula. It takes no contracts and has no guard. Express domain restrictions as part of the formula, such as value > 0 and ..., rather than predicate preconditions. Predicate calls resolve in specifications, including other predicate bodies, and respect module visibility. The compiler models :erlang.length at List<A> -> Integer. Native purity and totality are explicit declaration promises; recognizing a native target never grants those promises by name.

The pipeline:

  1. mix compile / gale compile: typecheck and emit sidecars. Contracts typecheck here, but nothing is proved.
  2. gale check / mix gale.check: typecheck without emitting or solving.
  3. gale verify / mix gale.verify: discharge contracts with Why3 and Z3. Checked Core lowers to WhyML; Why3 generates the verification conditions. Failed conditions and unsupported lowering retain their Gale source locations. Successful units cache in .gale/proofs. Each Gale release supports one exact Why3/Z3 pair (gale version reports it).

mix gale.verify requires a nonempty gale: [proofs: [...]] list of committed subjects. Use canonical module names, for example gale_std.list/member? or gale_std.map/has_key?:2; the optional arity selects one overload. Predicate and lemma entries use module/predicate:name and module/lemma:name. One gale verify process proves every listed subject. The CLI defaults are 5 seconds per goal, 120 seconds of wall time for the whole run, and one worker. {"gale_std.list/map", goal: 30, wall: 90} raises that subject’s goal limit and gives it a separate proving wall. gale: [options: ["--jobs", "4"]] passes extra arguments to that one process. Leave options unset to keep one worker, which is the CLI default.

Trust boundaries, stated plainly: extern requires/ensures are trusted as written (callers prove preconditions and may assume postconditions); uncontracted foreign calls are not specification evidence. Proofs cover Gale code that returns normally; they say nothing about process survival or message delivery. A false contract still typechecks; only gale verify proves it.

Reported lifecycle induction is conditional on the environment obeying the callback argument domains and preconditions, installing only the verified callback outcomes, and allowing no administrative state replacement. Check the report’s assumptions. A callback with requires { false } permits no invocation; proving its body does not justify invoking it from OTP or other foreign code.

Function types may carry contracts and checked properties:

pub type Advance = pure fn(value: Integer) -> Integer
requires { value >= 0 }
ensures { result > value }
pub fn advance() -> Advance {
fn(value: Integer) -> value + 1
}

An interface’s named inputs and result bind only its own formulas. It cannot capture values from an enclosing signature. A returned arrow with its own clauses must be parenthesized when written directly after a function’s ->; unparenthesized trailing clauses belong to the enclosing function. Arrow interfaces take requires and ensures; the implementation establishes termination through its body or numerical/structural measures.

Creating a lambda or named capture at an interface proves its precondition admission, normal-return postcondition and requested totality. Purity promises are checked during typechecking. Immutable captures can use facts established at the creation site. Calls through the value owe its preconditions and may use its postconditions. Contracts and properties survive generic substitution and storage in records and containers. An effectful arrow remains usable in ordinary normal-return proofs.

A bare fn type adds no contract restrictions. Capturing a named function at that type therefore owes its requires for every typed input; callers receive the arrow’s output type, plus any independently checked summary for a known implementation. The bare type alone contributes no summary. Converting an interface to another proves that its admitted calls satisfy the destination, including when forgetting a restriction. Runtime functions and native calling conventions are unchanged.

Support and limits

The verification reference defines the normal-return guarantee, selected source scope, trusted assumptions and supported models. Default verification selects library roots, including private and unused functions, then checks their reached source dependencies. Tests are typechecked and can be selected explicitly as proof roots.

Well-typed code is not necessarily supported by the verifier. A receive proves the result of one matching arm or a finite after clause. It does not establish that a message arrives, that time elapsed, or that the function terminates. Mailbox-capable callable proof interfaces currently report unsupported lowering. Polymorphic recursion and cyclic construction of proof-callable functions are unsupported; generic predicates and lemmas are supported with checked type substitution, definition bodies and call-admission duties. Contracted callback implementations dispatch through their clauses like ordinary functions; the direct single-clause form requires plain named parameters. Ordinary ordered functions are supported. Float reasoning is conservative as described above. Resolved native Integer division/remainder calls expose truncation-toward-zero identities through Why3 ComputerDivision; modulo adjusts the remainder to the divisor’s sign, and nonnegative powers use a checked bridge to Why3 Power. Native correspondence remains an explicit assumption. Unsupported, timeout and unproved outcomes are not successful proofs.

Guidelines for verifiable code

  • Model alternatives with ADTs and persistent validity with opaque invariants. Decode external input before constructing application values.
  • Reuse a small checked executable validator in runtime checks and contracts. Add optional lemmas only when the property needs them.
  • Give package APIs stable postconditions. Eligible small helpers and callbacks can infer summaries, but a public contract avoids coupling consumers to bodies.
  • Use callable contracts for a stable stored or returned callback interface; ordinary collection callbacks can often infer the needed facts.
  • Make recursive descent structural or give a numeric decreases measure. Use pure to explicitly request checked logical-call eligibility; ordinary helpers used in specifications establish it without a qualifier.
  • Prefer direct recursive traversal when a callback would call back into the same traversal. This keeps recursive descent visible and avoids requiring a separate totality proof for a recursively created callback.
  • Matching [] and [head | tail] inside Term preserves dynamic tails, including improper lists. Structural recursion on a matched head or tail uses the finite native cons-cell size model; a cons match alone does not prove that its tail is a proper list.
  • Keep foreign assumptions narrow and test them against runtime behavior. Run both proofs and tests; inspect the report’s scope and assumptions. A proof of selected domain functions does not prove an excluded receive loop or Elixir body.

Decoding and reusable refinement

Untrusted Term data needs explicit decoding before use as a narrower type. Decoders and schemas are ordinary library values; the compiler gives them no special typing or proof rules.

A verified combinator can relate its returned function to a predicate through an ordinary quantified contract. Matching a successful result provides the facts stated by that contract. Factories, local bindings and stored values retain justified facts; transformations need their own output relation. An opaque codec representation or descriptive metadata alone proves neither validation behavior nor an inverse law between encoding and decoding.

Standard library

Library functions use the same language and contract facilities as user code; foreign primitive models remain explicit reported semantic bridges.

For package usage, including the standard library, read deps/<package>/AGENTS.md and follow its README and source links for exact APIs. Use the resolved package root for path dependencies; in the Gale repository, these files are under libs/<package>/AGENTS.md.

Commands

Command What it does
gale new <name> [--sup] Create a Mix project with Gale sources
gale compile Typecheck and emit Elixir sidecars
gale check Typecheck without emitting sidecars
gale verify Prove contracts and invariants (Why3/Z3)
gale version Toolchain versions (--json for machines)
gale format [--check-formatted] [--line-length N] Format .gale/.🌀 sources
gale clean Remove generated sidecars
gale lsp Language server (stdio)
gale guide Print this guide

Use gale help <command> for command-specific options, for example gale help check or gale help format. Every command also accepts --help without running the command.

<name> in gale new <name> [--sup] is one snake_case identifier: lowercase letters, digits, and underscores. Reserved words and dotted names are rejected before anything is written, because both would produce a project whose mod declaration or Mix app atom cannot be represented. Module names inside a project may still be dotted (lib/pkg/mod.🌀 is mod pkg.mod).

Project options: --root DIR, --lib DIR, --test DIR, --no-test, plus --runtime-typechecks and --generated-marker. --test selects test sources (default: ROOT/test if present); --no-test excludes them. In Mix projects with mix_gale, the same work runs as mix compile, mix test, mix gale.check, mix gale.verify, mix gale.path, mix gale.clean; Mix compiles Gale test sources only in the test environment. clean recognizes ownership by the generated header, including files left by an earlier marker setting. It preserves handwritten Elixir, needs no source typechecking or dependency resolution, and removes the old _build/gale cache. --no-test keeps test sidecars; custom --lib and --test directories are respected. Mix also supplies resolved dependency roots and application names for namespace checks. The compiler does not evaluate mix.exs. Direct CLI calls without GALE_PACKAGE_APPS check source semantics without validating Mix app namespaces; use Mix commands or supply the resolved metadata described by the mix_gale package instructions for that check.

Modules selected from the test directory must end in _test. Their pub functions take no arguments and become ExUnit tests, not callable helpers. Use private functions for helpers within a test module and ordinary library modules for shared helpers. A library module ending in _test remains an ordinary library module; source selection determines its role. gale_std.test.assert runs at runtime; assert { ... } is a proof obligation that also runs when runtime checks are enabled. Gale expressions in @doc examples with iex> prompts are lowered to Elixir doctests by the compiler; they are not commands to paste unchanged into IEx. The compiler checks each example’s input and expected value in the declaring module’s type and alias scope. Use ...> for a multiline expression. Examples call public Gale functions and use Gale constructor syntax for expected values; run the generated examples with ExUnit’s doctest. These are runtime tests. Public transparent aliases retain their checked expansion and @typedoc in Elixir type declarations; private aliases erase from emitted signatures. Handwritten Elixir calls the generated module, e.g. Hello.greet("Ada").

For executable feature examples and tests, see tour examples. The website guide renders this file alongside the language tour. Use the guide shipped with your compiler when the installed release differs from the website.

What Gale does not include

Macros/protocols/import/use, sigils/charlists/character literals, implicit conversion/truthiness, try/rescue/catch/throw syntax, comprehensions, distinct-signature overloads, anonymous multi-clause functions, ordinary default/keyword parameters, arbitrary dynamic apply, open records and global implementation search. Hot reload/code_change/code upgrades are excluded. Dedicated charlist conversion APIs are excluded; typed extern adapters can use native charlists internally when an Elixir or Erlang API requires them. Values are immutable; rebinding and the selected bit syntax are included. Model foreign features with typed externs and ordinary Gale functions. Reserved words are the syntax above plus Elixir special forms the generated code relies on (def, defmodule, for, import, try, …).

The compiler and its regression tests determine implemented behaviour. Report a disagreement with this specification as a documentation or compiler bug.

Proof reports preserve compiler subject identities: module/function:arity, module/predicate:name:arity, and module/lemma:name:arity. Source duties, proof units, dependency links and goal results use the same identity. Generated model-law subjects use model/name and retain their own obligation outcomes.

Formatting

gale format normalizes spacing and indentation while preserving declaration order, contract order, comments, literal bytes and existing line boundaries. It wraps long expressions at syntax boundaries, aiming for 98 columns by default. Use gale format --line-length 80 to choose another positive width. Indivisible strings, comments and identifiers may exceed the target; their contents are never split. Calls, parameters, collections, types and operators provide wrapping points. gale format - reads UTF-8 source from stdin and writes formatted source to stdout; gale format --check-formatted - checks it without producing source output. Stdin cannot be combined with file or directory inputs. --check-formatted exits with status 1 when input needs formatting; invalid options exit with status 2. Consecutive whole-line aliases are sorted within their group. Formatting reparses the result and checks that its syntax structure is unchanged; malformed sources are refused.