Skip to content

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):

  • defer remains an ordinary identifier (const defer = true, defer(x)).
  • Unambiguous defer { ... } or defer (exit) { ... } outside effect code recovers and reports EK7901 ("defer is only allowed inside effect code").

2. Semantics & Lowering

Every DeferStatement lowers directly to Effect 4's Effect.addFinalizer (with zero custom runtime wrapper):

  1. Expression form (defer expr):
    yield* Effect.addFinalizer(() =>
      Effect.gen(function*() {
        /* lowered expr */
      })
    )
    If expr contains no try (pure sync cleanup like defer cleanup()), it lowers directly to yield* Effect.addFinalizer(() => Effect.sync(() => { cleanup() })) (checking @throws per VIP-4!).
  2. Block form (defer { ... }):
    yield* Effect.addFinalizer(() =>
      Effect.gen(function*() {
        /* lowered statements */
      })
    )
  3. 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 defer execute in strict reverse registration order when the enclosing Scope closes.
  • Uninterruptible cleanup: Every defer finalizer runs uninterruptibly on normal return, typed failure (throw), defect, or fiber interruption.
  • Typed Scope propagation: Registering a defer automatically adds Scope.Scope to the enclosing Effect's R channel. Callers must close the scope (e.g., via Effect.scoped(...) or a parent Scope), 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 inside defer is a compile error (EK7903) — authors must handle it explicitly (catch, ignore, or orDie).
  • Control-flow isolation: return, break, continue, and yield (inside a producer) cannot escape out of a defer body (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

MistakeCode
defer statement outside effect code (including class field initializers and static blocks)EK7901
return, break, continue, or outer yield escaping a defer bodyEK7902
Unhandled typed failure (E ≠ never) inside a defer finalizer bodyEK7903
await directly inside a defer bodyEK0102

Testing & Verification Plan

  • Parser unit tests + FuzzDeferStatement verifying defer stays 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 defer statements
    • Execution on normal return, typed throw, defect, and fiber interruption
    • Exit inspection via defer (exit) { ... } (Exit.isSuccess / Exit.isFailure)
    • Compile-time error when Scope is not provided (TS2345)
    • Compile-time rejection of return/break/continue (EK7902) and typed failure inside defer (EK7903)
    • Proper interaction with effect function* producers (finalizer runs when Stream terminates or is interrupted).

Open Questions for Will

  1. Should defer inside a loop (for (...) { defer ... }) register on the enclosing Effect Scope (matching Effect.addFinalizer and Go's function-scoped defer, with a lint warning EK48xx when used inside a loop), or also allow an optional block-scoped form later?
  2. Should defer allow a bare Effect value without try (defer close(conn)), or require explicit try (defer try close(conn)) to stay 100% consistent with VIP-5 ("try always runs an Effect; bare expressions never implicitly run Effects")? (Recommendation: require try, consistent with VIP-5!)