Decision D005 · accepted in part; error layers and syntax proposed
Algebraic effects are the core mechanism, checked softly; effects are types
A record of the language's design, as it stood on 2026-11-18: written for the people who build Diaspar, and kept as it was written. Its code is a sketch, not a program of the site, and an older record may show syntax that a later one changed. It names files of the language's source, which is not public yet.
Status: accepted (2026-11-15) for effects as the mechanism, effects as types, (2026-11-18) an effect naming its operations' enum with of:, no strict effect typing, abandoned computations unwinding with cleanup, defer/with and the rules for errors inside them, hints from two sources, attempt and must, and error re-raising a Failure; proposed for three handler kinds in two stages, the two-layer error design, catch, Message, and the concrete syntax
Decision
One mechanism, algebraic effects with handlers, replaces several separate ones:
- exceptions and Common Lisp-style restarts;
- dynamic variables;
- generators;
- waiting for I/O and scheduling fibers (D006);
- capabilities: access to files, the network, the clock;
- deterministic testing: time, randomness, and the network are replaced by handlers.
Effects are not strictly part of a function's type. The compiler infers which effects a function can perform and warns instead of refusing. Strict checking applies only where it is unavoidable: in the runtime and in std.unsafe modules (D002).
Effects are types (accepted)
An effect is declared with defeffect, like a record type (D010). perform sends a value of that type; handle matches it with a pattern (D015).
(defeffect BadEntry [line])
(defn parse-entry [line]
(or (try-parse line) (perform (BadEntry line))))
(handle (import "data.csv")
(BadEntry line) [resume] (resume nil)) ; pattern, then the continuation, then the body
Why types rather than keywords (:bad-entry): two libraries can no longer collide on one name (csv.Log and http.Log are different, D011); a misspelled effect is an unknown type, not a silent new effect; errors become one effect among others.
A restart is a question the code asks its caller in the middle of the work. It works like a callback that intermediate functions do not have to pass along: the handler is found by type in the surrounding context, and resume returns its answer to the place that asked.
;; without effects, the callback is threaded through every call
(defn parse-entry [line on-bad] (or (try-parse line) (on-bad line)))
(defn parse-file [lines on-bad] (map (fn [l] (parse-entry l on-bad)) lines))
(defn import [path on-bad] (parse-file (read-lines path) on-bad))
(import "data.csv" (fn [line] nil))
;; with an effect, intermediate functions know nothing about it
(defn parse-entry [line] (or (try-parse line) (perform (BadEntry line))))
(defn parse-file [lines] (map parse-entry lines))
(defn import [path] (parse-file (read-lines path)))
(handle (import "data.csv")
(BadEntry line) [resume] (resume nil))
An effect names its operations (accepted, 2026-11-18)
An effect of several operations holds one value of an enum, and its field names that enum with of: (D034), as any struct's field names the type it holds:
(defenum FsOp
(Read [path] doc: "The text of the file at path.")
(Write [path text] doc: "Writes text to the file at path."))
(defeffect Fs [(op of: FsOp)] implementation: answer)
(perform (Fs (FsOp.Read "notes.txt")))
- The operations are the enum's variants. The documentation lists them as the effect's operations (docs.md §4.1); a handler matches them,
(Fs (FsOp.Read path:)). - Anything else is an error where the effect is made:
(perform (Fs 5))raises "Fs: op: takes an FsOp, not 5", as a field'sof:does at every construction, on both tiers (tests/cases/effect-ops-of.dias). - An effect that names no enum is one operation, its fields the operation's arguments:
(defeffect Ask [question]),(defeffect GetCaps [stream]).
Rejected: finding the enum by its name, Fs and FsOp, which the documentation tools guessed at first: a convention nothing checks, which std.bench's Allocs and AllocOp already broke. An ops: option on defeffect: a second way to say what of: on the field already says, and one the construction would not check.
Default handlers are installed by the root (accepted)
A module that declares an effect provides its implementation, but does not switch it on everywhere:
(defeffect Fs [(op of: FsOp)] implementation: real-fs) ; how it is done, not "always on"
The root that runs code installs the implementations around it, according to what that code may do:
| Root | Handlers it installs |
|---|---|
diaspar run |
all standard implementations: files, network, processes, clock… |
diaspar test |
all, with the clock and randomness deterministic and seeded (D016, D024) |
| the REPL and live sessions | all, or what the session's capabilities allow (D020) |
| macro expansion | none beyond reading sources (D015) |
a dependency limited by :effects |
checked statically (D025) |
Each root also opens a root scope and chooses the scheduler (D035, accepted 2026-11-17): prod for diaspar run, the REPL and live sessions, sim for diaspar test; macro expansion has none, and spawn there is an error.
process.exit in a program with tasks (proposed, 2026-11-17, D035) does not end the process at once. It cancels the root scope: every task unwinds and runs its cleanup, child processes are stopped, then the program exits with the code. If cleanup does not finish within its deadline, the program exits anyway and says which tasks were still cleaning up (design/concurrency.md §4.9).
There is no ambient authority: code outside any root's handlers cannot reach files or the network, as with Ferron's capabilities passed to main, but without passing them through every signature; a program's main writes nothing for it. An effect performed with no handler and no implementation installed is an error ("effect Fs is not handled").
Three kinds of handlers, two stages (proposed)
What differs between handlers is what they do with the computation that asked.
Kind 1. The handler does not resume: an exception. The computation inside handle stops, and the stack unwinds to handle, running cleanup; handle returns the handler's value.
Kind 2. The handler answers at once: ask and continue. The handler is called in place, on top of the current stack, and (resume v) makes perform return v. Dynamic variables, logging, and fake clocks in tests work this way. Common Lisp-style restarts are also this kind: a handler called in place may run a nested REPL and wait for the user to choose, exactly as Common Lisp's debugger works, without capturing continuations. Interactive restarts are therefore available in stage 1.
(defeffect Log [message])
(defn log [msg] (perform (Log msg)))
(handle (run-job)
(Log message) [resume] (do (print message) (resume nil)))
Kind 3. The handler sets the computation aside for later. The handler stores the continuation as a value and resumes it later, as a generator or the scheduler does. The computation must live on its own stack: fibers (D006).
(defeffect Yield [value])
(defn numbers [] (loop [i 0] (perform (Yield i)) (recur (inc i))))
| Kind 1: exceptions | Kind 2: ask and continue | Kind 3: set aside | |
|---|---|---|---|
| Gives | Errors | Logging, context, tests, restarts with the debugger | Generators, asynchronous I/O without coloring |
| Needs fibers | No | No | Yes |
| Risk | Low: every language has it | Low: a function call | High: the hardest part of the runtime |
| Stage | 1, before self-hosting | 1, before self-hosting | 2, together with fibers |
The compiler does not need kind 3 to self-host. User code does not change between stages: the same perform and handle; stage 2 only makes handlers that set computations aside possible. resume is one-shot; in stage 1 it can be called only while the handler runs.
Stage 2 (implemented, 2026-11-18)
Fibers exist (D035 step 1a; design/concurrency.md §5.1a), and the restriction of the next section is lifted:
resumeanywhere in a clause gives what the rest of the handled computation gives: the body's value, or the value of the clause that takes its next effect, which runs inside the resume. The handler stays in place (deep handlers, as OCaml 5 and Koka):(handle (* (perform (Ask "n")) 2) (Ask _) [resume] (+ 1000 (resume 21)))is 1042.resumeas a value may be kept, returned, stored and called later, from anywhere: the computation waits on a stack of its own. Generators and scripts that wait for frames are this (tests/cases/resume-kept.dias).- One-shot: a second call raises "a continuation is one-shot: it was resumed already".
- Never called and dropped, the computation unwinds with cleanup where its last reference disappears, as the section on abandoned computations says; a cleanup that fails there is raised as a failing automatic release is (D023 rule 5).
- Which handles pay: one whose clauses all resume as their last thing, or not at all, runs in place as in stage 1, at stage 1's cost. Only a handle with a clause that resumes earlier or uses
resumeas a value runs its body on a fiber. The choice is static, perhandle. - Where a handler runs: a clause of a handle on a fiber runs where its body was started or last resumed, with the handlers of that place; a handler in place runs where the effect was performed. Either way a clause sees only the handlers outside its handle.
- Builds without fibers (the seed's profile, the browser for now) raise when a handle that needs one is entered.
resume is the last thing a handler does, in stage 1 (accepted, 2026-11-18; lifted by stage 2)
In stage 1 resume returns to the place of perform; code of the handler after it never runs, and in stage 2 the same code would mean something else (resume returns the result of the rest of the handled computation, as in OCaml and Koka: (+ 1000 (resume 21)) would add 1000 to it). So in stage 1 a resume that is not in tail position of its handler clause is a compile-time error, "resume must be the last thing a handler does (until stage 2)", in all tools. Code that compiles in stage 1 keeps its meaning in stage 2, which lifts the restriction with the standard semantics. Found by the review of 2026-11 (S1).
Implementation (explanation)
defeffectis adeftypemarked as an effect. The address of the type's description is the effect's identity.handlepushes a handler frame onto a per-fiber list: the effect types it handles, the handler code, and the frame to unwind to.performtakes the type of its value and walks the list to the nearest frame that handles it; each step is one pointer comparison, and a per-type "top handler" cache makes frequent effects O(1). The handler is called as an ordinary function on top of the current stack.- Resuming is a plain return: the value passed to
resumebecomes the result ofperform. - Not resuming sets an "unwinding to handle frame N" status. In the generated C, every call checks the status after it returns; if it is set, the function runs its
defers, releases its references (Perceus, D004), and returns too. The targethandleclears the status and returns the handler's value. - Stage 2. When a handler may keep
resumefor later, the body ofhandleruns on its own fiber;performswitches to the handler's stack andresumeswitches back, as in OCaml 5. When the compiler sees that a handler resumes at once, exactly once, it keeps the stage-1 fast path instead, as Koka does for such handlers. - The bootstrap interpreter (D012) keeps the handler list in its state and unwinds with a dedicated
Err(Unwind { handle_id, value })that propagates through?to itshandle.
Abandoned computations unwind with cleanup (accepted)
An abandoned computation always unwinds and runs its cleanup.
- Stage 1. When a handler does not resume, the stack unwinds to
handle,defers run, and resources are released. - Stage 2. When a set-aside computation is never resumed and its last reference disappears, Perceus sees the count reach zero and unwinds it like a cancelled task, with cleanup. OCaml 5 requires doing this by hand; here it follows from reference counting.
Errors
Two layers (proposed)
An error has two parts, as in Rust's anyhow or Python's exceptions with their traceback and notes:
- The error itself, a value of the user's type, describing what happened. Handlers match on it.
- The failure report, a built-in record
Failuremade by the runtime::error(the error value),:trace(the chain of calls at the point of failure, captured once),:context(what the program was doing, innermost first), and:suppressed(errors from cleanup after this one).
The user's type stays clean, and where the error happened is never lost while it passes through handlers.
The Error protocol has message (one line), an optional hint (default nil), and an optional details (default none): extra lines such as at:, expected:, actual: for decoding errors (D010) (accepted).
(defenum ConfigError
(NotFound [path])
(Invalid [path line reason]))
(extend-type ConfigError Error ; the Error protocol: message, and an optional hint
(message [e]
(match e
(ConfigError.NotFound path:) (str "config not found: " path)
(ConfigError.Invalid path: line: reason:) (str path ":" line ": " reason)))
(hint [e]
(match e
(ConfigError.NotFound) "check that the file exists and is readable"
_ nil)))
(defn read-config [path]
(if (exists? path)
(parse-config path)
(error (ConfigError.NotFound path: path))))
error performs the built-in effect Fail with a new Failure holding the error value. A Fail that nobody handles stops the program with a diagnostic (D014); in the REPL it is printed and the REPL continues. Any other unhandled effect is an error: "effect Log is not handled".
catch (proposed)
catch is a macro over handle for errors. It matches the error value against patterns in order; an error that matches none propagates untouched, with the same report.
(catch (read-config "app.toml")
(NotFound path:) default-config
(Invalid line:) (do (log (str "bad config at line " line)) default-config))
The whole report is available when needed (sketch): (catch (sync-users) (Timeout) :as f (do (log f.trace) (retry))).
Quick errors (proposed)
For scripts and the REPL, a string becomes the built-in error type Message, as Rust's anyhow!("…") does:
(error "config not found" :path path)
;; is the same as
(error (Message text: "config not found" data: #{:path path}))
Context and hints (accepted)
Callers add context with the context macro, as with Rust's anyhow::Context and Ferron's context chains. It handles Fail in its body, adds its message to the report's :context, and performs Fail again with the same report, resuming with whatever the outer handler answers, so it is transparent.
Hints come from two sources:
- The error type gives a general hint that is true everywhere, through the optional
hintmethod (defaultnil). - The call site adds a hint from its own context, which a library cannot know (an application's command-line flags, for example).
(context "loading config" :hint "pass --config to use another file"
(read-config path))
error: config not found: app.toml
--> app.dias:4:5
= while: loading config
= help: check that the file exists and is readable
= help: pass --config to use another file
From errors to values: attempt (accepted)
attempt turns an error into a value, for the cases where errors must be collected rather than abort the work: validating several fields, batch processing, keeping the results of tasks in a scope, sending a result to an actor, tests.
(match (attempt (fetch url))
(Ok value:) value
(Err failure:) (log (message failure.error)))
Err holds the whole Failure, so the trace and context are kept. Swift has the same bridge: throws is primary, and Result exists for storing and passing results.
Rules that keep error handling from splitting into two styles:
- Only the caller uses
attempt. Functions, the standard library included, always report errors througherror. - A discarded result is a warning, as with Rust's
#[must_use]:(attempt (save-game))whose result is never used would lose an error silently. - One way to raise (accepted).
erroralso accepts aFailureand raises it again unchanged, with its original trace and context. There is no separateraise. - The way back:
must(accepted).(must r)returns the value of anOk, or raises theErr's failure again througherror. It is shorthand for amatch, named after Go'sMusthelpers. Unlike Rust'sunwrap, it is not a crash: it is the same error thatattemptcaught, catchable as before. Context is added the one usual way, withcontext.
(match r ; explicit
(Ok value:) value
(Err failure:) (error failure))
(must r) ; the same, short
(context "fetching users" (map must results))
Interactive errors in the REPL (accepted direction)
In the REPL, an unhandled error freezes the computation and opens a nested REPL on top of it, where the user fixes the code and chooses a restart. Designed in D017.
Cleanup: defer and with (accepted)
(defer expr) runs expr when the enclosing body finishes: the body of a fn, let, do, or one loop iteration. It runs on every exit: normal return, unwinding after an error, cancellation of a task (D006). Several defers in one body run in reverse order.
(defn update-shared [lock state]
(acquire lock)
(defer (release lock)) ; next to the acquisition, runs on any exit
(atom.swap! state step))
with is a macro over defer for values that know how to release themselves:
(with [l (lock m)
tmp (temp-file)]
(work l tmp))
;; expands to
(let [l (lock m)]
(defer (release l))
(let [tmp (temp-file)]
(defer (release tmp))
(work l tmp)))
Files and sockets usually need neither: with Perceus (D004) they close when the last reference to them disappears, including during unwinding. But Perceus releases a value after its last use, not at the end of a block, so cleanup tied to the end of a block (releasing a lock, rolling back, restoring state) needs defer.
Why defer as the primitive rather than only with: with covers values that have a release operation; defer also covers cleanup that is not a resource (restore a setting, delete a file, write a log line) without wrapping it into one, keeps cleanup next to the acquisition when acquisitions are interleaved with other code, and is what with itself expands to.
defer-on-error (Zig's errdefer), which runs only on an exit by error, comes later.
Errors inside deferred expressions (accepted). Two invariants: no error is ever lost, and no cleanup is ever skipped.
| Body | Deferred expressions | Result |
|---|---|---|
| finishes normally | all succeed | the body's value |
| finishes normally | one fails | that error propagates; its :context gets "during cleanup (defer at file:line)"; the remaining defers still run |
| fails | all succeed | the body's error |
| fails | one or more fail | the body's error propagates; each cleanup error is attached to it under :suppressed, in order; the remaining defers still run |
| is cancelled (D006) | one fails | the task fails with the cleanup error, which reaches scope like any task error |
An exit by a handler that returns without resuming counts as a normal exit for this table. When the handler is catch's, the caught failure already exists, and cleanup errors join its :suppressed before catch's clause runs. When it is a handler for another effect, there is no failure to attach to, so a cleanup error propagates; attaching it nowhere would lose it.
A failing cleanup on a normal exit is a real error, not noise: closing a file after writing can fail when the disk is full, and silently ignoring that is a classic bug in Go. To ignore a cleanup error deliberately, handle it inside the defer:
(defer (catch (remove-temp tmp)
_ (log (str "could not remove " tmp))))
Why not strict effect typing
If effects are part of a function's type, redefining the function in the REPL changes its type and can break the types of every caller. In a live environment that is constant friction. Soft checking keeps the benefit (you can see that a function touches the network or can raise NotFound) without breakage on redefinition. Types take the same approach (D007). Nothing is declared in signatures, unlike Java's checked exceptions; the editor shows "raises ConfigError.NotFound", and the compiler may warn that a catch misses an error the body can raise.
Why effects instead of separate mechanisms
- Every mechanism built before self-hosting is work. One mechanism that covers five tasks speeds up self-hosting.
- Effects are in production: OCaml 5 (in the runtime, untyped), Unison (abilities), Koka and Flix (typed).
Rejected alternatives
- Strictly typed effects, as in Koka: they break live redefinition.
- Separate mechanisms (exceptions, async/await, dynamic vars, generators): more work before self-hosting, and function coloring (D006).
- Effects named by keywords: names collide between libraries, and misspellings go unnoticed.
- Errors as maps, as in Clojure's
ex-info: no field checks, no exhaustiveness, no inference of which errors a function raises. - Errors as values (
Result) as the primary mechanism, as in Ferron and Rust: every intermediate function has to pass errors along;attemptgives values where they are actually needed. - Hints only in error types: a library cannot know the application's context.
Open questions
- Lexical handlers (passed as values) or dynamic ones (found by type on the stack, as above)?
- One-shot or multi-shot continuations? Proposal: one-shot by default, multi-shot as an explicit, expensive operation.
- Validate the design on real code before the syntax is settled: write the compiler's error handling and diagnostics, and a generator, with effects first.