# ADR 0010: Lexically scoped effect handlers **Status:** Accepted by the project owner on 2026-10-12; proposed 2026-10-08, decided by the project owner; needs engineering review (#44). This supersedes the parts of [ADR 0008](0008-effect-typing.md) that depend on dynamic scoping: equality of rows at calls, and `mask`. An independent soundness review shaped the rules below (eager resolution, no choice by type arguments, level-based escape check). ## Context In Koka, which Louise followed so far, an operation goes to the **innermost handler at run time** (*dynamic scoping*). That has two costs: - **Accidental handling.** A function that installs a handler for `log` also catches the `log` operations of callbacks it is given. This is why ADR 0008 requires a callee's effect row to *equal* the current one, and why a callback with fewer effects than its caller needs `mask`. - **Native lowering.** Finding a handler means a search at run time. The unwinding of [ADR 0003 Rev. 1](0003-effect-lowering.md) follows *Zero-Overhead Lexical Effect Handlers* (Ma et al., OOPSLA 2025), which is designed for lexically scoped handlers. **Lexical scoping** (Effekt; Biernacki et al., *Binders by day, labels by night*, POPL 2020; Lexa, OOPSLA 2024): an operation goes to the handler that is visible **where the operation is written**. Library code then cannot intercept effects by accident, and every operation knows its handler statically. ## Decision ### Handler instances - Each `handle` and each `region` creates a fresh **instance** of the effect it handles: a rigid type, like a region. - In types, every effect label carries its instance: `log` is internally `log<ι>`. Instances are never written and never printed. - `st` and `alloc` use their region `h` as the instance. - Effects without operations (`io`, `ffi`) have no instance. - Labels whose instances differ are different labels. This replaces the special rule that let `st` of different regions skip each other (ADR 0002 Rev. 1). ### Resolving an operation: eagerly, from the lexical environment At every operation, call, and use of a function as a value, each label of the callee's row is resolved against the **capability environment** at that point. Innermost first, it contains: 1. handlers and regions enclosing the point, inside the current function or lambda; 2. the current function's or lambda's own row (its capability parameters); 3. for a lambda, the environment where the lambda is written, then outwards. **Rules:** - **Known instance:** take the label with the same instance. If none is in scope, the program is rejected: the handler is no longer visible. - **Unknown instance:** take the **nearest** label of the same effect. - Type arguments never choose the handler. If they disagree, that is a type error, not a reason to keep searching. - So `get()` inside `handle state` nested in `handle state` reaches the `String` one, as written. - **Found outside the current lambda:** the label is added to the row of every lambda in between. A lambda's type then records which handlers it uses, and anyone calling it must have them in scope. - **Not found anywhere:** the label is added to the enclosing top-level function's row, if that row is inferred. Otherwise the effect is unhandled (E0502). ### Calls use inclusion A callee's row must be **included** in the current environment, not equal to it: - each label resolves as above; - a callee row variable becomes the current row minus the matched labels; - a closed callee row may leave labels unused. **Why this is now sound** (it was not in ADR 0008): routing goes by instance, so a `state` callback can never meet a `state` handler. The invariant: *every instance in the current row has its handler frame on the stack*. - It holds for `handle`, whose lexical scope lies inside its dynamic extent. - It holds for capability parameters by induction, and for closures because of the escape check below. - `resume: fn(x) -> R / outer` never mentions the handler's own instance. - Clauses run in the outer environment, so a clause that performs its own effect reaches the next handler out. `mask` is no longer needed and will not be added. ### Escape check An instance must not outlive its handler's body. - Each `handle`, `region` and capability-receiving lambda opens a **level**. - Binding a type variable from an outer level to a type mentioning an instance from an inner level is an error (E0701 for regions, E0703 for handlers). The result of the body must not mention the instance either. - This replaces the scan over variables made before a region. ### Capability parameters **Where the caller supplies the handler:** - A top-level function's own row: `fn greet() -> Html / ` takes the caller's `log`. Its instance is a type parameter of the scheme, instantiated at each call. - Effects in **declared arrow types** (parameters and fields in signatures, operation parameters, trait methods): `action: fn() -> a / ` says "whoever calls `action` provides `log`". The instance is bound at that arrow (internally `Bound(k)`), and every call supplies a fresh one. **Lambdas against such a type:** - A lambda checked against such a type receives its own capability. Its operations reach the caller's handler: in `with_console_log(fn() { log("x") })`, the `log` goes to the handler inside `with_console_log`. - A function name used where such a type is expected becomes a wrapper that forwards the capability. **Local annotations** (`let f: fn() -> () / = ...`) never bind instances. If they did, adding an annotation would change where operations go. ### Run time - **Capabilities are values:** - top-level functions take one per instance-carrying label of their own row; - closures take one per `Bound` label of their type; - closures capture all other capabilities like ordinary variables. A row variable `e` never needs a run-time representation, because operations in it can only be performed by closures that captured their capabilities. - `Perform` names its capability; `Handle` and `region` pass the new capability to their body. - **The interpreter** routes a request to the handler frame with that identity. Frames forward other requests outward, and continuations keep their frames. - **Roots:** - the runtime gives `main`, `@test` functions and every spawned actor a root `proc` capability; - actor bodies have closed rows, so a child cannot capture its parent's handlers. ## Consequences **Programs that change:** - A higher-order function without annotations that installs a handler around a callback is rejected. Example: `fn collect(action) { handle { action() } with { yield... } }`. - The callback would have to receive the handler, and inference does not invent capability parameters. - Annotating the parameter fixes it: `action: fn() -> a / `. This is Effekt's rule for block parameters. - A callback with fewer effects than its caller is accepted. This is the example in ADR 0008 that used to need `mask`. - A callback typed only with a row variable (`f: fn() -> a / e`) no longer reaches handlers installed by the function it is passed to. Its operations go where it was written. - Recursion inside a handler of the function's own effect needs a signature. Inferred recursion is monomorphic in instances. **Native backend (M5):** - Every operation knows its handler frame statically, as a capability variable. This is the setting of Zero-Overhead Lexical Effect Handlers: `fn` operations become direct calls through the capability. - `final ctl` unwinds to a known frame. - The per-effect choice of unwinding strategy (ADR 0003 Rev. 1) still applies. ## Alternatives considered - **Keep dynamic scoping (Koka).** Simpler inference and no capability parameters, but it keeps accidental handling, row equality and `mask`, and handler search at run time. - **Effekt's capture sets.** These track captured capabilities separately from effects. They are more precise, but they need a second kind of polymorphism. Here, instances in rows plus the level check give the same safety with HM inference. - **Evidence vectors built per call (Koka-style).** This would pass every capability, including those of row variables, at every call. It is unnecessary once closures capture their capabilities. - **Choosing a handler by its type arguments.** This makes routing depend on inference order and annotations. ## Note — 2026-10-18: a rigid row tail under a nonempty row **Status:** Proposed; needs engineering review (#44). Calling a function whose row's tail is a rigid row variable (a handler's parameter, an existential's, a callback's action) no longer requires the current row to be empty: its flexible tail becomes the callee's extra labels over the rigid one (`perform` in `louise_types::infer::effects`). That is what a `use` callback needs when it calls its action after a concrete effect (the postgres package's `savepoint`: `execute` then `action()`). One restriction stays: after such a call, a *new* concrete effect in the same scope can't extend the now-rigid tail (E0502) — perform it first. Also, the dead-row lint (issue #203) reads the zonked row of each call's effects, so effects performed through a callback's row variable count as performed; and a site already reported by `resolve` isn't repeated by `unhandled` (one E0502 per site).