DocsLanguage Reference
Statements
Every statement, its forms, and how control leaves a scope.
A statement is the unit of a function body: it declares something, evaluates an expression for its effect, or directs control. Sable's statements are separated by newlines, by the rule in Lexical Structure; a ; puts several on one line. This chapter lists every statement and the rules for each, and ends with how control leaves a scope.
The guide teaches these in Control Flow, Pattern Matching, Error Handling, Concurrency and Compile-Time Evaluation.
Block = "{" { Statement } "}" ;Statement = Declaration | ExpressionStatement | IfStatement | GuardStatement | WhileStatement | RepeatStatement | ForStatement | MatchStatement | SwitchStatement | DoStatement | RegionStatement | UsingStatement | DeferStatement | ReturnStatement | ThrowStatement | YieldStatement | BreakStatement | ContinueStatement | FallthroughStatement | UnsafeBlock | ComptimeBlock | ConditionalCompilation | LabeledStatement | Block | NL ;A block, { … }, is a statement of its own too: it opens a scope, and the bindings in it end at its }. Its opening brace must be on the line of whatever it belongs to.
Bindings#
VariableDecl = [ "async" ] [ "using" ] ( "let" | "var" ) BindingPattern [ ":" Type ] [ "=" Expression ] [ Accessors ] [ "," | ";" ] NL ;ConstDecl = "const" Identifier [ ":" Type ] "=" Expression NL ;let x = 42 // immutable, inferred Intlet y: F64 = 3.14 // annotatedvar count = 0 // mutablevar total: I64 // declared; assigned before it is readlet (q, r) = divmod(17, 5) // tuple destructuringlet { name, age } = person // record destructuring by field namelet { name: n } = person // with a renamestatic let maxUsers = 10_000const pi: F64 = 3.14159265358979letbinds a value once.varbinds a variable that may be reassigned, and whose contents may be changed in place.- The type may be left out when there is an initialiser; it is inferred from it. A binding with no initialiser needs a type.
- Definite assignment. A binding must be assigned on every path before it is read; reading it earlier is an error, not a zero. A
letdeclared without a value may be assigned exactly once. - Destructuring. A tuple pattern binds each element; a record pattern
{ field, field: newName }binds fields of a struct by name. Nested patterns and_are allowed. See Patterns. - Shadowing a name from an enclosing scope is allowed; declaring the same name twice in one scope is an error.
static letandstatic varat module level, and a type's static stored properties, are initialised once, on one thread, beforemainbegins: each after those its initial value reads (directly or through what it calls), otherwise in the order written, the standard library's first. Two that need each other are S3411. Reading one costs only the read.constis a compile-time constant, computed while compiling and written as a literal wherever it is read. Its type may be left out when its value is a literal, another constant, a call or arithmetic on those. See Compile-time blocks and Declarations.async letstarts a child task; see async let.using letscopes a resource; see using.
Expression statements#
ExpressionStatement = Expression NL ;An expression evaluated for its effect: a call, an assignment, an await. A call whose result is left unused is warned of (the unused_result lint) unless the function is @discardable; write _ = f() to drop one on purpose.
counter += 1log.write("started")_ = cache.remove(key)if#
IfStatement = "if" ConditionList Block { "else" "if" ConditionList Block } [ "else" Block ] ;ConditionList = Condition { "," Condition } ;Condition = "let" BindingPattern [ ":" Type ] [ "=" Expression ] | "var" BindingPattern [ ":" Type ] [ "=" Expression ] | "case" Pattern "=" Expression | Expression ;An if runs its block when every condition in its list holds, checked left to right; a later condition may use what an earlier one bound. Each condition is one of:
| Condition | Holds when |
|---|---|
expr |
The Bool is true |
let name = expr |
The optional holds a value; name is bound to it (var binds a mutable copy) |
let name |
Shorthand for let name = name: an optional of that name, unwrapped under the same name |
case pattern = expr |
The value matches the pattern; its bindings are bound |
if x > 0 { print("positive")} else if x < 0 { print("negative")} else { print("zero")}if let user = findUser(id) { greet(user) }if let timeout { wait(timeout) }if let a = p, let b = q, a.id == b.id { merge(a, b) }if case .Circle(let r) = shape { print(r) }Bindings made by the conditions are in scope in the block they guard, not in else. A test of a type or of none narrows the tested binding in the block; see Types. Where a value is wanted, an if with an else is an expression (Expressions).
guard#
GuardStatement = "guard" ConditionList "else" Block ;guard checks conditions and, when any fails, runs its else block, which must leave the enclosing scope: by return, throw, break, continue, or a call returning Never. Falling out of the end of it is an error. What the conditions bound, and what they narrowed, holds for the rest of the enclosing block.
guard let user = findUser(id) else { return .notFound }guard x > 0 else { throw .invalid("x must be positive") }guard case .X25519(let own) = key else { return false }while#
WhileStatement = "while" ConditionList Block ;while checks its conditions before each pass and runs the body while they all hold. The conditions take the same forms as if's:
while !queue.isEmpty { process(queue.removeFirst()) }while let line = await file.readLine() { print(line) }while case [let first, ...] = pending { pending = handle(first) }repeat#
RepeatStatement = "repeat" Block "while" Expression NL ;repeat runs its body once, then again while the condition holds. while on the line after the } continues the repeat rather than starting a loop.
repeat { attempt += 1} while !connect() && attempt < 3for#
ForStatement = "for" [ "try" ] [ "await" ] BindingPattern "in" Expression [ "where" Expression ] Block ;for goes through a sequence: it calls makeIterator() on it (makeAsyncIterator() for for await) and binds each element that next() gives to the pattern.
for i in 0..<10 { }for i in 0...10 { } // inclusivefor item in collection { }for (key, value) in dictionary { }for i in stride(from: 0, to: 100, by: 5) { }for item in collection where item.isActive { }for try line in file.lines() { } // a sequence that may throwfor await message in stream { } // an AsyncSequencefor try await row in query.rows() { }- The pattern is a name,
_, or a tuple or record destructuring. whereskips elements for which its condition is false.for tryis required when the sequence'sFailureis notNever(S3032 otherwise); an error fromnext()leaves the loop as atrywould. Arrays, ranges, collections and non-throwing generators need none.for awaitgoes through anAsyncSequence, suspending for each element;for try awaitone that may also throw.- A loop over a range, held or written in place, or a
stride, compiles to a counting loop.
Labelled statements#
LabeledStatement = Identifier ":" ( WhileStatement | ForStatement | RepeatStatement | Block ) ;A loop or a block may carry a label, so that break and continue in a nested loop can name it.
outer: for row in rows { for cell in row { if cell.isEmpty { continue outer } if cell.isTarget { break outer } }}Control transfer statements#
ReturnStatement = "return" [ Expression ] NL ;ThrowStatement = "throw" Expression NL ;YieldStatement = "yield" Expression NL ; (* only in a generator's body: SYNTAX.md §5, "Generators" *)BreakStatement = "break" [ Identifier ] NL ;ContinueStatement = "continue" [ Identifier ] NL ;FallthroughStatement = "fallthrough" NL ;| Statement | Effect |
|---|---|
return, return expr |
Leaves the function, with a value when it has a result |
throw expr |
Leaves with an error of the function's thrown type, converted through From if it differs; or into the enclosing do's catch |
yield expr |
In a generator, gives the next element and pauses |
break, break label |
Leaves the innermost loop or switch (or the labelled statement) |
continue, continue label |
Begins the next pass of the innermost loop (or the labelled one) |
fallthrough |
In a switch, goes on into the next case's statements |
return, throw, break, continue and fallthrough always end at the newline: what they take must be on the same line.
yieldoutside a generator is S3480, and in adeferbody S3481;returnwith a value in a generator is S3482. See Declarations.fallthroughoutside aswitchcase, or in the last case, is S6020.throwis also an expression (Expressions).
defer#
DeferStatement = "defer" Block ;A defer block runs as the scope it is written in is left — by reaching its end, return, break, continue, or a thrown error. Several run in reverse order of writing. A defer body may not yield (S3481).
fn copy(from source: String, to destination: String) throws(IoError) { let input = try File.open(source) defer { input.close() } let output = try File.create(destination) defer { output.close() } // runs first try output.write(input.readAll())}In a generator, a pending defer runs when the generator finishes or when its iterator is dropped early.
using#
UsingStatement = "using" ( "let" | "var" ) BindingPattern [ ":" Type ] "=" Expression NL ;using let binds a resource that is released — its deinit run — at the end of the enclosing block, in reverse order of declaration. The binding is consumed there, so using it afterwards is a compile-time error. It is the @noncopy-aware equivalent of defer.
using let conn = pool.acquire()using var tx = conn.begin()tx.execute(query)// tx, then conn, released at the end of the blockusing has no braced form: in using let f = open(p) { … } the brace would be a trailing closure on open. For a narrower scope, put the using in a block of its own.
match#
MatchStatement = "match" Expression "{" { MatchCase } "}" ;MatchCase = "case" PatternList [ "where" Expression ] ( "=>" ArmBody | ":" { Statement } ) | "default" ( "=>" ArmBody | ":" { Statement } ) ;ArmBody = Expression | Block | ReturnStatement | BreakStatement | ContinueStatement ;PatternList = Pattern { "," Pattern } ;match compares a value with each arm's patterns in order and runs the first arm that matches. It is both a statement and an expression.
match command { case .Move(let dx, let dy) => position.move(dx, dy) case .Say(let text) where text.isEmpty => { } case .Say(let text) => print(text) case .Quit => return}match n { case 0: return 0 case let m where m > 0: return 1 default: return -1}- An arm is
casewith one or more patterns separated by,(any of which may match), an optionalwhereguard, and a body.defaultmatches anything. - Arrow arms,
=> body, take an expression, a block, or areturn,breakorcontinue. Statement arms,: statements, take statements up to the nextcase— the C-like form, which never falls through. - Exhaustiveness is checked: a
matchthat does not cover every value, withoutdefault, is an error naming a missing case. A@flagsenum always needs adefault, as does a public union of another module that is not@frozen. The algorithm and the pattern forms are in Patterns. - In a
whereclause,identifier =>at the end is read as the arm's arrow, not a closure. - An arrow arm's
return,breakorcontinueleaves as it would anywhere:case .Some(let r) => return ris=> { return r }.
switch#
SwitchStatement = "switch" Expression "{" { SwitchCase } "}" ;SwitchCase = "case" ExpressionList ":" { Statement } | "default" ":" { Statement } ;ExpressionList = Expression { "," Expression } ;switch is the C-shaped dispatch on values, for integers and enums where explicit fall-through is wanted. It does not bind patterns; match is preferred otherwise.
switch code { case 200, 201: handleOk() case 301: fallthrough case 302: redirect() default: fail()}The subject is compared with each case's values in order, by ==; default, wherever it is written, runs when none is equal. A case ends where the next begins. fallthrough continues into the case written after it, break leaves the switch early, and continue goes on with the enclosing loop.
do and catch#
DoStatement = "do" Block { CatchClause } ;CatchClause = "catch" [ Pattern [ "where" Expression ] ] Block ;do runs a block in which errors are caught. An error thrown by a try in it goes to the first catch clause whose pattern matches the error, and whose where guard, if any, holds. A catch with no pattern catches everything and binds the error as error.
do { let text = try read("config.toml") apply(text)} catch .NotFound(let path) { log.warn("missing \(path)")} catch IoError.AlreadyExists(_) where tries < 100 { tries += 1} catch { throw .io(error)}An error no clause catches propagates to the enclosing function, which must be able to throw it. A do with no catch is just a scope. try … catch in expression form is in Expressions.
async let#
async let profile = fetchProfile(id)async let friends = fetchFriends(id)let page = try await render(profile, friends)async let is a binding statement, not an expression: it starts its initialiser as a child task, running alongside the rest of the scope. Its work may await and throw without saying so; reading the name awaits the result, and trys it when it may throw. A child that is never read, or that a return or throw leaves behind, is cancelled and awaited as the scope ends. What its initialiser captures must be Sendable (S3236).
Region blocks#
RegionStatement = "region" [ Identifier [ "=" Expression ] ] Block ;region name { … } opens a bump-allocated arena for the length of the block: name.alloc(value) places a value in it and gives a reference (a T& that writes). Everything in the region is released at once at the }. References into the region are rooted in it and may not outlive it; toOwned() copies a value out.
fn parse(_ src: String) -> Ast.Module { region arena { let tokens = arena.alloc(Token[>..]()) lex(src, into: &tokens) return parseModule(tokens, in: arena).toOwned() }}region name = existing { … } opens a nested scope of an existing region (a stored region field, say): what it allocates is given back at the block's end. A stored region's reset() gives back everything in it, and a reference into it used after the reset is an error. See Memory and Ownership.
Unsafe blocks#
UnsafeBlock = "unsafe" Block ;An unsafe block permits what the compiler cannot check: calling an unsafe fn (or taking one as a value), reading and writing raw memory, and sharing non-Sendable state across tasks on the programmer's word. Outside one, those are S3470. sable build --deny-unsafe fails on any unsafe block in the program's own code (S3472). Root inference still runs inside an unsafe block; the spec's unsafe.assumeRoot(p, as: x), to override it, is not implemented. See Unsafe Code and C Interop.
unsafe { let p = RawPtr<U8>.allocate(count: 1024) defer { p.deallocate() } p.initialize(to: 0xFF, at: 0)}Compile-time blocks#
ComptimeBlock = "comptime" Block ;A comptime block runs once, in the compiler's interpreter, while compiling, and leaves no code. It may be written at the top level or in a body; in a body it cannot see the function's parameters or locals. What it calls must be a const fn, a const init, a compiler-written initialiser or a pure member of Sable.Core (S3220). Reaching compileError("…") in it is a compile error (S3222).
comptime { if Platform.pointerWidth != 64 { compileError("64-bit only") }}Conditional compilation#
ConditionalCompilation = "#if" CompileCondition { Statement | Declaration } { "#elseif" CompileCondition { Statement | Declaration } } [ "#else" { Statement | Declaration } ] "#endif" ;CompileCondition = Expression ; (* restricted: identifiers, os(), arch(), feature(), !, &&, ||, parentheses *)#if regions may enclose statements as well as declarations. The conditions, and the directive rules, are in Lexical Structure.
Local declarations#
Any declaration may be written in a body: functions, structs, classes, unions, enums, aliases, constants. Local declarations are ordinary statements, scoped to their block. A local function that captures nothing is a plain function; one that uses a local of the enclosing function captures it, as a closure does.
fn outer() { fn helper(_ x: Int) -> Int => x + 1 struct Pair { var a: Int, var b: Int } print(helper(Pair { a: 1, b: 2 }.a))}How control leaves a scope#
- A scope is left by reaching its
}, or byreturn,throw,break,continue, atrythat propagates, or a call that returnsNever(fatalError,todo,unreachable, a trap). - On the way out, in this order:
deferblocks run, last written first, andusingbindings are released, last declared first; then every other value going out of scope is destroyed. This happens on the throwing path too. - A function with a result must
returna value, or leave bythroworNever, on every path. Aguard'selsemust leave. - A trap — a failed
precondition, an overflow,!onnone, an index out of range — is not an error that can be caught: it ends the program (or, undersable test, the test's process). Panics are not catchable in normal code.