Files
lux/examples/handlers.lux
Brandon Lucas 9511957076 feat: implement resumable effect handlers
Add support for the `resume(value)` expression in effect handler
bodies. When resume is called, the value becomes the return value
of the effect operation, allowing handlers to provide values back
to the calling code.

Implementation:
- Add Resume(Value) variant to EvalResult
- Add in_handler_depth tracking to Interpreter
- Update Expr::Resume evaluation to return Resume when in handler
- Handle Resume results in handle_effect to use as return value
- Add 2 tests for resumable handlers

Example usage:
```lux
handler prettyLogger: Logger {
    fn log(level, msg) = {
        Console.print("[" + level + "] " + msg)
        resume(())  // Return Unit to the call site
    }
}
```

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 09:54:51 -05:00

46 lines
1.2 KiB
Plaintext

// Demonstrating resumable effect handlers in Lux
//
// Handlers can use `resume(value)` to return a value to the effect call site
// and continue the computation. This enables powerful control flow patterns.
//
// Expected output:
// [INFO] Starting computation
// [DEBUG] Intermediate result: 10
// [INFO] Computation complete
// Final result: 20
// Define a custom logging effect
effect Logger {
fn log(level: String, msg: String): Unit
fn getLogLevel(): String
}
// A function that uses the Logger effect
fn compute(): Int with {Logger} = {
Logger.log("INFO", "Starting computation")
let x = 10
Logger.log("DEBUG", "Intermediate result: " + toString(x))
let result = x * 2
Logger.log("INFO", "Computation complete")
result
}
// A handler that prints logs with brackets and resumes with Unit
handler prettyLogger: Logger {
fn log(level, msg) = {
Console.print("[" + level + "] " + msg)
resume(())
}
fn getLogLevel() = resume("DEBUG")
}
// Main function
fn main(): Unit with {Console} = {
let result = run compute() with {
Logger = prettyLogger
}
Console.print("Final result: " + toString(result))
}
let output = run main() with {}