VIP-79: defer Scoped Finalizers in effect Code
Status: accepted by Will, 2026-11-30. Will: "I accept 76 to 81". (Previously open, 2026-11-28.)
Will's words
"Let's add a VIP for defer"
Motivation
Deterministic resource cleanup is one of Effect's greatest strengths (Scope, Effect.acquireRelease, Effect.addFinalizer), yet writing scoped cleanup in plain Effect forces developers to invert their control flow into nested acquire/release callbacks:
const handle = yield* Effect.acquireRelease(
openTempFile(path),
(file) => Effect.ignore(file.close())
)Earlier, VIP-8 (using / scoped keyword) was denied on 2026-10-28 because ECMAScript already specifies using and await using for synchronous/Promise Symbol.dispose — overloading using for Effect Scope would blur JavaScript's resource semantics with Effect's typed Scope.
defer has zero collision with ECMAScript, is instantly understood by Go, Zig, and Swift engineers, keeps linear top-to-bottom control flow, and makes the Scope requirement completely visible in the type system:
export effect function exportReport(path: string) {
const tmp = try openTempFile(path)
defer try orDie(tmp.remove())
const conn = try openConnection()
defer (exit) {
try logDebug(`closing connection (${exit._tag})`)
try orDie(conn.close())
}
return try writeReport(conn, tmp)
}
// Inferred type: (path: string) => Report ! (IoError | DbError) ! (Scope | FileSystem | Db)Decision
1. Grammar
Under [+Effect] (inside effect functions, effect arrows, effect methods, effect blocks, and effect function* producers — see Appendix A [Effect] parameter):
DeferStatement :
defer ( BindingIdentifier ) Block
defer Block
defer [lookahead ∉ { ( [ ` + - / /= < ! as satisfies is }] Expression ;?The expression form excludes every leading token that can also continue an expression beginning with an identifier named defer. defer(x), defer[0], defer`t`, defer + 1, defer - x, defer / 2, defer < n and defer! therefore keep their existing meaning inside effect code and register no finalizer, so code that already binds defer (for example import { defer } from "lodash") does not change. defer ++x and defer --x are deferred expressions only when an operand follows on the same line. To defer an expression that starts with one of the excluded tokens, use the block form: write defer { (conn).close() }, defer { -x } or defer { [a].forEach(f) }, not defer (conn).close().
Outside [+Effect] (in plain TypeScript/JavaScript functions and async functions):
deferremains an ordinary identifier (const defer = true,defer(x)).- Unambiguous
defer { ... }ordefer (exit) { ... }outside effect code recovers and reportsEK7901("deferis only allowed insideeffectcode").
2. Semantics & Lowering
Every DeferStatement lowers directly to Effect 4's Effect.addFinalizer (with zero custom runtime wrapper):
- Expression form (
defer expr):Ifyield* Effect.addFinalizer(() => Effect.gen(function*() { /* lowered expr */ }) )exprcontains notry(pure sync cleanup likedefer cleanup()), it lowers directly toyield* Effect.addFinalizer(() => Effect.sync(() => { cleanup() }))(checking@throwsper VIP-4!). - Block form (
defer { ... }):yield* Effect.addFinalizer(() => Effect.gen(function*() { /* lowered statements */ }) ) - Exit-observing form (
defer (exit) { ... }):yield* Effect.addFinalizer((exit) => Effect.gen(function*() { /* lowered statements; exit: Exit.Exit<unknown, unknown> */ }) )
3. Execution Guarantees (Inherited from Effect Scope)
- LIFO order: Finalizers registered via
deferexecute in strict reverse registration order when the enclosingScopecloses. - Uninterruptible cleanup: Every
deferfinalizer runs uninterruptibly on normal return, typed failure (throw), defect, or fiber interruption. - Typed
Scopepropagation: Registering adeferautomatically addsScope.Scopeto the enclosing Effect'sRchannel. Callers must close the scope (e.g., viaEffect.scoped(...)or a parentScope), so leaking an unclosed resource is a compile error. - Infallible finalizers: Because Effect finalizers have signature
(exit) => Effect<void, never, R>, throwing a typed error insidedeferis a compile error (EK7903) — authors must handle it explicitly (catch,ignore, ororDie). - Control-flow isolation:
return,break,continue, andyield(inside a producer) cannot escape out of adeferbody (EK7902).
4. Reconciliation with VIP-8 (Denied)
VIP-8 (using / scoped keyword) remains denied. VIP-79 introduces neither using overloading nor a scoped block keyword; callers continue to use standard Effect.scoped(program) (or scoped(program) from VIP-6 Effect globals) to close a Scope.
5. Static Rules
| Mistake | Code |
|---|---|
defer statement outside effect code (including class field initializers and static blocks) | EK7901 |
return, break, continue, or outer yield escaping a defer body | EK7902 |
Unhandled typed failure (E ≠ never) inside a defer finalizer body | EK7903 |
await directly inside a defer body | EK0102 |
Testing & Verification Plan
- Parser unit tests +
FuzzDeferStatementverifyingdeferstays an ordinary identifier in plain TS/JS code (const defer = 1,defer(fn)). - Runtime acceptance cases (
typescript/vibelang/cases/vip79-*) verifying:- LIFO execution order across multiple
deferstatements - Execution on normal return, typed
throw, defect, and fiber interruption - Exit inspection via
defer (exit) { ... }(Exit.isSuccess/Exit.isFailure) - Compile-time error when
Scopeis not provided (TS2345) - Compile-time rejection of
return/break/continue(EK7902) and typed failure insidedefer(EK7903) - Proper interaction with
effect function*producers (finalizer runs when Stream terminates or is interrupted).
- LIFO execution order across multiple
Open Questions for Will
- Should
deferinside a loop (for (...) { defer ... }) register on the enclosing EffectScope(matchingEffect.addFinalizerand Go's function-scopeddefer, with a lint warningEK48xxwhen used inside a loop), or also allow an optional block-scoped form later? - Should
deferallow a bare Effect value withouttry(defer close(conn)), or require explicittry(defer try close(conn)) to stay 100% consistent with VIP-5 ("tryalways runs an Effect; bare expressions never implicitly run Effects")? (Recommendation: requiretry, consistent with VIP-5!)