Skip to content

11. Failure

Taught in Pattern Matching.

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)?.

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’s name), user.address?.city and a.b()?.c()?. After a ! it applies to the payload, so half(4)!? is `?` requires a Result or Maybe, got Int unless the payload is itself a Result or Maybe. not ready(x)? is not (ready(x)?).
  • In a pipe it follows a stage (§8 Pipes). |> then? fn v -> ... propagates the lambda’s result, and tap? is an error (§8 The tap stage).
  • A boundary is the enclosing fn, lambda or test body, or a concurrent block (§16). A ? in a lambda returns from the lambda, so the lambda’s result is a Result or Maybe. 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 a once initializer, a parameter or field default, or a subtests row 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 ?:

  1. The boundary returns a Result or a Maybe. `?` 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 returns Unit and has the same error.
  2. The kinds agree. A ? on a Result needs a Result boundary, and one on a Maybe a Maybe boundary: `?` 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.
  3. The error type fits the boundary’s, or converts to it. For a ? on a Result<T, E> in a function declared Result<_, 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’s From, in the prelude), and the function returns Err(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 the map_err stage when one is plain: the boundary enum’s one variant whose payload is the error (|> Result.map_err(AppError.Io)?), or, for a String boundary and an error with a Display impl, |> Result.map_err(&"...: ${&1}")?.

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 of From (§12 Foreign Types), so a module may also write impl From<MyError> for String.
  • One conversion. The ? looks up F’s impl at E only. It does not follow impl From<IoError> for DbError and then impl From<DbError> for ApiError; a ? on an IoError there 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 error inconsistent error types in `?` expressions: String vs Int. A ? on a Maybe contributes no error type.
  • When no ? fixes the error type, it stays open, as Ok(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.

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, so user.address!.city reads the payload’s city. As a pipe stage it unwraps the stage’s result. In a capture, &half(&1)! is fn 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!= y is x != y; to compare an unwrapped value, write x! == y. not found! negates found!.

  • The operand must be a Result or a Maybe. 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 a Bool, the help says to write an assert.

  • The trap quotes the expression as written, on one line, cut after 60 characters with .... An Err(e) shows e by its Display when its type implements Display, and by its Debug otherwise. A None says 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 nothing
    

    The 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 a Maybe or Result to handle, or to pass on with ?.

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 an Err or a None (Unwrapping with !), such as an index it computed and unwrapped (Vector.get(v, i)!);
  • an unreachable it reaches, or a todo it left in;
  • Task.await of 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 Decimal whose scale is outside -2147483648 to 2147483647 or that has more digits than a Decimal holds (Decimal.sqrt(2d, 4294967298, .HalfEven); Decimal.round, Decimal.pow and Float.to_decimal too), or a String.repeat of more copies than memory holds;
  • consumes the whole of an iterator that never ends (§13 Infinite iterators);
  • closes a once cycle through a function value (§6 once Bindings).

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 Failed outcome (§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).

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.

  • N is 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 of Decimal.format’s own, prints line 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.sqrt with a scale past a Decimal’s) gets the line of the program’s call.
  • A todo names its own file and line instead (Unwritten code: todo).
  • nomi run, nomi test, a built executable and the REPL print the same line.

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. todo never 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 todo is Bool, n == todo has n’s type). As a statement it is Unit and does not exit. An unannotated binding expects nothing, so x = todo is the error cannot infer a type for 'x' from `todo`: annotate the binding (`x: T = todo`). _ = todo is accepted.
  • Reason. A string literal: "...", """...""" or a raw backtick string. An interpolated or tagged reason is the parse error a `todo` reason is a plain string literal: it cannot interpolate or carry a tag.
  • Running it. Reaching a todo traps with todo 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 todo has its parameters exempt from the never-read error, and so are the names an arm, an else arm, an if condition or a test’s setup binding binds when the body they scope over holds one.
  • Builds. nomi build refuses a program that holds a todo (tooling reference).
  • A name. todo is a contextual keyword (§2 Keywords): a bare todo in the scope of a binding named todo reads the binding, and todo "reason" is the placeholder everywhere.

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 is cannot infer a type for 'x' from `unreachable`: annotate the binding (`x: T = unreachable "..."`).
  • Reason. Required, a string literal in the forms a todo reason takes. A bare unreachable is `unreachable` needs a reason.
  • It exits. A statement after an unreachable statement is the error unreachable code after `unreachable`. It is finished code: a function that holds one still reports a parameter it never reads, and nomi build accepts 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.

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