Home / Docs / Language guide
Expressions and control flow
5.1 Blocks, let and statements
A block is a sequence of statements followed by a final expression, which is the block's value.
module demo
pub kind Seats = Int in 0..5000
pub kind Availability = SoldOut | Few | Open
pub kind Event
name: Text
remaining: Seats
clamp_seats(raw: Int) -> Seats = if raw < 0 then 0 else if raw > 5000 then 5000 else raw
availability(e: Event) -> Availability = if e.remaining == 0 then SoldOut else if e.remaining < 20 then Few else Open
pub status(n: Text, raw: Int) -> Availability
=
let seats = clamp_seats(raw)
let event: Event = Event(name: n, remaining: seats)
availability(event)- A plain
letis immutable. An editable binding is declaredlet edit(§5.6). - A statement that is not a
let, an assignment, aforloop, atogetherblock or anifwithoutelsemust have typeUnit(U2011). To ignore a value, bind it. - A
letwhose right-hand side is in RL keeps an exact fact that later proofs can use: afterlet half = total / 2, the verifier knowshalf == total / 2. Aletbound to a function call keeps only what that function'sensurespromises.
5.2 if
module demo
pub size(n: Int) -> Text = if n > 100 then "large" else "small"
pub band(n: Int) -> Text
=
if n > 100
"large"
else if n > 10
"medium"
else
"small"ifused as an expression always has anelse.- In edition
0.2, a block-formifwithoutelseis a statement of typeUnit, used to update editable bindings (§5.5).
5.3 when
module demo
pub kind Seats = Int in 0..5000
pub kind Availability = SoldOut | Few | Open
pub kind Registration
name: Text
pub kind Lookup = Found(registration: Registration) | Missing
--- Variants.
pub label(status: Availability) -> Text
=
when status
is SoldOut -> "sold out"
is Few -> "few seats left"
is Open -> "open"
--- A payload bound by its field name, or under another name.
pub name_of(lookup: Lookup) -> Text
=
when lookup
is Found(registration) -> registration.name
is Missing -> "unknown"
pub name_again(lookup: Lookup) -> Text
=
when lookup
is Found(registration: r) -> r.name
is Missing -> "unknown"
--- Ranges, proven to cover every `Seats` value.
pub band(remaining: Seats) -> Availability
=
when remaining
in 0..0 -> SoldOut
in 1..<20 -> Few
in 20..5000 -> Open
--- Literals, with `else`.
pub reason(code: Int) -> Text
=
when code
is 200 -> "ok"
is 404 -> "not found"
else -> "other"
--- A block arm.
pub greeting(status: Availability) -> Text
=
when status
is SoldOut ->
let note = "try another date"
note
else -> "welcome"Rules:
- Variant arms must be exhaustive, or end with
else(U2007). - Range and literal arms without
elsecreate an obligation: the compiler must prove the arms cover every value the subject can take. WithSeats = Int in 0..5000, the three ranges above are proven exhaustive. Arms over a fixed-width value take its type, and a bound that does not fit is U2022. elsemust be the last arm, and unreachable arms are rejected (U2008).- Single-field variants bind their field under any name:
is Some(r). - Results of
attemptare matched withis Ok(value)andis Err(failure)(§6.4).
5.4 One effect per line
A capability operation, a call to a function that uses capabilities or can fail, or a call with an edit or take argument, must be the whole expression of a statement, a let or a final expression, optionally wrapped in attempt (U3013). It cannot be nested inside another expression.
module demo
pub kind Availability = SoldOut | Few | Open
pub kind Registration
name: Text
status: Availability
pub kind StoreError = | Timeout
pub kind CheckInError = NotRegistered | Unavailable
pub capability Registrations
op find(key: Text) -> Option[Registration]
fails StoreError
pub status_of(key: Text) -> Availability
uses @registrations: Registrations[find]
fails CheckInError
=
let registration = @registrations.find(key)
if error fail Unavailable
if none fail NotRegistered
registration.status-- fails with U3013
module demo
pub capability Store
op get(key: Text) -> Int
double(x: Int) -> Int = x * 2
pub doubled(key: Text) -> Int
uses @store: Store[get]
=
double(@store.get(key))This fixes evaluation order, gives every failure a handling site and makes every effect visible on its own line. Pure calls nest freely. Example do lines are exempt (§10).
5.5 for loops (edition 0.2)
for x in xs visits the elements of a list in order, and for i in a..<b or for i in a..b the integers of a range in increasing order (spec/17 §1, §4).
module demo
--- A `for` loop over a list, updating a `let edit` binding.
pub total(xs: List[Int]) -> Int
=
let edit sum = 0
for x in xs
sum = sum + x
sum
--- Over a range: `a..<b` excludes `b`, `a..b` includes it. The bounds are evaluated once.
pub squares(n: Int) -> List[Int]
=
let edit out: List[Int] = []
for i in 0..<n
out = out.append(item: i * i)
out
--- The loop variable takes the integer type of the bounds: here `U8`.
pub bytes(low: U8, high: U8) -> List[U8]
=
let edit out: List[U8] = []
for b in low..high
out = out.append(item: b)
out
--- An `if` without `else` is a statement.
pub count_large(xs: List[Int], limit: Int) -> Int
=
let edit count = 0
for x in xs
if x > limit
count = count + 1
count- The bounds, and the list, are evaluated once, before the first iteration. There is no
breakand nocontinue. - The loop variable is a plain binding (U2019 on assignment). A range's bounds are integers of one type,
Intor a fixed-width type, and a literal bound takes the type of the other, sofor b in low..highoverU8bounds givesb: U8. An inclusive range ends at its upper bound without computing its successor, so0..255overU8does not overflow. - As a statement, a loop has the value
unit. It updateslet editbindings declared before it. - Verification. The refinements of the bindings the loop updates are its invariant: the body is checked once, for any iteration, with those bindings fresh at their declared types, and no fact about their values survives the loop. Inside a range loop,
a <= i < b(or<= b) holds. There is noinvariantclause. - Failures inside the body end the loop and the function; the bindings it updated keep their values from before the loop (§5.6).
- Labels. A loop over a list runs under the top label of the list, and a range loop under the labels of its bounds. In such a body,
failand calls that can fail are U4002 when that label is notpublic. - Edition
0.4addsstopandskip, which end a loop or an iteration early,for until c decreases m, which runs untilcholds, andfor everwithon stopin a function that saysdiverges, which runs until it is stopped (spec/26 §3 to§6). See Loops that run until stopped.
5.6 Mutable value semantics (edition 0.2)
Una has no references and no lifetimes: values stay values, and a binding declared editable can be rebound (ADR 0056, spec/17).
let edit x = edeclares an editable binding, andx = erebinds it. A place is an editable binding or a field path of one:t.last = valuerebuildstwith that field changed. Assigning anything else is U2019.- Fixed type. An editable binding keeps its declared type, refinement and label at every rebind; each rebind carries the refinement obligation of an annotated
let. Without an annotation, its type is that of its initial value without its refinement. editparameters are passed in and out:record(edit t: Tally, ...)receives the caller's value and returns its final value. The caller writesedit tat the argument (U2020 for a missing or extra marker), and the argument is a place. Inensures,tis the final value andold(t)the value on entry.takeparameters consume their argument: afterf(take a), usingais U2017 until an assignment gives it a new value.- Exclusivity. An
edit pargument together with any other use of the root binding ofpin the same call is U2018. - Lists change through
setandappend:edit ys.set(index: i, item: v), withrequires 0 <= index and index < xs.len. - Transactional values. A call that fails leaves its
editarguments unchanged for the caller. Effects already performed stay performed. - Operations and handlers cannot declare
editortakeparameters (U2020).
module demo
pub kind Tally
seen: Int
last: Int
--- An `edit` parameter is passed in and out; `old(t)` is its value on entry.
pub record(edit t: Tally, value: Int) -> Unit
ensures t.seen == old(t).seen + 1
=
t.seen = t.seen + 1
t.last = value
pub tally(xs: List[Int]) -> Tally
=
let edit t = Tally(seen: 0, last: 0)
for x in xs
edit t.record(value: x)
t
--- `take` consumes its argument: the caller cannot use it afterwards.
pub finish(take t: Tally) -> Int = t.seen
pub summary(xs: List[Int]) -> Int
=
let t = tally(xs)
let n = finish(take t)
n
--- List elements change through `set`.
pub reset_first(xs: List[Int]) -> List[Int]
=
let edit ys = xs
if ys.len > 0
edit ys.set(index: 0, item: 0)
ys-- fails with U2017
module demo
pub finish(take xs: List[Int]) -> Int = xs.len
pub twice(xs: List[Int]) -> Int
=
let n = finish(take xs)
xs.len + n-- fails with U2019
module demo
pub bump(x: Int) -> Int
=
let n = x
n = n + 1
nA backend may update a uniquely held value in place, and reuse the memory of a value passed by take. None of this is observable.
5.7 Concurrent tasks with together (edition 0.2)
together runs independent work as concurrent tasks, and every task ends before its block does (ADR 0065, spec/19). A program's result and its trace are those of running the tasks one after another, in order.
module demo
pub capability Sensor
op reading() -> Int
pub kind FetchError = Missing | Gone
handler fixed(value: Int) for Sensor
op reading() = value
pub warmest() -> Int
uses @north: Sensor[reading]
uses @south: Sensor[reading]
=
together
let north = reading() with @sensor = @north
let south = reading() with @sensor = @south
max(north, b: south)
reading() -> Int
uses @sensor: Sensor[reading]
=
@sensor.reading()
fetch(id: Int) -> Int
fails FetchError
=
if id < 0
fail Missing
else
id * 10
--- One task per element; the results come back in list order.
pub pages(ids: List[Int]) -> List[Int]
fails FetchError
=
let pages = together for id in ids
fetch(id)
if error pass
pages
--- Over a range, the variable takes the integer type of the bounds.
pub doubled(n: U8) -> List[Int]
=
let out = together for i in 0..<n
i.to_int() * 2
outtogetheris a statement whose indented body holds two or moreletstatements, its branches (U2024 otherwise). Each branch's expression, with itswithbindings and its handling clauses, runs as a task. The branches' bindings are in scope after the block.together for x in xsstands where aletvalue can, and runs one task per element of a list or of a range. Its body is a block, and the result is the list of the body's values, in element order. Over a range,xtakes the integer type of the bounds, as in aforloop.- Handling clauses go on their own indented lines below the call, as everywhere (§6.3).
- Captures. A task sees the bindings before the block, never its siblings', and captures their values. Assigning a binding declared outside the task, or passing it as
editortake, is U2023: return new values from the task instead. - Capabilities in scope can be used by every task, and so can
uses ofparameters. - Failures. When a task fails, the tasks after it are canceled, and the block fails with the failure of the lowest-indexed failing task, as running the tasks one after another would. A canceled task stops at its next call, operation or loop iteration; an operation in progress completes.
- Labels.
together forruns its tasks under the top label of its list, or the labels of its range bounds, as aforloop does, and its result carries that label. - Traces list the events of the tasks in task order, each with its task's path, as
"task": "2.1". A canceled task that had started ends with acancelledevent. - Runtimes. The interpreter runs the tasks one after another. A native executable runs the tasks on
--workersthreads, one per core by default, so the lines that tasks print may interleave.
-- fails with U2023
module demo
bump(edit n: Int) -> Int
=
n = n + 1
n
pub count(xs: List[Int]) -> Int
=
let edit seen = 0
together
let a = xs.len
let b = bump(edit seen)
seen + a + b-- fails with U2024
module demo
pub one() -> Int
=
together
let a = 1
a