Exact Hindley–Milner type, error, and effect inference compiling to zero-overhead
ES2022+ JavaScript, strict TypeScript .d.ts,
and standalone C99 — written in pure Odin.
export type Shape
Circle(radius: Float)
Rect(w: Float, h: Float)
end
--- Compute the area of a geometric shape.
export fn area(shape)
match shape with
Circle(r) then Float.pi * r * r
Rect(w, h) if w == h then w * w
Rect(w, h) then w * h
end
end
export fn totalArea(shapes)
sum = 0.0
for s in shapes do
sum = sum + area(s)
end
sum
end
fn main()
shapes = [Circle(3.0), Rect(4.0, 4.0), Rect(2.0, 5.0)]
print("total area = {totalArea(shapes):.2}")
end
Exp infers every function's exact effect row, error constructors, escape mode, and
linearity qualifier before codegen. Each backend selects the fastest legal lowering tier —
so pure modules never import a runtime and synchronous helpers never allocate a Promise.
| Tier | Inferred Row / Form | ES2022+ JavaScript Lowering | Runtime Cost | Enforced Budget |
|---|---|---|---|---|
| Tier 0 Pure Code | ! {} | Plain ES2022+ functions, switch over compact int tags, monomorphic records | 0 B runtime · 0 capability args | B1 ≤ 1.05×, B2 = 0 B |
| Tier 1 Service Handlers | ! {Users, Cache} | Compile-time topological DI wiring, static handler specialization / direct calls | 0 heap allocs · no service container | B3 ≤ 1.05× |
| Tier 2 Structured Loops & Blocks | for / while / each / fold | Native JS loops + inlined literal-block combinators (#inline_blocks verified) | 0 closure allocs | B1 ≤ 1.05× |
| Tier 3 Typed Errors & Cleanup | ! {Fail<E[A | B]>} | Monomorphic tagged result / local jumps + LIFO try/finally for defer & affine close | 0 new Error() · 0 stack capture | B4 ≤ 1.15× |
| Tier 4 Colorless Concurrency | ! {Async} | Native async/await + scope token; sync callers specialize to sync JS | 0 Promises in sync instantiations | B6 = 0 Promises |
| Tier 5 Control Handlers | with resume (1-shot / multi) | Isolated continuation lowering emitted strictly for reachable subgraphs | 4,128 B min / 1,984 B gz full runtime | B7 ≤ 8 KB min / 3 KB gz |
Hover any identifier to inspect inferred signatures, effect rows, and error constructor
sets. Switch tabs to inspect real compiler output across ES2022+ JavaScript, strict
.d.ts, and C99 — or press Run to
execute directly in your browser.
Raising fail(InvalidId(id)) records the exact
constructor in the inferred row Fail<UserError[InvalidId | ...]>.
Handling constructors subtracts them from the type; once every UserError case
is handled, it vanishes completely while Fail<DbError> propagates cleanly.
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 use handle CachedUsers(db), MemoryCache, StdoutLogger solves
handler dependencies topologically at compile time. Missing capabilities propagate into
the caller's row; cycles are compile errors (E0051);
zero runtime Context map is ever emitted.
type User
id: Int
name: String
end
type LookupError
NotFound(Int)
end
effect Cache
get(key: String) -> Option<User>
set(key: String, user: User) -> Unit
end
effect Database
queryUser(id: Int) -> User ! {Fail<LookupError[NotFound]>}
end
effect Logger
info(msg: String) -> Unit
end
effect Users
find(id: Int) -> User ! {Fail<LookupError[NotFound]>}
end
handler MemoryCache: Cache
store = Ref.new([:])
fn get(key) store.get().get(key) end
fn set(key, user) store.set(store.get().set(key, user)) end
end
handler CachedUsers(db: Handler<Database>): Users
fn find(id)
key = "user:{id}"
match Cache.get(key) with
Some(user) then user
None then
user = db.queryUser(id)
Cache.set(key, user)
Logger.info("cached {user.name}")
user
end
end
end
handler TestDb: Database
fn queryUser(id)
if id == 1 then { id: 1, name: "Ada" } else fail(NotFound(id)) end
end
end
handler StdoutLogger: Logger
fn info(msg) print("[log] {msg}") end
end
fn main()
db = TestDb
use handle CachedUsers(db), MemoryCache, StdoutLogger
first = handle Users.find(1) with fn Fail.raise(NotFound(_)) { id: 0, name: "none" } end end
second = handle Users.find(1) with fn Fail.raise(NotFound(_)) { id: 0, name: "none" } end end
print("1st={first.name}, 2nd={second.name} (cache hit)")
end
Any type defining fn T.close(self) is automatically affine.
Owned handles and defer blocks unwind in strict LIFO order
across normal return, early return, Fail,
and scope cancellation — lowered directly to lexical try / finally.
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
Non-tail handlers capture deep continuations via with resume.
Continuation lowering applies strictly to reachable code, and Exp's linearity qualifier
(E¹) rejects multi-shot handlers whenever an affine
resource is live (E0049).
effect Choose
pick() -> Bool
end
fn pairs()
a = if Choose.pick() then 10 else 20 end
b = if Choose.pick() then 1 else 2 end
a + b
end
fn allOutcomes() -> List<Int>
handle pairs() with
fn value(x) [x] end
fn Choose.pick() with resume
resume(true) ++ resume(false)
end
end
end
fn main()
outcomes = allOutcomes()
print("outcomes = {outcomes}")
end
Structural records sort fields canonically so V8 hidden classes stay monomorphic.
Named record types fill default values and Option fields
automatically, while single-parameter abilities provide zero-boilerplate polymorphism.
type RequestOptions
timeoutMs: Int = 5000
retries: Int = 2
bearerToken: Option<String>
end
type Printable
fn format(self) -> String
end
type Metric
Metric(name: String, value: Float)
end
fn Metric.format(m)
"{m.name}={m.value:.2}"
end
fn renderAll(xs)
xs.map(x => x.format()).join(", ")
end
fn defaultRequest() -> RequestOptions
{ retries: 3 }
end
fn main()
opts = defaultRequest()
metrics = [Metric("p99_ms", 1.62), Metric("bundle_kb", 3.30)]
print("timeout={opts.timeoutMs} retries={opts.retries} token={opts.bearerToken}")
print(renderAll(metrics))
endExplore the interactive browser playground or dive straight into the Getting Started guide.