ludic/selfhost/backend/emit_expr.ludic
Orkuncakilkaya 0d1b09e4f0
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
feat(errors): recoverable failures as values — try/else over ok/err results (#46)
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>
2026-08-31 15:04:14 +03:00

237 lines
9.5 KiB
Text

# 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)
}
# short-circuit `and`/`or`: seed a slot with (left!=0), branch to decide whether
# to overwrite with (right!=0).
function emit_logic(e: Node) -> Val {
let slot = emit_alloca("i32")
let la = emit_expr(e.a)
let lc = emit_bind(`icmp ne i32 {la.code}, 0`)
let lz = emit_bind(`zext i1 {lc} to i32`)
emit(" store i32 "); emit(lz); emit(", ptr "); emit(slot); emit("\n")
let ev = lbl("sc"); let done = lbl("scend")
if (e.s == "and") { emit(" br i1 "); emit(lc); emit(", label %"); emit(ev); emit(", label %"); emit(done); emit("\n") }
else { emit(" br i1 "); emit(lc); emit(", label %"); emit(done); emit(", label %"); emit(ev); emit("\n") }
emit(ev); emit(":\n")
let rb = emit_expr(e.b)
let rc = emit_bind(`icmp ne i32 {rb.code}, 0`)
let rz = emit_bind(`zext i1 {rc} to i32`)
emit(" store i32 "); emit(rz); emit(", ptr "); emit(slot); emit("\n")
emit(" br label %"); emit(done); emit("\n")
emit(done); emit(":\n")
return val(emit_bind(`load i32, ptr {slot}`), "bool")
}
function cmp_code(op: pointer) -> pointer {
if (op == ("<")) { return "slt" }
if (op == ("<=")) { return "sle" }
if (op == (">")) { return "sgt" }
if (op == (">=")) { return "sge" }
if (op == ("==")) { return "eq" }
return "ne"
}
function is_cmp(op: pointer) -> bool {
return (op == ("<")) or (op == ("<=")) or (op == (">")) or (op == (">=")) or (op == ("==")) or (op == ("!="))
}
function arith_code(op: pointer) -> pointer {
if (op == ("+")) { return "add" }
if (op == ("-")) { return "sub" }
if (op == ("*")) { return "mul" }
if (op == ("/")) { return "sdiv" }
if (op == ("&")) { return "and" }
if (op == ("|")) { return "or" }
if (op == ("^")) { return "xor" }
if (op == ("<<")) { return "shl" }
if (op == (">>")) { return "lshr" } # logical shift (unsigned)
return "srem"
}
# widen an int value to Q16.16 by shifting left 16 (a fixed value passes through)
function to_fixed(v: Val) -> pointer {
if (v.ty == "fixed") { return v.code }
return emit_bind(`shl i32 {v.code}, 16`)
}
# coerce a value's code to the LLVM type of `target`, for the only cross-width
# pair the language has: int (i32) <-> long (i64). int widens with sext, long
# narrows with trunc; everything else (same width, or ptr) passes through.
function coerce_code(v: Val, target: pointer) -> pointer {
let lt = llty(target)
let vt = llty(v.ty)
if (lt == vt) { return v.code }
if (lt == "i64") and (vt == "i32") { return emit_bind(`sext i32 {v.code} to i64`) }
if (lt == "i32") and (vt == "i64") { return emit_bind(`trunc i64 {v.code} to i32`) }
return v.code
}
# widen an int value to i64 (a long passes through) — the long analogue of to_fixed
function to_long(v: Val) -> pointer {
if (llty(v.ty) == "i64") { return v.code }
return emit_bind(`sext i32 {v.code} to i64`)
}
# string operators: `a + b` concatenates, `a == b` / `a != b` compare by content.
# Both call the @fn_str_* prelude (emitted once per program that uses them).
function emit_str_op(op: pointer, a: Val, b: Val) -> Val {
g_uses_str = true
if (op == ("+")) {
return val(emit_bind(`call ptr @fn_str_concat(ptr {a.code}, ptr {b.code})`), "string")
}
let r = emit_bind(`call i32 @fn_str_eq(ptr {a.code}, ptr {b.code})`)
if (op == ("!=")) {
let c = emit_bind(`icmp eq i32 {r}, 0`)
return val(emit_bind(`zext i1 {c} to i32`), "bool")
}
return val(r, "bool")
}
function emit_bin(e: Node) -> Val {
if (e.s == "and") or (e.s == "or") { return emit_logic(e) }
let a = emit_expr(e.a)
let b = emit_expr(e.b)
# strings are pointer-typed, so any `+` with a pointer operand is concatenation,
# and `==`/`!=` between pointers is content comparison — except `x == null`,
# which is a pointer-identity test and falls through to the icmp below.
let ptrish = (llty(a.ty) == "ptr") or (llty(b.ty) == "ptr")
let isnull = e.a.kind == E_NULL or e.b.kind == E_NULL
if ptrish {
if (e.s == ("+")) { return emit_str_op("+", a, b) }
if ((e.s == ("==")) or (e.s == ("!="))) and not isnull { return emit_str_op(e.s, a, b) }
}
let fx = (a.ty == "fixed") or (b.ty == "fixed")
# a 64-bit operand (and no fixed/ptr involved) promotes the whole expression to
# i64: the other side widens with sext, and the result stays `long`.
let lng = ((llty(a.ty) == "i64") or (llty(b.ty) == "i64")) and not fx and not ptrish
if is_cmp(e.s) {
var ac = a.code; var bc = b.code
var ct = "i32"
if fx { ac = to_fixed(a); bc = to_fixed(b) }
else { if lng { ct = "i64"; ac = to_long(a); bc = to_long(b) }
else { if (llty(a.ty) == "ptr") or (llty(b.ty) == "ptr") { ct = "ptr" } } } # `p == null`, str/record identity
let c = emit_bind(`icmp {cmp_code(e.s)} {ct} {ac}, {bc}`)
return val(emit_bind(`zext i1 {c} to i32`), "bool")
}
if lng {
let al = to_long(a); let bl = to_long(b)
return val(emit_bind(`{arith_code(e.s)} i64 {al}, {bl}`), "long")
}
if fx {
let af = to_fixed(a); let bf = to_fixed(b)
if (e.s == ("*")) {
let a64 = emit_bind(`sext i32 {af} to i64`)
let b64 = emit_bind(`sext i32 {bf} to i64`)
let m = emit_bind(`mul i64 {a64}, {b64}`)
let sh = emit_bind(`ashr i64 {m}, 16`)
return val(emit_bind(`trunc i64 {sh} to i32`), "fixed")
}
if (e.s == ("/")) {
let a64 = emit_bind(`sext i32 {af} to i64`)
let ash = emit_bind(`shl i64 {a64}, 16`)
let b64 = emit_bind(`sext i32 {bf} to i64`)
let dv = emit_bind(`sdiv i64 {ash}, {b64}`)
return val(emit_bind(`trunc i64 {dv} to i32`), "fixed")
}
let r = emit_bind(`{arith_code(e.s)} i32 {af}, {bf}`)
return val(r, "fixed")
}
let r = emit_bind(`{arith_code(e.s)} i32 {a.code}, {b.code}`)
return val(r, "int")
}
# ---- named arguments -------------------------------------------------------
# An argument list is either all-positional or all-named. When named, each kid
# is an E_FINIT (label -> value); this rewrites e.kids into plain value exprs in
# the order the callee declares its parameters, so the rest of emit_call is
# oblivious to whether the caller used names.
function args_are_named(e: Node) -> bool {
var i = 0
while i < len(e.kids) { if e.kids[i].kind == E_FINIT { return true }; i = i + 1 }
return false
}
function reorder_named(e: Node, labels: []pointer) -> void {
if not args_are_named(e) { return }
var i = 0
while i < len(e.kids) {
if e.kids[i].kind != E_FINIT { perr("named and positional arguments cannot be mixed in one call") }
i = i + 1
}
if len(e.kids) != len(labels) { perr("wrong number of arguments") }
let out = new []Node
var li = 0
while li < len(labels) {
var found: Node = null
var k = 0
while k < len(e.kids) { if (e.kids[k].s == labels[li]) { found = e.kids[k] }; k = k + 1 }
if (found == null) { perr(`no argument named {labels[li]}`) }
push(out, found.a)
li = li + 1
}
e.kids = out
}
# The parameter labels of a resolved fn/extern, in declaration order.
function param_labels(fn: Node) -> []pointer {
let out = new []pointer
var i = 0
while i < len(fn.kids) { if fn.kids[i].kind == N_PARAM { push(out, fn.kids[i].s) }; i = i + 1 }
return out
}
function param_types(fn: Node) -> []pointer {
let out = new []pointer
var i = 0
while i < len(fn.kids) { if fn.kids[i].kind == N_PARAM { push(out, fn.kids[i].ty) }; i = i + 1 }
return out
}