Exp 0.1
Effects & Concurrency

Typed Errors & Resources

Constructor-level restrictable Fail<E> sets with automatic subtraction, strict error/defect separation, inferred affine ownership, LIFO defer cleanup, and E¹ multi-shot safety.

Restrictable Fail<T[A | B]> & subtraction

Expected domain errors in Exp are operations of the built-in Fail<E> effect raised with fail(err). Rather than collapsing errors to a coarse base type, Exp's polarized row inference tracks the exact set of variant constructors each expression can raise:

  • fail(InvalidId(id)) contributes Fail<UserError[InvalidId]>.
  • Different error types occupy distinct row entries (Fail<UserError[...]>, Fail<DbError[...]>).
  • Matching a constructor inside handle ... with fn Fail.raise(...) subtracts that constructor from the row. Handling every raised constructor eliminates the entry completely.
  • On the JavaScript backend (Tier 3), synchronous Fail lowers to a monomorphic tagged-result protocol with 0 new Error() allocations and 0 stack-trace captures (B4 ≤ 1.15×).
type UserError
    InvalidId(Int)
    NotFound(Int)
    Banned(String)
end

type DbError
    Timeout
    Disconnected
end

effect Users
    find(id: Int) -> { id: Int, name: String } ! {Fail<UserError[NotFound | Banned]>, Fail<DbError>}
end

fn loadProfile(id)
    if id <= 0 then fail(InvalidId(id)) end
    Users.find(id)
end

fn loadOrGuest(id)
    handle loadProfile(id) with
        fn Fail.raise(InvalidId(_) | NotFound(_)) { id: 0, name: "guest" } end
        fn Fail.raise(Banned(reason)) { id: 0, name: "banned: {reason}" } end
    end
end

handler MockUsers: Users
    fn find(id)
        if id == 1 then { id: 1, name: "Ada" }
        else if id == 4 then fail(Banned("policy"))
        else fail(NotFound(id))
        end
    end
end

fn main()
    use handle MockUsers
    for id in [1, -3, 4, 99] do
        p = handle loadOrGuest(id) with
            fn Fail.raise(_) { id: -1, name: "db offline" } end
        end
        print("id={id} -> {p.name}")
    end
end
Hover or focus any symbol to inspect inferred types, effects, and errors

Exact error polymorphism (Error<U>)

Generic combinators like Async.retry need to catch and re-raise arbitrary caller error unions without losing constructor precision. A catch-all handler clause over an open or multi-type union binds Error<U>, and calling fail(e) re-raises the exact union U verbatim.

Typed errors vs untyped defects

Category Examples In effect row? Cleanup & handling
Typed Errors (Fail<E>) fail(NotFound(id)), #extern(..., throws: NetErr) Yes — exact constructor set Handled lexically via handle ... with fn Fail.raise(...); runs all LIFO cleanups on unwind.
Defects panic, assert, assertEq, 64-bit Int overflow, out-of-bounds xs[i], missing m[k] No — never pollutes signatures Represents program bugs; unwinds all lexical defer and affine closes in LIFO order and surfaces only at supervisor boundaries.

Affine resources & inferred ownership

Any type holding an external native handle or defining fn T.close(self) is automatically affine (used at most once), as is any record, variant, or list containing one.

  • Inferred borrow vs move: ownership is inferred per SCC — parameters are lent by default unless a path moves them (sink). Method calls and field reads lend; returning, storing, rebinding, or passing to a sink moves ownership.
  • Using an affine value after moving it is a compile-time error (E0050).
  • Owned resources close automatically at lexical scope exit on every exit path — normal return, early return, break, continue, Fail, escape, sibling cancellation, and defects.

LIFO defer & lexical try/finally lowering

defer expr and defer do ... end attach arbitrary cleanup actions to the enclosing block, unified with affine resource drop elaboration in Core IR. Cleanup never relies on GC timing or FinalizationRegistry; in JavaScript it lowers directly to nested lexical try { ... } finally { ... } blocks in strict LIFO order.

type DbError
    EmptyRow
end

type Connection
    Connection(url: String, open: Ref<Bool>)
end

fn Connection.close(c)
    c.open.set(false)
    print("closed {c.url}")
end

fn openConnection(url: String) -> Connection
    print("opened {url}")
    Connection(url, Ref.new(true))
end

fn importBatch(url: String, rows: List<String>) -> Int ! {Fail<DbError>}
    if rows.isEmpty() then return 0 end
    defer print("defer: batch finished")

    conn = openConnection(url)
    count = 0
    for row in rows do
        if row == "" then fail(EmptyRow) end
        print("wrote '{row}' -> {conn.url}")
        count = count + 1
    end
    count
end

fn main()
    n = handle importBatch("pg://local", ["ada", "", "grace"]) with
        fn Fail.raise(EmptyRow)
            print("recovered EmptyRow")
            -1
        end
    end
    print("result = {n}")
end
Hover or focus any symbol to inspect inferred types, effects, and errors

Control-flow linearity (E¹)

Whenever an effect operation is performed while an affine resource is live in the lexical frame, Exp annotates that effect entry with the linearity qualifier ¹ (at-most-once resumption). Tail-resumptive service handlers and one-shot handlers satisfy E¹ trivially; applying a multi-shot with resume handler fails at compile time with E0049.