# RFC 0003: Direct-style effects | | | | --- | --- | | Status | Stage 1 implemented (direct-style effect bodies + unified tail-resumptive `handle` compiling to Effect 4 TypeScript and in-process `runEffectProgram`, backwards-compatible with `do!`/`pure`/`catch`/`provide`/`layer`); Stages 2–4 (full unannotated effect inference, `without` row subtraction, evidence-passing JS and Perceus-FBIP native/Wasm backends) remain planned | | Created | 2026-10-06 | | Updated | 2026-12-03 | | Scope | Direct-style algebraic effects, unified `handle`, service operations, evaluation order, Effect 4 TypeScript lowering, and planned multi-backend targets | | Direction | Ordinary Lisp calls and bindings, unified tail-resumptive `handle` for services and typed failures, Effect 4 TypeScript as the first backend, and planned zero-overhead evidence-passing JS / Perceus-FBIP native & Wasm backends | ## Summary Effectful operations use ordinary direct-style calls, `let`, `if`, `match`, and sequential bodies — without requiring `do!` or `pure` — while keeping `do!`, `pure`, `catch`, `provide`, and `layer` 100% backwards-compatible. A unified `handle` form discharges both local service operations (tail-resumptive via `(resume val)` or direct return) and typed failures (`(fail Err [e] recovery)`) in one construct. **Implemented today (Stage 1):** - Direct-style effect calls inside Effect operations (`(: op (-> ... (Effect A [E] [R])))`): service calls, calls to other Effect operations, `fail`, and `handle` inside `let`, sequential bodies, `if`, `match`, and nested arguments lift automatically into `Effect.gen` + `yield*`, while pure subexpressions compile to plain JavaScript with zero fiber overhead. A pure final expression returns cleanly without `(pure ...)`. - Unified `(handle expr (Service.method [args...] (resume val)) ... (fail ErrName [e] recovery) ...)`: tail-resumptive service clauses discharge `Service.method` from the required effect row and lower to `Effect.provideService` / local service objects; `fail` clauses catch typed errors and lower to `Effect.catchTag`. Both clause kinds may appear together in a single `handle` block, and both run in-process via `runEffectProgram`. - **First compilation backend:** Effect 4 TypeScript (`Effect.gen`, `yield*`, `Effect.provideService`, `Effect.catchTag`). **Planned (not yet implemented):** - Full effect inference on unannotated functions and zero-argument deferred functions (`(fn [] ...)`) with effect-polymorphic higher-order combinators (see also [RFC 0023](./0023-effect-polymorphism.md) Stages 4 & 6 for `without` subtraction, and [RFC 0014](./0014-local-providers.md) for `:delegate` partial providers). - **Zero-overhead evidence-passing JavaScript backend:** Koka-style evidence passing for tail-resumptive handlers without fiber allocation on synchronous paths. - **Perceus-FBIP native / WebAssembly backend:** Reference-counted native and Wasm code generation with Functional But In-Place (FBIP) reuse for immutable data structures. - General multi-shot continuation capture (remains out of scope for the tail-resumptive core). This RFC builds on [RFC 0001](./0001-unified-syntax.md) and [RFC 0002](./0002-modules-and-packages.md), and cross-links [RFC 0014](./0014-local-providers.md) (local providers), [RFC 0022](./0022-effect-hosts.md) (host-neutral lowering), [RFC 0023](./0023-effect-polymorphism.md) (effect-polymorphic signatures), and [RFC 0030](./0030-open-polymorphic-variants.md) (open polymorphic variants). The [Effect reference](../effect/reference.md) documents the shipped Effect surface. ## Implemented surface (Stage 1): Direct-style calls and unified `handle` ### Direct-style effect bodies (no `do!`, no `pure`) Inside an Effect operation, authors write ordinary direct-style Forma: ```lisp (error NotFound {:id String}) (service Users (: find (-> String (Effect {:name String :email String} [NotFound])))) (service Mailer (: send (-> String String (Effect Unit)))) (: checkout (-> String (Effect String [NotFound] [Users.find Mailer.send]))) (define checkout [id] (let [user (Users.find id)] (Mailer.send user.email "Receipt") user.name)) ``` The compiler lifts only the effectful subexpressions (`(Users.find id)`, `(Mailer.send ...)`) into `yield*` inside `Effect.gen`, leaving pure bindings, field projections, and the final `user.name` return as plain JavaScript with no `do!` or `(pure ...)` wrapper. Existing `do!` / `pure` / `catch` / `provide` / `layer` programs continue to work unchanged. ### Unified `handle` `handle` unifies local service handling and typed error recovery in a single expression: ```lisp (: checkout-safe (-> String (Effect String))) (define checkout-safe [id] (handle (checkout id) (Users.find [uid] (resume {:name "Ada" :email "ada@example.com"})) (Mailer.send [_to _body] (resume nil)) (fail NotFound [e] (str "missing user: " e.id)))) ``` - **Service clauses** `(Service.method [args...] (resume val))` (or a direct tail expression `(Service.method [args...] val)`) are tail-resumptive: they discharge `Service.method` from the required effect row and compile to `Effect.provideService` with a local service implementation in Effect 4 TypeScript (and execute in-process in `runEffectProgram`). - **Failure clauses** `(fail ErrName [e] recovery)` discharge `ErrName` from the error row and compile to `Effect.catchTag` in Effect 4 TypeScript (and execute in-process in `runEffectProgram`). - Service clauses and `fail` clauses may be combined in one `handle` block, or used independently. Unhandled effects or errors remain compile-time errors. ## Planned direction (Stages 2–4): Full inference and deferred computations ```lisp (import "./orders.lisp" [OrderId Order]) (import "@forma/effect" [service]) (export Payments pay) (service Payments (: charge (-> OrderId Int Unit))) (define pay [order] (do (Payments.charge order.id order.total-cents) {:id order.id :total-cents order.total-cents :status :paid})) ``` The service declaration makes `Payments.charge` a capability operation. Its call returns `Unit` and contributes `Payments.charge` to the caller's inferred requirements. The surrounding function returns the record after charging succeeds. It needs neither `do!` nor a discarded-result binding. Inference determines the function's structural input and output types. It does not invent the author's intended named domain type. An optional signature can require the exact public contract: ```lisp (: pay (-> Order Order :requires [Payments.charge])) ``` If charging can fail, the declaration and public contract can express that too: ```lisp (error PaymentDeclined {:id OrderId}) (service Payments (: charge (-> OrderId Int Unit :throws [PaymentDeclined]))) (: pay (-> Order Order :requires [Payments.charge] :throws [PaymentDeclined])) ``` The return type is the normal successful value. Requirements and failures describe evaluation of the function. Service interfaces still need signatures because they have no bodies from which to infer their contracts. ## Calling now and deferring until later Within an executing function, a call performs its operations and produces a result: ```lisp (let [paid (pay order)] paid) ``` `paid` is the successful order. The charge has already happened before the body of the `let` continues. The caller must provide the required capability or propagate the requirement to its caller. A zero-argument function defers that call: ```lisp (let [payment-job (fn [] (pay order))] (payment-job)) ``` Creating `payment-job` does not charge anything. Invoking it performs the call. Every invocation evaluates its body again; this is not a memoized result or an already-running task. Ordinary lexical capture applies: values computed outside the function are captured, while expressions inside its body run on invocation. ### Running a deferred computation Inside an executing Forma program, call the function normally: ```lisp (let [job (fn [] (pay order))] (job)) ``` `(job)` returns the successful paid order, or propagates the call's typed failure. Its requirements become requirements of the caller. There is no separate source `run` operation for deferred functions: ordinary application supplies that behavior. If a provider is needed at that point, it can be installed while invoking the job: ```lisp (provide job PaymentsLive) ``` The CLI or host runner starts the outer entry function with its configured providers. Calling an exported generated TypeScript function follows the target's Effect API: it creates an Effect value that the host executes through that target's runner. Source-level application inside a running Forma program is compiled to the required sequencing; it does not ask the author to run a second runtime manually. This distinction is needed whenever an operation must control execution, for example retrying, starting a child task, or installing a service provider before calling a function. Those operations can accept ordinary functions: ```lisp (retry (fn [] (load-order id)) :times 3) (fork (fn [] (pay order))) (provide (fn [] (pay order)) PaymentsLive) ``` These examples show proposed library APIs. `retry` invokes its argument for each attempt. `fork` schedules its argument as a child task. `provide` installs the provider while invoking its argument. Their own effect types describe the requirements and failures that remain after each operation. With ordinary eager argument evaluation, `(retry (load-order id) :times 3)` would load the order before `retry` receives its argument. It would receive the result, not a function it can invoke again. The higher-order API therefore requires a function and rejects that call by type. ### Do we need `suspend`? We need a way to represent execution that has not happened yet. Existing function syntax already supplies that way: | Expression | Proposed meaning | | --- | --- | | `(pay order)` | Call now in the current execution context | | `(fn [] (pay order))` | Construct a function that calls when invoked | | `(suspend (pay order))` | Possible convenience spelling, not required by this RFC | If `suspend` merely expands hygienically to `(fn [] ...)`, it adds no new runtime semantics. The initial design should use functions and avoid introducing another construct for the same behavior. A distinct first-class computation type could be useful for interoperability or additional operations. That would need its own rules for construction, execution, and capture. It must not be introduced by silently changing which ordinary calls execute or by automatically unwrapping values according to their type. ## Evaluation and inference Function arguments and record fields evaluate from left to right. `do` sequences expressions. `let` evaluates bindings in order, making prior bindings available to later ones. `if`, `match`, and boolean short-circuiting evaluate only the selected path at runtime. Static inference accounts for every path that might execute. A function's effects include those of its evaluated expressions and called functions. Creating a function does not execute its body: the body's effects belong to its function type and become relevant when that function is called. Asynchronous calls preserve the same sequencing unless an explicit concurrency operation changes it. Higher-order functions must be polymorphic over their callbacks' effects. For example, `map` with a pure callback is pure, while a sequential `map` with an effectful callback propagates its effects and preserves element order. Parallel traversal remains an explicit library operation. The syntax for open effect rows requires a separate decision; the compiler model must support them. [RFC 0023](./0023-effect-polymorphism.md) proposes that decision for signatures: error-set and requirement-set variables that are solved at each call, so every call result and operation boundary stays closed. An absent function signature means infer its input types, result, requirements, and failures. This applies to local and exported functions. An explicit signature is checked as a contract: inferred effects must fit within its declared rows. For the proposed closed signatures, omitted `:requires` and `:throws` options mean empty rows. Authors who write `(-> Order Order)` therefore assert purity; they can omit the signature entirely to request inference. Pure helpers remain checked as pure when their signatures require it. A call to an effectful function cannot enter a pure expression unnoticed. The language does not require special binding syntax to maintain that property. ## Failures, providers, and execution contexts Typed failure aborts the current normal evaluation path. A proposed direct-style `raise` operation contributes its error type; `catch` handles selected errors and removes the handled cases from the outgoing failure row. Handler code may introduce new requirements or failures of its own. ```lisp (catch (pay order) (PaymentDeclined error) {:status :declined :id error.id}) ``` `catch` is a control construct: it establishes the handler before evaluating its protected expression. Its result type must accept the results of both the normal path and the handled path. Typed failures remain distinct from runtime defects and task interruption. Requirements carry resolved service and member identities across modules. A provider discharges the requirements it implements and propagates any dependencies needed by that implementation. Providers are resolved in the invocation context; creating a deferred function does not implicitly freeze a provider environment. Applications that need a fixed provider can explicitly invoke `provide` inside their deferred function. Module initialization is pure. It can construct functions and immutable data, but cannot perform service operations merely because the module was imported. An application exposes a zero-argument entry function: ```lisp (export main) (define main [] (pay example)) ``` The runner invokes `main` with the configured providers. Missing requirements are diagnosed at the configured application boundary. Resource scopes, finalization, child-task cancellation, and escaping resource values must retain explicit rules; direct syntax does not remove their runtime semantics. ## Lowering and runtime scope ### First backend (implemented): Effect 4 TypeScript & in-process runner Effect 4 TypeScript is the first compilation backend. Direct-style effect bodies lower to `Effect.gen` with `yield*` inserted only at effectful calls, while pure subexpressions remain ordinary JavaScript expressions with zero fiber overhead. Services lower to `Context.Service`, unified `handle` service clauses lower to `Effect.provideService` (local service objects), `fail` clauses lower to `Effect.catchTag`, top-level `layer` declarations lower to `Layer.succeed` / `Layer.effect`, and typed failures lower to `Schema.TaggedError`. The in-process runner (`runEffectProgram`) executes the same direct-style and `handle` forms against in-memory layers and handlers. ### Planned future backends (not yet implemented) Because the surface language commits to tail-resumptive algebraic effects rather than Effect-specific syntax, future backends can compile the same direct-style Forma source without changing user code (building on the host-neutral lowering architecture in [RFC 0022](./0022-effect-hosts.md)): - **Zero-overhead evidence-passing JavaScript backend (planned):** Compiles tail-resumptive `handle` clauses to Koka-style evidence vectors passed as hidden parameters, eliminating generator/fiber allocation for synchronous effectful paths. - **Perceus-FBIP native / WebAssembly backend (planned):** Compiles Forma to native and Wasm targets using Perceus precise reference counting and Functional But In-Place (FBIP) memory reuse for immutable records, lists, and variants. Full algebraic effect handlers with arbitrary multi-shot continuation capture or repeated resumption remain a separate extension and are not implied by the tail-resumptive `handle` surface. ## Implementation stages and validation 1. **Direct-style bodies & unified `handle` on Effect 4 TS (implemented):** Direct-style `let`/sequence/`if`/`match`/nested calls without `do!`/`pure`, unified tail-resumptive `handle` (service clauses + `fail` clauses) compiling to `Effect.gen` / `yield*` / `Effect.provideService` / `Effect.catchTag`, in-process `runEffectProgram` execution, and 100% backwards compatibility with `do!`/`pure`/`catch`/`provide`/`layer`. 2. **Full unannotated effect inference & effect-polymorphic HOFs (planned):** Inferring latent effects on unannotated functions and function values, paired with [RFC 0023](./0023-effect-polymorphism.md) Stages 4 & 6 (`without` row subtraction) for reusable `handle` wrappers. 3. **Zero-overhead evidence-passing JS backend (planned):** Evidence-passing lowering for tail-resumptive handlers on JS runtimes without fiber overhead. 4. **Perceus-FBIP native / Wasm backend (planned):** Native and WebAssembly lowering with Perceus reference counting and FBIP reuse. Acceptance coverage includes exactly-once sequencing, conditional evaluation, failure short-circuiting, effect propagation, pure-signature rejection, and cross-module calls. Deferred-function fixtures verify no work at construction, fresh evaluation per invocation, provider scope, and retry attempts. Higher-order fixtures distinguish callback construction from callback invocation. Integration checks compare results, failures, operation traces, and cleanup across engines and generated targets. The [module RFC](./0002-modules-and-packages.md) uses the current Effect-value surface in its examples. This proposal changes those examples to direct-style calls and zero-argument entry functions when adopted. The existing implementation remains as documented until this proposal is implemented. ## Decisions still required - The exact syntax and inference rules for open requirement and failure rows. [RFC 0023](./0023-effect-polymorphism.md) proposes set variables and `without` in signatures; this RFC adopts that notation if both are accepted. - Whether `suspend` is useful enough to add as a convenience macro later. - Whether a distinct first-class computation type is needed beyond function values. - Library contracts for retry, providers, resources, and task operations. - Resource escape rules and the boundary between typed failures, defects, and interruption. - Scope and runtime support for any future general algebraic handlers. ## Related designs Koka presents Hindley–Milner-style inference for types and row-polymorphic effects. See [Koka: Programming with Row Polymorphic Effect Types](https://arxiv.org/abs/1406.2061). Unison describes capability requirements on function types, ordinary expression syntax for effectful programs, and ability handlers. See its [abilities and ability handlers reference](https://www.unison-lang.org/docs/language-reference/abilities-and-ability-handlers/). Those designs inform this proposal; the syntax and target restrictions here are Forma-specific choices.