Alloy Language — Formal Language Specification

Status: draft · Revision: 2026-10-14 · Source of truth for: the Alloy language, its standard library (language/std/), and the alloyc compiler (language/alloyc/).

Code samples and asides explain; they do not define. Where an example and a rule disagree, the rule wins.

Table of Contents

  1. A Complete Program
  2. Lexical Grammar
  3. Syntactic Grammar
  4. Type System & Static Semantics
  5. Execution Semantics
  6. Standard Library & Primitives
  7. Compile-Time Evaluation & Macros

1. A Complete Program

One program using the pieces the rest of this document defines one at a time: imports (§6.4), an interface and a type that conforms to it (§6.2), an extension function (§5.5), a standard library container (§6.4), a for loop over a custom iterable (§5.3), and the use-site forms that make every borrow, move, and expensive copy visible (§5.2).

import std::io;
import std::string;
import std::vector;

interface Named {
    fn name(self: &) -> &[u8];
}

type Point : Named = struct {
    x: i32,
    y: i32,
};

// Extension function on Point; satisfies Named.
fn name(self p: &Point) -> &[u8] {
    return &"point";              // a reference to static data
}

fn render(self p: &Point) -> String {
    var out = String::empty();
    out.append(&p.name());        // a '&[u8]' parameter takes '&…'
    out.append(&" (");
    out.append(p.x);      // a by-value parameter takes the bare value
    out.append(&", ");
    out.append(p.y);
    out.append(&")");
    return move out;              // 'out' owns heap: hand it over
}

fn main() -> i32 {
    var points = Vector<Point>::empty();
    points.push(Point { .x = 1, .y = 2 });
    points.push(Point { .x = 3, .y = 4 });

    for (points) |&p| {
        var line = p.render();
        print_line(&line.view());
    }

    return 0;
}

Printed output:

point (1, 2)
point (3, 4)

Each String built in the loop owns its buffer and is freed at the end of the iteration that built it (§5.2). Nothing here frees memory by hand.


2. Lexical Grammar

2.1 Character Set

Source files are UTF-8; a byte sequence that is not valid UTF-8 is a compile-time error. Identifiers and string literals may contain any Unicode character.

2.2 Whitespace & Comments

whitespace     ::= ' ' | '\t' | '\n' | '\r'
line_comment   ::= '//' <any char except '\n'>*
block_comment  ::= '/*' ( block_comment | <any sequence not containing '/*' or '*/'> )* '*/'

Whitespace and comments separate tokens and are otherwise ignored. Newlines are plain whitespace; statements end at ; (§3.1). A line comment ends at the newline.

Block comments nest. A block comment ends only when every block opened inside it is closed. An unclosed block comment is a compile-time error.

2.3 Identifiers

identifier     ::= ( letter | '_' ) ( letter | digit | '_' )*
letter         ::= [a-zA-Z] | <any non-ASCII UTF-8 sequence>
digit          ::= [0-9]

An identifier that spells a keyword (§2.4) is that keyword and cannot name anything.

Any non-ASCII UTF-8 sequence is allowed in an identifier, at the start and after it. Narrowing this to the UAX #31 character categories is planned.

2.4 Keywords

Reserved — cannot be used as identifiers:

import   as       extern   type     enum     struct
const    var      fn       if       else     while
for      match    break    yield    return   new    move
self     pub      exp      true     false    macro  interface
is       to       continue panic    copy     defer

