A fallible function returns a `result` value, built with ok(payload) on success
or err(message) on failure. The caller recovers a value with `try EXPR else {
… }`: on ok the whole expression is the payload; on err the else block runs —
with the failure message bound to `error` — and its trailing expression supplies
the fallback. It is a plain branch on the result's tag: no exceptions, no hidden
control flow, nothing unwinds. is_ok(r) / is_err(r) classify without unwrapping.
Payloads are any i32-width scalar (int/fixed/bool/entity). The feature is
additive and only kicks in when ok/err/try are used, so untouched programs
compile byte-identically (verified) and the C-free bootstrap fixpoint holds.
Complements panic/assert from #8 (the unrecoverable half). The optional
top-level frame `recover` stays deferred (needs a frame-abort mechanism); the
full tagged-union/any generalization is tracked in #1.
Adds the `try` keyword and ok/err/is_ok/is_err builtins across the compiler,
the vocabulary header, JetBrains + TextMate/VSCode grammars, the docs inventory
and pages, examples/library/recover.ludic, and a regression case.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1.2 KiB
1.2 KiB
id: fn-err name: err category: builtins kind: builtin tokens: err sig: err(msg: string) -> result tip: Wrap a failure message in a result — the sad half, recovered by try/else. order: 13
Wraps a failure in a result, carrying a message that says what went wrong. It is the counterpart to ok: a fallible function (declared -> result) returns err("…") on the sad path instead of crashing or returning a magic sentinel. The caller recovers with try/else — the else block sees the message as error — or tests it with is_err. Unlike panic, which aborts, err is a value: the program keeps running and chooses a fallback.
Parameters:
msg— a message describing the failure (a string)
program Config {
function volume(pct: int) -> result {
if pct < 0 or pct > 100 { return err("volume out of range") }
return ok(pct)
}
test "err drives the fallback" {
let v = try volume(150) else { 100 } # clamp to a safe default
expect_eq(v, 100)
}
}