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
- A Complete Program
- Lexical Grammar
- Syntactic Grammar
- Type System & Static Semantics
- Execution Semantics
- Standard Library & Primitives
- 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:
| Category | Symbols |
|---|---|
| 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
\n(line feed),\r(carriage return),\t(tab),\0(null byte)\\(backslash),\"(double quote),\'(single quote)\xHH(one byte, hex)\u{HHHH}(Unicode scalar value)
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:
var x = "abc"copies the bytes intox, a stack[u8 : 3].&"abc"is a reference to the static bytes, valid for the whole program run, converting to&[u8]where one is required (§4.3).&var "abc"is a compile-time error: static data is constant.new "abc"copies the bytes into a fresh heap array, type*[u8].
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:
decimals: a float written with exactly that many digits after the point, rounded half to even on its exact value ({2.5:.0}is2,{0.125:.2}is0.12). On any other type it is a compile-time error.radix: an integer in hexadecimal (x,Xfor upper-case digits), binary (b) or octal (o), a negative one as its two's complement at its own width ({-1 to i8:x}isff). On any other type it is a compile-time error.width: the piece is padded to at least that many characters (UTF-8 code points) with thefillbyte, a space unless given, placed asalignsays:<after the piece,>before it,^split around it with the extra one after. A number aligns right and anything else left unlessalignsays otherwise.0before the width pads a number with zeros after its sign ({-42:06}is-00042); the fill and alignment are then ignored. On any other value0is part of nothing and the width alone applies.
An unknown spec is a compile-time error.
Character Literal Typing
A character literal's type is the unsigned integer that fits its bytes:
- Single quotes hold one character, or a run of characters up to 8 bytes.
- A 1-byte ASCII character (
'a') is au8. - An 8-byte packed sequence (
'abcdefgh') is au64. - A multi-byte Unicode character takes the smallest unsigned integer wide enough to hold its bytes (usually
u32). - Bytes are packed first byte least significant:
'ab'is0x6261. On a little-endian target the integer's bytes in memory are then the literal's bytes in order, so'abcd'equals four bytes read from memory as au32(§4.5).
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:
- Bare expressions —
if (c) a else byields the chosen branch's value implicitly. Noyield, and this form is valid in value position only. - Blocks —
if (c) { yield a; } else { yield b; }yields throughyield(§5.3).
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:
- A
<after a name opens a generic argument list when the tokens up to the matching>read as a comma-separated list of types and that>is immediately followed by(,{, or::. Sof<a, b>(c)is a generic call,Vector<u8> { … }a generic struct literal, andVector<u8>::empty()a call to a type-scoped function ofVector<u8>. It also opens one when that>is followed by., by a conformance test's:(§4.4), or by a token that cannot begin an operand —),],},,,;, orelse— since no comparison could end there: the name and its arguments are then a generic type written as a value (§4.4), as inVector<u8>.size(),Vector<u8>: Formatorif (c) Vector<u8> else u8. Anywhere else<is the less-than operator: inf(a < b, c > d)the>is followed byd, so both are comparisons. Where the two readings are both possible the generic one wins, and a comparison written that way needs parentheses:a < b > (c)is the generic calla<b>(c), and the comparison is(a < b) > (c). - After
as,to, oris, the right operand is a type, and a<after its name opens a generic argument list when the tokens up to the matching>read as a comma-separated list of types; nothing need follow that>. Otherwise the type ends at its name and the<is the less-than operator:x as u32 < ycompares the cast withy. Where both readings are possible the generic one wins, and the comparison is written(x as T) < y. - A generic argument or parameter list that expects its closing
>where the next token is>>,>=, or>>=takes one>off the front of that token and leaves the rest as the next token. SoVector<Option<T>>closes both lists,var x: A<B>= yreads asA<B>then=, andvar x: A<B<C>>= yreads asA<B<C>>then=. The lookahead scans above see the tokens split the same way. - A
(in value position starts a lambda without captures (§5.4) when the next token is), or the next two are an identifier and:, or the tokens up to the matching)are identifiers separated by commas and=>,->or{follows it; otherwise it starts a parenthesised expression.()is never an expression on its own. - A
{in statement position starts an anonymous struct literal when the next token is., and a block otherwise — one token of lookahead, since every member initializer begins with.({ .x = 1 };is a literal,{ x = 1; }a block). So{}in statement position is an empty block. The same lookahead settles anifbranch and amatcharm, where a block is also possible:{there starts a block unless the next token is.. Everywhere else in value position{starts a struct literal, and{}there is the empty one, every member taking its default (§4.2).
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:
|x|— a copy of the value; valid only when the value owns no heap (§5.2)|copy x|— a deep copy of a value that owns heap|&x|— an immutable reference to the value in place|&var x|— a mutable reference; the subject must be mutable|move x|— an owning capture: it moves the value intoxexactly likemove(§5.2) — a pointer transfers, a value moves its owning members out and copies the rest, a reference does that to its pointee — leaving the source (the enum subject of anistest ormatch, the element of aforsubject, or the captured variable of a lambda) moved-from with its pointers nulled. When the value owns anything the subject must be mutable; a value that owns nothing is simply copied.
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.
| Precedence | Operators |
|---|---|
| 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
| Name | Width | Signed | Float |
|---|---|---|---|
u8 | 1 byte | No | No |
u16 | 2 bytes | No | No |
u32 | 4 bytes | No | No |
u64 | 8 bytes | No | No |
i8 | 1 byte | Yes | No |
i16 | 2 bytes | Yes | No |
i32 | 4 bytes | Yes | No |
i64 | 8 bytes | Yes | No |
f32 | 4 bytes | — | Yes |
f64 | 8 bytes | — | Yes |
bool | 1 byte | No | No |
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
| Syntax | Kind | Notes |
|---|---|---|
struct { f: T, ... } | Struct | Members in declaration order |
enum { A, B: T, ... } | Enum (sum type) | Variants, each with an optional payload |
enum : u32 { A = 19, ... } | Enum with chosen tags | Payload-less variants laid out as the integer named, each with its tag |
[T : N] (N ≥ 0) | Fixed array | Compile-time size; stack or inline |
&[T] | Slice | Non-owning view: raw pointer + u64 length |
*[T] | Heap array | Owned heap block, length fixed at allocation |
(T1, T2) -> R | Function type | First-class function value capturing nothing; |=| and |&| bounds (§5.4) |
type X = BaseType | Named type | Distinct by name; assignable down its own chain (§4.3 rule 4) |
*T / *var T | Pointer | Owned heap instance, immutable / mutable |
&T / &var T | Reference | Non-owning borrow, immutable / mutable — made by &x / &var x (§5.2) |
&I / *I (I an interface) | Interface object | Data 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.
| Formed | Is | Like |
|---|---|---|
&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 X | the same, mutably |
*T or *var T, T = *X or *var X | T itself | the 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:
- The type after the
:is an integer primitive,u8tou64ori8toi64; a named type,boolor a float is a compile-time error. - Either every variant writes a tag or none does: an enum naming its integer needs a tag on each variant, and a tag on a variant of an enum naming none is an error. Each tag is a compile-time context (§7.1), as an array length is: an integer literal in any radix with an optional
-, a constant, arithmetic over them, a character literal (Byte = 'y', §2.6), another enum's tag (Next = (Op::Load to u16) + 1), a call compile-time code may make. It is evaluated as a value of the enum's integer when the enum is declared, before bodies are checked, so it must fit it and be of a type converting to it implicitly (§4.3; au32constant in anenum : u16takesto), and the tags of one enum are distinct; each error points at the tag. A tag may not depend on the enum it belongs to. - The variants carry no payload, and there is at least one.
- The enum is laid out as its integer (§4.9), so
Op.size()is 4, it crosses the C boundary as that integer (§6.3), and it sits in a struct C takes by value. x to u64gives the tag, converted as from the enum's integer (§4.5), andn to Opthe variant whose tag isn, a runtime fault in checked builds when none has it.Op::from(n)takes a value of the enum's integer and gives anOption<Op>:::Someof the variant with that tag,::Nonewhen there is none.fromis built in, there for every enum with chosen tags and no other.- Everything else is as for any enum: variants are named
Op::TypeVoidor::TypeVoid,matchmust cover every variant when used as a value (§5.3),==compares variants, constant arrays of them are static data (§3.1), and the enum satisfies no interface implicitly butEqualandKey, as every enum==compares and every enum of keys does (§4.10, §6.1a), so a formatted value declaresFormatas any enum would, its functions readingx to u32.
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:
- A contextual type — a declared variable type, an expected payload or return type, a
matchorissubject — 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::Xtakes part in overload selection like any argument (§4.6). - 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
- Identity — identical types are compatible.
- 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 becomesi32. An array literal of untyped elements takes a contextual element type (var a: [u8 : 3] = [1, 2, 3]). - Untyped float literal — compatible with
f32andf64;f32with no context, andf64as 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 invar 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. - 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;andtype Distance = Meters;, aDistanceis compatible withMetersand withf32. The reverse never holds: nothing converts implicitly up a chain, so anf32is not aMeters, 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, isx as T(§4.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 needsto). Crossing classes needsx to T(§4.5). - 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. - 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. - Dropping mutability —
&var Tis compatible with&T,&var [T]with&[T], and*var Twith*T. Nothing gains mutability implicitly, with one exception: a pointer a call returns has novarorconstof its own, somove make()(§5.2) takes the mutability its target asks for, asnewdoes. - 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 itsNelements. This is how&"abc"and&[a, b, c]meet a&[u8]/&[T]parameter. - Interface objects —
&C,&var C,*C, and*var Care compatible with the same indirection of an interfaceIwhen the concrete typeCdeclaresIas a marker, whenCis a numeric primitive andIisNumber, or whenCis a type parameter constrained byI(§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:
- A type written as an expression, as above.
- Built-in macros —
#type_of(expr),#struct_type(),#enum_type(), and#implementers_of(I), specified in §7.4. void— "no payload". Passed as the member type toadd_memberon an enum it makes a payload-less variant, and reflected enums report theirs the same way.voidis not a value type: written anywhere but compile-time code it is an error.
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.
| Method | Signature | Semantics |
|---|---|---|
is_struct | () -> bool | True iff the type is a struct. |
is_enum | () -> bool | True iff the type is an enum. |
is_primitive | () -> bool | True 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 | () -> bool | True iff the type is an interface. |
name | () -> [u8] | The type's declared name. |
equals | (other: type) -> bool | True 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 | () -> u64 | The 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 | () -> u64 | The 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.
| Operator | Name | Semantics |
|---|---|---|
x as T | Reinterpretation cast | Views the memory of x as a T without changing it. No runtime cost. |
x to T | Conversion cast | Converts the value to a T, producing a new value. |
asis a view: it never copies or allocates. On a place (a variable, field, element or pointee),x as Tis itself a place of typeTover the same memory, and §5.2 applies to it like to any place: read where a value is needed (word as f32), written through ((p as Flipped).b = 9writesp), and an implicit copy of a heap owner is the usual error, so a heap owner is moved or copied through the view (move v as ByteVec,copy v as ByteVec;moveandcopybind tighter thanas). On a temporary (Vector<u8>::empty() as ByteVec) it views the fresh value, which flows on unchanged.x as &Tandx as &var Tborrowxas&xand&var xwould, then view it as aT: the target picks the borrow like an expected type (§5.2). A reference (&S) views its pointee the same way, and&x as &Tis the same asx as &T. The right operand is never a pointer:x as *Tis a compile-time error, sinceasdoes not allocate, and a copy goes to the heap withnew (x as T).asneeds both types to have the same byte width, by the §4.9 layout rules for the build target; for a borrow or a reference the width rule applies to the pointees. In a generic body the rule is checked per instantiation, as a compile-time error at the call that forms it. A view involving an address's width (&Tasu64) therefore compiles for some targets only;std::ffi::c_pointeris an integer of the target's address width for that reason (§6.3).ason a slice (&[S] as &[T]) views the same elements' bytes asTs, again with no copy. A slice's length is a runtime value, so the width rule becomes a runtime one: the view's byte length (length * S.size()) must be a multiple ofT.size(), and its data must be aligned forT— breaking either is a runtime fault in checked builds. The result hasbyte length / T.size()elements and aliases the source, so a write through either view is visible through the other. A zero-sizedTis a compile-time error. A slice has no width of its own, so anaswhose target is unsized takes a slice:&"/length" as &[u8],&[T : N] as &[T]and their&varforms are compile-time errors, the error naming the way, which is the implicit conversion of a reference to an array into a slice where one is expected (const a: &[u8] = &"/length";, §4.3 rule 9); in a generic body this is checked per instantiation. This is how raw storage becomes typed:bytes[offset..offset + #T.size()] as &var [T](§4.4) carves oneTout of a byte page.asapplies to values that own heap memory as well: like every reinterpretation it is unchecked, and ownership follows the use-site form, so a view never leaves two owners.asneither forms nor opens interface objects: anaswhose source or target is an object, or a reference or pointer to an interface, is a compile-time error. A value becomes an object by implicit conversion (§4.3 rule 10), and onlyisandmatchreach an object's concrete type (§4.2).asnever gains mutability:x as &var Tneeds a place&var xcould borrow, and&S as &var Tand&[S] as &var [T]are compile-time errors, while a&varsource may cast to either form.tois defined forNumbertypes (§6.2) and keeps the value's meaning in the new format. A value the target cannot represent — a negative into an unsigned, a magnitude past the target's range — is a runtime fault in checked builds. Converting a float to an integer drops the fractional part (rounds toward zero), and the whole part must fit; converting into a float rounds to the nearest representable value. An untyped operand whose value is known — a literal, a constant, or the negation or float arithmetic of them — takes the target type directly when it fits: an integer value in an integer type that holds it or in a float type, a float value in a float type it stays finite in. So0.1 to f64is thef64nearest 0.1, rounded once, and5000000000 to i64compiles. Otherwise the operand first takes its default type (§4.3) and converts from there (2.5 to i32is2,300 to u8faults).toon an enum value gives its integer representation: the variant's tag, its zero-based declaration index (§4.9), or its chosen tag for an enum naming its integer (§4.2), which converts from that integer, a negative tag of a signed one staying negative. The target must be an integer type, the usual range rule applies, and the payload of a carrying variant plays no part. The operand reads through pointee transparency like any use, so a&Econverts its pointee's tag. The reverse, integerto E, builds the variant whose tag equals the value: a value outside the enum's variants, no chosen tag of an enum with chosen tags, or naming a payload-carrying variant —tocannot invent the payload — is a runtime fault in checked builds;E::from(n)asks without faulting (§4.2). The payload area is zeroed either way, so a release-mode conversion still drops safely.is(§4.2) is in the same grammar family but is a runtime test, giving abooland an optional capture.
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.
- One viable candidate: it is called.
- Several: the one matching every argument type identically, with no coercion, wins. When more than one matches identically, a non-generic candidate beats a generic one, so
fn len(self v: &Vector<u8>)specializesfn len<T>(self v: &Vector<T>)for aVector<u8>receiver; it must return the type the generic one returns there. Any other tie, or no identical match, makes the call ambiguous, a compile-time error. - Inside a generic body a call is checked once against the generic candidates, and the specialization, if any, is picked when the body is instantiated (§4.7). The specializations it can pick are those visible where the generic body is written, so a body behaves the same whoever instantiates it: a
fn len(self v: &Vector<u8>)in a user's module specializes that module's own calls, never the calls insidestd's generic bodies. - None: a compile-time error listing the candidates.
4.7 Generic Type Parameter Inference
A generic function's type parameters bind at each call site:
- Explicit arguments (
make<u64>(7)) bind left to right, and may stop short: the parameters after them are inferred. Withfn convert<T, U>(value: U) -> T,convert<u64>(x)bindsTand infersUfromx. 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. - The rest are inferred by unification: each declared parameter type is matched against the argument's type, the
selfreceiver included, and every unbound parameter binds to the type in its position. Withfn push<T>(self v: &var Vector<T>, item: T),vector.push(x)bindsTfrom the receiver and checksxagainst it, soxmay 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)andsame(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)withnumbers: [u64 : 4]passes a&u64); alone, it binds its default type (identity(5)bindsi32). An argument that takes its type from context, such as::None, is checked after the others. A parameter never binds an unsized type:&Tdoes not match&[u8], and a function over slices takes&[T]. - 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. - A parameter that appears only in another parameter's constraint binds through that constraint: once
Cis bound,C: Iterable<T, It>unifies with the conformance the bound type declares, sofn total<T, It: Iterator<T>, C: Iterable<T, It>>(items: &C)called astotal(&v)withv: Vector<u32>bindsT = u32andIt = VectorCursor<u32>fromVector's marker. The marker outranks the expected type: withfn first<T, It: Iterator<T>, C: Iterable<T, It>>(items: &C) -> T,const wide: u64 = first(&v)bindsT = u32, and theu32result then widens tou64. 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. - A parameter still unbound is a compile-time error, and so are conflicting bindings (
Tunified with bothu32andf32). 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:
constdeclares an immutable binding,vara mutable one.- Parameters are immutable. A function changes caller state only through
&var/*varindirections passed to it. - Assignment, compound included, needs a mutable target: a
varlocal, or a location reached through a&var/*var. On a reference or pointer binding the right-hand side's form (§5.2) says which: a value writes through to the pointee, so it needs a&var/*varbinding whatever the binding's own mutability; a new indirection (&y,&var y,new y,move p,move make()) re-points the binding itself, so it needs avarbinding. - An owning capture is mutable:
|move x|in anistest, amatcharm or aforbinds a value it owns like avar(while (files.pop() is ::Some |move f|) { f.dispose(); }); in a lambda's capture list it stays immutable, since the closure may run again. &var x, and|&var x|/|move x|captures, needxto be mutable. A plain&xborrow is always immutable, whatever the binding (§5.2). Two exceptions:movemay clear a by-value parameter or a lambda's owning capture (|move x|), or a field or element held in place inside one, although both are immutable, because each owns its value (§5.2); and a|&var x|capture of a payload that is itself a&var Tborrows its pointee through that reference, whatever the subject (if (pick(&var big) is ::Some |&var r|)), since writing through it changes nothing the subject owns, while a&Tpayload never gives|&var x|.- Mutability travels with pointee transparency (§5.2): a field reached through a
&var Tis mutable even when the reference binding isconst, and through a&Tit is immutable even on avarbinding. Direct fields and elements take the binding's mutability.
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.
| Operators | Operand types | Result |
|---|---|---|
+ - * / % | numeric | the operand type |
+% -% *% | integer | the operand type |
unary - | signed integer or float (never unsigned) | the operand type |
& | ^ | integer | the operand type |
<< >> | integer (left), any integer type (right) | the left type |
unary ~ | integer | the operand type |
&& || | bool | bool |
unary ! | bool | bool |
== != | numeric, bool, enum, struct, array (any form) | bool |
< <= > >= | numeric | bool |
- Unary
-on an unsigned integer is a compile-time error. Inside a generic body it is allowed on aT: Numbervalue, and an instantiation bindingTto an unsigned type is a compile-time error at the call that instantiates the body, as for literals (§4.3). - One operand type. Apart from the shift amount, a binary operator's two operands must have a single type once §4.3 applies: untyped literals take the other operand's type, and numeric widening meets in the wider type (
i32withi64isi64). Mixing signed and unsigned, or integers and floats, needsto(§4.5). A named type takes the operators of its underlying chain and keeps its own name in the result. - Arithmetic. Integer
/truncates toward zero, and integer%takes the sign of the dividend, as in C. Float%is the Cfmodremainder. Overflow and division by zero follow §5.2.>>on a signed integer is arithmetic. A shift by the left operand's bit width or more is a runtime fault in checked builds. - Wrapping arithmetic.
+%,-%and*%add, subtract and multiply modulo 2 to the operand type's width, two's-complement for signed types, and never fault in any build or at compile time:h = (h ^ byte) *% 0x100000001B3. They are for hashes, random number generators and checksums, where wrapping is the intent;+-*keep their overflow fault. Like the bitwise operators they take integer primitives and named types over them, not the functions ofNumber. - Equality compares values, never addresses: numerics and
boolby value; enums by variant and then payload; structs field by field; arrays of any form —[T : N],&[T],*[T]— by length and then element by element. Comparing interface objects or function values (§5.4) is a compile-time error. - Equality through
Equal. A type declaring the lang itemstd::equal::Equaldefines its equality withfn equals(self: &, other: &Self) -> bool:a == bisa.equals(&b)anda != bits negation, and every comparison reaching a value of the type as a part — a field, a payload, an element, a pointee — calls it too.StringandVector<T>declare it and compare their contents, so capacity plays no part:String::from(&"abc") == sholds for anysholdingabc, and aVector<String>compares its strings by content. A named type compares through the first type of its chain declaringEqual(type Label = Stringcompares as aString). In generic code==applies to a type parameter constrained byEqual(fn count<T: Equal>(...)), which every primitive type satisfies too. - Implicit
Equal. Every enum and struct that==compares, each of its fields, payloads, elements and pointees comparing in turn, satisfiesEqualwith no marker, sotype Tier = enum { Standard, Reduced, Premium }is aT: Equalandtier.equals(&other)istier == other, whether called on the type or through a constraint. This implicit conformance is one like a declared one (§6.2): an extensionfn equals(self t: &Tier, other: &Tier) -> booldoes not take its place,tier.equals(&other)still comparing structurally, so no call reaches it and it is an error at its definition; so withKey'shashandsame. A part==rejects — a function value or an interface object — leaves the type without it, and a generic type satisfies it per instantiation (Pair<u8>does,Pair<(u32) -> u32>does not). The comparison is the structural one above, a part declaringEqualcomparing through its ownequals; a type declaringEqualkeeps its ownequals. Only enums and structs satisfy it this way: a named type over a primitive or an array satisfies only what its own markers say (§6.1). Every enum and struct whose parts are all keys satisfiesKeythe same way, hashing and comparing part by part (§6.1a). - Compound assignment
a op= bisa = a op bwithaevaluated once. - Operators through
Number. A named type declaringNumber(§6.2) takes+-*/%and unary-from its functionsadd,subtract,multiply,divide,remainderandnegate, each called with both operands borrowed (a + bisa.add(&b)), and<<=>>=fromcompare, whoseOrderingthe operator tests (a < bisa.compare(&b)givingLess); the compound assignments follow. The first level down the type's chain that either is a numeric primitive or has the function decides, so a type over a primitive keeps the built-in operators unless it defines its own (type Wrapping : Number = u8with its ownadd). A type implements only the functions it uses: an operator whose function its type lacks is a compile-time error where it is written, or, in generic code, at the call that instantiates it.==and!=stay structural, and bitwise operators and shifts stay with the integer primitives. A type over no numeric primitive takes no literal and noto(§4.3, §4.5). - Generic bodies. A value typed by a type parameter takes no operator unless its constraint provides one:
T: Number(§6.1a) gives the arithmetic and ordering operators and equality, each the bound type's as above.
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 type | Source 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.
- Bare
xreads the value. For a value that owns no heap — primitives, references, slices, interface objects, and structs, arrays, and enums with no owning member — that is a plain copy. A value that owns heap is never read bare into a by-value target, since that would be a hidden allocation: the compile-time error namescopyandmove. copy xdeep-copies: every allocation the value owns is duplicated into a fresh one owned by the copy. It marks the copy as expensive. On a value that owns nothing it is allowed and plain, which is what lets a generic body writecopy itemfor anyT(§4.7).copygives a value, never a pointer: on a*[T]or&[T], whose array has no fixed size, or on an interface object (§4.2), it is a compile-time error, andnew pgives the new owning*[T]or*I.move xtransfers ownership instead of copying (below). Its result has the operand's type.new xevaluatesx, deep-copies the result into a fresh heap allocation, and gives a pointer:new 5,new T {},new [0 : n],new some_local. It is already a copy, so it takes nocopy;new move xmovesx's value into the allocation instead. The pointer's mutability follows the target's declared type (var p: *var [u8] = new "abc"), and is*Twhen inferred.&x/&var xgive a reference to a place: a local, a field, an element, or a heap value behind a pointer (&preferencesp's pointee). On a heap array the reference is a slice (&[T]) over every element in place — the only non-owning view of a*[T], as subslicing (§3.1) is of a range; on a fixed array it is a&[T : N], which converts to a slice where one is required (§4.3). The written form fixes the reference's mutability:&xis always immutable, and&var xis valid only when the location is itself mutable (§4.8). On an operand that already is a reference — a reference binding, a call result, a subslice —&passes the same reference through immutably, and&varpasses it through mutably, a compile-time error when the source reference is immutable.
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.
- Scope-end drop. When an owning local goes out of scope — at every
returnpath and at the fall-through — the runtime drops it, in reverse order of declaration and among the block's deferred statements (§5.3), freeing the heap it owns. Dropping a pointer frees its allocation (a*[T]releases the malloc base atuser_ptr - 8); dropping a*[T]first drops every element, all of which are initialised; dropping a struct / array / enum drops each owning field, element, or active payload; dropping a closure frees its environment. Recursive owning types, like aNodeholding a*Node, stop at the first null pointer. movetransfers ownership.movereads its operand like any read, but transfers what the value owns instead of copying it. The operand is a place: a variable, a field, or an element.- On a pointer (
*T/*var T/*[T]) it copies the pointer out and nulls the source: aftervar q = move pthe bindingpis null and its scope-end drop does nothing. The result has the pointer's own type. - On a value (
T: a struct, array, enum, or primitive) it yields aTwhose owning members — pointers at any depth, the active enum payload included — are transferred and whose other members are copied. The source keeps its shape with those pointers nulled, so it still drops safely, and any later dereference through one of them is a use-after-move. A deep copy of a moved-from value is another moved-from value: a null pointer copies as null and allocates nothing. ATthat owns nothing is simply copied. Zero bytes are a moved-from value of every type, every pointer, object, closure environment and payload pointer in them null:T.moved()gives one (§4.4), and a repeat of a value known to be all zero bytes (T.moved(),0,false) allocates zeroed memory and copies nothing. - On a reference (
&var T) it does the same to the pointee and yields aT. Through an immutable&Tit is allowed only whenTowns nothing, since a real move writes the source. - On a value typed by a type parameter it yields a
Tand acts on whatever the instantiation binds (§4.7): a pointer transfers, a value moves member-wise, a reference is copied because it owns nothing. This is how generic containers hand elements on:std::vector'spushstoresmove item, and its growth moves the old buffer's elements into a buffer ofT.moved()values with one range move (§5.2), so an owning element keeps its allocation.
Whenever the move writes its source, the source must be mutable (§4.8) — a pointer parameter counts as mutable for this purpose, since the callee owns it, and so does an owning capture (
|move x|), as do a by-value parameter and the fields and elements either holds in place (fn name_of(b: Big) -> String { return move b.name; }). A whole struct is therefore transferred either by moving a*Structor bymoveon the struct value itself.- On a pointer (
- Returns follow the use-site forms. A
returnis a use site of the function's result type.return move vhands what a local owns to the caller and clears the source,return copy vreturns a deep copy, and a barereturn vis valid only when the value owns no heap. A*[T]result takesmove vornew v.yieldandbreakwork the same way. A value built inside thereturnexpression is fresh and owned by the caller directly. - Pointer parameters take ownership. A
*T/*var T/*[T]parameter says "I take this allocation", so the caller passesmove p, a returned pointer (take(move make())), or a fresh allocation (take(new T {}),take(new x)); a pointer is never borrowed. The callee owns it, and the parameter drops at the function's scope end like any owning local, unless moved on or returned. To lend a value, pass&x/&var xto a&T/&var Tparameter. - By-value parameters follow the use-site forms. A value that owns no heap is passed bare; one that owns heap is passed
copy xormove x, and either way the callee owns its parameter. - Free-on-reassign. Assigning to an owning location (
buf = new […],obj.field = move p,s = copy t) drops what it currently owns first, so the old allocation is freed rather than leaked. - Integer overflow is a runtime fault in checked builds and wraps two's-complement in release builds; compile-time evaluation always faults. The wrapping operators (§4.10) never overflow. Division by zero faults in every build.
- Stack overflow is a runtime fault in every build: a program that runs out of stack reports
stack overflowand exits like any other fault. Drops, deep copies and==walk a value's tree recursing into all but its last owning part and looping into that one, so a chain along last parts — a linked list of any length — takes constant stack; past 10000 levels of the remaining nesting, they fault instead. - Checked builds null-check every dereference of a
*T, so a use-after-move traps. Release builds skip the checks, so a use-after-move dereferences null and the OS faults. The null store inmovestays in every build: it is the moved-from mark the drop machinery reads, which keeps drops and free-on-reassign single-free after a transfer. - Definite use-after-move is a compile-time error. The compiler tracks moves of bare locals flow-sensitively, for any local whose type owns heap (a pointer, or a value with owning members): after
move x, or an owning capture|move x|, readingx, writingx.field, moving it again, or capturing it is rejected until a plain=rebinds it. Branches merge conservatively — a move survives a merge only when every falling-through path performs it — so a move under a condition, in one branch, in a loop body, or of a field (move x.inner) stays a runtime check.
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'
...
}
- Disposable types. A type is disposable when it declares
Disposableor owns a disposable value: an owning pointer (*T,*var T) or an array ([T : N]with N above 0,*[T]) of disposable elements, a*Disposableobject, a struct or enum holding one. References and slices borrow and are not. A named type holding a disposable part must declareDisposableitself and dispose its parts (below). - Disposed or moved, once. A disposable value a local holds — a binding, a by-value parameter, a moving capture — must be consumed on every path before its scope ends: disposed (
x.dispose(),p.dispose()through a pointer the local owns, a consuming loop for an array) or moved away (move x, passing, returning or storing it). Afterwards the local is consumed: using it is an error, as after a move, until=gives it a new value — which is in turn an error while it may still hold one. A disposable value no local holds, such as a call's result, must be bound, moved or disposed where it is made —File::open(path).dispose(), or a test that moves its payload out when no other variant holds anything to dispose (if (map.remove(&key) is ::Some |move f|),while (files.pop() is ::Some |move f|)), or amatchwhose moving arms take every variant that does; discarding or borrowing it otherwise (File::open(path);,&File::open(path),File::open(path).write(...)) is an error. A moving capture leaves its subject moved-from (§5.3), so on a local it consumes the local under the same condition and is an error otherwise; and it disposes nothing when the enum is disposable itself while its payloads hold nothing to dispose (type Fd : Disposable = enum { Open: i32, Closed }), whose values only its own functions take apart. Apanicends the program, so its path needs nothing disposed. The check follows paths like the use-after-move check (§5.2), eachdeferrunning where its block is left (§5.3), sodefer x.dispose();right after the binding covers every way out. - Never copied. A by-value use of a disposable value takes
move, even when the type owns no heap memory;copyof one,newcopying one from a place, a fill of them ([file : 4]) and a by-value capture (|x|,|copy x|) are errors, so one resource never becomes two values. - Parts are the holder's business. Writing over a disposable field or element, or moving one out, would lose or duplicate the value, so it is an error — except through
selfin a function of the type holding it (self.part, or a reference taken from it), which is that type's own bookkeeping, as are copies and fills there of values typed by the holder's own type parameters:Vector<File>::pushwrites into its buffer and fills its growth with moved-from elements. - A holder's
dispose. In thedisposeimplementingDisposablefor a struct, every disposable field ofselfmust be disposed or moved on every path. For an enum, so mustself's payload: through amatchorisonselfthat moves it out (|move f|, which leavesselfmoved-from on every path) or borrows it (|&var f|, disposingfdisposes the payload); an arm or branch whose variants carry nothing disposable has nothing to dispose. - Arrays: consuming loops. An array of disposable elements is disposed by a loop that takes it,
for (move files) |&var f| { f.dispose(); }: the loop owns its moved subject, so|&var f|may borrow each element in place, and|move f|takes it out instead. The body must dispose or move the element on every path and may not leave the loop early —break,return, or ayieldout of it — thoughcontinueafter disposing is fine. A consuming loop may take a range of the array,for (move buffer[..count]): it disposes the whole array, the elements outside the range taken to be moved-from, which is what containers keep there. A non-consuming loop may only borrow disposable elements. - Generic code. A generic type holding values of a type parameter declares
Disposableconditionally (§6.2),type Vector<T> : Disposable if (T: Disposable), with adisposeconstrained the same way,fn dispose<T: Disposable>(self vector: &var Vector<T>):Vector<File>must be disposed andVector<u8>is untouched. A generic body is checked again for every instantiation binding a type parameter to a disposable type, its errors shown in the body and at the call leading there. In a function of a generic holder, values typed by the holder's own type parameters are its bookkeeping like the parts reached throughself: the standard containers move, write and fill their elements without the checks, and dispose them in theirdispose, and so must every function of theirs that drops an element:Vector'ssetdisposes the element it overwrites,truncateandclearthe ones they remove, deciding per instantiation withif (T: Disposable)(§4.4), so aVector<u8>does no extra work. - Nothing hides one. An owning interface object (
*I,*var I) of a disposable type, or a closure capturing one by value, would carry it past the check: both are errors, except a*Disposableobject, which is disposable itself (itsdisposedispatches). Borrow instead: a&Iobject, a|&file|capture. A task (§5.6) runs exactly once, so it may take a disposable value withmove(spawn { handle(move connection); }), which leaves the variable moved-from after thespawnand holds the task's own copy to dispose or move on every path, as a parameter would. - Checked builds count resources. The check above trusts a holder's own code, which may still lose a value. A checked build therefore counts the values of each resource type — one declaring
Disposableand holding nothing disposable, likeFile— made at each site (a struct or enum literal of the type, or an extern's result) and the runs of itsdispose. Whenmainreturns with more made than disposed, the program faults, naming the type and where its values were made:runtime fault: 1 value of type 'File' never disposed (made 2: main.alloy:5:16 (1), main.alloy:6:16 (1); disposed 1). Disposing more values of a type than were made faults at once, at thedispose. A release build counts nothing, and apanicreports nothing, since it skips disposal.
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
&Tcan 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 whereneworcopyis 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.
- Definite return: a function or lambda with a return type must terminate on every path; falling off the end is a compile-time error.
- Definite yield: a bare-expression branch of a value
ifyields by itself and always counts as terminating; every block branch of a valueifmust terminate; a bare-expression arm of a valuematchlikewise yields by itself; every block arm of a valuematchmust terminate unless an externalelsesupplies the fall-through value, in which case thatelsemust terminate; theelseof a value-yielding loop must terminate. - Unreachable code: a statement after a terminating statement in the same block can never run, and neither can a
matchpattern already covered by an earlier arm. The compiler warns about both and compiles them anyway.
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> { ... }
- Cursor lowering.
for (c) |x| { ... }becomesit = c.iterator()then repeatedmatch (it.next()) { ::Some |x| <body> ::None { break the loop } }. A cursor-shaped type without theIterablemarker is not aforsubject: the marker is required, and the check verifiesiterator/nextagainst the instantiated signatures (§6.2). - Counting-loop lowering. When the count and element access are directly available — every array form and every range generator — the compiler must lower the
forto a counting loop over an index, never the cursor protocol. A range generator as a subject (for ([..n]) |i|) builds no array at all, which is why runtime bounds are valid here withoutnew. - Element binding is the same in both lowerings and follows the capture rules (§3.1):
|x|copies an element that owns no heap,|copy x|deep-copies one that does, and|&x|/|&var x|borrow it in place. The cursor hands the loop anOption<&T>, so a copying capture reads through that reference (§5.2) and a borrowing capture keeps it. - Multi-subject loops. A
formay take several subjects with one capture each, in order:for (a, b) |x, y| { ... }. They iterate in lockstep, every subject must be iterable, and all must have the same length; a mismatch is a runtime fault in checked builds. elseneeds expression position. A trailingelseon a loop is only allowed when the whole loop is used as an expression. Such a loop is value-position, soyield valuein the body produces the loop's value andbreak valuedoes the same; either ends the loop at once. Theelseruns if and only if the loop finishes without producing a value — the subjects ran out, or the condition failed — and its own value becomes the loop's value, which must match the body's type. Anelseon a statement loop is a compile-time error.
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;
};
- Subjects: an enum value, a numeric primitive (character literals included, §2.6), a
bool, a byte array of any form (matched against string-literal patterns by length and bytes), or an interface object (§4.2). Patterns follow §3.1: literals of the subject's type, enum variants named fully (State::Idle) or implied (::Idle, §4.2), concrete types for an interface object, or named constants. - Constant patterns: a path naming a visible
constof a primitive type — top-level (LIMIT), type-scoped (Op::HALT, §6.4) or imported (codes::FIRST) — matches the constant's value, as its literal would; its type must convert to the subject's (§4.3), so au64constant does not match au32subject. A path naming a variant of the subject's enum stays the variant, and a name that is neither a variant, a type nor a constant is the error it always was. A constant of any other type (a struct, an enum, a slice), or one known only per instantiation (T::NAME), is a compile-time error as a pattern. Like a literal repeated, a constant whose value an earlier arm already matches is a warning. - Captures are valid only on enum variants that carry a payload and on the concrete-type arms of an interface object (§4.2); using one on numbers, characters,
bools, or strings is a compile-time error. They follow §3.1:|a|copies a payload that owns no heap,|copy a|deep-copies one that does,|&a|and|&var a|borrow it in place, and|move a|moves it out, leaving the subject moved-from after thematch. An arm listing several patterns may capture only when every listed variant carries a payload of the same type; a capture over several concrete types of an interface object is a compile-time error, since the value would have no single type. - Exhaustiveness: only a
matchused as an expression must cover every subject value, since it has to produce one. An enum subject is exhaustive when every variant is named by some arm's patterns, or when an internalelsearm is present. Numbers, characters, strings, and interface objects have open domains, so in expression position they always need an internalelse. A non-exhaustive value-yieldingmatchis a compile-time error. A statementmatchhas no such rule: it may cover any subset and does nothing when no arm matches. - Arm bodies: an arm body is a block, or — in value position only — a bare expression ended with
;(::Idle 0;), which yields that value implicitly. The;keeps the next pattern from being read as a continuation of the expression, since::A x ::Bwould otherwise parse as the pathx::B. A block arm produces the value withyield value. Abreakorcontinueinside an arm targets the enclosing loop, never the match. - External
elseblock: the optionalelseafter the closing brace is only allowed when thematchis an expression. It runs if and only if the selected arm finished without ayield— it is not a fallback for an unmatched subject — and must supply a value of the expected type. An externalelseon a statementmatchis a compile-time error.
5.4 Lambdas / Closures
|&var x, y| (param: T) -> R { body }
|=, &a| (param: T) -> R { body }
(param: T) -> R { body }
(param) => expression
- The optional capture list names variables from the enclosing scope, each with an optional modifier (
|&var x|) saying how the outer variable is reached inside the lambda; §3.1's capture rules apply unchanged. A|move x|capture moves the variable's pointer into the closure environment, leaving the outer binding moved-from after the lambda expression. - Default capture. The list may begin with a default:
=(by value),&(by reference) or&var(by mutable reference). It captures every enclosing variable the body uses and the list does not name, in that form;|=, &a|capturesaby reference and everything else the body uses by value. An entry may repeat the default's form. Each variable taken by the default must allow its form (§4.8), and the by-value default takes the plainxform, so a used variable whose value owns heap is a compile-time error unless listed ascopy vormove v. A list without a default captures only the variables it names. The token|=at the start of a lambda opens a capture list with the default=. - One name, one binding. The names a list binds are distinct: two parameters of a function,
selfincluded, or of anextern, interface function or macro, two captures of a lambda, or a capture and a parameter of one lambda, may not share a name, and neither may two captures of aforor of oneiforwhilecondition (a is ::Some |v| && b is ::Some |v|). Each is a compile-time error. - Capture lists are value-only. Type names, including the enclosing function's generic parameters, stay visible in the lambda without being captured.
- The parameter list and optional return type use the same syntax as a function, and the lambda's type is the matching function type
(T) -> R, with the capture bound its captures need (below). A parameter may be written as its name alone where the lambda's expected type is a function type, whose parameter takes its place:apply((x) => x + 1)withapply(f: (i32) -> i32). A call infers its type parameters from its other arguments first (§4.7), so a lambda's left-out types may name what they bound; one naming a type parameter nothing else binds is a compile-time error, written then. - Expression bodies.
=> expressionstands for a body returning the expression, for lambdas and named functions alike:(x) => x * 2,fn twice(x: i32) -> i32 => x * 2;, the definition ending with;. Where the function returns nothing the expression is evaluated for its effects, and an assignment may follow the arrow:(c) => c.count += 1. Only an expression body may leave out a result the function returns: a lambda's then comes from its expected function type, or, with none known, from the expression's type, an untyped literal taking its default (§4.3); a named function's comes from the expression's type, its body checked when a caller first needs it (fn greeting() => &"abc";gives&[u8 : 3]). A function reached before its result is known, as by calling itself, writes the result; so does one implementing an interface's function (§6.2), which conformance checks before any body. A block body's result is always written, or there is none. - A lambda without a capture list leaves the delimiters out:
(param: T) { ... }, and captures by value what its body uses, as|=|would. An empty capture list (||) is not valid. - Capture bounds. A function type says what its values may capture:
(T) -> Rnothing,|=| (T) -> Ronly what they own,|&| (T) -> Ranything. A lambda's type has the narrowest bound its captures allow: none with no captures;|=|when every capture is by value,copyormoveand its type holds no reference, that is no&Tor&var T, no interface object (whose concrete type may hold one) and no|&|function value, at any depth of structs, enums, arrays and pointers;|&|otherwise. A named function's value captures nothing. A function value converts to the type of the same parameters and result with a wider bound ((T) -> Rto|=| (T) -> Rto|&| (T) -> R), never to a narrower one, and a lambda written where a narrower bound is expected is a compile-time error naming the capture. In a generic body a capture whose type involves a type parameter is checked per instantiation,Tbeing possibly a reference. A function kept beyond the call receiving it takes|=|, so it never outlives what it would borrow, and one handed to another thread outside ascope(§5.6) is safe for the same reason; one only called before the call returns takes|&|:fn sort_by<T>(values: &var [T], before: |&| (&T, &T) -> bool) { ... } type Button = struct { on_press: |=| () = () {} }; fn background(work: |=| () -> |=| (&var Ui)) { ... } - Named function types. A lambda, or a named function used as a value, converts to a named type whose chain ends in a function type it converts to (§4.3 rule 4), as a literal takes a named number type's place: its untyped parameters and its result come from that function type, its captures are checked against that type's bound, and the value is then of the named type, called through it, stored and passed as it. An overloaded name picks the overload of that function type. A function value held elsewhere, in a local, a field or a call's result, stays of its own type, converted by
as(§4.5). The named type's markers stay its own (§6.1), as any named type's:type Rule<T> = |=| (&Ui, &T) -> Option<String>; fn length(min: u32) -> Rule<String> => |=| (ui, text) => if (text.length() < min) ::Some(f"at least {min}") else ::None; type Checker = (u32) -> bool; const positive_only: Checker = positive; // fn positive(x: u32) -> bool const rules = [length(3), (ui, text) => ::None]; // a [Rule<String> : 2] - A named, non-generic function used in value position becomes a function value of its signature's type. A generic function cannot (its parameters are unbound), an overloaded name must resolve to one function, and an
externfunction cannot be a function value. - Function values have no identity: comparing them with
==/!=is a compile-time error.
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)
- Called on its receiver only (user, 2026-11-01). An extension is called with dot notation and in no other way: a plain call
add(&v, &other), a qualified one through an import's alias (tx::find_byte(&bytes, '=', 0)), and naming it as a function value (const f = add;) are compile-time errors, the first two naming the method call to write (v.add(...)), the last the lambda that takes its place ((v, other) => v.add(&other)). Where free functions share the name, a plain call chooses among them alone (§4.6). Like the unreachable extension of §6.2, these are errors in the program's own library: a package's are found when it is packed (alloyc lib,publish), so one packed before the rule keeps working. - A
selfparameter is a reference: its type is&Tor&var T. A by-value or pointerselfis a compile-time error; a function that copies or consumes its subject takes it as an ordinary parameter (consume(move p)). - The receiver is the one implicit borrow.
v.f(...)reads as "doftov", which already saysvmay change, so the receiver takes no use-site marker (§5.2): the call borrowsvasself's type asks. A&varselfneeds a mutable place (§4.8) or a temporary, which nothing else sees change (make().push(1),map.insert(key, file).dispose()); a&Tselfaccepts any receiver, a temporary included. - The receiver counts as the first argument for overload resolution.
- Imports and method calls.
v.f(...)considers every visible extensionfof the module's imports, aliased ones included: an import's alias decides how its names are written (§6.4), and a method call writes none, the receiver's type choosing among them. Whenfis a function of an interfacev's type conforms to, the conformance's implementation stands for the visible extensions with its parameter types, visible or not (§6.2). - Dot-call precedence: extensions win. When no extension or interface function (§6.2) has the name,
v.f(...)calls through a function-typed fieldfofv. selfmay appear only on the first parameter.- Temporaries live to the end of the statement. A temporary made anywhere in a statement — a receiver, an argument, an operand — is dropped only when that statement completes, so a view borrowed from it (
print(&make().view())) stays valid for the rest of the statement, and an inlineiscapture (§4.2) taken in anifcondition may borrow from one through the body. Awhilecondition is evaluated afresh each iteration, so its temporaries live for that iteration and drop at its end. Amatchorforsubject lives through the whole construct, since its arms and body borrow it. A reference to a temporary that would outlive its statement is a compile-time error: one a binding keeps (const v = &make();,const x = &point(1).x;), whether written directly or as the value of aniformatch, one an assignment re-points a reference binding to, and one a function returns (return &point(3);). Bind the value to a local first. A call returning a reference borrows from each temporary among its reference arguments, the receiver included, since nothing says which one the reference comes from: keeping its result, or a place within what it refers to, is the same error (const seats = §ions().get(k).label;,const v = &names.get(&String::from(&"a"));), even where the reference is in fact static or into another argument (&tier_of(x).name()wherenamereturns a literal); a temporary passed by value is not borrowed, and the fix again binds the temporary to a local (const all = sections(); const seats = &all.get(k).label;). A call whose result is not a reference but may hold one — a struct or enum with a reference among its parts (Option<&T>, a reader keeping&[u8]), an interface object, a function value capturing by reference — borrows from its temporary reference arguments the same way, and so does a call passed such a value by value: keeping the result in a binding, an assignment or a return is the same error (var r = JsonReader::of(&summary_json(&c, &e));,const n = names.try_get(&key_of(x));,const p = wrap(JsonReader::of(&make()));), while using it within the statement stays fine (JsonReader::of(&make()).read()); bind the temporary to a local first (const json = summary_json(&c, &e); var r = JsonReader::of(&json);). A struct, enum or array literal keeps what its parts keep: one with a part borrowing a temporary, or a call part holding such a borrow, is the same error when kept (const h = Holder { .text = &make() };,instance = ::Some(face.at(&values_of(x).view()));) and fine within the statement (Holder { .text = &make() }.length()). The value of anif,matchor loop is a temporary too:&and&vargive a reference to a place or pass through an operand that already is a reference (§5.2), and a value-position construct is neither, since each branch converts to the type the borrow expects (§4.3), its pointee. Soreturn &var match (p) { ... };returning a&var Nodeis an error, and the fix writes the form in each branch, where a reference passes through:return match (p) { Pick::First &var pass(&var a); Pick::Second &var pass(&var b); };. Literals made only of literals live in static memory (§3.1) and may be kept, and a temporary's reference passed within the statement (size(&make())) is fine. - When
self's type is an interface (fn area(self s: &Shape) -> f32), the extension is that interface function's default implementation (§6.2). - A named type inherits down its chain.
type ByteVec = Vector<u8>;has every extension ofVector<u8>,Vector<u8>'s type-scoped functions and constants (ByteVec::empty(), §6.4), and so on down its chain (§4.3 rule 4); a named type over an enum has its variants too (type Alias = Plain;builds, matches and testsAlias::None). The receiver is borrowed as the type the inherited extension is written for, and an inherited definition takes and gives the named type wherever its parameter, result or constant type holds the type it comes from:ByteVec::empty()returns aByteVec, and aByteVec's inheritedfn append(self v: &var Vector<u8>, other: &Vector<u8>) -> Option<Vector<u8>>takes a&ByteVecand returns anOption<ByteVec>. A definition written for the named type itself overrides the inherited one, for every use on aByteVec: an extension overrides the one of the same name and parameter types (fn push(self v: &var ByteVec, item: u8)), and a type-scoped definition every inherited one of its name (fn ByteVec::empty() -> ByteVec). The underlying type keeps its own. Inheriting functions never makes a type satisfy an interface: that takes a marker (§6.2),CFunctionaside, which a named C function type satisfies by what it is (§6.1a), andEqualandKey, which a named type over an enum or struct satisfies as that type does (§4.10, §6.1a).
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;
}
scope { ... }is a statement. Its block runs on the thread that entered it, and the scope ends only once every task started in it has finished: whatever way leaves the block — its end,return,break,continue,yield— first waits for the scope's tasks, then runs the block's deferred statements and drops its locals. So a task may use the enclosing function's variables by reference.spawn { ... }starts a task running its block on another thread, alongside the code after it. It belongs to the innermostscopeof its own function or task: aspawnmay sit in loops and branches inside that scope, but not in a lambda or task without ascopeof its own, which is a compile-time error. A task's block is a function taking nothing and returning nothing, with its ownreturn.- Captures. A task captures the variables its block uses as a lambda's default would (§5.4), each in the form its use needs: a variable written after
move(move x) is moved into the task, leavingxmoved-from after thespawn; a variable declared in a block of the scope that ends before the scope does — a loop's body, a branch — is copied into the task, since it is gone before the task ends (one owning heap memory must then be writtenmove x); a reference variable is captured through to its pointee; any other variable is borrowed, mutably when it is mutable. - Race checks. Within one scope, at compile time: a variable one task writes — assigns, borrows
&var, moves from, or changes through a&var selfcall — is used by no other task and by none of the scope's own statements, which run alongside the tasks; a variable several of them use is only read. A task spawned in a loop of the scope may write only variables declared inside that loop, which are new each iteration. A variable moved into a task is taken at itsspawn, so the scope's statements before thespawnmay still use it. Values whose types declare the lang itemstd::sync::Shared(§6.1a) synchronize their own changes and are exempt. A variable's owned parts are covered with it, since an owning pointer is unique (§5.2); what references the function was given may alias, as everywhere in Alloy (§5.2), so two tasks writing through two&varparameters are the caller's to keep apart —chunks(std) hands out disjoint&var [T]pieces of one slice. - Sharing.
std::syncprovidesAtomic<T>over integers andbool, which alone satisfy its constraintT: AtomicValue(§6.1a) (Atomic<u64>::from(0);load,store,exchangegiving the value before,compare_exchange(expected, desired)saying whether it stored, and on integersadd, wrapping and giving the value before; all sequentially consistent),Mutex<T>(Mutex<T>::from(value)), whoselock()gives aGuard<T>that isDisposable(§5.2), so every path unlocks it, withguard.value()the locked&var T, andChannel<T>(Channel<T>::empty()), moving values from task to task first in first out (send(move x);receive() -> Option<T>, waiting for a value,Noneonce the channel is closed and empty;try_receive(),Noneat once when nothing is queued;close(), which wakes every receiver waiting); a moved pointer crosses without a copy. AMutex<T>orChannel<T>of a disposableTis disposable itself (Disposable if (T: Disposable)): itsdisposedisposes the value, or the values still queued, oldest first.chunks(&var items, n)gives a slice's disjoint pieces of at mostnelements as aVector<&var [T]>, so tasks may each change one:var pieces = chunks(&var bodies, 1024); scope { while (pieces.pop() is ::Some |&var piece|) { spawn { integrate(piece, step); } } } - Runtime. In a built program, tasks run on a pool of worker threads, one per core, started by the first
spawn; a scope's thread runs queued tasks while it waits for its own. Each thread has 8 MiB of stack, a stack overflow on any thread is the usual fault (on WebAssembly, whose threads' stacks have no guard, a program using tasks checks its stack in each function), and a fault orpanicin any task ends the whole process. - The interpreter (
alloyc run,alloyc test) runs tasks as cooperative tasks of its own on one thread, each with its own stack of frames: a task waits in its scope's queue until something waits — a scope's end, or a blockingstd::syncoperation — and then the earliest-spawned task able to go on runs until it finishes or waits in turn, where it is suspended and later resumed. Runs are the same every time, tasks waiting on each other in turn (a ping-pong over two channels) run as in a built program, and every task waiting with none able to go on is a deadlock fault. A wait reached inside a call the interpreter makes on its own behalf, such as anequalsbehind==, cannot suspend its task and runs the others inside it instead. Compile-time code may not start tasks (§7.2):scopein a compile-time context is a compile-time error, and one reached by compile-time code a fault.
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 form | Where the length lives |
|---|---|
[T : N] fixed | Known at compile time; .length() folds to the constant N. |
&[T] slice | The u64 half of the fat pointer. |
*[T] heap array | The 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 item | Canonical path | Declaration | Compiler hook | ||
|---|---|---|---|---|---|
Option<T> | std::option::Option | enum { Some: T, None } | for over a custom iterable matches on next()'s Option<&T> (§5.3). | ||
Iterable | std::iterable::Iterable | interface Iterable<T, It: Iterator<T>> { fn iterator(self: &) -> It; } | Gates for over custom types (§5.3). Arrays need no marker (§6.1). | ||
Iterator | std::iterable::Iterator | interface Iterator<T> { fn next(self: &var) -> Option<&T>; } | The cursor contract behind for (§5.3). | ||
Number | std::number::Number | interface 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). |
arguments | std::process::arguments | fn 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). | ||
Equal | std::equal::Equal | interface 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). | ||
Key | std::hash::Key | interface 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). | ||
Format | std::format::Format | interface 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. | ||
Disposable | std::dispose::Disposable | interface 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. | ||
Shared | std::sync::Shared | interface 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. | ||
AtomicValue | std::sync::AtomicValue | interface 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. | ||
Float | std::math::Float | interface 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). | ||
CFunction | std::ffi::CFunction | interface 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_stream | std::io::standard_stream | fn standard_stream(index: u32) -> i64 | The 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). | ||
| accessors | std::vector::get, get_var, last, replace, remove, swap_remove; std::map::get, get_var; std::string::get; std::json::get, at | Every overload of these plain-name lookups, which fault on a bad argument where their try_* companions give an Option | A 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:
| Name | Satisfied by |
|---|---|
Number | u8 u16 u32 u64 i8 i16 i32 i64 f32 f64, and named types declaring it that cannot own heap memory |
Key | every primitive type, String, every enum and struct whose parts are all keys, and types declaring it |
Equal | every primitive type, String, Vector<T>, every enum and struct == compares, and types declaring it |
Iterable | Types declaring the conformance and providing iterator() (§5.3). Never arrays (§6.1). |
Iterator | Cursor 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
- 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()wherehandle: &Shape) resolves at runtime through the carried type identity, matched against the closed world of implementers (§6.4). - Generic constraint. An interface used as a bound (
fn do<T: I>(...), or<T: I + J>for several) limits the generic to types implementingI, and calls resolve statically at each instantiation with no runtime dispatch. Inside the body aTvalue 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; aT: Numbervalue 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"; }
- A default makes that interface function optional for implementing types.
- One default a function. An interface function has at most one default: two extensions on the interface with its signature, in two modules (
fn width(self w: &Widget) -> u32in each), are an error at the interface naming each and where it is, as two extensions satisfying one function for one type are (Verification, rule 1), so what every type relying on the default runs never depends on the order modules load. Visibility does not matter here either: a private default in one module meets a second in another. - An extension written for a concrete type overrides the default for that type.
- A call on a conforming value runs what the conformance recorded. On a value whose type conforms to an interface (its own marker, holding for the type's arguments, or a lang item a primitive satisfies), a method call naming one of the interface's functions —
v.f(...)withf's parameter types as the type instantiates them — calls the function verification found for it (below): the type's own, one it inherits down its chain, or the default, whether or not that function is visible at the call, as a call through an object or a constraint does. It takes the place of every visible extensionfwith those parameter types, the default among them. Other overloads offstay candidates by the ordinary rules (§4.6). An extension taken the place of on every call is never called, since extensions are called on their receivers only (§5.5): it is an error at its definition, naming the interface.EqualandKey, which an enum or struct satisfies with no marker (§4.10, §6.1a), are conformances here too: ontype Point = struct { x: i32, y: i32 },p.hash()is the structural hash andp.equals(&q)the structural==, so afn hash(self p: &Point) -> u64beside them is that error, and on a named type over one declaring them (type B = Awithtype A : Key = ...) the calls runA's functions, afn hash(self b: &B) -> u64being the error too. A type conforming to no interface with such anf— a named type over a conforming one without the marker (type B = A) for any other interface, or a generic type whose conditional marker fails for its arguments — calls only the visible extensions, and a functionNumberleaves optional that the type lacks is resolved as any other.
// 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
- A generic interface's functions cannot have defaults: the receiver would be a generic interface object, and those need full instantiation, so no single receiver type covers every instantiation.
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;
- The interface fixes the type. An implementer's constant is checked as if declared with the required type, so an annotation, if written, must be that type. A generic implementer supplies it as a default with optional specializations (§6.4). The type may be the unsized array
[T], whose implementers each keep their own length ("square"is[u8 : 6]). The type may not mention the interface's type parameters, so a constant reads the same for every instantiation of a generic interface; a default is allowed in any interface. - Reading a constant.
Square::NAMEnames the implementer's constant, or the default when it has none. Inside a generic bodyT::NAMEreads it for the type bound toT: Shape(§4.7) and is a compile-time value per instantiation, usable in compile-time contexts (§7.1). Through an interface object, which has no fields to clash with,shape.NAMEreads the constant of the object's concrete type at runtime (&shape.NAMEis a&[u8]view of the static bytes). Read throughT::NAMEor an object, a constant has the interface's declared type, so an unsized one is borrowed in place like any unsized value (§3.1). - A constant read through
T::NAMEor an object is visible wherever the interface is. ReadingSquare::NAMEdirectly needs the type-scoped constant visible (§6.4), or the interface when it reads the default.
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:
- A satisfying extension function (§5.5) must exist in the merged unit: one belonging to
T, oneTinherits down its chain (withtype A : I = struct {...},type B = AhasA's functions but satisfies nothing, whiletype C : I = AsatisfiesIthrough them, each taking and givingCwhere it takes and givesA, sotype Id : Equal = u32;satisfiesEqualthroughu32'sfn equals(self value: &u32, other: &u32) -> bool), or a default implementation, tried in that order:C's own function beatsA's, andA's beatsI'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 ofTnaming 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). - 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 againstCursor<T>withE = T). Parameters afterselfline up positionally. - The receiver indirection is fixed by the interface, not the implementer:
fn next(self: &var)is satisfied byfn next(self c: &var Cursor<T>), never byfn 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 aself: &varfunction through a&Iobject is a compile-time error. - 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
- No owning returns: an
externmay not return*T,*var T, or*[T]. Those carry Alloy ownership, and the drop machinery (§5.2) would free memory Alloy never allocated. Model a C pointer result as&T/&var Tor as an opaque integer handle —std::iotypes C'sFILE*asi64— and manage its lifetime by hand in the wrapper. - Slice decay: a slice crossing the boundary passes only its data pointer, as C expects; the length stays behind. A string literal's static bytes are followed by a NUL (§2.6), so
&"abc"passed to C is a valid C string; a copy of a literal (var x = "abc") and a runtime-built byte array carry no terminator, and terminating them is the caller's job. - C strings: a parameter C reads up to a NUL is declared
c_string, written alone (extern fopen(path: c_string, mode: c_string) -> i64;), and takes a&[u8]like any byte slice. A string literal, or a constant holding one, is accepted as it is, since its static bytes end in a NUL; any other argument must hold a NUL among its own bytes, which a checked build tests at the call, faulting withargument 'path' of 'fopen' is not NUL-terminatedotherwise. A release build does not test.c_stringnames no type anywhere else: a variable, a field, a non-extern parameter or&c_stringis a compile-time error. - Integers of the target's width:
std::ffigives the C types whose width follows the target, for externs to write as the C header does:c_size(size_t,uintptr_t:u32on wasm32,u64elsewhere),c_ssize(ssize_t,ptrdiff_t:i32/i64alike),c_long(long:i32on Windows and wasm32,i64on Linux and macOS) andc_ulong(unsigned long). Each is a named type computed per build target, declaringNumber, so values convert withto(strlen(s) to u64) and literals take it directly;extern strlen(s: c_string) -> c_size;then links and runs on every target, where-> u64would mismatch wasm32's C. - Variadic promotions: arguments in a variadic tail follow the C defaults — integers narrower than 32 bits widen to
i32by their own signedness,f32widens tof64, and an untyped float takesf64(§4.3); a struct passes as below. - Enums with chosen tags (§4.2) cross as their integer, as a C
enumof a fixed type does (typedef enum : uint32_t { ... } Op;), in parameters, results and struct fields alike; any other enum is no C type. - Structs by value: an extern, and a C function type, takes and gives a struct by value when the struct holds, at any depth, only numbers,
bool, enums with chosen tags, references to sized values and C function types, in structs and arrays of length one or more; any other struct (one owning heap memory, holding a slice or an interface object, or empty) is a compile-time error. Such a struct crosses the boundary as the C struct of the same layout (§4.9) does under the target's C calling convention, so C code compiled for the target agrees with it in both directions. Onlinux-x86_64that is System V's: a struct of at most 16 bytes whose fields are all aligned passes in up to two registers, each eightbyte in a general-purpose register when it holds anything but floats and in a vector register otherwise (twof32sharing one), and any other struct, or one whose registers have run out, is copied onto the stack; results come back the same way inrax/rdxandxmm0/xmm1, or are written where a hidden first argument points. Onwindows-x86_64it is the Windows x64 convention's: a struct of 1, 2, 4 or 8 bytes passes in one register, any other as a pointer to a copy the caller makes, and a result of any other size is written where a hidden first argument points. Onlinux-aarch64it is AAPCS64's: a struct of one to four floating-point values allf32or allf64(a homogeneous floating-point aggregate, nested structs and arrays flattened) passes in as many vector registers, any other struct of at most 16 bytes in one or two general-purpose registers, and a larger one as a pointer to a copy the caller makes; arguments that no longer fit the registers left go on the stack whole; results come back the same way inv0-v3orx0/x1, or are written wherex8points. Onmacos-x86_64it is System V's, as on Linux; onmacos-arm64it is Apple's variant of AAPCS64, which classifies structs the same way but packs what goes on the stack to each argument's own alignment and passes every variadic argument on the stack. Onwasi-wasm32it is WebAssembly's basic C ABI: a struct holding a single scalar, at any depth, passes as that scalar, any other as a pointer to a copy the caller makes, and a result of any other kind is written where a hidden first argument points; its addresses take 4 bytes there, as C's do (§4.9). - C function types:
extern (T1, T2) -> Ris a plain code pointer called the C way, 8 bytes, copied like a number, and is what an extern takes or gives where C has a function pointer. An extern parameter of an Alloy function type,(T) -> R, is a compile-time error: an Alloy function value is a closure C cannot call. A named, non-generic function, or a lambda capturing nothing, converts to a C function type of the same parameters and result where one is expected; the compiler gives it an entry taking and returning values the C way. Any other function value (a variable, a closure) does not convert. A C function type takes and gives only what C can pass: primitives and named types over them, enums with chosen tags, references&T/&var Tto sized values, other C function types, structs C can take (above), andc_stringparameters, which the Alloy function takes as&[u8], its bytes up to the NUL (the C caller passes achar *). Slices are not passable. Calling a C function value from Alloy is an ordinary call,f(x), passing arguments as to an extern,c_stringarguments tested for a NUL in checked builds (argument 1 of a C function pointer is not NUL-terminated).import std::ffi; extern qsort(base: &var [i32], count: u64, size: u64, compare: extern (&i32, &i32) -> i32); extern pthread_create(thread: &var u64, attributes: u64, start: extern (c_pointer) -> u64, argument: c_pointer) -> i32; fn descending(a: &i32, b: &i32) -> i32 { return if (a < b) 1 else if (a > b) -1 else 0; } fn count(argument: c_pointer) -> u64 { const total: &var u64 = &var argument.as_var<u64>(); total += 1; return 0; } qsort(&var numbers[..], 5, 4, descending); qsort(&var numbers[..], 5, 4, (a: &i32, b: &i32) -> i32 { return a - b; }); pthread_create(&var thread, 0, count, c_pointer::from(&var total)); - State through C: callbacks capture nothing; what they work on travels through the C API's user-data pointer, which
std::ffitypes asc_pointer(an unsigned integer of the target's address width:u32on wasm32,u64elsewhere), made from a reference withc_pointer::from(&var x)orc_pointer::from(&x)and read back withp.as_var<T>()orp.as_ref<T>(). Nothing checks the type named on the way back or that the value is still alive: this is manual safety, as in section 5.2. Memory C gives is read the same way:p.view<T>(n)andp.view_var<T>(n)are thenvalues of typeTat the address (an array a callback receives, a mapped file, a buffer to fill),p.c_text()the C string there up to its NUL, andc_pointer::of(&items)the address of a slice's first element (0 for an empty one), for C to read or fill. A heap value C holds on to, as the state a browser calls back aftermainreturns (std::web), is handed over withc_pointer::keep(move p), which gives its address and leaves it unfreed, and owned again withp.take<T>(). - Calls from C: C may call an entry on any thread, one Alloy did not start included; the first call on such a thread sets up the runtime's per-thread state (the stack-overflow check's stack). A fault or a
panicin code C called ends the process as anywhere else (exit 134); nothing unwinds through C frames. Data reached from a thread C started is outsidescope's race checks and is shared throughstd::sync. - Shared libraries:
std::ffi::Library::open(path)loads a shared library while the program runs (a.soon Linux and Android, a.dylibor framework on Apple systems, a DLL on Windows), by path or by a bare name the system searches for, givingNonewhen it cannot;library.symbol<F>(name)gives the address of one of its functions as the C function typeF,Nonewhen it has no such symbol.Fmust satisfystd::ffi::CFunction, a lang item every C function type and every named type over one satisfy with no marker and nothing else does (§6.1a), and must be the function's C prototype, which nothing checks. One symbol may be read as several types, as Objective-C'sobjc_msgSendis, whose callers each cast it to the message's own prototype (it is not variadic: a variadic call passes its arguments whereobjc_msgSenddoes not look for them). A library stays loaded until the program ends. On Linux a static program cannot load libraries, so a program reachingLibrary::openlinks glibc dynamically (alloyc build, §6.5); WebAssembly loads none.const vulkan = if (Library::open(&"libvulkan.so.1") is ::Some |l|) l else { return no_gpu(); }; const get_proc = vulkan.symbol<extern (c_pointer, c_string) -> c_pointer>(&"vkGetInstanceProcAddr"); - JavaScript on the web: a module's JavaScript sits beside it,
window.web.jsnext towindow.alloy, an ES module whose top-levelexport function(orexport const,let,class,async function) lines give the externs the module declares for the browser. On WebAssembly each extern it exports imports from it, under the module's key (pkg::acme::window), and the module's other externs link as anywhere else;alloyc build --target web-wasm32bundles the JavaScript of every module whose exported externs the program calls into<program>.js, andalloyc libpacks it with its module, as the file<module path>.web.js. The JavaScript reaches the program throughalloy:alloy.memory,alloy.bytes(at, length)andalloy.view()over its memory,alloy.text(at, length)decoding UTF-8, andalloy.call(f, ...args), which calls a C function value the program gave it (an index in the module's exported function table), a fault there ending the program. A module's JavaScript may exportasync function prepare(), which<program>.jsawaits beforemainstarts, in the thread running it: what the browser gives only through a Promise, such as a GPU device, is then there for the externs to use at once.std::web::keep_running()letsmainreturn to the browser with the program still running: the checks made whenmainreturns are skipped, and the browser calls back what the program gave it until the page closes, so what the callbacks use lives on the heap or in statics; elsewhere it panics.// timer.alloy extern al_later(milliseconds: u32, callback: extern (u32), count: u32);// timer.web.js export function al_later(milliseconds, callback, count) { setTimeout(() => alloy.call(callback, count), milliseconds); } - Interpreting:
alloyc runand compile-time code have no externs but std's, and load no library (Library::openfaults there); a C function value made from an Alloy function is called directly there, so code that only passes them around among Alloy functions runs the same.
6.4 Module System
- Module paths mirror the filesystem:
import a::b::cnamesa/b/c.alloy. - Standard library: ordinary Alloy source shipped with the compiler, not a prelude, and a library of its own: programs see its
expdefinitions. The modules arestd::option(Option<T>),std::result(Result<T, E>,enum { Ok: T, Err: E }, withis_ok,is_err, andokanderrgiving a copy of the payload as anOption; no operator propagates an error, a caller matches),std::numberandstd::iterable(the constraint interfaces),std::dispose(Disposable, §5.2),std::equal(Equal, §4.10),std::vector(Vector<T>),std::sort(sortandsort_by, in place),std::hash(Key,hash_bits,hash_bytes),std::map(Map<K: Key, V>, a hash map keeping insertion order, whoseStringkeys are also looked up as&[u8]),std::string(String),std::text(searching and parsing&[u8]text),std::math(sqrt,cbrt,sin,cos,tan,asin,acos,atan,atan2,sinh,cosh,tanh,exponential(expbeing a keyword),exp2,log,log2,log10,pow,floor,ceil,round,trunc,fma,hypot,copysign,is_nan,is_infinite,is_finiteover anyFloat;min,max,clamp,absandlerpover anyNumber; untyped constantsPI,TAU,E,SQRT_2and others taking the type they are used at, andINFINITYandNANasf64),std::format(Format,out.write(&value)for any formattable value or text,write_allfor an array,text_of,write_fixedwith exact decimals rounded half to even,write_radix,pad_from, and the functions interpolated strings call, §2.6),std::float_digits(the shortest decimal digits of a float),std::sha256(sha256andsha256_text, which the registry checks files with),std::net(TCP: aListeneron IPv4,Connection::connectreaching a host by name over IPv6 or IPv4 within a timeout,shutdownfrom any task,NetError; natively only),std::tls(TLS 1.2 and 1.3 over a connection,Tls::connectandTls::accept, through Mbed TLS, which only programs reaching it link; the certificate authorities of the fileALLOY_CA_FILEnames, else the system's trust),std::http(an HTTP/1.1 client:Request,sendwaiting for the wholeResponse,send_withand theControlanother task follows or cancels it through,HttpError; natively only),std::url(Url::parse,resolve,encoded,decoded,Query),std::deflate(inflate,deflate,gzip,gunzip,crc32),std::sync(Shared,AtomicValue,Atomic<T>,Mutex<T>and itsGuard<T>,Channel<T>,chunks, §5.6),std::json(Jsonvalues: parsing, floats read correctly rounded, reading, building and writing JSON),std::io(console and file I/O,Filedisposable and synced to the disk bysync, the library's FFI barrier so programs never touch C directly;print_linewrites its line whole, which no other task's output splits),std::fs(metadata,exists,is_file,is_directory,list_directorysorted bytewise,make_directory,make_directories,remove_directory,remove_file,rename,copy_file,MappedFile(a file mapped read-only into memory, its pages read as touched,viewits bytes, disposed to unmap it; read whole where nothing maps, on the web, under WASI and in the interpreter) andKeptMappedFile(the same mapped until the program ends, for a holder that cannot be disposed),data_directoryandcache_directory, the directories an app keeps its data and caches in, and the path functionsjoin,parent,file_name,stem,extensionin the target's style, Linux's/or Windows'\or/with drive and share roots, each with an_inform taking aPathStylefor paths of the other system),std::storage(Store, a disposable store of JSON values by key read whole when opened: natively a file in the app's data directory written atomically byflush, on the weblocalStorageitems;KeptStore, the same for a holder that cannot be disposed),std::time(Instant::now()on the monotonic clock,elapsed,since,Duration,wall_clock()in nanoseconds since 1970,sleep; the calendar'sDate,Month,Weekday,TimeOfDayandDateTime;Zone, a time zone by name from the platform's database orZone::system(),localgiving a moment on its clocks andmomentthe way back asResolved; ISO 8601, RFC 3339 and HTTP dates read and written),std::locale(Locale, CLDR's data for every locale of modern coverage, the same on every target:Locale::ofa BCP 47 tag,Locale::system(), the first weekday and the clock, month and weekday names, dates and moments written from components (DateFormat) or a pattern, numbers and prices in a currency's minor unit),std::languages(the system's preferred languages,preferred_languages(), and whether a BCP 47 tag's language is written right to left,writes_right_to_left, apart fromstd::localeso that they load none of its tables),std::random(Random, xoshiro256** seeded by SplitMix64:from_seedgiving one sequence on every platform and in the interpreter,from_entropyfrom the system's random source;next,belowwithout bias,rangeover anyNumber,unit,chance,shuffle); the interpreter reaches the same system functions as native programs (alloyc/src/support/system.c), reading the real clocks and entropy,std::process(target(), the platform the build is for, §6.5;arguments()),std::testing(expectandexpect_equal, §6.5), andstd::macros(the built-in macro declarations, §7.4). alloyc buildimport resolution: compiling one file to an executable (alloyc build file.alloy [-o out] [--release]) resolves eachimport a::b::ctoa/b/c.alloy, searched in this order: the importing module's directory, the entry module's directory, the compiler executable's directory, then$ALLOY_STDLIB. The first step lets a module reach its siblings without naming the directory —import token_kindinsidetokenizer/tokenizer.alloyfindstokenizer/token_kind.alloy— and such a module takes the directory-qualified key (tokenizer::token_kind) while its unqualified alias stays the path's last segment.std::andpkg::imports skip that first step. Resolution never depends on the shell's working directory, so a build means the same thing from anywhere and matches how editor tooling resolves against the open file. Apkg/folder of.alloylibpackages is found next to the entry module. Builds are checked by default;--releaseselects the release semantics of §5.2. The compiler generates the executable itself, through LLVM and LLD built into it, with no other tool installed: unoptimized with debug info for checked builds, optimized for release, where x86-64 code for Linux and Windows keeps each jump and fused compare-and-jump within an aligned 32-byte block, padded before it (LLVM's-x86-branches-within-32B-boundaries, which LLVM's Mach-O writer does not apply, so macOS x86-64 code is not padded), since Intel processors since Skylake, patched for their jump erratum, run a jump crossing one from the slower legacy decoders. On Linux an executable links statically against the C library shipped with the compiler (musl), with the mimalloc allocator in place of musl's, so it runs on any Linux of its architecture. On Windows an executable links against MinGW-w64's C runtime over the Universal C Runtime (ucrtbase.dll, part of every Windows 10 and later) and the import libraries of the system DLLs, all built from pinned source and shipped with the compiler, again with mimalloc as the heap, so it needs no other DLL installed; any compiler builds for any of its targets. The licenses of what a target's programs link sit beside it inlib/<target>/. For a quick edit-and-run loop,alloyc runinterprets the program instead of building it.- Debug info: checked builds embed DWARF — file, function, statement line and column, and local variables with their types — so LLDB and GDB set breakpoints, step by statement, and show Alloy names in call stacks. For Windows (
--target windows-x86_64) the same information is CodeView, which the linker writes into<program>.pdbbeside the executable together with a natvis file (language/editors/natvis/alloy.natvis) that shows strings, vectors, maps, slices andOptionby their contents in Visual Studio's debuggers. For macOS the DWARF stays in the object file, which a checked build keeps beside the executable as<program>.o, and the executable keeps a map to it that LLDB follows. Release builds carry none. - Program entry: execution starts at a zero-parameter
mainin the entry module. An integer result becomes the process exit code, truncated to the platform's width; any other result type, or none, exits with 0. - Declaration order: a module's definitions may appear in any order; every one is visible throughout the module, and to its importers, regardless of where it is written. Imports come first (§3.1).
- Top-level constants:
const NAME [: T] = expression;at module level names a compile-time value. The initializer is a compile-time context (§7.1), so it may use literals, functions, and other constants, andNAMEthen stands for the resulting literal (§5.2): used bare it is copied, and&NAMEreferences its static data. There is no top-levelvar, so the program has no mutable global state. - Type-scoped definitions:
fn Type::name(...)andconst Type::NAME = ...;define a function or a constant in the scope of a named type visible to the defining module, read asType::name(...)andType::NAMElike an enum variant. A named type inherits the type-scoped definitions down its chain and may override them (§5.5). A type-scoped function is a plain function, so it takes noself(§5.5). A type-scoped constant is a top-level constant in every other respect. Type-scoped names never collide with module-level names, but within one type a constant, a function, and an enum variant cannot share a name (type-scoped functions still overload among themselves). Visibility markers work as on any definition. An interface may require a type-scoped constant of its implementers (§6.2). - Generic types: default and specializations. On a generic type the bare form is the default for every instantiation, and the type's own parameters are in scope under their declared names:
fn Vector::empty() -> Vector<T>,const Vector::GROWTH = 2;. Naming concrete arguments specializes it for that instantiation:fn Vector<u8>::empty() -> Vector<u8>,const Vector<u8>::GROWTH = 4;. The arguments are ordinary types, never new parameters. A specialization needs no default: without one, only the instantiations it names have the definition (Box<u8>::only()exists,Box<u32>::only()is a compile-time error). With a default, it must match the default's signature or type with the arguments substituted. A use names the instantiation (Vector<u32>::empty()) or leaves it to inference from the expected type and the arguments, like any type parameter (var v: Vector<u8> = Vector::empty();,Box::make(x)bindingBox'sTfromx, §4.7), and gets the specialization when one exists, the default otherwise. Inside a generic body the default is what is checked (a name with only specializations cannot be used there with the type's own parameters), and the specialization is picked per instantiation. A type has at most one default and one specialization per instantiation of a given name in the whole program. - Visibility follows imports. A module sees every definition of its own, the
pubandexpdefinitions of each module it imports from its own library, and theexpdefinitions of each module it imports from another library — nothing else. Imports do not chain: a module importingstd::stringdoes not seeOptionuntil it importsstd::optionitself, whateverstd::stringimports. The executable's own modules form one library; the standard library is another, whose public API is thereforeexp; each package is its own. - Qualified vs. unqualified access: a visible imported name may be written plain (
Vector) or qualified (std::vector::Vector). Every import introduces an alias for qualified use — the explicitasname, or the path's last segment (import pkg::acme::mathxallowsmathx::twice(...)). An import withoutasalso makes its visible names available unqualified; an aliased one (import pkg::acme::liba as la) is reachable only through the alias (la::Pair), with one exception: method-call syntax finds its visible extension functions as an unaliased import's, since the receiver gives the scope (§5.5), so withimport std::text as tx;bytes.find_byte('=', 0)works, the only way to call an extension (tx::find_byte(&bytes, '=', 0)andfind_byte(&bytes, '=', 0)are errors). - Name collisions: within one module, a name colliding with an existing definition is a redeclaration error, except that functions overload (§4.6) and a macro may share a name with functions —
#name(...)always calls the macro, a barename(...)never does (§7.3). Names that are never visible together never collide, so different modules and libraries reuse names freely. Where two visible definitions share an unqualified name — the module's own and an import's, or two imports' — functions overload across all of them, as one candidate set (§4.6); any other pairing, or two functions with identical parameter types, is a compile-time error at the import, fixed by aliasing one import. Two imports whose aliases collide are also an error. - Struct members have visibility like definitions. In the struct layout a
typedefinition gives (type P = struct { … }), a member with no marker is visible only inside the defining module, apubmember wherever the type is visible within its library, and anexpmember across libraries too; a member may not be more visible than its type. Reading, writing, or initializing a member needs it visible, so a struct with any member hidden from a module cannot be built there by a struct literal — it is built through the defining module's functions (String::empty()). Enum variants are always exactly as visible as their enum. A layout written as a compile-time value (in atypedefinition's right-hand side or a macro body) may carry markers too, on its own members only, which apply once it becomes a definition's type (type Pick<T> = if (T.size() > 2) struct { pub v: T } else struct { pub v: u16 };); a member more visible than that type is an error there, for a generic type at the use instantiating it. An inline layout anywhere else has no owner to hide its members from: they are always visible and take no marker. A named struct converts to an anonymous layout (§4.3 rule 6) only where all its members are visible. - Interface satisfaction ignores visibility: whether a type satisfies an interface, what an interface object dispatches to, and what a method call on a value of a conforming type naming one of the interface's functions runs, consider every extension in the merged unit (§6.2). Visibility governs only who may name a definition.
Import Namespaces
import a::b— a relative import: the filea/b.alloy, found by the search order ofalloyc buildabove — the importing module's directory first, then the entry module's directory and the fallbacks. Inside a library, relative imports stay in that library's namespace.import std::x— the standard library.import pkg::scope::name[::module]— a package: the onename-<major.minor.patch>.alloylibin thepkg/scope/folder next to the entry module, which the registry fills. Every package lives in a scope, the account or group publishing it, so that two authors may each publish aunits(pkg::alice::units,pkg::acme::units); importing both takesasfor one, their default aliases being the same.pkg::scope::nameimports the package's entry module, the one named after it, andpkg::scope::name::pathits module at that path (pkg::acme::geometry::shapes);pkg::namealone names no package. Two files of one package in its folder are an error: a program uses one version of each. Inside a package, a relative import names another of its modules, searched from the importing module's directory within the package and then from its root; itspkg::imports resolve in the samepkg/folder as the program's.
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>
- Header.
alloylib 1names the format's version;packagethe package's full name, its scope and its name each a letter or_, then letters, digits and_(acme::geometry), and its version;languagethe spec revision it was checked against, which the consuming compiler must have reached; an optionallicenseline the package's license as an SPDX expression (license MIT OR Apache-2.0), which publishing requires; eachrequiresline a package its modules import and the version it was built against. - Sections end their first line with a count, so no source text can be read as a boundary and the file stays readable and diffable:
exports <lines>, thenmodule <path> <bytes>andfile <path> <bytes>sections of exactly that many bytes, each followed by a newline. - Exports list every
expdefinition, one line each,<module path>: <signature>: the definition's source up to its body (a function's block or=>body, a type's right-hand side, a constant's value; an interface, an extern and a short function leaving its result to its body whole), comments left out, white space one space, none inside brackets or before,and;. They give the registry and editors the library's API at a glance. The source stays authoritative: a consuming compiler regenerates the lines of each module it loads and rejects a file whose section differs. - Requirements follow minimal version selection:
requires acme::units 2.1.0is met by anyacme::units2.x at 2.1.0 or later, so libraries asking for 2.1.0 and 2.3.0 share the 2.3.0 the program'spkg/holds. A different major version, or an earlier one, is an error naming both. - Embedded files.
#read_filein a package's code reads the files packed with it, so shaders and tables travel with the library. alloyc lib entry.alloy --scope <scope> --version <major.minor.patch> [--license <spdx>] [-o out]checks the library standalone — all §4 and §5 rules, flow and move analysis included, its non-generic functions lowered — and packs it, by default as<name>-<version>.alloylibnext to the entry module. The name is the entry module's, in the scope given; the modules are the entry and every module of its own it reaches by relative imports, at their paths relative to its directory without a leading folder named after the package (geometry/shapes.alloybesidegeometry.alloyis the moduleshapes, which the library's ownimport geometry::shapesstill names), two modules that would share a path being an error; the requirements are the versions of the packages they import from the author's ownpkg/folder; the files are those#read_fileread. No manifest file is involved.std::andpkg::dependencies are not packed: they stay imports the consuming program resolves.- The file holds the complete source: packages are open source and build from source with the consuming program, so a library never breaks across compiler releases that accept its
language. - Export boundary:
expmarks a definition as exported. Inside one compilation unitexpbehaves likepub; across a library boundary onlyexpdefinitions are visible to consumers, whilepubcovers a library's internal structure without leaking it. - Interface satisfaction stays closed-world: whether a type satisfies an interface (§6.2) considers every extension in the merged unit, internal ones included, so dispatch spans the whole program. Visibility governs who may name an extension in a method call, not what backs dispatch.
- Compile-time code re-runs per program (§7): a library's compile-time contexts and macros are re-evaluated in the consuming program's merged unit, so compile-time reflection sees the final closed world, not just the library's own.
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
- Commands. Packages are named as imports name them,
<scope>::<name>, orpkg::<scope>::<name>as written in the import.alloyc get <scope>::<name>[@<version>]puts the newest release of the package (or that version) into thepkg/folder of the program in the current directory (--in <directory>names another), replacing any other version of it.alloyc getwith no package named reads the program from its entry module, that directory'smain.alloyor the<entry.alloy>given (pkg/then beside it), and gets each package the program's own modules import thatpkg/lacks asget <scope>::<name>would, leaving those present as they are; a package the registry does not have is an error at its import, and nothing is added. Builds,run,testand the language server never reach the registry: a package missing frompkg/is an error saying to runalloyc get.alloyc update [<scope>::<name>] [--major]moves each package, or the one named, to its newest release of the same major version, or of any with--major. Both then meet every package's requirements by minimal version selection: a missing package, or one older than a requirement, takes the version required, or the next release when that one is yanked; a change that would break another package's requirement of a different major version is refused.alloyc search [<text>]lists the registry's packages whose full names hold the text, with their newest versions. A release is a candidate only when this compiler has reached itslanguagerevision and it is not yanked. - Publishing.
alloyc publish <entry.alloy> --scope <scope> --version <v> --license <spdx>checks and packs the library asalloyc libdoes,alloyc publish <file.alloylib>takes one packed already, and either is checked again with the versions it requires taken from the registry, which must have them. The license must name only licenses the Open Source Initiative approved, by SPDX identifier, joined byORorAND. A published version never changes: publishing it again is an error, andalloyc yank <scope>::<name>@<version>only marks it, sogetandupdatepass it by while programs holding it keep working. - Layout. A registry is files, the same in a directory (
--registry <directory>) and served over HTTPS (--registry https://...; without the option, theALLOY_REGISTRYenvironment variable, else the default registry, which stays local until a public registry is deployed: the directoryalloy/registryunder$XDG_DATA_HOME, else~/.local/share/alloy/registry):packages, a line a package,<scope>::<name>with its newest version that is not yanked;index/<scope>/<name>, a line a release, oldest first; andfiles/<scope>/<name>/<name>-<version>.alloylib. An index line reads1.4.2 language=2026-10-11 sha256=<64 hex digits> requires=acme::[email protected],acme::[email protected] yanked license=MIT OR Apache-2.0,requiresandyankedappearing only when they apply. - Trust.
getandupdatecheck each file's SHA-256 against the index before writing it, and the list of packages and each index are signed:<path>.sigholds an ECDSA P-256 signature over the file's SHA-256, DER-encoded, in hexadecimal. The client checks it with the registry's public key, its uncompressed point in hexadecimal, from--key, else theALLOY_REGISTRY_KEYenvironment variable; a registry served over HTTP(S) needs a key, a directory is checked only when one is given. HTTPS connections verify the server's certificate againstALLOY_CA_FILE, else the system's certificate authorities. Building a package runs none of its author's code outside the compile-time sandbox (§7.2): there are no build scripts. - Compiler releases. Releases take semantic versions from
0.1.0, reaching1.0.0when the language is declared stable. An installation is the compiler,alloyc(alloyc.exeon Windows), withstdandlib(what programs link) beside it, whichalloycfinds through its own path. The registry keeps releases per platform:releases/index/<platform>(linux-x86_64,linux-aarch64,windows-x86_64), a signed line a release (0.2.0 language=2026-10-11 sha256=<digest>), which compilers and the install scripts read ignoring words they do not know, so a later marker (0.2.0 language=2026-10-11 sha256=<digest> yanked) breaks none already released, while a malformed version,language=orsha256=(empty, a digest not of 64 digits, one given twice) or a line withoutsha256=leaves the list damaged, andregistry releasekeeps the lines there as written, andreleases/files/<platform>/alloyc-<version>.release, the installation's files in one file.alloyc upgradeinstalls the newest release over the running compiler's installation when it is newer thanalloyc --versionsays, putting each ofstd,libandalloycin place of the old one (on Windows the runningalloyc.exeis renamed aside, and the new compiler removes it when it next starts), andalloyc upgrade --to <directory>installs it there;alloyc upgrade --version <v>installs exactly that release instead, older ones too (over the installation, nothing when it is that release already), a version the registry has no release of being an error naming those it has; the release is checked against its SHA-256 first.alloyc registry release <installation> --version <v> --registry <directory> --sign <file>adds one, for Windows when the installation holdsalloyc.exeand for ARM64 Linux when itsalloycis an ARM64 executable. A release may carryregistry.confbeside the compiler (registry <address>andkey <public key>lines, written byscripts/release.sh --registry <address> --key <key>): the installed compiler then uses that registry and key when neither--registrynorALLOY_REGISTRYnames one, so the release, signed in the registry's list, is what tells a new installation where its registry is.upgradewrites the installed release's version asversionbeside the compiler, whichalloyc --versionreports. A registry servesinstall.sh(published byregistry/installer.sh, with its address and key filled in):curl -fsSL <registry>/install.sh | shchecks the signed list of releases withopenssl, the newest release, or the oneALLOY_VERSIONnames, against its SHA-256, and has the release's own compiler install it into$ALLOY_HOME(default~/.alloy), adding it toPATH; on Windows,irm <registry>/install.ps1 | iexdoes the same in PowerShell,$env:ALLOY_VERSIONtoo, checking the signature with .NET, into%LOCALAPPDATA%\alloyand the user'sPATH. - The registry service (
language/registry) is written in Alloy: it serves a registry's files over HTTP or, given a certificate, HTTPS, takespublishandyankfrom accounts holding a token, runs the compiler to check and store what they send, and lets an account publish and yank only in its scopes: the scope of its own name, and each group listing it. Groups are made by hand on the server (<data>/groups, a line a group,<group> <account>...). The project's own scopes,alloy,std,core,pkg,alloycand every name starting withalloy_, are groups of the accountalloy, and no account takes a group's name. An account's name is its scope, so it is a package name. Accounts sign in with GitHub's device flow:alloyc loginasks the service to start it (POST <address>/api/login, the service asking GitHub for a device code with its OAuth app's client id, no secret involved), prints the code and the page to enter it at (https://github.com/login/device), and polls the service (POST <address>/api/login/pollwith the device code) at the interval GitHub gives, waiting longer when told to slow down and stopping when the code expires or the user refuses; once the code is entered, the service reads the user's GitHub id and login, makes the account on the first sign-in and answers with a new token. An account takes the GitHub login lowercased,-becoming_and a leading digit getting_before it (Sky-Pjackissky_pjack,42catsis_42cats), and keeps it when the login changes on GitHub, the service knowing it by the GitHub id; a login whose name is a group's, one of the project's, or another account's is refused (choosing another name, one that is no other GitHub user's login and no group's, is not built yet). A name never changes once a package is published in it.alloyc loginkeeps the token in the user'scredentialsfile, a line a registry,<address> <token>, readable by the user alone, in$ALLOY_HOME, else~/.alloy(%LOCALAPPDATA%\alloyon Windows);alloyc logoutforgets it. The service may also answer a website's host name from a folder of its own (alloylang.orgbesideregistry.alloylang.org). - Keeping a registry.
alloyc registry key <file>makes a key pair, writing the private key to the file and printing the public key;publishandyankon a directory sign what they change with--sign <private key file>, andalloyc registry sign <directory> --sign <file>signs a directory's list and indexes again. A registry service takespublishandyankasPOST <address>/api/publish(the.alloylibas the body) andPOST <address>/api/yank(<scope>::<name>@<version>, thenundoto restore), authorized by the token--tokenorALLOY_TOKENgives, else the onealloyc loginkept for that registry.
6.5 Command Line
alloyc build file.alloy [-o out] [--release] [--symbols] [--cpu <cpu>] [--target <target>] [--windows-gui] [--libc musl|glibc]compiles a program to a native executable (§6.4), statically linked for its target (a release build without its symbol table unless--symbols, which profilers and debuggers read names from):linux-x86_64orlinux-aarch64(64-bit ARM Linux, against musl as on x86-64; a program reachingstd::ffi::Library::open, which a static program cannot do, links dynamically against the system's glibc instead, binding only to what glibc 2.34 has, so it runs on any Linux with glibc 2.34 or later, Ubuntu 22.04 and Debian 12 on, through stub libraries the compiler ships, and--libcforces either), the building machine's own by default,macos-arm64(Apple Silicon) ormacos-x86_64(Intel Macs), for macOS 11 and later, linked dynamically against the system library through a text stub the compiler ships, so no Apple SDK is needed (ARM64 executables are signed ad hoc, as Apple Silicon requires; none has run on a Mac yet), orwindows-x86_64, named.exe(Windows executables link with their runtime and std in place, faults and running out of stack reported as on Linux with exit status 134, the console and the arguments in UTF-8, the standard streams carrying bytes as they are, 8 MiB of stack formainand for workers, and the compiler itself is built for Windows asalloyc.exe; the run tests pass on Windows 11; the system DLLs std and windows need (kernel32, ws2_32, bcrypt, user32, gdi32, dwmapi) are imported when called, and--link -l<name>names another's import library, as-lole32;--windows-guilinks it for the Windows subsystem instead of the console's, so a program started from Explorer, a game, opens no console window, its standard streams then writing nowhere, whilemainstays its start), orwasi-wasm32, a WebAssembly module named.wasmfor runtimes of WASI preview 1 such as wasmtime, linked against wasi-libc, its addresses 4 bytes wide (§4.9), files reached in the directories its runtime grants,std::netfailing, tasks running on threads (a program reaching ascopeis built for wasi-threads with a shared memory, so its runtime must give threads:wasmtime run -W threads=y -S threads=y, or the JavaScript below, which runs each thread in a Web Worker and needs a browser page served cross-origin isolated; a host that cannot start a thread faults at the firstspawn), and a fault trapping after its message, orweb-wasm32, the same module and beside it<program>.js, which runs it in a browser (<script type="module">, its output on the console) or under node with its arguments, giving it no files. What a target's programs link, its runtime and C library, sits inlib/<target>/beside the compiler.std::process::target()names the build's target; the compiler replaces each call with that name, and anifwhose condition is made of literals alone (true,false,!,&&,||, and==or!=between string literals, astarget() == "windows-x86_64"becomes) builds only the branch taken, so the other may call what the target lacks, as withT: I(§4.4).--cpupicks the instruction set it may use:x86-64-v3by default (AVX2, FMA and BMI2: Intel Haswell and AMD Zen 1 on), sofma,floorand the like are single instructions and loops vectorize 256 bits wide;x86-64builds for any 64-bit x86 CPU, for old or low-end hardware;x86-64-v2(SSE4.2, 2009 on) andx86-64-v4(AVX-512) sit between and beyond, andnativetargets the building machine's own CPU. Formacos-arm64the level isapple-m1, the default, which every Apple Silicon Mac at least is, andmacos-x86_64takes the x86-64 levels. Forlinux-aarch64the levels arearmv8.2-a, the default (LSE atomics, so tasks' atomic operations are single instructions: Cortex-A55/A75 and Neoverse N1 on, the Raspberry Pi 5, Apple Silicon), andarmv8-a, any 64-bit ARM CPU (a Raspberry Pi 4 needs it);nativeis the building machine's when it is ARM64 too. Forwasi-wasm32andweb-wasm32the level isgeneric, LLVM's baseline with tail calls (WebAssembly 3.0). A program built for a level its CPU lacks stops with an illegal instruction.alloyc test --nativetakes the same option. The released compiler itself is built forx86-64-v2, so it runs on every x86-64 PC still in use whatever its programs target, and the ARM64 one,linux-aarch64's, forarmv8-a, so it runs on every 64-bit ARM Linux machine; every compiler builds for every target.alloyc run file.alloy [arguments…]checks the program exactly asbuilddoes, then executes it in the compiler's interpreter — the one that runs compile-time code (§7) — without generating code: a quick way to test a program. The run has checked-build semantics (§5.2),arguments()(§6.1a) gives the program path followed by the given arguments, and the process exits withmain's result like a built executable. Unlike compile-time evaluation it is not sandboxed (§7.2): the interpreter supplies host implementations of the C functions the standard library declares, sostd::ioworks as in a native build, and of C'sprintffor the conversions%d,%i,%u,%x,%c,%s,%f, and%%, with thelandlllength modifiers; each conversion reads its argument at the width C gives it, so%uprints the low 32 bits of au64as a native build does. Calling any otherexternis a runtime fault. A runtime fault printsruntime fault:, its message, and the faulting location to standard error, and exits with status 134, as a nativeabortdoes.alloyc lib entry.alloy --version <major.minor.patch> [--license <spdx>] [-o out]checks and packs a library (§6.4).alloyc doc entry.alloy [-o dir] [--private] [--json file]documents a library. It checks the library aslibdoes and writes a static site into the directory (docby default):index.html, listing the library's modules and its dependencies; a page a module, std's and packages' included, so every link stays within the site and works offline fromfile://; a source page a module with an anchor a line (#L12); one stylesheet; and a search in plain JavaScript oversearch-index.js. Beside it,doc.jsongives each definition of the library's modules with its kind, name, signature and the definitions it names, comment and the links in it, members and line, for editors and tools (--json filewrites it alone,-to standard output). A definition's documentation is the//comment block directly above it, with no blank line between; a member's is the block above it or a//comment ending its line; a module's is the block its file starts with, before its imports (a block running straight into a definition documents the definition). The library'sexpdefinitions are documented,--privateadding the others of its own modules, and dependencies show theirexpones. A page shows each definition's signature as written, whichalloyc fmtkeeps in its one style (a function's or macro's up to its body, a struct's or enum's up to its layout, whose visible members and variants follow, an interface's header, its required functions and constants following with their defaults), every name in it linked to its definition, its comment, a type's functions (scoped to it or taking it as receiver) and an interface's implementers among the documented types. Comments are Markdown: paragraphs, lists (-,*,1.), code blocks fenced with three backticks or indented four spaces,`code`spans, and links written[name],[Type::name](a scoped definition, a field, a variant or a required function),[module::name]or[module](a single letter,[T], reads as the array type it writes), resolved as a name in the module's code is, imports' aliases and modules' keys included; a link naming nothing is a warning, and the output ends with how many definitions have no comment and how many links name nothing. The language server's hover shows the same comments, a link's path as code. An```alloyblock in a documentation comment of the program's own library is an example thatalloyc testruns as a test named<module>: example at line N: its code is the body of a test in a module of its own, importing the module, the module's imports,std::testingand what the block's leadingimportlines name, so it sees what the module shows its library, and its errors and failures point at the comment's lines.```textblocks are only shown, and builds and the language server leave examples out.alloyc doc --stdopens the standard library's documentation, which every installation carries indoc/beside the compiler, in the browser (throughxdg-open,openon macOS,starton Windows, the path printed when none can), writing it first when it is missing; with-o dirit writes it there instead.alloyc,alloyc helpandalloyc --helpprint every command with its options; a command used wrongly prints its own part of that usage to standard error and exits with status 2.alloyc get,update,search,publish,yank,upgrade,loginandlogoutuse the package registry (§6.4);alloyc --versionprints the compiler's release and the language revision it implements.alloyc test file.alloy [--filter text] [--native]runs tests. A test is a top-level definitiontest "name" { ... }: a body like a function's, taking and giving nothing, that sees its module's private definitions; its name is unique in its module, and it takes nopuborexp.build,runandlibleave tests out entirely, unchecked, so test-only code never slows or breaks a build;testand the language server check them.alloyc testchecks the program with the tests of the file's own library (the file and the modules of its own it reaches; the standard library's and packages' tests do not run, unless the file is one of std's modules, whose library is then std, its examples included) and runs those whose names hold the filter text, module by module in source order. Each runs on its own, in a fresh interpreter or, with--native, in a process of its own running a checked build, so a failed expectation, apanic, a runtime fault, a value left undisposed or a leak fails that test alone. For each it printsokorFAILand the failure, then the counts, and it exits 1 when one failed.std::testinggivesexpect(condition: bool)andexpect_equal(actual: &T, expected: &T)forT: Equal, with an overload for&[u8]; a failure ends the test, reported aspath:line:column: test failed: expected 5, found 4at the test's call rather than inside them, andexpect_equalprints both values when they are integers,bool, text orStrings, other types once std can format them:import std::testing; fn add(a: u32, b: u32) -> u32 { return a + b; } test "add sums its operands" { expect(add(2, 3) == 5); expect_equal(&add(2, 3), &5); }alloyc lsp [--stdlib dir]is a language server, speaking the Language Server Protocol over standard input and output, for editors. It keeps the texts the editor has open, unsaved ones included, and once no message is waiting checks the programs they belong to asbuildwould, short of generating code, publishing every file's diagnostics. A file belongs to the nearestmain.alloyin its directory or above whose program imports it, or else is checked as the entry of a program of its own. It formats documents asalloyc fmtdoes, and answers from the last check: hover shows a name's definition (its signature and the//comment above it) or a local's type, and it gives definitions, references, highlights, document and workspace symbols, and renaming, which renames every use and refuses names the standard library defines or uses; semantic tokens classify every name, and inlay hints show the type of a local declared without one (unless its initializer starts with the type's name) and the parameter each argument goes to (unless the argument has its name); completion offers after.the receiver's visible fields and the functions taking it as receiver, afterName::what the type scopes, after#the visible macros, and elsewhere the locals before the cursor, visible definitions, keywords and primitive types, and signature help shows the parameters of the call around the cursor. Quick fixes write the use-site form a diagnostic asks for, declare withvara local that is not mutable, import a module (the standard library's included) exporting an unknown name, and add a missing;; lenses over the entry module'smainrun, build or debug the program, and lenses over each test run it.alloyc fmt [--check] <path>…formats source files, and those in directories, recursively, in place: one fixed style with no options, changing only white space, so every token and comment stays as written. Each token keeps its line; within a line binary operators are spaced, prefix operators and capture lists tight,<>tight around type arguments, and a colon tight before it except before interface markers and in[T : N]and[v : n]; lines are indented four spaces per enclosing bracket, a statement going on to the next line four further, a{alone on its line joins the line before, and blank lines collapse to one. A line over 100 columns splits at its own&&and||, outside any brackets, and otherwise at the commas of its longest outermost bracket pair, one item per line, at&&and||in parentheses, or inside the brackets ending a sole item (f(g(a, b))keepsf(g(together). A file that does not parse is left as it is, with its errors reported.--checkchanges nothing and lists the files that would change;alloyc fmt --stdout file.alloyprints one file formatted, andalloyc fmt -formats standard input to standard output, for editors.
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:
- the right-hand side of a
typedefinition, top-level or local (§4.4), which must produce a type:type T = if (DEVELOPMENT) u32 else u64;; - the initializer of a top-level or type-scoped
const(§6.4), and an interface constant's default (§6.2); - an array length:
[u8 : N * 2]; - a variant's chosen tag (§4.2), which must produce a value of the enum's integer:
Attach = BASE + 1,Byte = 'y'; - a macro's arguments and its body (§7.3);
- an expression operating on a
typevalue inside a runtime body (§4.4).
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:
- Pointer barrier: what crosses from compile time to runtime is a literal or a reference to one, so a compile-time result cannot be or contain a pointer (
*T), a heap array (*[T]), a closure, a&var T, or a&Tto anything but a literal (static data such as&"abc"or&NAME, §5.2); breaking this is a compile-time error. Static data has no owner to free it, and a reference crossing points into static data, never back into the evaluation. An array result of any length crosses as the literal[T : N]of the length it was produced with, so a macro producing a string works, and the use site borrows it (&#label("x")) or copies it like any literal. An array of arrays[[T]]crosses as[[T : M] : N]only when its arrays all have one lengthM; arrays of different lengths are a compile-time error at the call, and such a result is declared[&[T]]instead, a list of references to literals (return [&"ab", &"cde"];). - Sandboxing: compile-time evaluation reaches the filesystem only through
#read_file(§7.4), and only inside the project root, which is the entry module's directory tree, or, in a package's code, the files packed with it (§6.4). Every other host capability is unreachable. - No FFI: compile-time code cannot call
externC functions (§6.3); it runs only safe Alloy code and built-in macros. The one exception isstd::math's functions (§6.1aFloat), which read no memory, soconst ROOT_2: f64 = sqrt(2.0);works. Theargumentslang item (§6.1a) is unreachable for the same reason — there is no command line during compilation.
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
}
- Signature: a macro declares its result type with
->, like a function, and the type is required — nothing is inferred from the body. The type may be a runtime type ([u8],u32,&[u8], a named struct) ortype(§4.4),[type]for an array of them. Since the result crosses as a literal (§7.2), a result type holding a pointer (*T,*[T]), a closure or a&var Tis a compile-time error at the macro. Parameters are typed the same way. A macro is the only function that takes or returns atype: afnwhose signature holds one is a compile-time error. - Declaration-only macros: a macro may be declared without a body (
exp macro type_of(value) -> type;), like an interface function, and the compiler supplies the implementation. Its parameters need no type annotations — a built-in like#type_ofaccepts an expression of any type — while a macro with a body must type every parameter. The result type is declared either way. Calling a declared macro the compiler does not implement is a compile-time error. The built-in macros (§7.4) are declared this way instd::macros. - Invocation: every macro call is prefixed with
#and runs at compile time, inside a runtime body too; its arguments are a compile-time context (§7.1). Because that distinguishes them, a macro may share its name with functions (§6.4):#name(...)always picks the macro, a barename(...)only the functions. Macros overload on their parameter types like functions (§4.6). - Declaration order: because the result type is declared, a call type-checks without running the body, so a macro's body may reference definitions declared later, exactly like any compile-time context calling regular functions. Evaluation order still decides what a body observes: a type synthesised by an earlier comptime declaration is complete, one synthesised later is not (§7.4).
- Unsized arrays are values at compile time. The interpreter tracks every array's length, so inside compile-time code an unsized
[T]is an ordinary value: a parameter (name: [u8], which takes a string literal bare), a local, or a result. A macro returning an array therefore declares-> [T]without hard-coding the length, and each call's result is the literal[T : N]of the length it produced (§7.2). - Where a result may go follows the declared type. A macro returning a runtime type may be called in value position (
const x = #m(1);), and the legal runtime results are literals: primitives, bools, arrays (strings included), and named struct or enum values holding no pointer, and references to literals (return &"abc";with-> &[u8]) — a reference to anything else, such as a local of the body, is a compile-time error at the call (§7.2). A macro returningtype, or any type holding one such as[type], may only be called where a type is expected (type T = #m(...);) or inside a larger compile-time expression (#implementers_of(Shape).length()), since atypecannot cross into runtime (§4.4). - Macro bodies are type-checked like function bodies. With typed parameters and a declared result, a body is checked statically under every §4 and §5 rule — overload resolution, reference explicitness, definite return against the declared type — before it ever runs, so a call to a missing function or a mismatched argument is an error at the macro, not a fault at its first use. The one difference from a function body is that it is compile-time context throughout:
typevalues may be held in locals and passed around, and inline layouts (struct { ... }) are plain expressions there. The body then runs in the compile-time interpreter, where a runtime fault (overflow, an exhausted budget, a failed#read_file) is a compile-time error at the call site; a body that produces something other than its declared type is an error at the call site too.
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 #.
| Macro | Signature | Semantics |
|---|---|---|
type_of | (value) -> type | The type of the argument expression (§4.4), which is not evaluated, so it may name a runtime local of the enclosing body. |
struct_type | () -> type | A fresh, empty struct type to build on. |
enum_type | () -> type | A 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.