test is a keyword only at the top level before a string literal, where it starts a test (§6.5); elsewhere it is an ordinary identifier. Likewise scope and spawn are keywords only at the start of a statement before a block (scope {, spawn {, §5.6).

2.5 Operators & Punctuation

Every symbolic token:

CategorySymbols
Arithmetic+ - * / % +% -% *%
Compound assign+= -= *= /= %= <<= >>= &= |= ^= +%= -%= *%=
Comparison== != < <= > >=
Logical&& || !
Bitwise& | ^ ~ << >>
Assignment=
Arrow->
Expression body=>
Path separator::
Member access.
Range..
Variadic...
Type annotation:
Separator, ;
Delimiters( ) { } [ ]
Macro call prefix#

When several tokens share a prefix, the longest one wins.

2.6 Literals

integer_literal  ::= decimal_literal | hex_literal | binary_literal | octal_literal
decimal_literal  ::= [0-9]+
hex_digit        ::= [0-9a-fA-F]
hex_literal      ::= '0x' hex_digit+
binary_literal   ::= '0b' [01]+
octal_literal    ::= '0o' [0-7]+

float_literal    ::= [0-9]+ '.' [0-9]+ [ exponent ] | [0-9]+ exponent
exponent         ::= ( 'e' | 'E' ) [ '+' | '-' ] [0-9]+
string_literal   ::= '"' ( escape_seq | <any char except '"' or '\n'> )* '"'
char_literal     ::= '\'' ( escape_seq | <any char except '\'' or '\n'> )+ '\''
escape_seq       ::= '\\' [nrt0\\'"] | '\\x' hex_digit{2} | '\\u{' hex_digit+ '}'

Integer literals come in decimal, hex (0x), binary (0b), and octal (0o). A base prefix or an exponent needs at least one digit after it, and a number literal may not run straight into a letter, a digit outside its base, or _: 0x, 1e+, 123abc, 0b102, and 0xFFg are compile-time errors.

A float literal needs at least one digit after the dot, so 1. is not a literal and 1.foo() is member access on an integer literal. Scientific notation uses e / E (6.02e23, 1e-9, 2.5E+3); the exponent is decimal and may carry a sign.

String and character literals stay on one line. A raw newline inside one is a compile-time error (reported as an unterminated literal); write \n instead. An escape outside the list below is a compile-time error.

Escape Sequences

String Literal Typing

A string literal is an array literal of its bytes: "abc" has type [u8 : 3], after escapes are resolved, and "" is [u8 : 0]. Like every literal (§5.2), its bytes live in static program memory, and the use site picks what happens to them:

The static bytes of a string literal are followed by a NUL byte that is not part of its length, so &"abc" is a valid C string (§6.3). A copy carries no terminator.

Interpolated Strings

interpolated_string ::= 'f"' ( escape_seq | '{{' | '}}' | hole | <any char except '"', '{', '}' or '\n'> )* '"'
hole                ::= '{' expression [ ':' format_spec ] '}'
format_spec         ::= [ [ fill ] align ] [ '0' ] [ width ] [ '.' decimals ] [ radix ]
align               ::= '<' | '>' | '^'
width               ::= [0-9]+
decimals            ::= [0-9]+
radix               ::= 'x' | 'X' | 'b' | 'o'

f"x = {x}, mean = {total / count:.2}" is a String (std::string) holding the text with each hole's value written in its place; the compiler loads std::format for a module that uses one. The text takes the escapes of a string literal, and {{ and }} stand for { and }. A hole holds any expression, nested interpolated strings and brackets included; at bracket depth 0 its own } ends it, or a : that does not start ::, after which the format spec runs to the next }. Like a string literal, an interpolated string stays on one line, holes included.

Each hole is evaluated once, left to right, and its value read in place (borrowed, never copied or moved; a call's result is a temporary of the statement). Text ([u8 : N], &[u8], String) is written as it is, another array or slice as [a, b, c] through its elements, and any other value through the lang item Format (§6.1a), which every primitive satisfies and String, Option<T> and Vector<T> declare; a value whose type does not declare it is a compile-time error. An untyped literal takes its default type (§4.3), so {1.5} is an f32. Nothing is parsed at run time: the compiler turns the string into calls to std::format's functions writing into a fresh String. A statement s.append(&f"...".view());, with s a String reached from a local or parameter through fields alone and named by no hole, writes the parts straight into s instead, each hole evaluated just before its part is written, with no intermediate String; a hole that reads s through another reference sees it partly written, and one that changes it is an error the compiler does not detect (§5.2's manual-safety caveat).

The format spec:

An unknown spec is a compile-time error.

Character Literal Typing

A character literal's type is the unsigned integer that fits its bytes:


3. Syntactic Grammar

3.1 Full EBNF

Notation. = defines a rule and ; ends it, | separates alternatives, { x } is zero or more x, [ x ] is optional, "..." is a literal token, (* ... *) is a comment, and <...> states in words what the grammar cannot.

Trailing commas. A comma-separated list closed by ), ], }, or > may end with a comma before that delimiter; the rules leave it out to stay readable. No other list takes one: not a capture list (closed by |), not a type's interface markers (followed by =), not a match arm's patterns, and nothing follows an extern's ....

(* Top level *)
module          = { import_decl } { definition } EOF ;   (* definitions in any order *)

import_decl     = "import" identifier { "::" identifier } [ "as" identifier ] terminator ;

definition      = [ "pub" | "exp" ] ( type_def | const_def | fn_def | extern_def | interface_def | macro_def )
                | test_def ;
test_def        = "test" string_literal stmt_block ;   (* "test" is a keyword only here, §6.5 *)
const_def       = "const" [ type_scope ] identifier [ ":" type ] "=" expression terminator ;   (* a compile-time context, §7.1 *)
type_def        = "type" identifier [ "<" type_param { "," type_param } ">" ] [ ":" type_marker { "+" type_marker } ] "=" expression terminator ;   (* a compile-time context giving a type, §7.1 *)
interface_def   = "interface" identifier [ "<" type_param { "," type_param } ">" ] "{" { interface_fn | interface_const } "}" ;
interface_fn    = "fn" identifier "(" receiver { "," param } ")" [ "->" type ] terminator ;
interface_const = "const" identifier ":" type [ "=" expression ] terminator ;   (* a required constant and its default, §6.2 *)
receiver        = "self" ":" ( "&" | "&" "var" ) ;
interface_marker = identifier { "::" identifier } [ "<" type { "," type } ">" ] ;
type_marker     = interface_marker [ "if" "(" expression ")" ] ;   (* a conditional marker: "T: I" predicates joined by "&&" and "||", §6.2 *)
fn_def          = "fn" [ type_scope ] identifier [ "<" type_param { "," type_param } ">" ] function ;   (* a "=>" body ends with ";" *)
type_scope      = identifier [ "<" type { "," type } ">" ] "::" ;   (* arguments specialize, §6.4 *)
macro_def       = "macro" identifier "(" [ macro_param { "," macro_param } ] ")" "->" type
                  ( stmt_block | terminator ) ;
macro_param     = identifier [ ":" type ] ;
extern_def      = "extern" identifier "(" extern_params ")" [ "->" type ] terminator ;
extern_params   = /* empty */
                | param { "," param } [ "," "..." ]
                | "..." ;

type_param      = identifier [ ":" constraint ] ;
constraint      = interface_marker { "+" interface_marker } ;   (* every one of them, §4.7 *)

(* Functions *)
function        = "(" [ param { "," param } ] ")" [ "->" type ] ( stmt_block | "=>" arrow_body ) ;
arrow_body      = expression [ assign_op expression ] ;   (* §5.4 *)
param           = [ "self" ] identifier ":" type ;   (* a 'self' parameter's type is '&T' or '&var T', §5.5; a lambda's may be the identifier alone, §5.4 *)

(* Types *)
type            = { type_modifier } base_type ;
type_modifier   = ( "*" | "&" ) [ "var" ] ;

base_type       = named_type
                | struct_type
                | enum_type
                | array_type
                | fn_type
                | "type" ;               (* the type of types, compile-time only, §4.4 *)

named_type      = identifier { "::" identifier } [ "<" type { "," type } ">" ] ;
struct_type     = "struct" "{" [ struct_member { "," struct_member } ] "}" ;
struct_member   = [ "pub" | "exp" ] identifier ":" type [ "=" expression ] ;   (* markers only in a 'type' definition's own layout, §6.4; defaults, §4.2 *)
enum_type       = "enum" [ ":" type ] "{" [ enum_member { "," enum_member } ] "}" ;   (* the integer of chosen tags, §4.2 *)
enum_member     = identifier [ ":" type ] [ "=" expression ] ;   (* a chosen tag, compile-time code, §4.2 *)
array_type      = "[" type [ ":" expression ] "]" ;  (* sizeless form only under "&" or "*" *)
fn_type         = [ capture_bound ] "(" [ type { "," type } ] ")" [ "->" type ] ;
capture_bound   = "|" "=" "|" | "|" "&" "|" ;   (* what its values may capture, §5.4 *)

(* Statements *)
statement       = var_def
                | type_alias
                | stmt_block
                | if_expr
                | for_expr
                | while_expr
                | match_expr
                | break_stmt
                | continue_stmt
                | yield_stmt
                | return_stmt
                | panic_stmt
                | defer_stmt
                | scope_stmt
                | spawn_stmt
                | expr_stmt ;

var_def         = ( "var" | "const" ) identifier [ ":" type ] "=" expression terminator ;
type_alias      = "type" identifier "=" expression terminator ;   (* a local alias, §4.4 *)
stmt_block      = "{" { statement } "}" ;
break_stmt      = "break" [ expression ] terminator ;
continue_stmt   = "continue" terminator ;
yield_stmt      = "yield" expression terminator ;
return_stmt     = "return" [ expression ] terminator ;
panic_stmt      = "panic" [ expression ] terminator ;   (* the expression is a byte-array message read in place, §5.3 *)
defer_stmt      = "defer" statement ;   (* not a declaration; runs when the enclosing block is left, §5.3 *)
scope_stmt      = "scope" stmt_block ;   (* waits for its tasks on every way out, §5.6 *)
spawn_stmt      = "spawn" stmt_block ;   (* a task of the innermost scope of its function or task, §5.6 *)
expr_stmt       = expression ( assign_op expression terminator | terminator ) ;

terminator      = ";" ;   (* the block statements above carry none *)

assign_op       = "=" | "+=" | "-=" | "*=" | "/=" | "%="
                | "<<=" | ">>=" | "&=" | "|=" | "^="
                | "+%=" | "-%=" | "*%=" ;

(* Expressions *)
expression      = cast_expr { binary_op cast_expr } ;  (* grouping per the §3.2 precedence table *)

binary_op       = "+" | "-" | "*" | "/" | "%" | "+%" | "-%" | "*%"
                | "==" | "!=" | "<" | "<=" | ">" | ">="
                | "&&" | "||"
                | "&" | "|" | "^" | "<<" | ">>" ;

cast_expr       = unary_expr { "is" ( implied_variant | named_type ) [ "|" capture "|" ] | "as" type | "to" type | ":" constraint } ;   (* ":" asks whether a type satisfies interfaces, §4.4 *)

unary_expr      = unary_op unary_expr | postfix_expr ;
unary_op        = "-" | "~" | "!" | "&" [ "var" ] | "new" | "move" | "copy"
                | "*" [ "var" ] ;   (* a pointer type, on a type only, §4.4 *)

postfix_expr    = primary_expr { postfix_suffix } ;
postfix_suffix  = "(" [ expression { "," expression } ] ")"                            (* call *)
                | "<" type { "," type } ">" "(" [ expression { "," expression } ] ")"  (* generic call *)
                | "." identifier                                                  (* member access *)
                | "[" expression "]"                                         (* array index *)
                | "[" [ expression ] ".." [ expression ] "]" ;               (* subslice *)

primary_expr    = literal
                | identifier_expr
                | implied_variant
                | named_struct_init
                | anon_struct_init
                | "(" expression ")"
                | array_fill
                | array_range
                | array_literal
                | if_expr
                | for_expr
                | while_expr
                | match_expr
                | lambda_expr
                | macro_call
                | struct_type | enum_type | fn_type ;   (* types as values, §4.4 *)

identifier_expr   = identifier { "::" identifier } [ "<" type { "," type } ">" [ "::" identifier ] ] ;   (* Vector<u8>::empty, Vector<u8> *)
implied_variant   = "::" identifier ;
literal           = integer_literal | float_literal | string_literal | interpolated_string | char_literal | "true" | "false" ;   (* interpolated_string, §2.6 *)

array_literal     = "[" [ expression { "," expression } ] "]" ;
array_fill        = "[" expression ":" expression "]" ;   (* the value's own operands take no ":", so "[(T: I) : n]" *)
array_range       = "[" [ expression ] ".." expression "]" ;

named_struct_init = identifier { "::" identifier } [ "<" type { "," type } ">" ] "{" [ member_init { "," member_init } ] "}" ;
anon_struct_init  = "{" [ member_init { "," member_init } ] "}" ;   (* "{}" only in value position *)
member_init       = "." identifier [ "=" expression ] ;   (* ".x" alone is ".x = x" *)

lambda_expr       = [ "|" ( capture_default { "," capture } | capture { "," capture } ) "|" ] function ;   (* "(x: T)" opens a lambda when "=>", "->" or a block follows its ")", else it is "(" expression ")" *)
capture_default   = "=" | "&" [ "var" ] ;
capture           = [ "&" [ "var" ] | "move" | "copy" ] identifier ;

if_expr     = "if" "(" expression ")" if_branch [ "else" ( if_expr | if_branch ) ] ;
if_branch   = stmt_block | expression ;   (* bare expression only in value position *)

for_expr    = "for" "(" expression { "," expression } ")"
              [ "|" capture { "," capture } "|" ]
              stmt_block [ "else" stmt_block ] ;

while_expr  = "while" "(" expression ")" stmt_block [ "else" stmt_block ] ;

match_expr  = "match" "(" expression ")" "{"
              { ( pattern { "," pattern } | "else" ) [ "|" capture "|" ] match_arm }
              "}" [ "else" stmt_block ] ;
pattern     = [ "-" ] ( integer_literal | float_literal )
            | string_literal | char_literal | "true" | "false"
            | implied_variant
            | identifier { "::" identifier } [ "<" type { "," type } ">" ] ;   (* a variant, a concrete type or a constant *)
match_arm   = stmt_block | expression terminator ;   (* bare expression only in value position *)

macro_call  = "#" identifier { "::" identifier } "(" [ expression { "," expression } ] ")" ;

Macro calls and types in expressions. # marks a macro call (§7.3) and nothing else: #name(args) is a primary expression, so #implementers_of(Shape).length() calls length on the macro's result. Compile-time evaluation itself has no marker (§7.1). In an expression a type is written as in an annotation, and the prefixes &, &var, * and *var and the brackets [X] and [X : N] build a type when their operand is a type (§4.4); (u32) -> u32 is a function type, told from a parenthesised expression by its -> or its number of members. A type statement in a body is a local alias (§4.4).

Braces are required. The body of an if, an else, a while, a for, and every match arm is a block. There is no brace-less body: if (c) doA(); is a syntax error, written if (c) { doA(); } instead. Two things may stand where a body would: an else may carry another if directly, in statement and value position alike (if (a) { … } else if (b) { … } else { … }), and the branches of a value-position if may be bare expressions (below).

Statement termination. Every statement ends with ;, as do the declarations without a body — imports, type, const, and extern definitions, interface functions and constants, and body-less macros. A function, an interface, or a macro with a body ends at its closing }. Inside a body, the exception is the block statements — a { … } block, and an if, while, for, or match in statement position — which end at their closing } and take no ;:

if (x) { doA(); } else { doB(); }        // statement: no ';'
var v = if (x) { yield a; } else { yield b; };   // value: the 'var' still ends with ';'
var w = if (x) a else b;                 // value form with bare branches

Using one of those constructs as a value changes nothing about the enclosing statement: the var, return, argument, or assignment around it ends with its own ; as always. Newlines are whitespace, so a statement may span lines and several may share one. There is no empty statement, so a ; that terminates nothing is a compile-time error. A statement starting with if, while, for, match, or { always parses as the statement form, never as an expression statement.

if as a value. An if in value position has two branch forms, and both branches must be present:

The two mix freely (if (c) a else { yield b; }), and an else carries another if for a chain (if (a) x else if (b) y else z) as it does in statement position.

match arms take the same two forms. An arm body is a block, or — in value position — a bare expression that yields implicitly. A bare-expression arm ends with ;, which is what stops the next pattern from being read as more of the arm's expression: without it, ::A x ::B would parse as the path x::B (§5.3).

Match patterns are not expressions. A pattern is a literal (a number may carry a leading -), an implied variant (::Some), or a path naming a variant (Option::None), on an interface object a concrete type (Circle, §4.2), or a constant (LIMIT, Op::HALT, codes::FIRST, §5.3). Because a pattern never continues into an operator, a struct literal, or a call, what follows it is unambiguous: a | opens the arm's capture, and a { opens the arm's block — Option::None { } is the arm for None, never an empty struct literal. A { beginning a bare-expression arm follows the if-branch rule below.

An arm may list several patterns separated by commas, and runs when any of them matches: 1, 2 { … }, ::Moved, ::Resized |&delta| { … }, ::Idle, ::Paused &"waiting";. An internal else stands alone and cannot be listed with others.

Array types. [T : N] is the fixed array, and the count is any expression the compiler can evaluate at compile time (§4.2). In runtime code [T] appears only under & or * (&[T], *[T]); compile-time code also holds [T] values by themselves (§7.3).

Array-fill count. The count in [value : count] is any expression, but a stack array [T : N] needs a compile-time one — checked after parsing, not by the grammar. A runtime count is only valid for new [value : count] (§5.2). In a runtime body the count is compile-time only when written as an integer literal, a constant's name (N, Type::N, T::N, §6.4), reflection on a type (u32.size(), T.size(), §4.4), or the name of a const local whose initializer is compile-time evaluable (§7.1), operators included there (const k = N * 2; then [0 : k]); any other expression written as the count, even one that could be evaluated while compiling (N - 1, width()), is a runtime count. A count naming a type parameter is known per instantiation. Inside a compile-time context (§7.1) every count is compile-time.

Empty array literal. [] is the zero-length array [T : 0]. It has no elements to infer from, so its element type comes from context; with none it is a compile-time error. &[] is the empty slice, which a &[T] target accepts like any other reference to static data.

Range generators. [start..end] is the array of integers from start (inclusive) to end (exclusive), so [0..5] is [0, 1, 2, 3, 4]; [..end] starts at 0. Both bounds are integers of one type (§4.3); untyped bounds take the element type the context expects (var a: [u64 : 3] = [0..3];), else default to i32. A literal end below a literal start is a compile-time error, and a runtime end below start a runtime fault in checked builds. Literal bounds — written as a fill count must be to be compile-time, above — give a stack array [T : end - start], runtime bounds need new (giving *[T]) — except as a for subject, where no array is built and runtime bounds are always fine (§5.3).

Subslicing. arr[start..end] denotes the unsized array value [T] of elements start to end in place; arr[..end] starts at 0, arr[start..] runs to the length, and arr[..] is the whole array. The subject may be any array form. Like any unsized value, the bare form is valid only where it is consumed in place (§5.2): a method receiver, an index or subslice subject, a for subject, an operand of new — new arr[start..end] copies the range into an owned *[T]. Anywhere else it is borrowed with the use-site forms of §5.2: &arr[start..end] is the immutable view &[T], &var arr[start..end] the mutable &var [T], valid only when the subject is mutable; a bare subslice in a value position is a compile-time error. Bounds must satisfy start <= end <= length; breaking that is a runtime fault in checked builds. Like any reference, the view dangles once the subject is dropped, moved, or reallocated.

Range assignment. An assignment whose target is an array with no fixed size — a subslice (dest[a..b], dest[..]) or the elements a slice reference reaches — copies elements into it: dest[a..b] = src[c..d] copies the elements of the value, read in place, over the target's, as element assignment would one by one. The value is any array form ([T : N], a subslice, &[T], *[T], an array literal, whose untyped elements take the target's element type) with the target's element type exactly, and the target must be mutable. The two lengths must be equal, a runtime fault in checked builds otherwise, and the two sides may overlap: the result is as if the value were copied out first. Since the copy is of the bytes, an element type that owns heap memory is a compile-time error (the elements are moved instead, below), and only = applies: compound assignment works on single elements. A [T] value that compile-time code holds directly (§7.3) is not a range: assigning to it replaces it whole, while a subslice of it or a reference to it takes a range assignment.

Range moves. dest[a..b] = move src[c..d] moves elements of any type: their bytes are copied as by memmove, and the target's elements are written over without being dropped, so each must be moved-from unless the source covers it (§5.2), which a checked build checks, a runtime fault otherwise, as for unequal lengths. When src is a range of a local owning its array (*var [T], including a parameter or a |move| capture) and the target is not in that local's array, the move takes the array: it is freed, its elements outside the range taken to be moved-from (which a checked build checks too), and the local is moved-from afterwards. Otherwise the source's elements the target does not cover are left moved-from, and the source must be mutable; elements owning nothing are simply copied. Wrong code thus leaks in a release build rather than freeing twice. Growing a container is one zero-filled allocation and one move: grown[..count] = move buffer[..count];.

Constant array literals are static data. An array literal whose elements are all constants — literals, payload-less enum variants, and nested literals of those — is a literal like a string literal (§2.6): its elements live in static program memory and are never rebuilt at runtime. The use-site forms of §5.2 apply unchanged: [a, b, c] copies the elements into a [T : 3], &[a, b, c] references the static data for the whole program (converting to &[T], §4.3), and new [a, b, c] copies them into a fresh *[T]. The data is constant, so &var over it is a compile-time error:

const stops: &[TokenKind] = &[TokenKind::Semicolon, TokenKind::Import];   // static

Any other array literal is a temporary that lives to the end of its statement (§5.5), so a reference to one may not outlive it.

Struct literals. A named literal (Point { .x = 1, .y = 2 }) builds that type, and an anonymous one ({ .x = 1, .y = 2 }) builds the type its context expects — a named struct, like an implied variant takes its enum from context (§4.2), or an anonymous layout; with no expected type it is the anonymous layout of its members. Either way every member is initialized exactly once, by the literal or by its default (§4.2), and a member the literal writes must be visible (§6.4). A member initializer written .x alone is shorthand for .x = x, so a constructor reads return Vec2 { .x, .y };. The shorthand is a bare use of x (§5.2), so a member that owns heap is still written out: .name = move name.

Disambiguation. These forms need lookahead, and an implementation must resolve them this way:

is capture versus bitwise OR. A | right after an is test's type always opens a capture, never bitwise OR, and the capture binds tighter than any binary operator: a is ::Some |b| && c is (a is ::Some |b|) && c. There is nothing to disambiguate: | takes integer operands only (§4.10), and an is test yields bool, so a is ::Some | b has no valid reading without the capture.

Capture typing. A capture binds a name exactly as a binding would take the captured value through the use-site forms of §5.2, so it writes the same marker before the name, and there are five forms:

A capture carries no type annotation: the type always comes from the subject. Pointee transparency (§5.2) applies: "the value" is what the subject reads as, so |&x| on an owning-pointer payload borrows the pointee — a *T payload gives &T, a *[T] payload gives the slice &[T] — never a reference to the pointer itself. The captures of one site bind distinct names (§5.4). This is the only capture syntax, and it is identical at every capture site: lambda capture lists, is tests (§4.2), for, and match arms. An interface-object capture must state a reference or owning form — |&x|, |&var x|, or |move x| — because an erased value cannot be copied; |x| and |copy x| there are compile-time errors (§4.2).

3.2 Operator Precedence & Associativity

Higher number binds tighter. All binary operators are left-associative.

PrecedenceOperators
100 (tightest)* / % *%
90+ - +% -%
80<< >>
70< <= > >=
60== !=
50& (bitwise AND)
40^
30| (bitwise OR)
20&&
10 (loosest)||

The expression rule is flat; this table alone fixes the grouping. Unary prefixes (-, ~, !, &, &var, new, move, copy, and * / *var on a type) bind tighter than every binary operator and are right-associative. Postfix operators (call (), generic call <>(), member ., index []) bind tighter still. The casts (is, as, to, §4.5) and the conformance test X: I (§4.4) sit between: looser than the unary prefixes, tighter than every binary operator, so T: Key && U: Format is two tests joined by &&, while the + in T: Key + Format belongs to the test's list of interfaces.


4. Type System & Static Semantics

4.1 Primitive Types

NameWidthSignedFloat
u81 byteNoNo
u162 bytesNoNo
u324 bytesNoNo
u648 bytesNoNo
i81 byteYesNo
i162 bytesYesNo
i324 bytesYesNo
i648 bytesYesNo
f324 bytes—Yes
f648 bytes—Yes
bool1 byteNoNo

true and false are keywords. A character literal takes the primitive that fits its bytes (§2.6).

A bool is stored as one byte, false as 0 and true as 1. A byte holding anything else, which only as can make (§4.5), reads as true wherever a bool is used: a condition, &&, ||, !, ==, != and a match on a bool all treat any nonzero byte as true, so !(2 as bool) is false and (2 as bool) == true holds.

The floats follow IEEE 754 binary32 and binary64. The sign and payload of a NaN that an operation produces are the processor's, as IEEE 754 leaves them: x86-64 makes sqrt(-1.0) a NaN with the sign bit set and ARM64 one without, so a NaN may print as nan or -nan, may differ between checked and release builds, and a NaN a constant computes at compile time may differ in its bits from the one the same expression makes at run time on another architecture. Only is_nan (std::math) or x != x tells a NaN; no program should read its bits.

4.2 Composite & Derived Types

SyntaxKindNotes
struct { f: T, ... }StructMembers in declaration order
enum { A, B: T, ... }Enum (sum type)Variants, each with an optional payload
enum : u32 { A = 19, ... }Enum with chosen tagsPayload-less variants laid out as the integer named, each with its tag
[T : N] (N ≥ 0)Fixed arrayCompile-time size; stack or inline
&[T]SliceNon-owning view: raw pointer + u64 length
*[T]Heap arrayOwned heap block, length fixed at allocation
(T1, T2) -> RFunction typeFirst-class function value capturing nothing; |=| and |&| bounds (§5.4)
type X = BaseTypeNamed typeDistinct by name; assignable down its own chain (§4.3 rule 4)
*T / *var TPointerOwned heap instance, immutable / mutable
&T / &var TReferenceNon-owning borrow, immutable / mutable — made by &x / &var x (§5.2)
&I / *I (I an interface)Interface objectData pointer + the concrete type's identity (§6.2)

Member defaults. A member of the struct a type definition gives may have a default, gap: f32 = 0.0, which a literal leaving the member out takes; only a member with a default may be left out. The default is any expression of the member's type, evaluated each time a literal leaves the member out, in the defining module's scope, where it sees no local and no other member. A literal's written members are evaluated first, in the order written, then the defaults it takes, in declaration order. A member hidden from the literal's module (§6.4) may be left out when it has a default, so Column { .gap = 8.0 } builds a type with private bookkeeping members. A generic struct's defaults may name its type parameters and are checked per instantiation (items: Vector<T> = Vector::empty()). The parameter's own layout of a function may carry defaults too, belonging to that declaration and not to the layout type, which compares members by name and type alone (§4.3 rule 6): an anonymous literal passed for that parameter takes them, which gives named and defaulted arguments with no further feature.

fn place(at: struct { x: f32 = 0.0, y: f32 = 10.0 }) { ... }
place({ .x = 4.0 });   // y is 10.0
place({});             // both defaults

Defaults are written nowhere else: an inline layout of a variable, a result, a member's type or a type argument takes none.

No indirection behind another. The pointee of a written pointer or reference is never itself a pointer or reference: **T, *var *T, &*T, *&T, and & &T are compile-time errors. A named type cannot hide an indirection either: type Handle = *Node is a compile-time error. An indirection that has to sit behind another is wrapped in a struct: type Handle = struct { data: *Node }, then *Handle or &var Handle. Pointee transparency (§5.2) therefore always reads through exactly one level.

Indirections a type argument brings in. When a generic type or function is instantiated with a pointer or reference for T, the types it forms read through that indirection the way the use-site forms of §5.2 read through a value: a name always refers to the value, and & / &var reach it.

FormedIsLike
&T, T = &X or &var X&X&r passes a reference through
&T, T = *X or *var X&X&p borrows a pointer's pointee
&var T, T = &var X or *var X&var Xthe same, mutably
*T or *var T, T = *X or *var XT itselfthe allocation's own pointer; its mutability is T's

The rest cannot read through and are compile-time errors where an instantiation forms them — a generic type's fields, a call's instantiated signature, or a local in an instantiated generic body — reported at the use that instantiates it: *T with T = &X (a pointer cannot own what a reference borrows: Box<&Node> where Box<T> holds a *T), and &var T with T = &X or *X (it would write through an immutable indirection). So a Vector<*Node> gets, views, and iterates its elements as &Node, Option<&u32>'s unwrap_or takes and returns a &u32, and Holder<*Node> with an item: *T holds a plain *Node.

Inside the instantiated body the operations keep their meaning on T: reading a T through such a &T reads the indirection itself — a reference is copied as itself, and copy on a pointer gives a fresh pointer to a deep copy — and writing or moving a whole T through a *T writes or moves the pointer it collapsed to. Writing or moving a whole T through a &T / &var T is a compile-time error at the instantiation, since the reference reaches only what the indirection points at: fn replace<T>(slot: &var T, x: T) { slot = move x; } works for T = u32 and is an error for T = *var Node.

An interface used as a type — only behind an indirection (&I, &var I, *I, *var I) — is an interface object: the address of a value plus the identity of its concrete type, which calls dispatch through at runtime (§6.2). A value of type T converts to an interface object of I exactly when T declares I as a marker (type T : I = ...), when T is a numeric primitive and I is Number, or, inside a generic body, when T is a type parameter constrained by I, the object then being formed per instantiation. An object's value has no fixed size, so copy cannot give it (copy gives a value, §5.2): new p on a p: *I or &I copies the concrete value into a fresh allocation and gives a new owning *I. Going back down to the concrete type uses the same two constructs as enum discrimination, match and is.

By match, one arm per concrete type. The arms are concrete type names, and each capture binds the concrete value. The capture states its own form (§3.1), and the copying forms |c| and |copy c| are compile-time errors on an interface object: |&c| and |&var c| borrow the concrete value in place, giving &Circle / &var Circle, and |move c| takes ownership of it by taking over the allocation, giving a *Circle / *var Circle with nothing copied. The subject has to allow the form asked for — |&var c| needs a &var I or *var I subject, and |move c| an owning *I / *var I one, which is then moved-from after the match (§3.1). An arm or is test naming a type that forms no object of the interface (§4.3 rule 10) could never match, and is a compile-time error:

match (shape) {            // shape: &Shape
    Circle |&c| { /* c: &Circle */ }
    Square |&s| { /* s: &Square */ }
    else     { /* unhandled concrete type */ }
}

By is, a single test. x is Type is a boolean expression, and an attached capture also produces the downcast value, in the form the capture asks for:

if (shape is Circle |&c|) { /* c: &Circle, only when shape's concrete is Circle */ }

A capture is allowed only where a successful test guards every use: on a direct && conjunct of an if or while condition. Each conjunct may carry one, and each binding is visible to the conjuncts after it and to the branch body:

if (cursor.peek() is ::Some |first| && first == '/' && cursor.peek(1) is ::Some |second|) {
    // first and second both bound here
}
while (cursor.next() is ::Some |token|) { /* token re-binds each iteration */ }

A capture under ||, under !, or outside an if / while condition is a compile-time error, since a failed test could still reach its uses. In a while the captures re-bind every iteration and scope over the body; in an if they scope over the then-branch only.

is takes two kinds of left operand. On an interface object the right operand is a concrete type and the capture binds the downcast value, as above, always with an explicit & / &var / move. On an enum value the right operand is a variant of that enum, is tests whether the value holds it, and the capture binds that variant's payload — so it is only allowed on variants that carry one:

type SomeEnum = enum { ValueA: T, ValueB };
var val: SomeEnum = SomeEnum::ValueA(t);

if (val is SomeEnum::ValueA |&a|) { }      // a borrows the payload in place
if (val is SomeEnum::ValueA |a|) { }       // a is a copy (T owns no heap)
if (val is SomeEnum::ValueA |copy a|) { }  // a is a deep copy (T owns heap)

An owning capture (|move a|, §3.1) takes the payload out of the enum. The subject must be mutable or a temporary, which nothing else owns (while (items.pop() is ::Some |move item|)). On a match the payload moves into the capture exactly like move (§5.2) — a pointer payload transfers, a value payload has its owning members moved out — and the subject is left moved-from; on a miss the subject is freed by its normal scope-end drop. Either way the subject is moved-from after the construct, and using it again is a use-after-move error:

type Holder = enum { Boxed: *T, Empty };
var h: Holder = Holder::Boxed(new T {});

if (h is Holder::Boxed |move p|) { /* p owns the payload allocation */ }
// h is moved-from here, whether or not the branch ran

Enums with chosen tags

An enum may name an integer primitive after enum and give each variant a tag, the integer it is stored as: type Op = enum : u32 { TypeVoid = 19, TypeBool = 20 };. This is how the codes of a file format or a C library (SPIR-V's opcodes, a protocol's message kinds, a C enum) become an enum. The rules:

type Op = enum : u16 { Load = 1, Store = 2, Halt = 0xFFFF };
const code: u16 = read_code();
const op = if (Op::from(code) is ::Some |op|) op else Op::Halt;
match (op) {
    Op::Load { ... }
    Op::Store { ... }
    Op::Halt { ... }
}

Implied enum variants (::Variant)

A variant may drop its enum name and be written ::Variant, letting the compiler infer the enum. This works wherever a variant is named: construction (::Some(x), ::None), match arms, and is targets. A bare variant name without :: is never valid. In a match arm or an is target written with its enum (Option::Some), the enum must be the subject's, or one the subject's type is named over.

Inference needs exactly one candidate, found in two steps:

  1. A contextual type — a declared variable type, an expected payload or return type, a match or is subject — that is an enum with that variant. As a call argument the context is each overload candidate's parameter type in turn, so a candidate that cannot resolve the variant is simply not viable and ::X takes part in overload selection like any argument (§4.6).
  2. Otherwise every visible enum is searched. Exactly one with that variant wins; none or several is a compile-time error, fixed by writing the enum name.
var maybe: Option<u32> = ::Some(7);   // context: the declared type
match (state) {
    ::Idle { }                        // context: the match subject
    ::Busy |load| { }
}
if (state is ::Busy |load|) { }       // context: the 'is' subject

Generic enums infer their type parameters by the same unification as named construction (§4.7).

4.3 Type Compatibility & Coercion Rules

  1. Identity — identical types are compatible.
  2. Untyped integer literal — compatible with any numeric primitive except bool, and with any named type whose underlying chain reaches one. Radix makes no difference, and with no context the literal becomes i32. An array literal of untyped elements takes a contextual element type (var a: [u8 : 3] = [1, 2, 3]).
  3. Untyped float literal — compatible with f32 and f64; f32 with no context, and f64 as a variadic argument (§6.3). A float literal, or untyped float arithmetic, whose value overflows its type to infinity is a compile-time error.

    Inside a generic body both kinds of literal are also compatible with a type parameter constrained by Number (§6.2), as in var total: T = 0. The literal must suit every type the parameter is bound to: an integer literal must fit the bound type's range, a float literal is allowed only where the bound type is a float, and a bound type over no numeric primitive (§6.2) takes neither. Both are checked per instantiation (§4.7), and a failure is a compile-time error at the call that instantiates the body.

  4. Named type transparency (one way) — a named type is compatible with everything below it in its own chain: its underlying type, that type's underlying type, and so on down to the base, whether the links along the way are named or not. So with type Meters = f32; and type Distance = Meters;, a Distance is compatible with Meters and with f32. The reverse never holds: nothing converts implicitly up a chain, so an f32 is not a Meters, literals aside: an untyped literal takes a named number type's place (rule 2, const m: Meters = 3;), and a lambda or a named function written where a named type whose chain ends in a function type is expected takes that type's place when it converts to the function type (§5.4). Two named types that merely share a base are therefore incompatible in both directions — each converts down to the base, neither converts up into the other — as are two named types of identical layout on separate chains. Converting up a chain, or across to another, is x as T (§4.5).
  5. Numeric widening — a numeric primitive is compatible with a wider one of the same class: unsigned→unsigned, signed→signed, float→float (f32→f64, the reverse needs to). Crossing classes needs x to T (§4.5).
  6. Structural struct compatibility — a target expecting an anonymous layout (struct { a: u8, b: f32 }) accepts any value, named or anonymous, whose fields match exactly: same names and types in the same order, nested layouts compared the same way. Extra or missing fields never coerce, and named struct types are otherwise distinct.
  7. Structural enum compatibility — an inline enum { ... } is compatible with any enum whose variant list matches exactly: same names in the same order with the same payload types, and the same chosen tags of the same integer (§4.2). Two named enums stay distinct even with matching shapes; this rule needs at least one inline side.
  8. Dropping mutability — &var T is compatible with &T, &var [T] with &[T], and *var T with *T. Nothing gains mutability implicitly, with one exception: a pointer a call returns has no var or const of its own, so move make() (§5.2) takes the mutability its target asks for, as new does.
  9. Fixed array to slice — &[T : N] is compatible with &[T], and &var [T : N] with &var [T]: the reference to a fixed array becomes a slice over its N elements. This is how &"abc" and &[a, b, c] meet a &[u8] / &[T] parameter.
  10. Interface objects — &C, &var C, *C, and *var C are compatible with the same indirection of an interface I when the concrete type C declares I as a marker, when C is a numeric primitive and I is Number, or when C is a type parameter constrained by I (§4.2, §6.2).

These rules relate types. Which form a source expression must be written in — bare, &, &var, copy, move, new — is decided separately by the target's type (§5.2).

Joining branch types. When the branches of a value-position if, match, or loop else (§5.3) produce different types and nothing gives the construct a type from outside, their types are joined: the result is the first branch type every other branch converts to under the rules above. So if (c) &"high" else &"low" joins &[u8 : 4] and &[u8 : 3] into &[u8], and an untyped literal branch takes the other branches' type. With no such type the construct is a compile-time error, fixed by annotating the target. With an expected type — a declared variable, a parameter, a return — each branch simply converts to it.

Inline struct { ... } and enum { ... } types are allowed wherever a type is expected: parameters, return types, variable annotations, struct fields, enum payloads, generic arguments, array elements. Values of an inline enum are built with ::Variant (§4.2), since the type has no name to qualify with.

4.4 Types as Compile-Time Values (type)

A type is also a value, of the type type, that compile-time code can read and rebuild: a struct or enum layout, a primitive, an interface, or any other type. A type value exists only during compile-time evaluation (§7.1): no runtime variable, field, parameter or result holds one. type is written in macro signatures and inside compile-time code (macro m() -> type, a var members: [type] in a macro body), and a function may neither take nor return one (§7.3). Being a keyword, it never clashes with a user type named Type.

Types written as expressions. Where compile-time code expects a value, a type is written with the same syntax as in an annotation: a name (u32, Packet, Vector<u8>), an inline layout (struct { id: u32 }, enum { A, B: u8 }), or a function type ((u32) -> u32). Applied to a type, the forms that read as operators on values build types instead: &X, &var X, *X and *var X are the reference and pointer types, [X] the unsized array type, and [X : N] the fixed one, N being a compile-time context. The operand decides: &x borrows a value x and is a reference type for a type x. A list of types is an array literal of them ([u8, u16]); since a one-element list reads like the unsized array type, [u8] is the list of one type where the expected type is [type] (a macro parameter, an annotated local), and the type [u8] everywhere else. Inside a generic function a type parameter is such a value, bound per instantiation (§4.7).

A type value comes from one of three places:

All type methods run at compile time and are called with dot syntax on the type: Packet.member_names(), T.size(). One more, moved, gives a runtime value instead: T.moved() is a moved-from T, all of whose bytes are zero (§5.2), which containers fill their spare slots with (new [T.moved() : n]); of a disposable type it is allowed only where a fill of one is, in its holder's own functions.

MethodSignatureSemantics
is_struct() -> boolTrue iff the type is a struct.
is_enum() -> boolTrue iff the type is an enum.
is_primitive() -> boolTrue iff the type is a built-in primitive, or a named type whose chain reaches one (type Meters = u32), as is_struct and is_enum look through named types.
is_interface() -> boolTrue iff the type is an interface.
name() -> [u8]The type's declared name.
equals(other: type) -> boolTrue iff both denote the same type.
add_member(name: [u8], member: type)Appends a struct field or enum variant.
remove_member(name: [u8])Removes the named member.
member_names() -> [&[u8]]Member names, in declaration order, as references to static names, so names of different lengths cross into the program together (§7.2).
member_types() -> [type]Member types, in the same order.
size() -> u64The type's byte size under the §4.9 layout rules — C's sizeof, padding included. Computed from the members in hand, so a type rebuilt with add_member reports its new size. A type with no runtime layout — an interface, void, a generic type as a template — is a compile-time error.
alignment() -> u64The type's byte alignment under §4.9 — C's alignof, always a power of two. Same rules as size.

A type is a value: add_member and remove_member change the type in hand, not the type it came from, so they apply to a var holding one (var t = #struct_type(); t.add_member("x", u32);); on a named type the result is its layout, unnamed. An added field is private, like a field written without a visibility marker (§6.4). Adding a name already present, removing one that is missing, adding to a type that is neither a struct nor an enum, adding a variant to an enum with chosen tags (it would have no tag; removing one keeps the others' tags), and a struct field of a type with no runtime layout (void included) are compile-time errors. Given to a type definition (type T = <compile-time expression>, §7.1), it becomes the new type T. A synthesised struct behaves as a structural layout (§4.3 rule 6) and a synthesised enum as an inline enum (§4.3 rule 7), with variants built, matched, and tested through the name (T::Variant) like any declared enum. In a generic type definition the right-hand side may use the type parameters, and is evaluated per instantiation.

Asking for a conformance. X: I, X a type and I an interface, is a compile-time bool: whether X satisfies I as a constraint asks it (§6.2), through its own markers (a conditional one only on the instantiations meeting it), the primitives' lang items (§6.1a), or a type parameter's constraints; a generic interface is asked with its arguments (Box: Holder<u8>). X: I + J asks for both. Like reflection, it is compile-time code wherever it is written: X may be any expression giving a type, a type name, a type parameter, a generic type with its arguments (Vector<u8>: Format, Option<T>: Format), an array or indirection type ([u8]: Format, &T: Format), or a type value in compile-time code (if (member.type: Format) in a macro), and synthesised types satisfy nothing. The : takes the type directly before it, before any is, as or to.

Branching on a conformance. In a generic body, if (T: I), T a type parameter, is decided per instantiation, and only the branch taken is compiled for each: inside the then branch T also has the constraint I, so its functions, constants and operators may be used there and it meets constraints asking for I, and the disposal check (§5.2) follows only the taken branch. A condition joining tests with && constrains the then branch by each (if (T: Disposable && E: Format), or T: Disposable + Format); one using || or ! is decided the same way but constrains nothing; and one joining tests with runtime conditions by && (if (T: Format && verbose)) still constrains by its tests, its then branch compiled only where they hold. A test also constrains what follows it in its && chain, as an is capture's binding reaches the conjuncts after it, wherever the chain is written (an if or while condition, any bool expression): in if (T: Show && x.show() > 2) the call is checked with T: Show, and per instantiation the chain is built only up to a failing test, the conjuncts after it neither compiled for that instantiation nor evaluated. Conjuncts before a test, and the other side of an ||, are not constrained by it. Vector<T> disposes what set overwrites this way, while a Vector<u8> stays plain:

exp fn set<T>(self vector: &var Vector<T>, index: u64, item: T) {
    if (index < vector.count && vector.storage is ::Some |&var buffer|) {
        if (T: Disposable) { buffer[index].dispose(); }
        buffer[index] = move item;
        return;
    }
    if (T: Disposable) { var unused = move item; unused.dispose(); }
}

Reflection in runtime code. An expression that operates on a type value is evaluated at compile time even inside a runtime body: Packet.size(), T.name(), #implementers_of(Shape).length(), T: Format. Its first enclosing expression of a runtime type is replaced by the result, a literal (§7.1), so const n = Packet.size(); binds a u64 known while compiling. One naming a type parameter is evaluated per instantiation; since the body is checked once, a result of an unsized type, whose length may differ per instantiation, is only borrowed (&T.name() is a &[u8]) or used inside a larger compile-time expression, like an unsized T::NAME (§6.2). Such an expression may not read runtime state (§7.1).

Local type aliases. Inside a body, type T = expression; names a type from that statement to the end of its block:

fn func() {
    type T = some_other_module::LongTypeName;
    var t = T::empty();
}

Unlike a top-level type definition, which makes a new named type (§4.3 rule 4), a local type is an alias: T is the aliased type itself, so T::empty() gives a LongTypeName. Its right-hand side is a compile-time context like a definition's (type Index = if (WIDE) u64 else u32;). A local alias takes no type parameters and no interface markers.

4.5 Casting

Two operators cover what §4.3 does not do implicitly. Both take a type on the right.

OperatorNameSemantics
x as TReinterpretation castViews the memory of x as a T without changing it. No runtime cost.
x to TConversion castConverts the value to a T, producing a new value.
var raw: u32 = 0x3F800000;
var f = raw as f32;         // same bits, read as f32 (1.0)
var n: i64 = 300;
var u = n to u32;           // same value in a new format
var b = n to u8;            // runtime fault: 300 does not fit u8
var bytes: [u8 : 8] = [1, 0, 0, 0, 2, 0, 0, 0];
var words = bytes[0..8] as &[u32];    // two elements: 1 and 2, no copy
var odd = bytes[0..6] as &[u32];      // runtime fault: 6 bytes is not a multiple of 4
var whole = &bytes as &[u8];          // error: an array has a width a slice has not
const all: &[u8] = &bytes;            // the implicit conversion: a slice over the 8 bytes
(bytes as [u32 : 2])[1] = 7;          // writes bytes 4..8 through the view
var v = Vector<u8>::empty();
var copied = v as ByteVec;            // error: a heap owner read by value; write 'copy' or 'move'
var view = v as &var ByteVec;         // borrows 'v' as a ByteVec
var owned = move v as ByteVec;        // 'v' moves into 'owned'
var boxed = new (raw as f32);         // 'as' never allocates; 'new' does

4.6 Function Overloading

Functions, free and extension alike, may share a name as long as their parameter type lists differ. Same name and same parameter types is a redeclaration error, whatever the type parameters' constraints (fn kind<T: Number>(x: &T) and fn kind<T: Shape>(x: &T) clash), as is reusing a function name for a non-function definition (§6.4) — except a macro, which may share a name because # tells them apart (§7.3). Macros overload among themselves by the same rules (macro twice(n: u64) and macro twice(t: type)). extern declarations do not overload: a C symbol name is unique.

At a call site the candidates are every visible function with that name, except that on a value of a type conforming to an interface, a method call naming one of the interface's functions takes the conformance's implementation in place of the visible ones with its parameter types (§6.2). A candidate is viable when its arity matches and every argument is compatible (§4.3) with the matching parameter.

4.7 Generic Type Parameter Inference

A generic function's type parameters bind at each call site:

  1. Explicit arguments (make<u64>(7)) bind left to right, and may stop short: the parameters after them are inferred. With fn convert<T, U>(value: U) -> T, convert<u64>(x) binds T and infers U from x. On a type-scoped function the type's arguments are written on the type and the function's own after its name (Map<u8, u32>::from<Pairs>(p)), each list binding its own parameters.
  2. The rest are inferred by unification: each declared parameter type is matched against the argument's type, the self receiver included, and every unbound parameter binds to the type in its position. With fn push<T>(self v: &var Vector<T>, item: T), vector.push(x) binds T from the receiver and checks x against it, so x may coerce to it. Arguments other than the receiver bind strictly among themselves: when two of them bind the same parameter, their types must be identical, whatever their order (same(a_u8, b_u32) and same(b_u32, a_u8) are both conflicts). An untyped literal, bare or borrowed (5, &5, &-(2 * 3)), binds nothing while another argument, or a constraint (rule 4), can bind its parameter, and then takes the bound type (count_equal(&numbers, &3) with numbers: [u64 : 4] passes a &u64); alone, it binds its default type (identity(5) binds i32). An argument that takes its type from context, such as ::None, is checked after the others. A parameter never binds an unsized type: &T does not match &[u8], and a function over slices takes &[T].
  3. With a contextual expected type, the return type unifies against it before the arguments (var v: Vector<u8> = Vector::empty();); the arguments then unify against those bindings and may coerce to them.
  4. A parameter that appears only in another parameter's constraint binds through that constraint: once C is bound, C: Iterable<T, It> unifies with the conformance the bound type declares, so fn total<T, It: Iterator<T>, C: Iterable<T, It>>(items: &C) called as total(&v) with v: Vector<u32> binds T = u32 and It = VectorCursor<u32> from Vector's marker. The marker outranks the expected type: with fn first<T, It: Iterator<T>, C: Iterable<T, It>>(items: &C) -> T, const wide: u64 = first(&v) binds T = u32, and the u32 result then widens to u64. A type may declare one generic interface several times with different arguments (type Both : Sink<u8> + Sink<u16>); inference then binds through the one marker that fits, and with several fitting the parameter stays unbound.
  5. A parameter still unbound is a compile-time error, and so are conflicting bindings (T unified with both u32 and f32). Explicit arguments, the expected type, and the receiver bind first, in that order, and later sources may coerce to what they bound.

A bound parameter must satisfy its constraint (<T: Number>, §6.2), every interface of it when it lists several (<K: Key + Format>). A constraint naming a generic interface supplies its arguments (<T, It: Iterator<T>>), and those arguments may mention the constrained parameter itself and parameters declared to its left in the same list, never later ones. The first lets a generic body compare values of one type through an interface that has no other way to name it: fn largest<T: Comparable<T>>(items: &[T]) -> &T, with type Money : Comparable<Money>. The bound type must conform at exactly that instantiation once the call's bindings substitute in: It: Iterator<T> with T = u64 accepts an : Iterator<u64> conformer, not an : Iterator<u8> one. During overload resolution a candidate whose unification fails, leaves a parameter unbound, or breaks a constraint is not viable.

Building a variant of a generic enum works the same way: in Option::Some(x) the parameters bind by unifying the payload type against the argument and against the contextual expected type. A parameter neither source binds is a compile-time error (cannot infer type parameter 'T'). As a call argument, the context is each overload candidate's parameter type, like implied variants (§4.2).

A struct literal binds a generic type's parameters from the contextual expected type (var v: Vector<u8> = Vector { ... }) or explicitly, naming the instantiation before the braces (Vector<u8> { ... }, §3.1). Explicit arguments bind all parameters left to right and must match the parameter count; they are how to build a generic value where no context exists (var v = Vector<T> { ... } inside a generic body). As an argument of a generic call, a literal leaving its type arguments out is checked after the call's other arguments have bound the type parameters, as a lambda's untyped parameters are (§5.4), and takes the parameter's type then, its member defaults applying as anywhere:

type FieldOptions<T> = struct { label: &[u8], initial: Option<T> = ::None, width: u32 = 120 };
fn parsed<T>(self form: &var Form, text: &String, parse: |=| (&String) -> Result<T, String>, options: FieldOptions<T>) -> Field<T>;
const day = form.parsed(&text, Parse::date(), FieldOptions { .label = &"Day" }); // a FieldOptions<Date>

A parameter only the literal itself would bind leaves it unknown (only(FieldOptions { .label = &"x", .initial = ::Some(3 to u8) }) with fn only<T>(options: FieldOptions<T>)). A bare generic literal with neither source is a compile-time error.

Type parameters are opaque. Inside a generic body a value typed T is read, copied, stored, and dropped as a T, whatever the instantiation binds it to. Pointee transparency (§5.2) applies to the pointer and reference types written in the source — a &T parameter still reads as its T — not to the type a parameter is bound to: with T = *var u64, copy item on an item: T yields a fresh pointer (deep-copied like any owning value), not the u64 behind it. Only an indirection formed over T reaches through what T is bound to (§4.2). So Vector<*var [u8]> stores and owns the arrays themselves, pushing and popping them; borrowing one in place through get gives the &[u8] it holds, by the rules for indirections a type argument brings in (§4.2). A generic body behaves the same for every instantiation, except that a specialized type-scoped definition or extension (§6.4, §4.6) is picked per instantiation. Because a bound type may own heap, a T value never flows bare into a by-value use site in a generic body (§5.2): it is written copy item, a plain copy wherever the instantiation owns nothing, or move item, which has type T and transfers whatever the bound type owns.

4.8 Mutability

Bindings are immutable by default:

4.9 Data Layout

Struct layout is C-compatible: fields in declaration order, each at its natural alignment, padding as in C, total size rounded up to the largest field alignment. This makes extern structs work without annotations and gives as (§4.5) well-defined widths. An enum is a tag — the smallest unsigned integer that fits the variant count — followed by a payload area sized and aligned for the largest payload, as C would lay out the matching tagged union. An enum with chosen tags (§4.2) is its integer alone, holding the variant's tag.

Addresses follow the target. A reference or pointer to a sized value, a heap array pointer (*[T]) and a C function (§6.3) are one address: 8 bytes on the 64-bit targets and 4 on wasm32 (§6.4), as in C. A slice (&[T]) and an interface object are an address and a second 8-byte word (the u64 length, the concrete type's id) at offset 8, 16 bytes on every target; a closure (§5.4) is a u64 function index and an environment address at offset 8, also 16 bytes. So T.size() and T.alignment() (§4.4), as widths and the layout of structs C takes by value follow the build target, and compile-time code computes them for the target being built. The compiler's interpreter, which runs compile-time code and alloyc run, keeps 8-byte addresses for the values it holds itself; no address crosses from compile time into the program (§7.2), so the difference shows only to compile-time code viewing an address's bytes with as, which reads the interpreter's.

4.10 Operators

Precedence and grouping are §3.2's. Operands are read in place (§5.2), so a reference or pointer operand acts as its pointee; there is no address arithmetic or address comparison.

OperatorsOperand typesResult
+ - * / %numericthe operand type
+% -% *%integerthe operand type
unary -signed integer or float (never unsigned)the operand type
& | ^integerthe operand type
<< >>integer (left), any integer type (right)the left type
unary ~integerthe operand type
&& ||boolbool
unary !boolbool
== !=numeric, bool, enum, struct, array (any form)bool
< <= > >=numericbool

5. Execution Semantics

5.1 Evaluation Order

Eager evaluation. Every sub-expression is fully evaluated before its result is used, and call arguments are evaluated left to right before the call.

Short-circuit operators are the one exception: && evaluates its right operand only when the left was true, || only when the left was false. Every other operator, bitwise & and | included, evaluates both. Short-circuiting is what makes an inline is capture safe to use in a later conjunct (§4.2).

5.2 Memory Model & Pointer Assignment

Pointee Transparency

A pointer (*T, an owned heap object) and a reference (&T, a raw pointer in the C sense) are always used as their pointee. There is no dereference (*ptr) or arrow (->) syntax: field access, indexing, operators, method receivers, and plain reads all act on the pointed-at value. A bare name of pointer or reference type therefore means its pointee's value; the indirection itself is reached only through the use-site forms below.

var p: *Point = new Point { .x = 1, .y = 2 };
const a = p;            // a: Point, a copy of p's pointee (Point owns no heap)
const r = &p;           // r: &Point, references p's pointee
const b = r;            // b: Point, likewise a copy
const sum = r.x + p.y;  // reads through both

Pointer uniqueness. A *T is the unique pointer to, and owner of, its allocation: two pointers never point at the same object. A value that owns heap is duplicated only by copy or new, which give the duplicate fresh copies of everything the original owns, and is handed on only by move, which clears the source. References own nothing and may alias freely — mutable ones included, like C pointers. What two &var references to the same data do to it is the programmer's business.

Use-Site Forms

Every place a value flows into — a binding, an argument, an assignment, a member initializer, an array element, a return / break / yield, a capture (§3.1) — is a use site, and the type the use site expects decides how the source must be written:

Target typeSource written as
T (by value)x when the value owns no heap; copy x or move x when it does
&T / &[T]&x
&var T / &var [T]&var x
*T / *var T / *[T]move x or new x

The rule is the same everywhere, so a call reads like a binding: a &T parameter takes &x and a &var T parameter takes &var x, every time — including when x is itself a reference, which & / &var then passes through. A modification can therefore never hide behind a bare name: wherever data may be changed through a reference, &var is written where that reference is handed over. Method receivers are the one implicit borrow (§5.5).

When the target's type is inferred (var a = …), the form decides it: bare x and copy x give the value's type T (the pointee's, for a pointer or reference), &x gives &T, &var x gives &var T, move x gives the operand's own type, and new x gives *T.

Fresh values. A value no place owns yet — a call result, a struct or array literal built at runtime, an operator's result, a new — has nothing to copy from and nothing to clear, so it flows bare into any by-value target (and a new into any pointer target), and an inferred binding takes its type unchanged: var s = String::from(&"x") is a String. A call returning a reference is not an owner but a view, so it takes & like any reference (&s.view()). A call returning a pointer gives a temporary pointer, which pointee transparency reads like any pointer: written bare it is the value it points to, which nothing else owns, so it flows bare into a by-value target, moved out of the allocation, which is freed at the end of the statement. With fn make() -> *Node, const n = make() is a Node, and p = make() writes through p. move make() takes the pointer itself: const t = move null_terminated(&path) is the *var [u8] the call returns, a pointer parameter is passed move make(), and an assignment re-points a pointer binding with it. A bare temporary pointer where a pointer is expected is a compile-time error that names move, and so is one whose pointee has no fixed size (*[T]). copy and move apply only to places — variables, fields, elements, and what a reference or pointer reaches — with that one exception: move on any other fresh value is a compile-time error, and so is new on a temporary pointer, which would copy the pointee only to free the original; the error names move.

Literals. A literal is a value whose data lives in static program memory: a string literal (§2.6), a constant array literal (§3.1), and every compile-time result — a constant, a macro call, or reflection on a type (§7.1). A literal takes the use-site forms like any value: bare, it is copied out of static memory into the target; &lit references the static data, valid for the whole program run; new lit copies it to the heap. Static data is constant, so &var and move on a literal are compile-time errors. The static bytes of every byte-array literal — a string literal or a compile-time result of type [u8] — are followed by a NUL that is not part of its length, so a reference to one is a valid C string (§6.3). Numeric, character, and boolean literals are the trivial case.

Assignment through a reference or pointer binding follows the same forms, and the right-hand side's form says whether it writes through the binding or re-points it (§4.8):

var w = &var x;
w = y;            // writes through w: x == y afterwards
w = &var z;       // re-points w at z
var p: *var Point = new Point { .x = 1, .y = 2 };
p = q;            // writes q's value into p's existing allocation
p = new q;        // replaces the allocation, freeing the old one
p = make();       // writes the returned pointee into p's allocation (make() -> *var Point)
p = move make();  // replaces the allocation with the one make() returned

Positions that read a value in place take no marker: a method receiver (§5.5), an operator's operand, a field access, an index or subslice subject, a condition, a match or for subject, and a panic message (§5.3).

Slices (&[T]) versus Heap Arrays (*[T])

A slice is a non-owning view over a sequence whose length is not known at compile time — the pointer + u64 length pair of §4.2. A heap array is an owned heap block made by new:

var arr: *[u32] = new [0 : 120];    // 120 u32 elements, all 0
var n: u64 = 120;
var dyn: *var [u32] = new [0 : n];  // the count may be a runtime expression

The count in new [value : count] may be a compile-time literal — which also allows a fixed stack array [T : N] — or a runtime expression, which always allocates a *[T] of count elements, each set to value. The fill value is a use site of type T like any element, so a value that owns heap is written [copy x : count], and every element receives its own deep copy.

A pointer to a heap array points straight at the first element, so it drops into C code unchanged. Its length (arr.length()) lives in a metadata prefix immediately before the data, at a negative offset from the pointer.

Ownership, move, and Reclaim

Ownership is structural and automatic. A value owns heap if it is a *T / *var T / *[T] pointer, a closure (which owns its captured environment), or a struct / array / enum containing an owning member, element, or active payload. References and slices own nothing.

Disposal (Disposable)

Some values stand for something outside memory — a file, a socket, a lock — that a call must release; freeing their memory is not enough. A type says so by declaring the lang item std::dispose::Disposable (§6.1a), and the compiler checks that the program releases every such value. It never calls dispose itself: there are no hidden calls, only checks.

import std::dispose;

type File : Disposable = struct { fd: i32 };

fn dispose(self f: &var File) { close(f.fd); }

fn copy_lines(source_path: &[u8], target_path: &[u8]) {
    var source = File::open(source_path);
    defer source.dispose();
    var target = File::open(target_path);
    defer target.dispose();      // released before 'source'
    ...
}

Growth is manual. A *[T] has a fixed length once allocated; there is no in-place resize or realloc. A growable collection is built by hand: allocate a larger *var [T] with a runtime-sized new [value : count], copy the elements across, and reassign the owning field, which frees the old buffer. The standard library's Vector<T> (std/vector.alloy) and String (std/string.alloy) are written exactly this way; their mutating functions (push, append, …) take a &var self receiver and are called as methods (vector.push(x)).

Manual-safety caveats. Alloy has no borrow checker. References are unchecked raw pointers: a &T can outlive what it points at — a dropped local, a moved-from or reassigned owner — and dangle. Double frees are impossible by construction, since deep copying plus pointer uniqueness means no two owners share an allocation. There is no implicit allocation: heap is allocated only where new or copy is written (or inside a function that writes them), because a value that owns heap never flows bare into a by-value target (§5.2, use-site forms).


5.3 Control Flow Semantics

return [value] exits the enclosing function with value as its result.

break [value] exits the innermost enclosing loop, passing through any if or match in between:

for (items) |item| {
    if (item.done()) { break; } // exits the 'for'
}

With a value, the loop evaluates to that value — the same channel yield uses in a value-position loop (below). A break outside a loop is a compile-time error.

continue skips the rest of the body and begins the next iteration of the innermost enclosing loop, likewise passing through any if or match in between: a while re-evaluates its condition, a for advances to its next element — every subject of a multi-subject loop at once. A continue outside a loop is a compile-time error.

break and continue pass through a value-position if or match as well: leaving one that way abandons its value, and the path counts as terminating for definite yield (below).

yield value produces the value of the innermost enclosing value-position construct: an if, a match, or a for / while with an else clause. A yield inside a loop that is not itself value-position passes out through that loop to the nearest value-position if or match, exiting the loop on the way and dropping its owned locals normally. A yield with no value-position construct around it is a compile-time error: a statement-position if, match, or loop has nothing to receive the value — yield passes through all three.

panic [message] stops the program with a runtime fault, in every build mode — unlike the checks that guard indexing or to, it is not dropped in release builds. The optional message is any byte array — a literal, a [u8 : N], a &[u8] — read in place like an operator's operand, so it takes no marker (panic "bad state"); the fault prints it (a bare panic prints the word alone) and the process exits abnormally, like any other fault. Nothing after it runs, so it terminates for the path analysis below: it is the statement for a branch the programmer knows is unreachable but the compiler cannot prove so, and for an invariant whose violation has no recovery. Reached during compile-time evaluation (§7.1), a panic is a compile-time error carrying the message.

fn head(items: &[u32]) -> u32 {
    if (items.length() > 0) { return items[0]; }
    panic "head of an empty slice";
}

defer statement runs the statement when the enclosing block is left — by falling through its end, or by return, break, continue or yield — and not on panic. A block's deferred statements run latest first, among the drops of its owning locals: whatever was declared or deferred later runs first. A return computes its value before them, so a deferred statement may release what the value was computed from. The statement reads its variables as they are when it runs, not when it was deferred; it is analysed there, on each way out, so a variable moved before the block is left is a use after a move (§5.2).

fn copy_file(source_path: &[u8], target_path: &[u8]) -> bool {
    var source = File::open(source_path);
    defer source.close();
    var target = File::create(target_path);
    defer target.close();         // runs before 'source.close()'
    if (!source.valid() || !target.valid()) {
        return false;             // both still close
    }
    return target.write_all(&source.read_all().view());
}

The deferred statement may be any statement but a declaration (var, const, a local type), and it may not leave the block it is deferred in: a return, or a break, continue or yield whose target lies outside it, is a compile-time error. Jumps that stay inside it, a defer within it, and a lambda's own return are allowed.

if as a Value

An if in value position needs both branches (§3.1). Bare-expression branches yield their value implicitly; block branches yield with yield, and every path through such a block must yield:

var grade = if (score > 90) &"high" else &"low";                 // &[u8]
var level = if (score > 90) { yield &"high"; } else { yield &"low"; };

Path Termination

A conservative flow analysis runs over every function body at compile time. A statement terminates when control cannot fall out of it: return, break, continue, yield, and panic terminate; a block terminates when any statement in it does; an if with an else terminates when both branches do; a match terminates when it is exhaustive — every variant of an enum subject has an arm, or an internal else arm exists — and every arm does; while (true) with no break reaching it never completes. Conditions are never assumed, and ordinary loops always count as skippable.

Loops (for and while)

A for subject is either natively for-compatible — the array forms ([T : N], &[T], *[T]) and range generators, which need no interface marker — or a custom iterable: a type declaring Iterable (a lang item, §6.1a), whose iterator function gives a cursor conforming to Iterator:

// std::iterable (section 6.1a)
exp interface Iterator<T> {
    fn next(self: &var) -> Option<&T>;
}
exp interface Iterable<T, It: Iterator<T>> {
    fn iterator(self: &) -> It;
}

// a conforming container binds 'It' to its own cursor type
type Container<T> : Iterable<T, ContainerCursor<T>> = ...;
type ContainerCursor<T> : Iterator<T> = ...;
fn iterator<T>(self c: &Container<T>) -> ContainerCursor<T> { ... }
fn next<T>(self it: &var ContainerCursor<T>) -> Option<&T> { ... }

Match

var x = match (subject) {
    Pattern1 |payload_capture| { yield 10; }
    Pattern2 { yield 20; }
} else {
    yield 30; // external else: the fallback value
};

var y = match (state) {   // bare-expression arms, each ended with ';'
    ::Idle 0;
    ::Busy |load| load;
    else -1;
};

5.4 Lambdas / Closures

|&var x, y| (param: T) -> R { body }
|=, &a| (param: T) -> R { body }
(param: T) -> R { body }
(param) => expression

5.5 Extension Functions

A function whose first parameter is prefixed with self is an extension function, called with dot notation:

fn add(self v: &Vec3, other: &Vec3) -> Vec3 { ... }   // v.add(&other)

5.6 Concurrency

Code runs in parallel through tasks, structured into scopes:

fn total(numbers: &[u64]) -> u64 {
    const middle = numbers.length() / 2;
    var left: u64 = 0;
    var right: u64 = 0;
    scope {
        spawn { left = sum(&numbers[..middle]); }
        spawn { right = sum(&numbers[middle..]); }
    }   // waits for both
    return left + right;
}

6. Standard Library & Primitives

6.1 Arrays & Built-in Methods

Every array form — [T : N], &[T], *[T] — is natively for-compatible (§5.3) and implements no interface. Nothing in the language implements an interface implicitly; every conformance is declared (type T : I = ..., §6.2), with the exceptions the compiler supplies for the lang items about representation (§6.1a): the numeric primitives conform to Number, whose functions their built-in operators stand for, the primitives to Key, Equal and Format, every enum and struct == compares to Equal (§4.10), every enum and struct whose parts are all keys to Key (§6.1a), the integer types and bool to AtomicValue, f32 and f64 to Float, and the C function types to CFunction. A named type does not inherit its underlying type's conformances either, though it inherits the functions (§5.5): it conforms only through its own markers, except that a named type over a C function type satisfies CFunction as the type it names does, and one over an enum or struct Equal and Key as that type does. So a bound like <C: Iterable<...>> accepts only declared conformers, never a bare array.

The compiler supplies .length() -> u64 on arrays directly, since every form already carries its size:

Array formWhere the length lives
[T : N] fixedKnown at compile time; .length() folds to the constant N.
&[T] sliceThe u64 half of the fat pointer.
*[T] heap arrayThe metadata prefix before the pointee (§5.2).

The name is reserved on arrays: an extension named length whose receiver is an array form is a redeclaration error. A custom type that wants a length supplies its own length extension; it is part of no interface contract. Reinterpretation and conversion are the as / to operators (§4.5), not methods.

6.1a Compiler-Recognized Declarations (Lang Items)

A few standard library declarations are recognized by canonical path to drive syntax sugar. There is no prelude: lang items are ordinary Alloy source shipped with the standard library, and nothing is in scope until imported. The compiler's lowering refers to the declaration directly, so an import is needed only to name the item in source.

Lang itemCanonical pathDeclarationCompiler hook
Option<T>std::option::Optionenum { Some: T, None }for over a custom iterable matches on next()'s Option<&T> (§5.3).
Iterablestd::iterable::Iterableinterface Iterable<T, It: Iterator<T>> { fn iterator(self: &) -> It; }Gates for over custom types (§5.3). Arrays need no marker (§6.1).
Iteratorstd::iterable::Iteratorinterface Iterator<T> { fn next(self: &var) -> Option<&T>; }The cursor contract behind for (§5.3).
Numberstd::number::Numberinterface Number { fn add(self: &, other: &Self) -> Self; ... fn compare(self: &, other: &Self) -> Ordering; }Satisfied by the numeric primitives with no marker — one of the three implicit conformances, with Key and Equal — and by any named type that declares it and cannot own heap memory (type Meters : Number = u32, type Fixed : Number = struct { raw: i64 }). Bounds generics, backs to (§4.5), and gives the arithmetic and ordering operators, in generic bodies too (§4.10, §6.2): a type over a numeric primitive has the built-in ones, any other takes them from the functions it defines. compare gives a std::number::Ordering (Less, Equal, Greater). A &Number object calls none of the functions, which name Self, and exists for downcasts (`n is u32&x`, §4.2).
argumentsstd::process::argumentsfn arguments() -> &[&[u8]]The compiler supplies the command line, first element the program's own path. Natively the entry wrapper captures argc/argv at startup; alloyc run serves the arguments after the program path. Not available at compile time (§7.2).
Equalstd::equal::Equalinterface Equal { fn equals(self: &, other: &Self) -> bool; }Gives == and != to a type declaring it, wherever its values are compared, as parts too (§4.10). Every primitive type satisfies it with no marker, through the extensions std::equal defines on each (fn equals(self value: &u32, other: &u32) -> bool), so a T: Equal takes numbers and bool; == on a primitive stays the built-in comparison. So does every enum and struct whose parts == all compares, its equals the structural comparison (std::equal's private compare_parts, which the compiler calls), unless it declares Equal and writes its own (§4.10); v.equals(&w) on such a type calls that comparison, an extension of the signature, which no call would reach, being an error (§6.2).
Keystd::hash::Keyinterface Key { fn hash(self: &) -> u64; fn same(self: &, other: &Self) -> bool; }What a hash map's keys satisfy: same is key equality, and keys that are the same must hash alike. Satisfied by every primitive type with no marker, through the extensions std::hash defines on each (fn hash(self value: &u64) -> u64; a float's 0.0 and -0.0 are the same key and a NaN is the same as nothing), by String over its contents, and by any type declaring it (type Point : Key = struct { ... }). A missing extension for a primitive is an error at the interface, as is a second one of the same signature (§6.2). So does every enum and struct whose parts all satisfy it, each field and payload a primitive or a named type over one, a type declaring Key, or another such enum or struct, so type Card = struct { suit: Suit, rank: u8 } is a map key as written: its hash combines its parts' hashes in turn, an enum's tag first, and its same asks each part's same, an enum's tags equal first (std::hash's private hash_parts and same_parts, which the compiler builds for the type). A part that is not a key — a function value, an interface object, an array, a reference or pointer, a type with no Key such as Vector<T> — leaves the type without it; a generic type satisfies it per instantiation, and a type declaring Key keeps its own functions. On such a type k.hash() and k.same(&other) call these functions, or those of the first level of its chain declaring Key, an extension of either signature, which no call would reach, being an error (§6.2).
Formatstd::format::Formatinterface Format { fn format(self: &, out: &var String); }How a value writes itself as text, which out.write(&value) and an interpolated string's holes (§2.6) call. Satisfied by every primitive type with no marker, through the extensions std::format defines on each: integers in decimal, bool as true / false, floats as the shortest decimal that reads back to the same value — plain from 0.000001 to below 1e21, a whole number ending in .0, otherwise 1.5e-7 or 1e+21, and nan, inf, -inf — by Ryu's method in integer arithmetic (std::float_digits), so compile-time code formats too. String writes its bytes, and Option<T> (Some(3), None) and Vector<T> ([1, 2, 3]) declare it when T does.
Disposablestd::dispose::Disposableinterface Disposable { fn dispose(self: &var); }Marks a type whose values the program must dispose or move away on every path, never copy, and hide in no owning object or closure (§5.2). The compiler only checks; it never calls dispose.
Sharedstd::sync::Sharedinterface Shared {}Marks a type that synchronizes its own changes (§5.6): fields of a value of the type may change through a & to it, and the race checks of a scope let every task use such a value. Atomic<T>, Mutex<T> and Channel<T> declare it.
AtomicValuestd::sync::AtomicValueinterface AtomicValue {}What Atomic<T> holds (T: AtomicValue, §5.6): satisfied with no marker by the integer types and bool, and by nothing else, so Atomic<f64> or Atomic<String> is a compile-time error where it is formed.
Floatstd::math::Floatinterface Float { fn float_sqrt(self: &) -> Self; ... }What std::math's functions take (fn sqrt<T: Float>(x: T) -> T): satisfied with no marker by f32 and f64 alone, through std::math's float_* extensions on each, which compile the exact operations (sqrt, floor, ceil, round, trunc, abs, copysign, fma) to single instructions where the target has them and call musl's functions for the rest (sin, exponential, pow, ..., min, max), built from musl's pinned source for every target and linked into every program. So sqrt(2.0) is an f32 like any untyped float and const r: f64 = sqrt(2.0) an f64, and sqrt(3) is a compile-time error. The interpreter calls the same functions, so every target, native or alloyc run, agrees bit for bit on every result but a new NaN's sign and payload, which are the processor's (§4.1), and compile-time code may call them (§7.2).
CFunctionstd::ffi::CFunctioninterface CFunction {}What Library::symbol<F> reads a symbol as (F: CFunction, §6.3): satisfied with no marker by every C function type extern (T) -> R and every named type over one (type OutFunction = extern (c_pointer) -> i32;), since what it asks is the type's representation, and by nothing else.
standard_streamstd::io::standard_streamfn standard_stream(index: u32) -> i64The compiler supplies the C stream for standard input (0), output (1) or error (2) on each target, so std::io names no C runtime; alloyc run serves the host's. std::io reaches the console through it, and code calling C's file functions through its own externs can too. Not available at compile time (§7.2).
accessorsstd::vector::get, get_var, last, replace, remove, swap_remove; std::map::get, get_var; std::string::get; std::json::get, atEvery overload of these plain-name lookups, which fault on a bad argument where their try_* companions give an OptionA fault inside one of them in a checked build (alloyc run, alloyc test, a native build without --release) is reported at the site calling it, as a failure inside std::testing is reported at the test's call (§6.5), not at the line inside std: v.get(3) on three elements points at the program's line. The site is the outermost such call, so Map::get reaching Vector::get reports the program's call; code outside std that one of them calls, such as a key's hash, reports its own sites. Release builds are unchanged.
import std::option;

var maybe: Option<u32> = Option::Some(42);
match (maybe) {
    Option::Some |v| { /* v : u32 */ }
    Option::None    { /* empty */ }
}

A user definition colliding with an imported lang-item name follows the normal redeclaration rules (§6.4); lang items get no naming privileges.

6.2 Standard & User-Defined Interfaces

An interface is a named block of function signatures and required constants (below). Every interface function declares its receiver indirection — self: & or self: &var (§5.5) — as its first parameter, with no name and no type: the type is whatever concrete type implements the interface. Later parameters are ordinary. A named type links itself to interfaces in its declaration:

interface Serializable {
    fn serialize(self: &, format: u32) -> bool;
}

type Packet : Serializable + Iterable<u64, PacketCursor> = struct {
    id: u32,
    payload: *[u8],
};

Inside an interface's function signatures, Self names the implementing type: fn add(self: &, other: &Self) -> Self; is satisfied by fn add(self a: &Fixed, b: &Fixed) -> Fixed for a type Fixed : I, and through a constraint T: I it reads as T. An interface object's concrete type is unknown, so a function naming Self cannot be called through one; Self is not a type anywhere else, nor in a required constant.

The standard interfaces are lang items (§6.1a) written in ordinary library source:

NameSatisfied by
Numberu8 u16 u32 u64 i8 i16 i32 i64 f32 f64, and named types declaring it that cannot own heap memory
Keyevery primitive type, String, every enum and struct whose parts are all keys, and types declaring it
Equalevery primitive type, String, Vector<T>, every enum and struct == compares, and types declaring it
IterableTypes declaring the conformance and providing iterator() (§5.3). Never arrays (§6.1).
IteratorCursor types declaring the conformance and providing next(self: &var) -> Option<&T> (§5.3).

Conditional markers. A generic type may declare a marker that holds only for some instantiations: type Vector<T> : Disposable if (T: Disposable) = ... conforms to Disposable exactly when its argument for T does (its own marker, a constraint, or Number for a numeric primitive). The condition, in parentheses, is made of tests T: I on the type's own parameters (T: I + J asking for both), joined by && and || and grouped by parentheses; ! is an error, since a marker holding for a type parameter that fails a test would stop holding once the parameter is bound to a type passing it. Verification assumes the condition, and everything else — constraints, objects, X: I (§4.4) — sees the marker only on the instantiations meeting it. Under a condition joined by &&, the implementing functions may be constrained the same way; under one with ||, they constrain nothing and decide per part:

exp type Result<T, E> : Format if (T: Format && E: Format) + Disposable if (T: Disposable || E: Disposable) = enum { Ok: T, Err: E };

exp fn format<T: Format, E: Format>(self result: &Result<T, E>, out: &var String) { ... }

exp fn dispose<T, E>(self result: &var Result<T, E>) {
    if (result is ::Ok |&var value|) {
        if (T: Disposable) { value.dispose(); }
    } else if (result is ::Err |&var error|) {
        if (E: Disposable) { error.dispose(); }
    }
}

The Two Roles of an Interface

  1. Dynamic dispatch. An interface used as a type, always behind an indirection, is an interface object (§4.2). Any concrete type implementing it converts implicitly, and a call through the object (handle.do_something() where handle: &Shape) resolves at runtime through the carried type identity, matched against the closed world of implementers (§6.4).
  2. Generic constraint. An interface used as a bound (fn do<T: I>(...), or <T: I + J> for several) limits the generic to types implementing I, and calls resolve statically at each instantiation with no runtime dispatch. Inside the body a T value exposes the constraint's functions by dot notation, as candidates beside every other visible function of the name (§4.6), and so does an interface object; a T: Number value also supports the arithmetic and comparison operators (§4.10).

Generic Interfaces

An interface may declare type parameters (interface Iterator<T> { fn next(self: &var) -> Option<&T>; }), which scope over every signature in it. A parameter may be constrained, and a constraint's arguments may mention parameters declared to its left (interface Iterable<T, It: Iterator<T>>, §4.7).

A conformance marker supplies all of a generic interface's arguments (type Vector<T> : Iterable<T, VectorCursor<T>>), and those arguments may mention the conforming type's own parameters. Verification substitutes them into the declared signatures, so the satisfying extension must match the instantiated signature, and each argument must satisfy the interface's own constraints there.

A generic interface object needs full instantiation. It forms only with every parameter bound to a concrete type (&Iterator<u64>), which pins each signature so one call site has a fixed ABI while the implementer stays unknown until runtime. There is no partial erasure: a bare &Iterator is a compile-time error, and &Iterable<u64> with It erased cannot be written at all by the arity rule — an erased implementer-chosen type would give each implementer a differently sized result, which the call site cannot receive without an implicit allocation (banned, §5.2). Dispatch identity is per instantiation: a generic implementer conforms once per binding of its own parameters, so VectorCursor<u64> and VectorCursor<u8> carry distinct identities, derived by unifying the marker against the object's arguments. Hence no downcasting: is and match on a generic interface object are compile-time errors, because runtime identity picks dispatch targets but is not a nameable type test. Inside a generic body a constrained value still resolves statically (role 2); interface objects are only for call sites where the concrete type is genuinely unknown.

Default Implementations

An extension function whose self receiver is an interface is that interface function's default implementation:

interface Shape {
    fn area(self: &) -> f32;
    fn name(self: &) -> &[u8];
}

// default implementation of Shape::name, shared by every implementer
fn name(self s: &Shape) -> &[u8] { return &"shape"; }
// library a
exp interface Widget { fn role(self: &) -> &[u8]; }
exp fn role(self w: &Widget) -> &[u8] => &"generic";   // default

// library b, importing a
exp type Select : Widget = struct { options: u32 };
pub fn role(self s: &Select) -> &[u8] => &"combo box"; // seen only inside b
exp fn role(self s: &Select, option: u32) -> &[u8] => &"option";

// library c, importing a and b
fn describe(s: &Select) -> &[u8] => &s.role();          // "combo box", as through '&Widget'
fn first(s: &Select) -> &[u8] => &s.role(0);            // b's exported overload

Required Constants

An interface may require a constant of each implementer, written const NAME: T; among its functions. It is the compile-time counterpart of a function that takes no input and returns a fixed value, such as a name or an identifier. An implementer supplies it as a type-scoped constant (§6.4), and the interface may give a default that implementers without one take:

interface Shape {
    const NAME: [u8];
    const SIDES: u32 = 0;
    fn area(self: &) -> f32;
}

type Square : Shape = struct { side: f32 };
const Square::NAME = "square";
const Square::SIDES = 4;

Verification

When a type T carries markers (type T : I1 + I2 = ...), the compiler checks the merged compilation unit (§6.4). For every required constant, a type-scoped constant T::NAME must exist in the merged unit, its own or inherited down its chain, or the interface must give a default, and its value must convert to the required type; visibility does not matter, as for functions. For every function in each interface:

  1. A satisfying extension function (§5.5) must exist in the merged unit: one belonging to T, one T inherits down its chain (with type A : I = struct {...}, type B = A has A's functions but satisfies nothing, while type C : I = A satisfies I through them, each taking and giving C where it takes and gives A, so type Id : Equal = u32; satisfies Equal through u32's fn equals(self value: &u32, other: &u32) -> bool), or a default implementation, tried in that order: C's own function beats A's, and A's beats I's default. Visibility does not matter — satisfaction is closed-world, so a library-internal extension counts like an exported one, and calls on a value of T naming the function reach it (Default Implementations, above). There must be exactly one at the level found: two extensions satisfying one function for one type, with the same signature in two modules, are an error at the marker naming each and where it is, whichever module declares the type, so what a conformance holds never depends on the order modules load (a primitive's lang item, which has no marker, reports it at the interface).
  2. It must match the name, the parameter sequence, and the return type, with a generic interface's marker arguments substituted in first and the candidate's own type parameters bound through its receiver (fn next<E>(self c: &var Cursor<E>) checks against Cursor<T> with E = T). Parameters after self line up positionally.
  3. The receiver indirection is fixed by the interface, not the implementer: fn next(self: &var) is satisfied by fn next(self c: &var Cursor<T>), never by fn next(self c: &Cursor<T>). Because every implementer agrees on it, an interface object's call sites have one ABI, and the object's own indirection must be at least as permissive as the function's receiver — calling a self: &var function through a &I object is a compile-time error.
  4. With neither a type-specific extension nor a default, verification fails.

6.3 Extern FFI

External C functions are declared with fixed, concrete signatures. The return arrow is optional; leaving it out declares a C void function. extern is for porting C libraries — ordinary programs use native Alloy modules that wrap those declarations.

extern functionName(param: Type) -> ReturnType;
extern variadicFunc(...) -> &var u8;
extern releaseBuffer(buffer: &var u8);         // C void

6.4 Module System

Import Namespaces

Libraries (.alloylib)

A package is shared as one text file, packed by alloyc lib:

alloylib 1
package acme::geometry 1.0.0
language 2026-10-11
requires acme::units 2.1.0

exports 2
geometry: fn walk(kilometers: f64) -> f64
shapes: fn unit_square() -> Square

module geometry 822
<822 bytes of source>
module shapes 230
<230 bytes of source>
file geometry/banner.txt 12
<12 bytes>

The Package Registry

A registry hands out packages and keeps every published version; a program's committed pkg/ folder stays the only record of which ones it uses, so a build never needs the network.

$ alloyc get acme::geometry         # the newest acme::geometry, and what it requires
added pkg/acme/geometry-1.4.2.alloylib
added pkg/acme/units-2.3.0.alloylib (required by acme::geometry)
$ alloyc get                        # what main.alloy imports and pkg/ lacks
added pkg/acme/colors-1.0.3.alloylib
$ alloyc update                     # each package to its newest release of the same major version
$ alloyc update acme::units --major # to the newest release of any major version
$ alloyc search shapes
$ alloyc publish geometry.alloy --scope acme --version 1.5.0 --license MIT
$ alloyc yank acme::[email protected]  # '--undo' restores it

6.5 Command Line


7. Compile-Time Evaluation & Macros

7.1 Compile-Time Contexts

Some positions need their value while the program is compiled. Each is a compile-time context: its expression, written in the ordinary language with no marker, runs in the compiler's interpreter. Ordinary functions are called there like anywhere else and run in the interpreter. An expression that cannot be evaluated at compile time — it reads runtime state, calls an extern, faults — or that does not produce what the position needs is a compile-time error. The contexts are:

Everything else runs at runtime: an if whose condition is a constant is an ordinary if, and a local const is a runtime binding. A body obtains a compile-time value through a constant, a macro call, or reflection on a type.

A compile-time context is replaced by its result: a literal (§5.2) or a type. Like any literal, the result's data lives in static program memory: used bare it is copied into its target, and &NAME or &#label("x") references the static data. Values come out of a block through yield (§5.3), or implicitly from a bare-expression if (§3.1):

const LIMIT = if (DEVELOPMENT) 50 else 100;

Visible names. A compile-time context may use literals, any function in the program (including ones defined later in the file), visible top-level const definitions, and enclosing const locals whose initializers are themselves compile-time evaluable — transitively, so a const built from literals, other compile-time constants, and calls over them counts. Inside a lambda such a const of the enclosing body is visible without being captured, like a type name (§5.4). Runtime state is invisible: referencing a var binding, a parameter, or a const that depends on runtime state is a compile-time error. Inside a generic function the type parameters are visible as type values (§4.4); an expression naming one is evaluated per instantiation, when the parameter is bound, rather than once while checking, and every instantiation must succeed, including one reached only from a function main never calls. The same holds for a generic type definition, a local alias, or an array length naming a parameter: a computation failing for one instantiation is a compile-time error at the use that instantiates it (the call leading to a generic function's instance), with a note where the computation failed. A generic type definition whose computation uses its parameters only as types (type Known<T> = if (BIG) struct { v: T } else u8;) is computed once, before any instantiation, as an ordinary generic type. A generic body using a type of its own parameters that is computed per instantiation is checked once as far as that type is known, and the rest per instantiation, never less: its members are read, written and initialized by name (p.v on a Pick<T>), its variants built, tested with is and matched by name (Opt<T>::Some(move x), ::None), a match used as a value without an else arm having to cover every variant of each instance (a statement match may cover any subset, as for any enum), and conversions to and from it (anonymous struct layouts included), between arrays whose lengths are computed ([u8 : V::SIZE] to [u8 : T::SIZE], or from [u8 : 3]), of literals into it (integers and floats, alone or in array literals and fills, untyped arithmetic folded first), and to from or into it (w to u64 on a W<T>) hold or not for each instantiation, a failure being an error at the call leading to that instance. A condition converts such a value to bool per instantiation. What is already wrong is an error in the body: array elements that differ, a member initialized twice, a move through an immutable reference, a bare read where the target may own heap memory, and an operator (logical ones included), as, indexing, subslicing, a type test (is Sq), a literal pattern, for, a call on a value whose type is not known yet or a call picking among overloads by it, which a conversion to a known type allows (const w: u8 = p.w;). A generic type's constant naming a parameter in its value or its type (const Box::N: u64 = T.size() * 2;, const Opt::EMPTY: Opt<T> = ::None;) is computed the same way, for the arguments each read names, and read as that instance's type (Opt<u8>::EMPTY is an Opt<u8>). Types may nest at most 200 levels deep (in type arguments, elements and members): a type whose instantiation needs a deeper one without end is a compile-time error, not an endless compilation, and so is compile-time code that needs its own result for the same instantiation.

Untyped arithmetic. Untyped integer literals and the operations over them are evaluated as i64, untyped floats as f64; a result outside i64 is an overflow, and the result is again an untyped literal, which takes its type where it is used (§4.3).

A fault during compile-time evaluation — integer overflow, division by zero, an exhausted evaluation budget, a panic (§5.3), heap memory still allocated when the evaluation ends — is a compile-time error.

7.2 The Pointer Barrier & Sandboxing

Compile-time code runs under strict limits, so host memory and host capabilities cannot leak into the generated binary:

7.3 Macros

Macros are compile-time functions for reflection, source introspection, and type generation.

macro readTypeFromJson(path: [u8]) -> type {
    // introspection and type mutation using compile-time features
}
const DEVELOPMENT = true;
type T = #readTypeFromJson("types/T.json");
type P = if (DEVELOPMENT) struct { id: u32 } else #readTypeFromJson("types/P.json");

7.4 Built-in Macros

The compiler provides a few built-in macros, declared but not implemented in std::macros (§7.3), so they are discoverable like any other definition — exp macro type_of(value) -> type; and so on, with the declared result types below. Using one needs import std::macros;, and like all macros they are called with #.

MacroSignatureSemantics
type_of(value) -> typeThe type of the argument expression (§4.4), which is not evaluated, so it may name a runtime local of the enclosing body.
struct_type() -> typeA fresh, empty struct type to build on.
enum_type() -> typeA fresh, empty enum type.
implementers_of(target) -> [type]Every type in the merged unit implementing the interface target.
name_of(value) -> [u8]The variant name of an enum value, as a string.
read_file(path: [u8]) -> [u8]The bytes of a project file, read at compile time as static data. The path resolves against the entry module's directory and may not escape it (§7.2); a missing, absolute, or escaping path is a compile-time error. Distinct from std::io's runtime read_file — #read_file always picks the macro.

A type is also reflected directly, by its name (u32.size(), Packet.member_names()) — see §4.4.

implementers_of is whole-world (§6.4): because every module merges before checking, the result covers the whole program regardless of declaration order or library visibility, so a library-internal type implementing an exported interface is in it. Elements arrive in module order, then declaration order, so results are deterministic. Generic types are excluded — they reflect only as instances (§4.4). The array is a compile-time value, so use it inside a larger compile-time expression (#implementers_of(Shape).length(), #implementers_of(Shape)[0].name()); a type cannot be kept into runtime (§7.2). Types synthesised by comptime (type T : I = #m(...)) are listed like any declaration, but their members are only complete once their own # initialiser has run (§7.3).


End of specification.