9. Statements and control flow
Statements and the Unit rule
Section titled “Statements and the Unit rule”A block, and a function, lambda or test body, is a sequence of statements: a
binding (§6), an expression, defer, with, an assertion, return, break
or continue. Statements end at a newline (§2).
- A statement before the last one that is an expression must have type
Unit, unless it is adbgobservation. Its value would otherwise be lost:1 + 2there is the errornon-final expression has type Int, but only Unit results can be ignored — write `_ = ...` if intentional, use `dbg ...` to inspect it, or move it to the end to return it. Discard a value with_ = expr. - The last statement of a body whose return type is
Unit, written or omitted, may be adbgobservation:dbg expr, or a pipe whose last stage is|> dbg. The body returnsUnit. Any other last statement whose type is notUnitis the errorreturn type mismatch: expected Unit, got Int. - A statement after one that always exits is unreachable code and an error (§7 Returning).
import std::io fn main() total = 2 + 3 io.print("computed") [1, 2, 3] |> Iter.map(&(&1 * total)) |> Iter.to_list() |> dbg end
Taught in App Fields, Defer and Context.
defer call(args) registers a call to run when the enclosing block ends.
- The operand is a call. Anything else is the error
`defer` requires a function call. The call returnsUnit:defer g()with agthat returns aResult<Int, String>is`defer` call must return Unit, got Result<Int, String>. A call of a function value works (defer f()). - Operands are evaluated where the
deferstands. The function and its arguments are evaluated when the statement runs, with the bindings and the application fields (§15) in scope there. The call runs later with those values. - It runs when its block ends, the most recently registered first. A block
is a function, lambda or test body, an
ifbranch, acasearm, a binding’selsebody, aconcurrentbody or abeginblock. Adeferin a lambda runs when that call of the lambda ends, so one in anIter.loopor other iteration callback runs at the end of each iteration, before the next starts. - Every way out of the block runs it: reaching its end,
return, a callback’sbreakorcontinue, a?that propagates a failure, and a trap. A task stopped by cancellation runs its pending deferred calls as it unwinds (§16). A deferred call that traps does not stop the ones registered before it, and does not hide the failure that ended the block. - It is a statement.
x = defer f()is a parse error (unexpected `defer`). At file level it is the errorthis statement cannot be written at file level: a file holds declarations, and code runs inside a function. - A pending
deferstops a tail call. A call in tail position while adeferin a block around it is pending is an ordinary call, since the deferred call runs after it returns (§7 Tail-call optimization). Recursion that registers adeferat each step keeps a frame per step and counts toward the recursion depth limit (§7 Recursion depth). Adeferin a block that has ended, such as a branch of an earlierif, is not pending. - A function that uses
breakorcontinuecannot be the deferred call (§13 Named Functions as Callbacks). - In an entry file’s
boot, adeferwritten directly in its body runs aftermainand the tasks it owns have finished. In a test, one inbootorsetupruns when that test finishes, also when the test called boot itself (§15, §17).
defer on error call(args) registers a call that runs only if the block
is left through an error exit, and is dropped otherwise. It is otherwise a
defer: its operand is a Unit call evaluated where it stands, and it is on
the same list as the block’s other deferred calls, so it runs in its place
among them, most recent first.
- An error exit is a trap (and a cancelled task’s unwinding), or the
function, lambda or test body returning
Err(...)when its result is aResult, orNonewhen it is aMaybe, whichever way it returns it: a?that propagates,return Err(e), or a last expression that is anErr. - Anything else is a normal exit, and drops the call unrun: the block
reaching its end, a
returnor last expression of any other value, and a callback’sbreakorcontinue. Adefer on errorin a nested block whose end is reached is dropped there, even if the function fails later. - The function must be able to fail. In a function whose result is
neither a
Resultnor aMaybe, where only a trap could run it, it is the error`defer on error` runs only when `f` fails, and it returns Int, which carries no failure; write `defer`. on erroris not reserved. The two words open the form only right afterdeferon its line;onanderrorstay names everywhere else, anddefer on(x)defers a call ofon.- A function that registers one makes no tail call while it is pending, as
for
defer.
import std::io fn note(label: String) io.print(label) end fn half(n: Int) -> Result<Int, String> defer note("done") defer on error note("failed ${n}") if n % 2 != 0 then return Err("odd") Ok(n / 2) end fn main() _ = half(4) // done _ = half(3) // failed 3, done end
import std::io fn work(n: Int) -> Int defer io.print("a ${n}") defer io.print("b ${n}") io.print("work ${n}") n + 1 end fn main() _ = work(1) // work 1, b 1, a 1 Iter.each([1, 2], fn i -> defer io.print("end ${i}") io.print("body ${i}") end) // body 1, end 1, body 2, end 2 end
Releasing resources
Section titled “Releasing resources”Taught in Files.
A type that holds something outside the program (a file, a process, a
connection) implements the prelude interface Release, and a type whose
release throws away work done with the value also implements Commit<E>:
pub interface Release fn release(value: self) -> Unit end pub interface Commit<E> fn commit(value: self) -> Result<Unit, E> end
The body of an impl’s release or commit is one call, which names the
type’s usual release or commit: impl Release for Writer calls
Writer.discard(w), and impl Commit for Writer calls
Writer.close(w). In std, Reader releases with Reader.close_quietly,
Writer with Writer.discard and commits with Writer.close, File with
File.close_quietly, Child with Child.kill, http.StreamedResponse
(what http.stream returns) with StreamedResponse.close, and sql.Conn
with sql.close_quietly. A type of the program’s own may implement either.
An acquisition must be released. An acquisition is a call whose result is
a value of a Release type, or a Result with one in its Ok, and which
names no value of a Release type outside a lambda. Opening can fail
(fs.open, fs.create, process.spawn, http.stream, a database
driver’s open) or not (postgres.pool, a program’s fn lock() -> Lock).
A call given a Release value returns a view of it that its own release
covers: a transaction’s Conn from Conn.begin_transaction(conn), a child’s
Child.stdout(child). Two calls that return a Release value directly are
no acquisition:
- a constructor of a variant or distinct type (
Handle(raw)), which builds the value from parts the body already holds; - a call returning a
Readeror aWriter. std makes them over memory (Reader.from_text(s)) and borrows them from values of no Release type (Body.reader(body),Connection.reader(conn)), none of which the caller releases, so only aResultholding one acquires it.
A Release value that is not a call’s, such as io.stdout, a parameter or a
struct literal, is no acquisition either.
A name a body binds to an acquired value (w = fs.create(path)?, an
Ok(r) arm of a case over one, Ok(r) = fs.open(path) else return) is
released or handed on in that body:
- released: a
deferamong the statements after the binding, in the block the binding is in (or the arm’s block), calls a function that takes it:defer Writer.discard(w),defer Child.kill(child), the type’srelease; - handed on: it is returned, or is the value of its block; it is an
element of a list, set, vector, map, tuple or struct literal, or the
argument of a variant or distinct type’s constructor (
Ok(r),Body.Stream(r)), wherever that value goes; or another name is bound to it.
A defer on error that calls a function taking it releases it on the error
exits only, so it does not count as released on its own: a name with one
and no hand-on is the error `r` is released only if the body fails; write `defer Reader.close_quietly(r)` after it, or return it.
A value handed on is handed on along every path. A name with no defer
that releases it is handed on along each path that returns normally, or
released on it. A normal return is a return whose value is not Err(...)
or None, the body’s last expression through the branches of an if, a
case or a block that ends it, and the end of the block the binding is in.
The path hands the value on when the return’s value carries it (r,
Ok(Some(r)), a struct holding it) or an earlier statement on that path
handed it on, and releases it with a call of the type’s release or commit
that takes it (Reader.close_quietly(r)). A defer on error does not run on
a normal return, so it does not cover one. A path that does neither is the
error `r` leaks here: this path returns without handing it on or releasing it; call `Reader.close_quietly(r)` before the return, at the
return. A plain defer is no fix when another path hands the value on: it
would release that value too (A released value stays in its block, below).
fn maybe_open(path: String, want: Bool) -> Result<Maybe<Reader>, io.Error> r = fs.open(path)? defer on error Reader.close_quietly(r) if not want then Reader.close_quietly(r) // without it, `r` leaks here return Ok(None) end Ok(Some(r)) end
An acquisition whose value is dropped is the error the `Reader` this acquires is never released; bind it and write `defer Reader.close_quietly(reader)` after it: one bound to _
(_ = fs.open(path)?), and one that is the last expression of a body whose
value nothing takes, a test’s or a callback’s whose result is Unit (the
function Iter.each calls). Any other statement whose value is not Unit
is already an error.
Passing it to a call is a use, not a hand-on: the check reads one body and
does not follow the value into the callee, so a function that releases a
parameter does not release its caller’s acquisition. A body is a function’s,
a lambda’s or a test’s, each checked on its own. A name that is neither is
the error `r` is never released; write `defer Reader.close_quietly(r)` after it, or return it, at the binding, which names the type’s usual
release. A defer inside an if releases on one path only, so it does not
count.
A released value stays in its block. A deferred call runs when its block
ends, so a value it releases is released by the time anything outside the
block sees it. When a defer calls a function given a value of a Release
type, written as a name or a field path (db, db.conn), that value must
not leave the defer’s block after it: not as the block’s value, not in a
return, not inside a literal or a constructor that does (Ok(r),
App{store: db}), not through a name bound to one, and not captured by a
lambda that does. A value holding the released one counts too:
defer sql.close_quietly(db.conn) releases part of db, so db stays in
the block as well. Each is the error this `defer` releases `db.conn` when the block ends, but `db` leaves the block as its value; defer the release where `db` is finally used, or hand `db` on without deferring it here, at
the defer. Using the value in the block, passing it to a call, and a
defer in an outer block are fine. A defer on error is not held to this:
its release runs only when the block fails, so the value it covers is meant
to leave on the success path.
An error exit before the hand-on releases. In a body whose result is a
Result or a Maybe, or a test’s, an error exit between a binding and the
statement that defers its release, or, with no defer, the statement that
hands it on, leaks the value: a ? that propagates, or a return of
Err(...) or None, outside a lambda. With no deferred release it is the
error `conn` leaks if this `?` returns an error: it isn't released on that path; add `defer on error sql.close_quietly(conn)` after acquiring it
(if this `return` runs for a return), at the first such exit. With a
defer or a defer on error after it, the error says to move it up to
right after the binding. A trap and ! are not checked; the program stops.
The check stops at the first statement that hands the value on, so an
error exit after the value is stored in a struct that is later returned is
not seen.
pub fn open(path: String) -> Result<SqliteStore, sql.Error> conn = sqlite.open(path)? defer on error sql.close_quietly(conn) // released if a later `?` fails _ = Conn.exec(conn, Sql"CREATE TABLE IF NOT EXISTS notes (body TEXT)")? Ok(SqliteStore{conn:}) end
fn open_app(kind: String, path: String) -> Result<App, sql.Error> store = case kind "sqlite" -> db = sqlite_store.open(path)? defer sql.close_quietly(db.conn) // error: `db` leaves the block as its value db _ -> memory_store() end Ok(App{store:}) end
A deferred discard needs a commit on every normal return. When the
deferred call is a Commit type’s usual release (Writer.discard, which drops
a ReplaceAtomically writer’s temporary file), every path from the defer
that returns normally calls the commit, or the release itself, which discards
on purpose, before it returns. A normal return is a return or a block’s
last expression that is not Err(...) or None, and the end of a function
whose result is Unit; the end of the block the defer is in, when that
block is not the body’s last, discards too. A path that leaves by ?,
return Err(...), unreachable or a trap needs no commit, and neither does a
commit inside a lambda on the path, which counts as made. A path without one
is the error `w` is discarded here: this path returns without `Writer.close(w)?` at that return, written with ! in a body whose result
is neither a Result nor a Maybe. A deferred release that commits as it
releases (Writer.close_quietly, File.close_quietly) needs nothing more; a
failed close is then dropped, so the success path writes Writer.close(w)?
when it must report one.
fn save(path: String, rows: List<String>) -> Result<Unit, io.Error> w = fs.create(path, mode: .ReplaceAtomically)? defer Writer.discard(w) Writer.write_lines(w, rows)? if rows == [] then return Ok(Unit) // `w` is discarded here: this path returns without `Writer.close(w)?` end Writer.close(w)? Ok(Unit) end
The editor’s quick fix for an unreleased name writes the defer after the
binding and, for a Commit type, the commit before each return that lacks
it; the one for a dropped acquisition first binds it to a name; the one for
a missing commit writes the commit; the one for an error exit that leaks
writes the defer on error after the binding; the one for a normal return
that leaks writes the release before it, when the return starts its line.
break and continue
Section titled “break and continue”Taught in Iteration and Loops.
break and continue act on an iteration. They are valid only in a callback
passed to one of the iteration functions that take them (§13 Callbacks that
take break and continue), and in a named function passed as such a
callback (§13 Named Functions as Callbacks).
continueskips the rest of this element or round. It takes no value:continue xis the errorcontinue takes no value; it goes to the next iteration with the loop state or accumulator unchanged. To carry a new value forward, make it the callback's result: write it as the last expression, without continue (in Iter.loop that result is the next state).breakstops the iteration with what has accumulated so far.break valuestops it aftervalueis taken as this element’s result.- They leave only the callback they are written in. Nomi has no non-local control flow and no exceptions.
- They may be a
casearm’s body or anifbranch’s. - Outside an iteration callback they are an error. In a lambda that is not one
the error is
'break' can only be used inside an iter-callback (e.g. a lambda passed to Iter.map/Iter.filter/Iter.loop/etc.). In a named function never passed as a callback it is'main' uses break/continue but has no iter-callback call site — break/continue can only be used where an iter-callback (Iter.map/Iter.filter/Iter.loop/etc.) can catch them.
fn main() total = Iter.loop(0, fn n -> case n 3 -> break n _ -> n + 1 end end) dbg total // 3 end
with App.field = value replaces one application field from that line to the
end of its block. It is defined in §15.
assert and refute outside tests
Section titled “assert and refute outside tests”An assert or refute in a function body returns Err(AssertionFailure) from
the function when it fails (§17). The function must return a
Result<_, AssertionFailure>; otherwise the assertion is the error `assert` can return AssertionFailure, but the enclosing function returns Unit. An assertion in a lambda is an error.
import std::assertions.AssertionFailure fn checked(n: Int) -> Result<Int, AssertionFailure> assert n > 2 Ok(n) end fn main() dbg Result.is_ok(checked(3)) // True dbg Result.is_ok(checked(1)) // False end