# corophage > Algebraic effects for stable Rust corophage lets you define side effects as plain structs, write business logic that yields those effects, and attach handlers separately. Programs are testable, composable, and run on stable Rust with no macros beyond the optional `#[effect]` and `#[effectful]` attributes. - [Source Code](https://github.com/romac/corophage) - [Crate](https://crates.io/crates/corophage) - [API Documentation](https://docs.rs/corophage) --- ## Getting Started ## Installation Add `corophage` to your `Cargo.toml`: ```toml [dependencies] corophage = "0.7.0" ``` corophage requires **Rust 1.93** or later (stable). The default `macros` feature provides `#[effect]` and `#[effectful]`. Set `default-features = false` on the dependency to use [manual `Effect` implementations](@/docs/effects.md#manual-effect-implementation) and `Program::new`. The `Effects!` macro remains available. If you rename the dependency in `Cargo.toml`, the `#[effect]` and `#[effectful]` macros automatically use that Cargo name: ```toml [dependencies] coro = { package = "corophage", version = "0.7.0" } ``` You can then import the prelude with `use coro::prelude::*;`. ## What are effect handlers? Imagine you are writing a piece of business logic: 1. Log a "starting" message. 2. Read some configuration from a file. 3. Get the current application state. 4. Perform a calculation and update the state. 5. If a condition is met, cancel the entire operation. Traditionally, you'd write a function that takes a logger, a file system handle, and a mutable reference to the state. This function would be tightly coupled to these specific implementations. With effect handlers, your business logic function does none of these things directly. Instead, it *describes* the side effects it needs to perform by `yield`ing **effects**. The responsibility of *implementing* these effects is given to a set of **handlers**. You provide these handlers to a runner, which executes your logic and calls the appropriate handler whenever an effect is yielded. ## Your first program ```rust use corophage::prelude::*; // 1. Declare effects #[effect(())] struct Log(String); #[effect(String)] struct FileRead(String); // 2. Write the computation #[effectful(Log, FileRead)] fn my_program() -> String { yield_!(Log("Starting...".into())); let config = yield_!(FileRead("config.toml".into())); config } // 3. Attach handlers and run let result = my_program() .handle(|Log(msg)| { println!("{msg}"); Control::resume(()) }) .handle(|FileRead(f)| { Control::resume(format!("contents of {f}")) }) .run_sync(); assert_eq!(result, Ok("contents of config.toml".to_string())); ``` Let's walk through each step. ### Step 1: Declare effects ```rust #[effect(())] struct Log(String); #[effect(String)] struct FileRead(String); ``` An effect is a plain struct annotated with `#[effect(ResumeType)]`. The struct's fields carry the request data — `Log` carries the message to log, `FileRead` carries the path to read. The attribute argument defines what the handler sends back. `Log` resumes with `()` because logging doesn't produce a value. `FileRead` resumes with a `String` — the file's contents. ### Step 2: Write the computation ```rust #[effectful(Log, FileRead)] fn my_program() -> String { yield_!(Log("Starting...".into())); let config = yield_!(FileRead("config.toml".into())); config } ``` The `#[effectful(Eff1, Eff2, ...)]` macro marks a function as an effectful computation. Inside the function body, use `yield_!(effect)` to perform an effect — this pauses execution, hands the effect to its handler, and resumes with the handler's return value. The computation doesn't know *how* logging or file reading work. It just describes what it needs. ### Step 3: Attach handlers and run ```rust let result = my_program() .handle(|Log(msg)| { println!("{msg}"); Control::resume(()) }) .handle(|FileRead(f)| { Control::resume(format!("contents of {f}")) }) .run_sync(); ``` Calling `my_program()` returns a `Program` — a description of the computation, not the result. Each `.handle()` call attaches a handler for one effect. Handlers can be attached in any order. Once all effects are handled, `.run_sync()` executes the computation and returns a `Result`. If you try to call `.run_sync()` before all effects are handled, you'll get a compile error. ### Manual alternative You can also create programs directly with `Program::new` instead of `#[effectful]`: ```rust type MyEffects = Effects![Log, FileRead]; let program = Program::new(|mut y: Yielder<'_, MyEffects>| async move { y.yield_(Log("Starting...".into())).await; let config = y.yield_(FileRead("config.toml".into())).await; config }); ``` This is useful when you need more control over the closure (e.g., capturing specific variables by reference). ## Benefits - **Testability**: Swap in mock handlers for testing without touching the real world. - **Modularity**: The core logic is completely decoupled from its execution context. Run the same logic with different handlers for different environments. - **Clarity**: Business logic becomes a pure, high-level description of the steps involved, making it easier to read and reason about. > corophage provides **single-shot** effect handlers: each handler can resume the computation at most once. This is a deliberate design choice that keeps the implementation efficient and compatible with Rust's ownership model. --- ## Effects An **Effect** is a struct that represents a request for a side effect. It's a message from your computation to the outside world. ## Defining effects with `#[effect]` To define an effect, annotate a struct with `#[effect(ResumeType)]`. The resume type defines what value the computation receives back after the effect is handled. A bare `#[effect]` is shorthand for `#[effect(())]`. ```rust use corophage::prelude::*; #[effect(())] pub struct Log(pub String); #[effect(String)] pub struct FileRead(pub String); #[effect(Never)] pub struct Cancel; ``` The macro supports lifetimes, generics, named fields, and borrowed resume types: ```rust // Lifetime parameters #[effect(bool)] pub struct Borrow<'a>(pub &'a str); // Generic parameters #[effect(T)] pub struct Generic(pub T); // Named fields #[effect(Vec)] pub struct ReadDir { pub path: String, pub recursive: bool } // The resume type may reference the GAT lifetime 'r #[effect(&'r str)] pub struct Lookup(pub String); ``` A resume type that borrows a value of a type parameter, such as `&'r T`, needs that parameter to be `'static`: ```rust #[effect(&'r T)] pub struct Get(pub std::marker::PhantomData); ``` Only the type parameter must be `'static`. The handler can still resume with a short-lived borrow, such as a reference to a local value, and the program remains `Send`. Without the bound, the compiler reports that `T` may not live long enough. Removing the requirement would break `Send` for effects with lifetime parameters because of a current compiler limitation ([rust-lang/rust#100013](https://github.com/rust-lang/rust/issues/100013)). ## Manual `Effect` implementation If you need to implement the `Effect` trait by hand (without the macro), you must provide both the `Resume` associated type and the `shorten_resume` method: ```rust struct Ask(pub String); impl Effect for Ask { type Resume<'r> = &'r str; fn shorten_resume<'a: 'b, 'b>(resume: &'a str) -> &'b str { resume } } ``` The `shorten_resume` method witnesses that `Resume<'r>` is **covariant** in `'r` -- that is, a resume value with a longer lifetime can be safely used where a shorter lifetime is expected. This is required by [`invoke`](@/docs/programs.md#program-composition) to allow sub-programs to borrow from shorter-lived data than the outer program. The body is always just `resume`. The `#[effect]` macro generates this automatically, so you only need to write it when implementing `Effect` by hand. ## Effect sets with `Effects!` Effects are grouped into sets using the `Effects!` macro: ```rust type MyEffects = Effects![Log, FileRead, Cancel]; ``` This creates a type-level list (coproduct) of effects. The type system tracks which effects have been handled and prevents you from running a program until all effects have handlers. You can also compose effect sets using the `...Alias` spread syntax to splice in an existing type alias: ```rust type IoEffects = Effects![Log, FileRead]; type AllEffects = Effects![Cancel, ...IoEffects]; // Equivalent to: Effects![Cancel, Log, FileRead] ``` The spread must appear as the last argument. This follows the same convention as frunk's `Coprod!(...Tail)` syntax. ## Generic effect sets Use the `Effects<'a>` trait when a helper should accept any effect set. The trait and the `Effects!` macro share a name and are both available from the prelude: ```rust use corophage::prelude::*; fn identity<'a, Es: Effects<'a>, F>( program: Program<'a, Es, F>, ) -> Program<'a, Es, F> { program } ``` `Effects<'a>` is implemented automatically for effect coproducts whose payloads satisfy `Send + Sync + 'a`, including `Effects![]`. The lifetime permits effects to borrow local data. It does not require their resume values to be `Send` or `Sync`; sendable execution checks those requirements separately. A generic helper that invokes a callback's program also needs bounds to forward its effects and return the corresponding resumes. `Resumes<'r, Es>` names the coproduct of the effects' `Resume<'r>` types, in the same order as `Es`. Its resume lifetime is independent of the effect-set lifetime. ```rust use corophage::{EmbedEffect, ProjectResume, Resumes}; use std::future::Future; fn invoke_callback<'a, Es, F, Make, Indices>( make: Make, ) -> Program<'a, Es, impl Future + 'a> where Es: Effects<'a> + EmbedEffect, Resumes<'a, Es>: ProjectResume<'a, Es, Indices>, F: Future + 'a, Make: FnOnce() -> Program<'a, Es, F> + 'a, { Program::new(|mut y: Yielder<'a, Es>| async move { y.invoke(make()).await }) } ``` `EmbedEffect` forwards a child's effect into the parent set; `ProjectResume` returns the matching response to the child. Use the same generic `Indices` parameter in both bounds. These bounds are needed even when both sets are `Es`; concrete call sites infer the indices. When the child uses a subset of the parent's effects, use `SubEffs: EmbedEffect` and `Resumes<'a, OuterEffs>: ProjectResume<'a, SubEffs, Indices>` instead. These public bounds support generic program construction and invocation. Generic handler-list assembly and execution have additional dispatch bounds. --- ## Programs A **Program** combines a computation with its effect handlers. This is the primary API for using corophage. ## Creating a program with `#[effectful]` The simplest way to create a program is with the `#[effectful]` attribute macro: ```rust use corophage::prelude::*; #[effect(())] struct Log(String); #[effect(u64)] struct Counter; #[effectful(Log, Counter)] fn my_program() -> u64 { yield_!(Log("hello".into())); let n = yield_!(Counter); n * 2 } ``` The `#[effectful(Eff1, Eff2, ...)]` macro: - Transforms the return type to `Program<'_, Effects![Eff1, Eff2, ...], impl Future + '_>` - Wraps the body in `Program::new` - Enables `yield_!(effect)` syntax to perform effects The body future keeps its concrete type by default. Its auto traits, including `Send`, remain available to the caller. See [explicit boxing](@/docs/advanced.md#explicit-boxing-and-recursion) for stored, erased, or recursive programs. ### Lifetime handling Borrowed and generic arguments are captured for the lifetime of the returned program automatically. Elided references, `&self` receivers, generic parameters, and argument-position `impl Trait` do not need artificial lifetime annotations or outlives bounds. ```rust #[effectful] fn length(value: &str) -> usize { value.len() } ``` Borrowed wrappers can use placeholder lifetimes, including in nested argument types. Each placeholder is inferred independently: ```rust use std::borrow::Cow; #[effectful] fn cow_length(value: Cow<'_, str>) -> usize { value.len() } let text = String::from("hello"); assert_eq!(cow_length(Cow::Borrowed(&text)).run_sync(), Ok(5)); ``` Nested references also keep independent lifetimes. For example, the outer borrow in `&mut &str` can end before the inner string data expires. This permits sequential calls after each program completes or is dropped: ```rust #[effectful] fn advance(value: &mut &str) -> usize { *value = &value[1..]; value.len() } let text = String::from("abc"); let mut remaining = text.as_str(); assert_eq!(advance(&mut remaining).run_sync(), Ok(2)); assert_eq!(advance(&mut remaining).run_sync(), Ok(1)); assert_eq!(remaining, "c"); ``` Generic parameters, argument-position `impl Trait`, and borrowed receivers work the same way: ```rust #[effectful] fn stringify(value: T) -> String { value.to_string() } #[effectful] fn stringify_impl(value: impl ToString) -> String { value.to_string() } struct Label(String); impl Label { #[effectful] fn length(&self) -> usize { self.0.len() } } ``` For borrowed effects, declare a lifetime on the effect itself. Here, `BorrowedLog` carries a string reference. The macro infers the effect lifetime when the function has exactly one lifetime parameter: ```rust #[effect(())] struct BorrowedLog<'a>(&'a str); #[effectful(BorrowedLog<'a>)] fn log_msg<'a>(msg: &'a str) -> () { yield_!(BorrowedLog(msg)); } ``` With multiple lifetime parameters, specify the effect lifetime explicitly as the first argument: ```rust #[effectful('a, BorrowedLog<'a>)] fn log_msg<'a, 'b>(msg: &'a str, _other: &'b str) -> () { yield_!(BorrowedLog(msg)); } ``` An explicit lifetime can also be the only attribute argument. Declare a named lifetime on the function, enclosing `impl`, or enclosing `trait`; the attribute selects that declaration. A named lifetime needs no trailing comma, `'static` remains a concrete lifetime, and `'_` requests the same inference used when the lifetime is omitted: ```rust #[effectful('a)] fn named<'a>(value: &'a str) -> usize { value.len() } #[effectful('static)] fn static_value() -> &'static str { "static" } #[effectful('_)] fn inferred(value: &str) -> usize { value.len() } ``` Methods and associated functions can reuse a lifetime from their enclosing `impl`: ```rust struct Reader<'a>(&'a str); impl<'a> Reader<'a> { #[effectful('a)] fn text(&self) -> &'a str { self.0 } } let text = String::from("hello"); let reader = Reader(&text); assert_eq!(reader.text().run_sync(), Ok("hello")); ``` If existing code relied on the attribute to introduce a named lifetime, add a Rust declaration such as `fn read<'a>(...)`, or omit the attribute lifetime to use inference. ### `Send`-able programs The default program can be `Send` when its body and resume transport are `Send`. Add `send` to check the body guarantee at the function definition: ```rust #[effectful(Counter, send)] fn my_send_program() -> u64 { yield_!(Counter) } ``` ### Spreading an effects type alias If you define a reusable set of effects with `type MyEffs = Effects![...]`, you can spread it into the attribute with `...Alias` (the same syntax as frunk's `Coprod!(...Tail)`): ```rust type MyEffs = Effects![Log, Counter]; #[effectful(...MyEffs)] fn using_alias() -> u64 { yield_!(Log("hello".into())); yield_!(Counter) } ``` You can also prepend extra inline effects before the spread: ```rust #[effect(&'r str)] struct GetConfig; #[effectful(GetConfig, ...MyEffs)] fn with_extra() -> String { let cfg = yield_!(GetConfig); yield_!(Log(cfg.to_string())); format!("{cfg}: {}", yield_!(Counter)) } ``` The spread must be the last effect argument, before `send` or `boxed` flags if present. This combines naturally with lifetimes and `send`: ```rust type LogEffs<'a> = Effects![GetConfig, BorrowedLog<'a>]; #[effectful('a, Counter, ...LogEffs<'a>, send)] fn complex<'a>(msg: &'a str) -> u64 { yield_!(BorrowedLog(msg)); yield_!(Counter) } ``` ## Creating a program with `Program::new` You can also create programs manually with `Program::new`, which takes an async closure that receives a `Yielder`: ```rust use corophage::prelude::*; #[effect(())] struct Log(String); #[effect(u64)] struct Counter; type Effs = Effects![Log, Counter]; let program = Program::new(|mut y: Yielder<'_, Effs>| async move { y.yield_(Log("hello".into())).await; let n = y.yield_(Counter).await; n * 2 }); ``` When you `await` the result of `y.yield_(some_effect)`, the computation pauses, the effect is handled, and the `await` resolves to the value provided by the handler. A `Yielder` supports one effect operation at a time. Its `yield_` and `invoke` methods require `&mut self`, so the borrow checker rejects overlapping operations such as passing two `yield_` futures to `join!`. Await each operation before starting another. Computation bodies may also await ordinary futures. This works inside `#[effectful]` functions, manual `Program::new` closures, and invoked sub-programs when executed with `.run().await` or a low-level `asynk` runner: ```rust #[effectful(Counter)] fn delayed_count() -> u64 { tokio::task::yield_now().await; yield_!(Counter) } let result = delayed_count() .handle(async |_: Counter| Control::resume(42)) .run() .await; ``` Synchronous runners handle effect suspension but cannot wait for unrelated futures. If an ordinary future returns `Pending`, use `.run().await` instead. This includes a sub-program executed with `.run().await` inside a synchronously run body. Async runners yield to the executor after a bounded number of effects, so such a body panics once the sub-program performs enough effects. Use `invoke!` (or `Yielder::invoke`) to forward the sub-program's effects to the outer handlers, or `.run_sync()` to handle them locally. ## Attaching handlers Handlers are attached one at a time with `.handle()`. Handlers can be attached in any order — the type system tracks which effects remain unhandled. ```rust let result = my_program() .handle(|Log(msg)| { println!("{msg}"); Control::resume(()) }) .handle(|_: Counter| Control::resume(42u64)) .run_sync(); assert_eq!(result, Ok(84)); ``` You can also attach multiple handlers at once with `.handle_all()`: ```rust #[effectful(Counter, Log)] fn my_program() -> u64 { yield_!(Log("start".into())); yield_!(Counter) } let result = my_program() .handle_all(hlist![ |_: Counter| Control::resume(42u64), |Log(msg)| { println!("{msg}"); Control::resume(()) }, ]) .run_sync(); ``` ## Mapping return values Use `.map(...)` to transform a program's return value without changing its effects. You can map before, between, or after attaching handlers and state: ```rust let result = Program::new(|mut y: Yielder<'_, Effects![Counter]>| async move { y.yield_(Counter).await }) .map(|count| format!("count: {count}")) .handle(|_: Counter| Control::resume(42u64)) .run_sync(); assert_eq!(result, Ok(String::from("count: 42"))); ``` The synchronous `FnOnce` callback runs once, after the body completes. Construction remains lazy. Cancelling or dropping an incomplete program skips the callback and releases its captures. Mapping does not add a handler or handle cancellation: `.run()` and `.run_sync()` still return `Result`. If the body returns a `Result` itself, `.map(...)` receives that whole value. Mapping retains attached handlers, the remaining effect set, and the existing state borrow. An unhandled mapped program can still be [invoked](#program-composition) by a parent. Mapping itself adds no allocation; the body, callback captures, handlers, state, and resume transport determine whether execution is `Send`. Mapped programs use inferred execution, including when their original body was boxed. A local boxed body remains non-`Send`. To return an `Effectful` alias, apply `.boxed()` or `.boxed_send()` after mapping the unhandled program. ## Effectful callbacks A higher-order helper can invoke a callback's program while forwarding an unknown effect set. This example maps the `Some` branch of an `Option` and skips constructing the child entirely for `None`: ```rust use corophage::prelude::*; use corophage::{EmbedEffect, ProjectResume, Resumes}; use std::future::Future; fn option_map_eff<'a, T: 'a, U: 'a, Es, F, Make, Indices>( value: Option, make: Make, ) -> Program<'a, Es, impl Future> + 'a> where Es: Effects<'a> + EmbedEffect, Resumes<'a, Es>: ProjectResume<'a, Es, Indices>, F: Future + 'a, Make: FnOnce(T) -> Program<'a, Es, F> + 'a, { Program::new(|mut y: Yielder<'a, Es>| async move { match value { Some(value) => Some(y.invoke(make(value)).await), None => None, } }) } ``` The callback and child run when the outer program executes. Attach the child's handlers to the returned program; its declared effects still require handlers even when the input happens to be `None`. See [generic effect sets](@/docs/effects.md#generic-effect-sets) for the forwarding bounds. `cargo run --example higher_order` runs a complete borrowed lookup example, combines `option_map_eff` with `Program::map`, and asserts that `None` calls neither the callback nor its handler. The helper is example code that can be adapted downstream. It also works with `--no-default-features`. ## Running programs Once all effects are handled, you can run the program: - `.run_sync()` — execute inline with synchronous handlers and return `Result`; a body that suspends on an ordinary future causes a panic. - `.run().await` — execute asynchronously, with synchronous and asynchronous handlers in the same list. These rules apply to concrete and local boxed programs alike. Sendable boxed programs keep their explicit `Send` guarantees; see the [compatibility API](@/docs/advanced.md#compatibility-api). Attach shared state with `.with_state(&mut state)` before running. Handlers that use state take `&mut S` as their first argument; other handlers can omit it. The compatibility methods `.run_sync_stateful(&mut state)` and `.run_stateful(&mut state)` still bind state at their terminal call site. Async runners yield to the executor after a bounded number of effect dispatches, even when handlers are immediately ready. Each runner has its own budget (currently 128 dispatches; this value may change). This applies to `.run().await`, `.run_stateful(&mut state).await`, and the low-level `asynk` runners. It gives the executor opportunities to schedule other tasks and process cancellation, but does not guarantee task ordering or preempt a computation body or handler that does not return from its poll. ## Partially-handled programs A partially-handled program is a first-class value you can pass around, store, or extend later: ```rust fn add_logging(program: Program) -> Program { program.handle(|Log(msg)| { println!("{msg}"); Control::resume(()) }) } ``` Both execution methods require all effects to be handled. Missing or duplicate handlers cause a compile error. ## Program composition Programs can invoke other programs via `invoke!()` (or `y.invoke()` with the manual API). The sub-program's effects must be a subset of the outer program's effects — each yielded effect is forwarded to the outer handler automatically. ```rust use corophage::prelude::*; #[effect(&'static str)] struct Ask(&'static str); #[effect(())] struct Print(String); #[effect(())] struct Log(&'static str); #[effectful(Ask, Print)] fn greet() { let name: &str = yield_!(Ask("name?")); yield_!(Print(format!("Hello, {name}!"))); } #[effectful(Ask, Print, Log)] fn main_program() { yield_!(Log("Starting...")); invoke!(greet()); yield_!(Log("Done!")); } let result = main_program() .handle(|_: Ask| Control::resume("world")) .handle(|Print(msg)| { println!("{msg}"); Control::resume(()) }) .handle(|_: Log| Control::resume(())) .run_sync(); assert_eq!(result, Ok(())); ``` With the manual `Program::new` API, use `y.invoke(program).await`: ```rust let result = Program::new(|mut y: Yielder<'_, Effects![Ask, Print, Log]>| async move { y.yield_(Log("Starting...")).await; y.invoke(greet()).await; y.yield_(Log("Done!")).await; }) .handle(|_: Ask| Control::resume("world")) .handle(|Print(msg)| { println!("{msg}"); Control::resume(()) }) .handle(|_: Log| Control::resume(())) .run_sync(); ``` Sub-programs can be nested — a sub-program can itself invoke other sub-programs. The only requirement is that the inner program's effects are a subset of the outer program's effects. ## `Send`-able programs `Program::new` and default `#[effectful]` functions preserve conditional `Send`. The execution future can be passed to `tokio::spawn` when its body, handlers, handler futures, state, and resume transport permit it. Spawning also requires a `Send + 'static` result and a `'static` future: ```rust #[effectful(Counter)] fn my_program() -> u64 { yield_!(Counter) } // Can be spawned on tokio tokio::spawn(async move { let result = my_program() .handle(async |_: Counter| Control::resume(42u64)) .run() .await; }); ``` Or with the manual API: ```rust let program = Program::new(|mut y: Yielder<'_, Effects![Counter]>| async move { y.yield_(Counter).await }); tokio::spawn(async move { let result = program .handle(async |_: Counter| Control::resume(42u64)) .run() .await; }); ``` For local execution, the same constructor accepts `Rc` captures, non-`Send` state, and non-`Send` handler futures. A sendable body can also use local handlers or state. There is no blanket handler `Sync` bound on this path; an actual shared borrow across an await can still require `Sync`. Use `corophage::local(async |effect| { ... })` when an async closure borrows its captures across an await. This explicit adapter boxes one local future per call. Ordinary async handlers use `FnMut(...) -> Future` and need no dispatch allocation. See [Handlers](@/docs/handlers.md#lending-async-closures). Use `.with_state(&mut state)` with either execution method. Each stateful handler can borrow the state across awaits. See [Shared State](@/docs/state.md#send-able-async-execution) for a spawn example and [Advanced Usage](@/docs/advanced.md#compatibility-api) for the retained boxed contracts. --- ## Handlers A **Handler** is a function that implements the logic for a specific effect. It receives the effect instance and returns a `Control`, which tells the runner what to do next. ## Control flow `Control` has two variants: - `Control::resume(value)` — resumes the computation, passing `value` back as the result of `yield_`. The type of `value` must match the effect's `Resume` type. - `Control::cancel()` — aborts the entire computation immediately. The final result will be `Err(Cancelled)`. ## Sync handlers A sync handler is a regular closure: ```rust |Log(msg)| { println!("LOG: {msg}"); Control::resume(()) } ``` ## Async handlers An async handler is an async closure: ```rust async |FileRead(file)| { let content = tokio::fs::read_to_string(file).await.unwrap(); Control::resume(content) } ``` ## Named function handlers Programs can mix sync and async handlers in one `.run()` call, whether their body is concrete or boxed. `.run_sync()` accepts only synchronous handlers, even if an async handler would complete immediately. Handlers can also be named functions. When using stateful handlers, the state is passed as the first argument: ```rust struct AppState { verbose: bool } fn log(s: &mut AppState, Log(msg): Log) -> Control<()> { if s.verbose { println!("LOG: {msg}"); } Control::resume(()) } fn file_read(_: &mut AppState, FileRead(file): FileRead) -> Control { println!("Reading file: {file}"); Control::resume("file content".to_string()) } ``` ## Lending async closures Ordinary async handlers return a future through `FnMut(...) -> Future`. When an async closure borrows its captures across an await, wrap it with `corophage::local`: ```rust let mut messages = Vec::new(); let result = program .handle(corophage::local(async |Log(message)| { messages.push(message); tokio::task::yield_now().await; Control::resume(()) })) .run() .await; ``` Repeated calls borrow the same closure and retain its mutations. The adapter boxes one non-`Send` future per call. Use `corophage::local_stateful` for a lending closure that also takes a `&mut S` state argument. A runner using either adapter must be awaited locally. Ordinary handlers do not box dispatch futures. ## Cancellation Use `Control::cancel()` when an effect should abort the entire computation: ```rust #[effect(Never)] struct Cancel; // The handler cancels the computation |_: Cancel| Control::cancel() ``` The `Never` resume type indicates this effect can never resume — the handler must always cancel. ## Throwing errors `Control::cancel()` does not record why the computation stopped. To abort with a typed error, yield the built-in `Throw` effect and catch it when running: ```rust #[effect(Option)] struct Lookup(u64); #[derive(Debug)] struct NotFound(u64); #[effectful(Lookup, Throw)] fn find_user(id: u64) -> String { match yield_!(Lookup(id)) { Some(user) => user, None => throw!(NotFound(id)), } } let result: Result, Cancelled> = find_user(42) .handle(|_: Lookup| Control::resume(None)) .catch() .run_sync(); ``` `.catch()` handles `Throw` and changes what the run returns: `Ok(Ok(value))` on completion, `Ok(Err(error))` when the program throws, and `Err(Cancelled)` when a handler cancels. Use `?` to propagate the cancellation and keep the error: `find_user(42).handle(...).catch().run_sync()?` has type `Result`. Both `.run()` and `.run_sync()` are available after `.catch()`. Inside `#[effectful]` functions, `throw!(error)` can stand in for a value of any type. In a `Program::new` closure, use `y.throw(error).await`. In statement position, write `return y.throw(error).await` so the type can be inferred. Attach the other handlers and bind state before calling `.catch()`. A program catches one error type; use an enum when several errors are possible. A throw from an invoked sub-program aborts the whole computation, and catching inside a program body is not supported yet. Without `.catch()`, `Throw` is an ordinary effect that you can handle like any other. --- ## Shared State Bind shared mutable state with `.with_state(&mut state)`, then execute with `.run_sync()` or `.run().await`. Stateful handlers receive `&mut S` as their first argument. Handlers that do not use state can omit that argument. ## Basic example ```rust use corophage::prelude::*; #[effect(u64)] struct Counter; #[effectful(Counter)] fn count_up() -> u64 { let a = yield_!(Counter); let b = yield_!(Counter); a + b } let mut count: u64 = 0; let result = count_up() .with_state(&mut count) .handle(|s: &mut u64, _: Counter| { *s += 1; Control::resume(*s) }) .run_sync(); assert_eq!(result, Ok(3)); // 1 + 2 assert_eq!(count, 2); // handler was called twice ``` ## Multiple effects with shared state The program holds one state reference and reborrows it for each handler call. State-free handlers can share the same list: ```rust use corophage::prelude::*; use std::marker::PhantomData; #[effect(())] pub struct Log<'a>(pub &'a str); #[derive(Default)] #[effect(S)] pub struct GetState { _marker: PhantomData, } #[effect(())] pub struct SetState(pub S); #[effectful(Log<'static>, GetState, SetState)] fn my_program() -> u64 { yield_!(Log("starting")); let val = yield_!(GetState::default()); yield_!(SetState(val * 2)); yield_!(GetState::default()) } #[derive(Debug)] struct AppState { x: u64 } let mut state = AppState { x: 42 }; let result = my_program() .with_state(&mut state) .handle(|Log(msg)| { println!("{msg}"); Control::resume(()) }) .handle(|s: &mut AppState, _: GetState| Control::resume(s.x)) .handle(|s: &mut AppState, SetState(x)| { s.x = x; Control::resume(()) }) .run_sync(); assert_eq!(result, Ok(84)); assert_eq!(state.x, 84); ``` ## Send-able async execution `Program::new` and default `#[effectful]` functions retain their body's concrete type. The resulting runner is `Send` when all retained components permit it. Mutable handler access removes the blanket handler `Sync` bound. Handlers can retain their `&mut S` argument across awaits: ```rust use corophage::prelude::*; #[effect(u64)] struct Counter; async fn increment(state: &mut u64, _: Counter) -> Control { tokio::task::yield_now().await; *state += 1; Control::resume(*state) } let program = Program::new::(|mut y| async move { let first = y.yield_(Counter).await; let second = y.yield_(Counter).await; first + second }) .handle(increment); let (result, state) = tokio::spawn(async move { let mut state = 0; let result = program.with_state(&mut state).run().await; (result, state) }) .await .unwrap(); assert_eq!(result, Ok(3)); assert_eq!(state, 2); ``` The state is owned by the spawned task, so its mutable borrow stays valid until execution finishes. Outside `tokio::spawn`, a sendable runner can also borrow state and effect data from the surrounding scope; it does not require `'static` data. Ordinary async handlers can borrow the explicit state argument. For a closure that also borrows its captures across awaits, use `corophage::local_stateful(async |state: &mut S, effect| { ... })`. This adapter boxes one non-`Send` future per dispatch. The generic runner also accepts non-`Send` state and handler futures when awaited locally. ## State borrow duration The mutable borrow starts at `.with_state(...)`. You cannot access the original state while the configured program remains live. Completion, cancellation, or dropping the configured program or its execution future releases that borrow. Handler calls are serial and receive fresh short reborrows; the state owner and handler captures need not have the same lifetime. A handler cannot resume the computation with a reference borrowed from its temporary mutable state loan. A borrowed resume must instead refer to data that lives for the computation lifetime, such as external data carried by the effect. The compatibility methods `.run_stateful(&mut state)` and `.run_sync_stateful(&mut state)` retain their original borrow timing: the state borrow starts at that terminal call. Erased sendable programs retain their old `Send + Sync` handler checks on `.run_stateful()`. Calling `.with_state()` selects the new conditional execution path, including for erased bodies. ## Alternatives If your handlers do not need shared state, omit `.with_state()`. Captured `RefCell` or other interior mutability remains an alternative when it fits the application. --- ## Advanced Usage ## Borrowing non-`'static` data Effects can borrow data from the local scope by using a non-`'static` lifetime: ```rust use corophage::prelude::*; #[effect(())] struct Log<'a>(pub &'a str); #[effectful(Log<'a>)] fn log_it<'a>(msg: &'a str) -> () { yield_!(Log(msg)); } let msg = String::from("hello from a local string"); let result = log_it(&msg) .handle(|Log(m)| { println!("{m}"); Control::resume(()) }) .run_sync(); assert_eq!(result, Ok(())); ``` ## Borrowed resume types Because `Effect::Resume<'r>` is a generic associated type (GAT), handlers can resume computations with *borrowed* data instead of requiring owned values. ```rust use corophage::prelude::*; use std::collections::HashMap; #[effect(&'r str)] struct Lookup<'a> { map: &'a HashMap, key: &'a str, } #[effectful(Lookup<'a>)] fn lookup_config<'a>(map: &'a HashMap) -> String { let host: &str = yield_!(Lookup { map, key: "host" }); let port: &str = yield_!(Lookup { map, key: "port" }); format!("{host}:{port}") } let map = HashMap::from([ ("host".to_string(), "localhost".to_string()), ("port".to_string(), "5432".to_string()), ]); let result = lookup_config(&map) .handle(|Lookup { map, key }| { let value = map.get(key).unwrap(); Control::resume(value.as_str()) }) .run_sync(); assert_eq!(result, Ok("localhost:5432".to_string())); ``` ## Low-level `Co` and `CoSend` API `Program` is the primary API, but `Co` and `CoSend` are useful when you need to pass or store a computation before attaching handlers. They are available from the crate root rather than the prelude: ```rust use corophage::{Co, sync}; use corophage::prelude::*; #[effect(String)] struct FileRead(&'static str); let co: Co<'_, Effects![FileRead], String> = Co::new(|mut y| async move { y.yield_(FileRead("config.toml")).await }); let result = sync::run(co, &mut hlist![ |FileRead(path)| Control::resume(format!("contents of {path}")), ]); assert_eq!(result, Ok("contents of config.toml".to_string())); ``` Use `CoSend` for a sendable computation. Once its handlers are attached, the future returned by `Program::run` can be passed directly to `tokio::spawn` when the result and all handler futures are `Send`: ```rust use corophage::CoSend; fn read_file() -> CoSend<'static, Effects![FileRead], String> { CoSend::new(|mut y| async move { y.yield_(FileRead("config.toml")).await }) } let future = Program::from_co(read_file()) .handle(async |FileRead(path)| { Control::resume(format!("contents of {path}")) }) .run(); let result = tokio::spawn(future).await.unwrap(); assert_eq!(result, Ok("contents of config.toml".to_string())); ``` The low-level `sync::run` and `asynk::run` functions take all handlers in an `hlist!` at once. Handlers may appear in any order, and the list may include extra handlers, but every effect the computation can yield must have a compatible handler. ## Explicit boxing and recursion `Program::new` and default `#[effectful]` functions keep the body future concrete. A manual function can express that return type with `impl Future`: ```rust use std::future::Future; fn read() -> Program<'static, Effects![FileRead], impl Future> { Program::new(|mut y: Yielder<'_, Effects![FileRead]>| async move { y.yield_(FileRead("config.toml")).await }) } ``` For an existing erased signature, box the unhandled program explicitly: ```rust fn erased() -> Effectful<'static, Effects![FileRead], String> { read().boxed() } fn erased_send() -> Effectful<'static, Effects![FileRead], String, corophage::Sendable> { read().boxed_send() } ``` `.boxed()` erases `Send` even when the original body was sendable. `.boxed_send()` retains that guarantee and checks the body and resume transport. Each conversion allocates once for the body. `Effectful<'a, Effs, R, L>` remains the erased alias, including for callers generic over `L: Locality`. The concrete `Program` type now takes its body future as its third parameter; update explicit full `Program` signatures accordingly. Use the `boxed` macro flag for recursive functions or to limit concrete type growth. Combine it with `send` when the erased body must be sendable: ```rust #[effectful(FileRead, boxed, send)] fn recursive(depth: usize) -> String { if depth == 0 { yield_!(FileRead("config.toml")) } else { invoke!(recursive(depth - 1)) } } ``` Concrete nested futures grow with the invocation depth. Boxing bounds each body's stored type, but each active recursive call still consumes memory. ### Trait objects Default `#[effectful]` trait methods return a type containing `impl Future`, which prevents the trait from being used as `dyn Trait`. Add `boxed` to effectful methods that need dynamic dispatch. Use the same erased return type in any overriding implementation. The trait must also satisfy Rust's other requirements for dynamic dispatch. ```rust trait FileSource { fn path(&self) -> &'static str; #[effectful(FileRead, boxed)] fn read(&self) -> String { yield_!(FileRead(self.path())) } } struct Config; impl FileSource for Config { fn path(&self) -> &'static str { "config.toml" } } let config = Config; let source: &dyn FileSource = &config; let result = source.read() .handle(|FileRead(path)| Control::resume(format!("contents of {path}"))) .run_sync(); assert_eq!(result, Ok("contents of config.toml".to_string())); ``` ## Compatibility API `Co::new`, `CoSend::new`, `Program::new_send`, and `Program::from_co` remain available for erased signatures. Local erased programs also include values returned by `.boxed()` and `#[effectful(..., boxed)]`. Local erased programs accept the same handlers as concrete programs. Sync and async handlers can be mixed, and async closures that borrow their captures across an await use `corophage::local` or `corophage::local_stateful`. The low-level `asynk::run` and `asynk::run_stateful` functions follow the same rules: ```rust let mut paths = Vec::new(); let result = erased() .handle(corophage::local(async |FileRead(path)| { paths.push(path); tokio::task::yield_now().await; Control::resume(format!("contents of {path}")) })) .run() .await; assert_eq!(result, Ok("contents of config.toml".to_string())); assert_eq!(paths, ["config.toml"]); ``` Before 0.7, local erased `.run()` and `.run_stateful()` accepted only async closures, including closures that borrow their captures, and rejected synchronous handlers and the adapters. To migrate, wrap closures that borrow their captures across an await with `corophage::local` or `corophage::local_stateful`. Erased sendable programs retain explicit `Send` guarantees on `.run()` and `.run_stateful()`. The latter retains its `Send + Sync` handler bound. `.with_state()` instead selects the new mutable protocol and conditional `Send`, while keeping the already erased body. Rust can report that an implementation is not general enough (for example of `Effect` or `FnOnce`) when a program with lifetime-parameterized effects or GAT resumes is awaited inside another async block that must be `Send`, such as `tokio::spawn(async { ... })`. This affects both stateless and stateful runners, and can occur even if the run future itself passes a `Send` assertion. Passing the run future to `tokio::spawn` directly, without an enclosing async block, avoids the problem. Otherwise, box the unhandled body with `.boxed_send()` and use the compatibility `.run()` or `.run_stateful(&mut state)` method. Both have an explicit `Send` return guarantee. ## Polling context restriction `fauxgen` transports effects through the polling context. Effect operations must be polled through that context; placing them inside a combinator that substitutes its own context can break this transport. Ordinary awaited futures remain supported, but boxing the body or using an async runner does not remove this restriction. Keep `yield_!` and `invoke!` in the directly awaited computation flow, and await each operation before starting another. Effect operations are also not cancel-safe. The first poll of a `yield_!` or `invoke!` operation hands its effect to the runner. If the operation is then dropped before completing, for example by losing a `select!` race, the abandoned effect may still be handled at the computation's next suspension, with its resume value discarded, or it may be silently dropped. Do not race effect operations against other futures; await each one to completion. --- ## Performance The current implementation at commit `6cc6ff2` was compared with the boxed implementation at commit `fa68b5a` on 2026-10-19. The candidate was measured with no tracked changes, and the recorded source and generated-fixture hashes match that commit. Both builds used the same macOS arm64 machine, Rust 1.99.1, release optimization, LTO, and one code generation unit. ## Execution costs Each row measures a complete operation, including construction and execution. Async cases use a warmed Tokio runtime on the current thread with immediately ready handlers; the cooperative dispatch budget remains enabled. | Operation | Boxed baseline | Current | | --- | ---: | ---: | | Construct and drop | 12.9 ns | 0.7 ns | | One sync effect | 44.9 ns | 28.1 ns | | One async effect | 114.5 ns | 92.2 ns | | 1,000 sync effects | 10.4 µs | 9.6 µs | | 1,000 async effects | 16.2 µs | 11.6 µs | | 1,000 stateful sync effects | 10.4 µs | 9.5 µs | | 1,000 stateful async effects | 17.2 µs | 12.1 µs | | Five nested invocations | 406 ns | 209 ns | | Ten nested invocations | 734 ns | 376 ns | | Twenty nested invocations | 1,838 ns | 745 ns | Nested cases perform one effect at the leaf and run synchronously. Depth counts invocation edges, so depth 20 has 21 active programs. Every generated level invokes the preceding level exactly once. This comparison uses its own generated chains; corrected Divan stress fixtures are measured separately below. The current implementation is faster in every row. Construction no longer allocates, nested invocations take 49–60% less time, and the 1,000-effect loops are 8–9% faster when synchronous and 29–30% faster when asynchronous. Synchronous runners poll the program directly in an inline loop; async runners use the cooperative loop. Real handlers can have much larger costs than the dispatch itself. Do not apply these ratios to an application without measuring it. ## Stress nesting benchmarks The corrected Divan fixtures were measured on 2026-10-19 at commit `6cc6ff2` on macOS arm64, Rust 1.99.1, and the workspace's optimized bench profile with LTO. Each case has 1,000 samples of 1,000 iterations. The medians include program construction, synchronous execution with a no-op handler, and destruction. This suite counts active programs: the leaf has depth 1, and depth 20 has 19 invocation edges. The leaf-only case yields once. The other case yields once in each program and returns the number of yields. Regression tests run these same fixtures with guards that check peak active depth and handler calls; timing runs use a no-op observer. | Depth (active programs) | One leaf effect | One effect per level | | --- | ---: | ---: | | 1 | 28.08 ns | 28.7 ns | | 2 | 59.95 ns | 68.58 ns | | 3 | 94.58 ns | 121.7 ns | | 5 | 176.8 ns | 262.2 ns | | 10 | 376.5 ns | 795.4 ns | | 15 | 584.7 ns | — | | 20 | 799.5 ns | — | The old depth-15 and depth-20 fixtures both peaked at 11 active programs and yielded twice. The old depth-10 yielding fixture peaked at 6 programs and yielded 11 times. Their timings cannot support conclusions about the labelled depths; this table replaces those results. Yielding at every level also increases total work: at depth `d`, effects cross `d × (d − 1) / 2` invocation edges in total, versus `d − 1` for the single leaf effect. These are complete workload timings, not an isolated cost per invocation. They are separate measurements from the execution migration comparison above. To reproduce these cases, run: ```sh cargo bench -p corophage --bench stress -- nesting_depth --sample-count 1000 --sample-size 1000 --color never ``` The raw Divan output and source hashes are recorded in `corophage/benches/results/nesting.txt` in the repository. ## Allocations and future size Allocations were counted separately from timings, after runtime warmup. | Case | Boxed baseline | Current | | --- | ---: | ---: | | Construct and drop | 1 allocation | 0 allocations | | Flat run, 1 or 1,000 ordinary effects | 2 allocations | 1 allocation | | Twenty nested invocations | 42 allocations | 21 allocations | | Unhandled flat program | 48 bytes | 160 bytes | | Flat async execution future | 280 bytes | 448 bytes | | Depth-20 async execution future | 280 bytes | 8,048 bytes | Future sizes exclude heap allocations. The boxed baseline stores each body separately on the heap; concrete bodies are stored inside the surrounding future. Invocation stores each child once, so concrete storage grows linearly with the chain depth. Use explicit boxing for recursive programs or to limit stored type size. Explicit body boxing adds one allocation per body. A flat run using `local` required 2 allocations for one call and 1,001 for 1,000 calls: one runtime allocation plus one boxed future per handler call. Ordinary handlers add no per-dispatch allocation. Both local lending adapters explicitly box their returned futures. ## Build and code size The common measurement binary grew from 545,808 to 568,800 bytes (4.2%). Its Mach-O `__TEXT` segment grew from 384 to 400 KiB. One clean offline build, including dependencies, took 5.7 seconds for the baseline and 6.7 seconds for the candidate. These are single build observations, not stable estimates of application compile time or library footprint. ## Reproduce From the repository root, run: ```sh python3 scripts/execution/measure.py ``` The script archives the baseline into a temporary directory, builds both revisions with fresh target directories and compiler caching disabled, and writes `corophage/benches/results/execution.json`. Explicit target directories override `CARGO_TARGET_DIR` and Cargo target-directory configuration, including for the candidate-only cases. Timings report the median, minimum, and maximum of seven samples after calibration. The script measures explicit boxing and local lending in a separate candidate binary so those extra cases do not affect the common-workload code-size comparison. It records the compiler, platform, source hashes, build times, and allocation counts. The existing Divan suites remain available with `cargo bench`. The old published performance tables predate the default switch and have been replaced by this reproducible comparison. --- ## Example: Order Saga The [saga example](https://github.com/romac/corophage/blob/main/corophage/examples/saga.rs) models order processing as a sequence of effects — each step a service call — with automatic rollback when any step fails. Run it with: ``` cargo run --example saga ``` ## The pattern A saga is a multi-step workflow where each step can fail. When a step fails, all previously completed steps must be *compensated* (undone) in reverse order. Effects are a natural fit: each step is an effect, a shared `SagaState` struct records what completed, and `Control::cancel()` halts the workflow immediately. The caller then reads the state and runs compensations. ## Effects Each stage of the workflow is its own effect: ```rust /// Reserve `quantity` units of an item. Resumes with a reservation ID. #[effect(String)] struct ReserveInventory { item_id: String, quantity: u32 } /// Charge a payment method. Resumes with a transaction ID. #[effect(String)] struct ChargePayment { amount_cents: u64, card_token: String } /// Send an order confirmation email. Resumes with `()`. #[effect(())] struct SendConfirmation { email: String, order_id: String } /// Ship the order. Resumes with a tracking number. #[effect(String)] struct ShipOrder { order_id: String, address: String } ``` The workflow logic doesn't know about services, retries, or failure modes — it just yields effects. ## Workflow ```rust #[effectful(ReserveInventory, ChargePayment, SendConfirmation, ShipOrder)] fn process_order(order: Order) -> String { let reservation_id = yield_!(ReserveInventory { item_id: order.item_id, quantity: order.quantity, }); let order_id = format!("ORD-{}", &reservation_id[..8]); let transaction_id = yield_!(ChargePayment { amount_cents: order.amount_cents, card_token: order.card_token, }); yield_!(SendConfirmation { email: order.email, order_id: order_id.clone(), }); let tracking_number = yield_!(ShipOrder { order_id: order_id.clone(), address: order.address, }); format!("Order {order_id} complete! Tracking: {tracking_number}") } ``` ## Tracking state `SagaState` records what has completed and exposes a `compensate` method that undoes steps in reverse order: ```rust #[derive(Default)] struct SagaState { reservation_id: Option, transaction_id: Option, confirmation_sent: bool, tracking_number: Option, failure_reason: Option, } impl SagaState { fn compensate(&self) { if self.confirmation_sent { println!("Sending cancellation notice to customer"); } if let Some(tx_id) = &self.transaction_id { println!("Refunding transaction {tx_id}"); } if let Some(res_id) = &self.reservation_id { println!("Releasing inventory reservation {res_id}"); } } } ``` ## Handlers Each handler updates the state, then either resumes or cancels: ```rust async fn handle_payment(state: &mut SagaState, effect: ChargePayment) -> Control { if state.fail_at.as_deref() == Some("payment") { state.failure_reason = Some(format!( "Card {} declined for {} cents", effect.card_token, effect.amount_cents )); return Control::cancel(); } let id = format!("TXN-{:08x}", hash(effect.card_token.as_bytes())); state.transaction_id = Some(id.clone()); Control::resume(id) } ``` ## Running and compensating After running, inspect the result. On cancellation, the accumulated state tells you exactly what needs undoing: ```rust let mut state = SagaState { fail_at: Some("payment".into()), ..Default::default() }; let result = process_order(order) .with_state(&mut state) .handle(handle_reserve) .handle(handle_payment) .handle(handle_confirmation) .handle(handle_shipping) .run() .await; match result { Ok(summary) => println!("SUCCESS: {summary}"), Err(_cancelled) => { println!("FAILED: {}", state.failure_reason.as_deref().unwrap_or("unknown")); state.compensate(); // reverse completed steps in order } } ``` ## Testing with mock handlers Because workflow logic and service implementations are decoupled, tests swap in mock handlers with predictable behavior — no real services needed: ```rust let result = process_order(test_order()) .handle(async |_: ReserveInventory| Control::resume("RES-FAKE-0".into())) .handle(async |_: ChargePayment| Control::resume("TXN-FAKE".into())) .handle(async |_: SendConfirmation| Control::resume(())) .handle(async |_: ShipOrder| Control::resume("TRK-FAKE".into())) .run() .await; assert!(result.unwrap().contains("TRK-FAKE")); ``` To assert on effect payloads, extend the shared state with capture fields and write to them from the handler. See the [full example](https://github.com/romac/corophage/blob/main/corophage/examples/saga.rs) for complete tests covering payment failure, shipping failure, payload assertions, and stateless mock handlers. --- ## Example: Stepwise Debugger The [debugger example](https://github.com/romac/corophage/blob/main/corophage/examples/debugger.rs) is an interactive debugger for effectful computations, inspired by the [Stepwise library for Unison](https://share.unison-lang.org/@pchiusano/stepwise). It lets you step through pause points, inspect and replace values, and — the interesting part — rewind to any previous point. Run it with: ``` cargo run --example debugger ``` ## The effect The entire debugger is built on a single generic effect: ```rust /// Pause the computation with a label and a value. /// The handler may inspect, replace, or pass through the value. #[effect(T)] struct Pause { label: String, value: T } ``` A handler receives each `Pause` and decides what `T` to resume with. All debugger behavior — stepping, going, silencing, rewinding — lives in the handler. The type parameter lets you attach the debugger to any effectful computation whose pause values implement `Display`, `FromStr`, and `PartialEq`. ## The program ```rust #[effectful(Pause)] fn example_program() -> i64 { let x = yield_!(pause("x", 1 + 1)); let inner = yield_!(pause("what's this?", 99 + 1)); let y = yield_!(pause("y", x + x + inner)); x + y } ``` The program has no idea a debugger is attached. Swap in a different handler and it behaves differently — log the values, always pass through, fuzz the outputs, whatever you like. ## Debugger state The handler is stateful, threading a `DebuggerState` through each pause: ```rust struct DebuggerState { /// Decisions from a prior run to replay automatically. replay: Vec>, /// Decisions recorded during this run. decisions: Vec>, /// Current mode: Step (interactive), Go (print, no stop), Silent. mode: Mode, /// Set to true when the user presses "b" to go back. went_back: bool, } ``` ## Replay: how "back" works The "back" feature is the showstopper. When the user presses `b`: 1. The handler pops the last decision from `decisions` and sets `went_back = true`. 2. It calls `Control::cancel()` to halt the computation immediately. 3. The main loop detects `went_back`, saves the remaining decisions as the `replay` list, and re-runs the computation from scratch. 4. On the re-run, the handler auto-resumes through all replayed decisions without stopping, then hands control back to the user one step earlier. This works because effectful computations are *deterministic given the same handler responses*. The handler just feeds back its own recorded decisions: ```rust fn debugger_handler(state: &mut DebuggerState, effect: Pause) -> Control where T: Clone + Display + FromStr + PartialEq + Send + Sync, ::Err: Display, { let index = state.decisions.len(); // Replay phase: auto-resume with the previously recorded value. if index < state.replay.len() { let decision = state.replay[index].clone(); state.decisions.push(decision.clone()); return Control::resume(decision.resumed); } // ... interactive prompt follows } ``` The "back" command in the interactive prompt: ```rust "b" if can_back => { state.decisions.pop(); // drop the last decision state.went_back = true; return Control::cancel(); } ``` ## The main loop ```rust let mut replay: Vec> = Vec::new(); loop { let mut state = DebuggerState { replay: replay.clone(), decisions: Vec::new(), mode: Mode::Step, went_back: false, }; let result = example_program() .with_state(&mut state) .handle(debugger_handler) .run_sync(); match result { Ok(value) => { println!("Result: {value}"); break; } Err(_) if state.went_back => { replay = state.decisions; // replay one fewer decision next run println!("<< Rewinding..."); } Err(e) => panic!("Unexpected cancellation: {e}"), } } ``` Each re-run is a full execution of `example_program()` from scratch. The effect system guarantees that replaying the same handler decisions produces identical intermediate values, so the computation reaches the same state as before — one step earlier. ## What this shows This example demonstrates a non-obvious capability of the effect system: because computations are deterministic functions of their handler responses, you can implement time-travel debugging with no special support from the runtime. The entire implementation is a single generic handler and a short loop. Making `Pause` generic means the same debugger infrastructure works for any value type that can be displayed and parsed. See the [full source](https://github.com/romac/corophage/blob/main/corophage/examples/debugger.rs) for the complete interactive prompt, `replace` and `go` modes, and display formatting.