feat(errors): recoverable failures as values — try/else over ok/err results (#46)
All checks were successful
bootstrap / cfree-fixpoint (push) Successful in 17s
ci / build-and-test (push) Successful in 1m14s
commit-lint / conventional-commits (push) Successful in 3s
docs / build-and-deploy (push) Successful in 19s

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>
This commit is contained in:
Orkun ÇAKILKAYA 2026-08-31 15:04:14 +03:00
parent 498593311f
commit 0d1b09e4f0
21 changed files with 16590 additions and 15566 deletions

View file

@ -479,6 +479,50 @@ function emit_call(e: Node) -> Val {
emit(`{lok}:\n`)
return val("0", "void")
}
# --- recoverable failures as values (issue #46) -----------------------------
# A `result` is a heap `%Result = { i32 ok, i32 value, ptr err }`. `ok(v)` wraps
# a success payload (any i32-width scalar: int/fixed/bool/entity), `err(msg)` a
# failure with a message. `is_ok`/`is_err` test the tag; `try E else { … }`
# (emit_try) unwraps the value or runs the fallback. Each is guarded by a
# find_fn check so a user function of the same name still wins.
if (name == "ok") and (find_fn("ok") == null) {
g_uses_result = true
let v = emit_expr(e.kids[0])
let p = emit_bind("call ptr @malloc(i64 16)")
let okp = emit_bind(`getelementptr inbounds %Result, ptr {p}, i32 0, i32 0`)
emit(` store i32 1, ptr {okp}\n`)
let vp = emit_bind(`getelementptr inbounds %Result, ptr {p}, i32 0, i32 1`)
emit(` store i32 {coerce_code(v, "int")}, ptr {vp}\n`)
let ep = emit_bind(`getelementptr inbounds %Result, ptr {p}, i32 0, i32 2`)
emit(` store ptr null, ptr {ep}\n`)
return val(p, "result")
}
if (name == "err") and (find_fn("err") == null) {
g_uses_result = true
let m = emit_expr(e.kids[0])
let p = emit_bind("call ptr @malloc(i64 16)")
let okp = emit_bind(`getelementptr inbounds %Result, ptr {p}, i32 0, i32 0`)
emit(` store i32 0, ptr {okp}\n`)
let vp = emit_bind(`getelementptr inbounds %Result, ptr {p}, i32 0, i32 1`)
emit(` store i32 0, ptr {vp}\n`)
let ep = emit_bind(`getelementptr inbounds %Result, ptr {p}, i32 0, i32 2`)
emit(` store ptr {m.code}, ptr {ep}\n`)
return val(p, "result")
}
if (name == "is_ok") and (find_fn("is_ok") == null) {
let r = emit_expr(e.kids[0])
let okp = emit_bind(`getelementptr inbounds %Result, ptr {r.code}, i32 0, i32 0`)
let okv = emit_bind(`load i32, ptr {okp}`)
let c = emit_bind(`icmp ne i32 {okv}, 0`)
return val(emit_bind(`zext i1 {c} to i32`), "bool")
}
if (name == "is_err") and (find_fn("is_err") == null) {
let r = emit_expr(e.kids[0])
let okp = emit_bind(`getelementptr inbounds %Result, ptr {r.code}, i32 0, i32 0`)
let okv = emit_bind(`load i32, ptr {okp}`)
let c = emit_bind(`icmp eq i32 {okv}, 0`)
return val(emit_bind(`zext i1 {c} to i32`), "bool")
}
# The EV2 reflection ABI (the world table), exposed to Ludic so a Ludic mod can
# introspect the world by name — the same functions a foreign mod binds. Emitted
# only for a modding program (ECS + events), so a plain game is unchanged.
@ -629,6 +673,7 @@ function emit_expr(e: Node) -> Val {
return emit_load_at(a, g_addr_ty)
}
if e.kind == S_EMIT { return emit_emit(e) } # emit as an expression -> cancelled flag
if e.kind == E_TRY { return emit_try(e) } # try E else { … } -> recovered value (issue #46)
if e.kind == E_CALL { return emit_call(e) }
if e.kind == E_BIN { return emit_bin(e) }
if e.kind == E_UN {

View file

@ -35,6 +35,7 @@ var g_uses_fsrt: bool = false # Fs.*/Path.*/Mime.* was emitted -> emit the file
var g_uses_datert: bool = false # Date.*/DateTime.* was emitted -> emit the civil<->epoch conversions
var g_uses_expect: bool = false # expect/expect_eq/expect_near was emitted -> emit the test-assert globals
var g_uses_panic: bool = false # panic/assert was emitted -> declare @fprintf + the panic format
var g_uses_result: bool = false # ok()/err()/try was emitted -> define the %Result value type (issue #46)
var g_tests: []Node # test "name" { ... } blocks collected by the parser
var g_src_name: pointer = "?" # base name of the source file, for panic/expect file:line messages
var g_uses_longstr: bool = false # string(long) / interpolating a long was emitted -> emit fn_long_str

View file

@ -140,6 +140,7 @@ function emit_program() -> void {
g_uses_loopback = false
g_uses_expect = false
g_uses_panic = false
g_uses_result = false
g_cov_lines = new []int
g_cov_active = true
loc_name = new []pointer; loc_reg = new []pointer; loc_ty = new []pointer; loc_mut = new []int
@ -198,6 +199,7 @@ function emit_program() -> void {
emith("declare i32 @fprintf(ptr, ptr, ...)\n")
emith("@.fmt_panic = private unnamed_addr constant [6 x i8] c\"%s%s\\0A\\00\"\n")
}
if g_uses_result { emith("%Result = type { i32, i32, ptr }\n") } # issue #46: ok/err/try value
emit_cov_runtime() # issue #45: --coverage tables + exit dump
}

View file

@ -1,5 +1,53 @@
# emit_expr.ludic — lower an expression to IR, returning its register and type.
# issue #46: `try E else { BODY }` as an expression. Evaluate E (a `result`); on
# `ok` the expression is the payload, on `err` BODY runs with the failure message
# bound to `error` and its trailing expression supplies the fallback. Pure branch
# on the tag — no unwinding, no hidden control flow.
function emit_try_body(b: Node, slot: pointer) -> void {
var i = 0
while i < len(b.kids) {
if g_term { return }
let st = b.kids[i]
if (i == len(b.kids) - 1) and st.kind == S_EXPR { # trailing expression = the fallback value
emit_cov_hit(st.line)
let v = emit_expr(st.a)
emit(` store i32 {coerce_code(v, "int")}, ptr {slot}\n`)
} else { emit_stmt(st) }
i = i + 1
}
}
function emit_try(e: Node) -> Val {
g_uses_result = true
let r = emit_expr(e.a)
if not (r.ty == "result") { perr(`try expects a result value (got {r.ty}) — line {itoa(e.line)}`) }
let slot = emit_alloca("i32")
emit(` store i32 0, ptr {slot}\n`) # fallback default (an else block with no trailing value)
let okp = emit_bind(`getelementptr inbounds %Result, ptr {r.code}, i32 0, i32 0`)
let okv = emit_bind(`load i32, ptr {okp}`)
let isok = emit_bind(`icmp ne i32 {okv}, 0`)
let lok = lbl("tryok"); let lel = lbl("tryelse"); let lend = lbl("tryend")
emit(` br i1 {isok}, label %{lok}, label %{lel}\n`)
emit(`{lok}:\n`); g_term = false
let vp = emit_bind(`getelementptr inbounds %Result, ptr {r.code}, i32 0, i32 1`)
let vv = emit_bind(`load i32, ptr {vp}`)
emit(` store i32 {vv}, ptr {slot}\n`)
emit(` br label %{lend}\n`)
emit(`{lel}:\n`); g_term = false
let ep = emit_bind(`getelementptr inbounds %Result, ptr {r.code}, i32 0, i32 2`)
let ev = emit_bind(`load ptr, ptr {ep}`)
let eslot = emit_alloca("ptr")
emit(` store ptr {ev}, ptr {eslot}\n`)
let save = nloc
loc_push("error", eslot, "string") # bind the failure message inside the else block
emit_try_body(e.b, slot)
nloc = save
if not g_term { emit(` br label %{lend}\n`) }
emit(`{lend}:\n`); g_term = false
return val(emit_bind(`load i32, ptr {slot}`), "int")
}
function emit_load_at(addr: pointer, ty: pointer) -> Val {
let r = emit_bind(`load {llty(ty)}, ptr {addr}`)
return val(r, ty)

View file

@ -31,6 +31,9 @@ const S_EMIT: int = 49 # emit E(field: v, ...) — fire event E (calls
const S_CANCEL: int = 50 # cancel — inside a listener, veto a `cancellable` event
const N_TEST: int = 51 # test "name" { ... } — a named test block (the testing framework)
# s=name a=body block line=source line of the test
const E_TRY: int = 52 # try EXPR else { ... } — recover a fallible result as a value (issue #46)
# a=the fallible (result-typed) expression b=else block (its
# trailing expression is the fallback) line=source line
# statements
const S_LET: int = 10
const S_ASSIGN: int = 11

View file

@ -150,6 +150,19 @@ function p_primary() -> Node {
if (t.text == "false") { let n = node(E_BOOL); n.ival = 0; pi = pi + 1; return n }
if (t.text == "null") { pi = pi + 1; return node(E_NULL) }
if (t.text == "new") { pi = pi + 1; let n = node(E_NEW); n.s = ptype(); if is_op("{") { n.a = record() }; return n }
# try EXPR else { ... } — evaluate a fallible (result-typed) expression; on
# `ok` the whole expression is its payload, on `err` the else block runs (with
# the message bound to `error`) and its trailing expression is the fallback.
if (t.text == "try") {
pi = pi + 1
let n = node(E_TRY); n.line = t.line
n.a = expr()
skipnl()
if not is_id("else") { perr("try needs an `else { ... }` fallback") }
pi = pi + 1; skipnl()
n.b = block()
return n
}
let n = node(E_ID); n.s = t.text; pi = pi + 1; return n
}
if is_op("(") { pi = pi + 1; skipnl(); let e = expr(); skipnl(); eat_op(")"); return e }

File diff suppressed because it is too large Load diff