11. Failure
Taught in Pattern Matching.
Maybe and Result
Section titled “Maybe and Result”Maybe<T> is a value that may be absent, and Result<T, E> the outcome of an
operation that may fail. Both are prelude enums, and their variants are
written bare (§10 Variant patterns):
enum Maybe<T> Some T None end enum Result<T, E> Ok T Err E end
A program handles one with case, a pattern if, a binding with else (§10
Bindings with else), ? (Propagating with ?) or ! (Unwrapping with
!). The functions over them are in std::maybe and
std::results.
std::presence’s Presence<T>, Present(value) or Absent, says whether an
input gave a value at all, so Presence<Maybe<T>> tells a JSON key left out
(Absent) from one set to null (Present(None)). It is not in the
prelude, and its functions are in std::presence.
Absent is no failure, so ? and ! do not take a Presence: p? is the
error `?` requires a Result or Maybe, got Presence<Int>, and where
absence is a failure the program writes Presence.to_maybe(p)?.
Propagating with ?
Section titled “Propagating with ?”Taught in Pattern Matching.
expr? unwraps a Result or a Maybe. On Ok(v) or Some(v) its value is
v. On Err(e) or None the nearest function boundary returns Err(e) or
None at once:
x? ≡ case x { Ok(v) -> v, Err(e) -> return Err(e) }
x? ≡ case x { Some(v) -> v, None -> return None }
fn total(a: String, b: String) -> Maybe<Int> x = String.to_int(a)? y = String.to_int(b)? Some(x + y) end fn main() dbg total("2", "3") // Some(5) dbg total("2", "x") // None end
- It binds as tightly as a call.
f(x)?,load()?.name(the loaded value’sname),user.address?.cityanda.b()?.c()?. After a!it applies to the payload, sohalf(4)!?is`?` requires a Result or Maybe, got Intunless the payload is itself aResultorMaybe.not ready(x)?isnot (ready(x)?). - In a pipe it follows a stage (§8 Pipes).
|> then? fn v -> ...propagates the lambda’s result, andtap?is an error (§8 Thetapstage). - A boundary is the enclosing
fn, lambda or test body, or aconcurrentblock (§16). A?in a lambda returns from the lambda, so the lambda’s result is aResultorMaybe. A failing?in a test body ends the test with a report of the?and its value (§17). - Some places have no boundary. A
?written directly in aonceinitializer, a parameter or field default, or asubtestsrow or row name is a compile error:`?` cannot be used in the initializer of `once port`: a `once` has no function to return from(§6, §7 Default Arguments, §4 Default Values, §17). A lambda inside one is a boundary of its own.
The propagated value must fit the boundary’s declared result. Three rules,
each checked at the ?:
- The boundary returns a
Resultor aMaybe.`?` cannot propagate a Result out of a function returning Int: the enclosing function must return a Result or a Maybe. A function with no declared result returnsUnitand has the same error. - The kinds agree. A
?on aResultneeds aResultboundary, and one on aMaybeaMaybeboundary:`?` on a Maybe cannot propagate out of a function returning Result<Int, String>: the enclosing function must return a Maybe. In a lambda this is the lambda’s result. - The error type fits the boundary’s, or converts to it. For a
?on aResult<T, E>in a function declaredResult<_, F>, in this order:- E is F, or F is an interface E implements, and the
Err(e)propagates as it is, as an interface-typed parameter takes an implementor; - else F has an
impl From<E>(std’sFrom, in the prelude), and the function returnsErr(F.from(e)); - else the
?is an error naming both fixes:`?` error type mismatch: expected ApiError, got DbError (the enclosing function returns Result<Int, ApiError>); write `impl From<DbError> for ApiError` and the `?` converts the error, or convert it before the `?` with Result.map_err. It names the impl only when one of the two types is not std’s, since an impl between two std types is an orphan (§12 Foreign Types). Its help writes themap_errstage when one is plain: the boundary enum’s one variant whose payload is the error (|> Result.map_err(AppError.Io)?), or, for aStringboundary and an error with aDisplayimpl,|> Result.map_err(&"...: ${&1}")?.
- E is F, or F is an interface E implements, and the
A domain error type writes one From impl for each error it wraps, and each
? converts:
enum DbError Closed end enum ApiError Database DbError NotFound String end impl From<DbError> for ApiError fn from(e: DbError) -> ApiError ApiError.Database(e) end end fn count(open: Bool) -> Result<Int, DbError> if open then Ok(3) else Err(.Closed) end fn total(open: Bool) -> Result<Int, ApiError> n = count(open)? Ok(n + 1) end fn main() dbg total(True) // Ok(4) dbg total(False) // Err(Database(Closed)) end
- The impl is on the target.
From<E>is implemented for F, not for E:impl From<sql.Error> for ApiError. E is an input ofFrom(§12 Foreign Types), so a module may also writeimpl From<MyError> for String. - One conversion. The
?looks up F’s impl at E only. It does not followimpl From<IoError> for DbErrorand thenimpl From<DbError> for ApiError; a?on anIoErrorthere is the mismatch. - No identity impl. Equal types need none, and std declares none.
- Only a declared boundary converts. An inferred boundary (below) has no declared error type to convert to.
- The impl is an ordinary function.
ApiError.from(e)and|> ApiError.from()call it.
Result.map_err converts at one site, for a conversion that is that
function’s own:
fn status(text: String) -> Result<Int, Int> String.to_int(text) |> Maybe.to_result(400) end fn port(text: String) -> Result<Int, String> n = status(text) |> Result.map_err(&"error ${&1}")? Ok(n) end fn main() dbg port("x") // Err("error 400") end
Inferred boundaries. At a boundary with no declared result (a concurrent
block, an unannotated lambda) the error type is inferred from the ? sites in
it. A body whose last expression is Ok(...) fixes only the success type.
// outcome: Result<Int, String>; String comes from `Task.await(t)?` outcome = concurrent t = Task.spawn(fn -> fetch()) // fetch(): Result<Int, String> Ok(Task.await(t)?) end
?sites with different error types in one boundary are the errorinconsistent error types in `?` expressions: String vs Int. A?on aMaybecontributes no error type.- When no
?fixes the error type, it stays open, asOk(1)’s does (§5). - Rules 1 and 2 apply to the result the body produces:
`?` cannot propagate a Result out of a lambda whose result is Int: the lambda must produce a Result or a Maybe.
Unwrapping with !
Section titled “Unwrapping with !”Taught in Pattern Matching.
expr! unwraps a Result<T, E> or a Maybe<T>. Its value is the T in Ok
or Some. An Err or a None traps at the !’s line. It states that the
value is there, so a failure is a bug in the program.
fn half(n: Int) -> Result<Int, String> if n % 2 == 0 then Ok(n / 2) else Err("${n} is odd") end end fn main() ages = {"Ada" => 36} dbg Map.get(ages, "Ada")! // 36 dbg half(10)! // 5 dbg "42" |> String.to_int()! // 42 end
-
Any expression takes it: a call of any form, a field (
user.nickname!), a name (found!), a parenthesized expression ((a |> b())!). It binds as tightly as a call or field access, souser.address!.cityreads the payload’scity. As a pipe stage it unwraps the stage’s result. In a capture,&half(&1)!isfn x -> half(x)!. -
It is written against the expression, with no space, on its line. A
!that starts the next line is the C-family negation, an error (§8 Logical operators).x!= yisx != y; to compare an unwrapped value, writex! == y.not found!negatesfound!. -
The operand must be a
Resultor aMaybe. Anything else is an error at the!:`!` unwraps a Result or a Maybe, and `count(1)` is Int, whose help says to remove the!. For aBool, the help says to write anassert. -
The trap quotes the expression as written, on one line, cut after 60 characters with
.... AnErr(e)showseby itsDisplaywhen its type implementsDisplay, and by itsDebugotherwise. ANonesays it found nothing:line 7: `half(3)` failed: 3 is odd line 4: `Date.new(2024, 13, 1)` failed: invalid value: month out of range: 13 line 3: `Map.get(counts, "z")` found nothingThe line is the
!’s, even when the failure comes from inside the standard library (Where a trap is reported). On success a!costs the test of the variant. -
!is for a value the program knows is there: constant arguments (Date.new(2024, 1, 1)!), a key taken from the map itself, an index computed in range, input already validated. A failure that can happen is aMaybeorResultto handle, or to pass on with?.
Traps, Maybe and Result
Section titled “Traps, Maybe and Result”An operation that cannot always give the result asked for returns a Maybe
or Result, or takes a type that rules the failure out. std returns a
Maybe or Result when the outcome depends on data the caller does not
control (Map.get, String.to_int, I/O). Where the caller can check an
operand first, the parameter’s type requires the check: / and % take a
NonZeroInt divisor, so dividing by an Int that may be zero does not
compile (§8 Integer division and remainder). Writing Nomi’s
Pick the tool by what happens on failure applies the same rule
to code a program writes.
A trap stops the task it happens in, with a message. A program traps where it asks to:
- a
!on anError aNone(Unwrapping with!), such as an index it computed and unwrapped (Vector.get(v, i)!); - an
unreachableit reaches, or atodoit left in; Task.awaitof a task that failed or was cancelled (§16 Errors and cancellation).
Beyond those, a run stops when it:
- runs out of memory, or makes more than 100,000 nested calls (
stack overflow: more than 100000 nested calls); - asks std for a value too large to build: a
Decimalwhose scale is outside -2147483648 to 2147483647 or that has more digits than aDecimalholds (Decimal.sqrt(2d, 4294967298, .HalfEven);Decimal.round,Decimal.powandFloat.to_decimaltoo), or aString.repeatof more copies than memory holds; - consumes the whole of an iterator that never ends (§13 Infinite iterators);
- closes a
oncecycle through a function value (§6onceBindings).
Any other program that never finishes runs until something outside stops it.
- A trap is never caught inside the program. It ends the task it happens
in: a program’s main task ends the program with status 1, and a spawned
task’s trap is its
Failedoutcome (§16), which a supervisor may restart.
A function named get returns a Maybe (Map.get, Vector.get, Bytes.get,
Iter.get). A caller that knows the value is there writes Map.get(m, k)!. A
map pattern is refutable for the same reason (§10 Map Destructuring).
Where a trap is reported
Section titled “Where a trap is reported”A trap prints line N: and then its own text: line 4: `Int.from_digits(ds, 2)` found nothing,
line 8: unreachable: chunk_by never yields an empty run.
Nis a line of the program’s own code: the line of the operation that trapped or, when the trap happens inside the standard library, the line of the program’s call into it, however many std calls deep.shown = Decimal.format(1.5d, locale, fraction: Range.from(4_294_967_298))on line 2, which rounds through a std function ofDecimal.format’s own, printsline 2: Decimal.round: scale 4294967298 is past a Decimal's, which is -2147483648 to 2147483647.- A lambda of the program that traps while a std function runs it
(
Iter.map(xs, fn i -> Vector.get(v, i)!)) is the program’s code, so the trap names the lambda’s line. - A trap whose own text names no line (a host function’s, such as
Decimal.sqrtwith a scale past aDecimal’s) gets the line of the program’s call. - A
todonames its own file and line instead (Unwritten code:todo). nomi run,nomi test, a built executable and the REPL print the same line.
Unwritten code: todo
Section titled “Unwritten code: todo”Taught in Functions and Lambdas.
todo is a placeholder for code not written yet. It is an expression, bare or
with a reason: todo or todo "parse the header".
fn parse(text: String) -> Int todo "parse the header" end
- Type.
todonever produces a value, so it has the type its position expects: a function’s result, an annotated binding, an argument, a struct field, an arm or branch (whose type the others decide), a lambda body, a pipe stage, a generic function’s result, a condition, or an operand whose type its operator decides (not todoisBool,n == todohasn’s type). As a statement it isUnitand does not exit. An unannotated binding expects nothing, sox = todois the errorcannot infer a type for 'x' from `todo`: annotate the binding (`x: T = todo`)._ = todois accepted. - Reason. A string literal:
"...","""..."""or a raw backtick string. An interpolated or tagged reason is the parse errora `todo` reason is a plain string literal: it cannot interpolate or carry a tag. - Running it. Reaching a
todotraps withtodo reached at <file>:<line>, then: <reason>when there is one. The file is relative to the working directory. As a pipe stage, the piped value is computed first. - Unread names. A function or lambda whose body holds a
todohas its parameters exempt from the never-read error, and so are the names an arm, anelsearm, anifcondition or a test’s setup binding binds when the body they scope over holds one. - Builds.
nomi buildrefuses a program that holds atodo(tooling reference). - A name.
todois a contextual keyword (§2 Keywords): a baretodoin the scope of a binding namedtodoreads the binding, andtodo "reason"is the placeholder everywhere.
Unreachable code: unreachable
Section titled “Unreachable code: unreachable”Taught in Functions and Lambdas.
unreachable "reason" claims that the program never reaches this point.
Reaching it traps.
fn encode_run(run: List<String>) -> String case run [letter] -> letter [letter, ..] -> "${Iter.count(run)}${letter}" [] -> unreachable "chunk_by never yields an empty run" end end fn main() dbg encode_run(["a", "a"]) // "2a" end
- Type. As
todo’s. An unannotated binding of one iscannot infer a type for 'x' from `unreachable`: annotate the binding (`x: T = unreachable "..."`). - Reason. Required, a string literal in the forms a
todoreason takes. A bareunreachableis`unreachable` needs a reason. - It exits. A statement after an
unreachablestatement is the errorunreachable code after `unreachable`. It is finished code: a function that holds one still reports a parameter it never reads, andnomi buildaccepts it. - Running it. Reaching it traps with
line N: unreachable: <reason>at the program’s line. It always traps, in every build; the compiler never optimizes on it.
Error types
Section titled “Error types”The E of a Result<T, E> may be any type: String, an enum of the
program’s, Int. There is no built-in Error type or interface. An error type
that implements Display renders where a message is needed: io.print(e),
"${e}", and the text a failing main prints (§15).
enum UserError NotFound Int InvalidName String end impl Display for UserError fn to_string(e: UserError) -> String case e .NotFound(id) -> "user not found: ${id}" .InvalidName(name) -> "invalid name: ${name}" end end end fn main() dbg "${UserError.NotFound(3)}" // "user not found: 3" end