On this page

0275. Function values, closures and interface values

Context

Tenon has no function values (LANGUAGE.md "Absent"), ? needs an identical error type, and interfaces are not values (E0663). Keybindings, middleware, widget and tool registries become hand-written match dispatchers; error plumbing becomes match r { err(e) => return err(AppError.Io(e)), … }. 0042 blocks (v.map { x -> … }) cannot be stored. Values are immutable in scoped arenas (0007/0036), promoted on carry/escape (0037); no shadowing (0013); monomorphized generics (0024); static, globally coherent interfaces (0027/0069); backends agree (0003); fuel counts calls (0017).

Decision

Types. fn(A, B) -> R (unit: fn(A)) and dyn I; dyn becomes a keyword. Neither is an equality type: ==, map keys, Show/Json/Reflect derives and impl targets reject them (E06xx, allocate at implementation); records holding them lose ==.

One literal form. A closure is the 0042 block shape in expression position: { x, y -> body }, { -> body }. Parameters are never annotated; types come from the expected type (annotation, parameter, field, element, return); none is E07xx ("write let f: fn(i64) -> i64 = { x -> x + 1 }"). The { Ident (, Ident)* -> lookahead is 0042's, so record literals (Ident { Ident :, 0020) and if c { blocks are unaffected; other bare blocks stay E0700. BlockArgs after builtin methods stay non-escaping 0042 blocks; user functions still reject trailing blocks (E0701) and take closures as arguments: retry(3, { n -> fetch(url) }). A function name in value position with no visible local of that name is a non-capturing value (let keep: fn(i64) -> bool = is_even); generic items need a solved expected type (E0602). The body's value is its last expression; ? targets the closure's own option/result return; return/break/continue stay E0703. Closures recurse only through named fns.

Calls. f(x) on a visible fn-typed local is an indirect call. A fn-typed local may not share a visible function's name (E07xx), so let twice = 2; twice(twice) keeps its meaning. Fields are called (r.on_key)(k); r.on_key(k) without such a method gets E06xx naming it.

Capture by value. Each captured binding is snapshotted at creation. With immutable values that copies a handle and never aliases; assigning a captured outer var is E07xx ("closures capture snapshots; return the new value"). 0042 BlockArgs keep captured writes since they cannot escape. Rust move/borrows and Swift capture lists exist to manage shared mutation; Go and Kotlin capture variables by reference, so results depend on call order. With nothing mutable to observe, snapshot is the one rule an agent can predict.

? conversion (step 2). In a function returning result<U, E2>, r? with r: result<T, E1>, E1 != E2, yields err(E2.V(e)) iff enum E2 has exactly one variant whose sole payload is exactly E1; zero or several is E05xx listing the fix ("add Io(IoError) to AppError"). Static, impl-free, visible in the declaration (Rust #[from] without macros). Builtin block method r.map_err { e -> … } (0042 style) covers every other mapping.

Interface values (step 3). dyn Widget(c) wraps any c: T with impl Widget for T (explicit, like i64(x)). Dyn-compatible: every method takes self first and Self appears nowhere else (E06xx names the method; App.update(…) -> Step<Self> is not). The compiler provides impl Widget for dyn Widget, so vec<dyn Widget> meets <T: Widget>; one impl per (interface, type) keeps each vtable unique. No downcasts, no supertraits.

Lowering. Closure bodies are lambda-lifted into IR functions with a leading env parameter, so mono specializes them per enclosing instance. ir.rs gains Type::Fn, Type::Dyn and verified Rvalue::{MakeClosure{func, captures}, CallIndirect{callee, args}, MakeDyn{iface, ty, value}, CallDyn{iface, method, recv, args}}. C: per fn layout typedef struct { R (*code)(const void *env, A, B); const void *env; } tn_fnN; (named items via thunks, env NULL); dyn I is { const void *data; const tn_vt_I *vt; } with static const vtables in sorted mangled order. Callee and arguments hoist into temporaries left to right; large results use the 0043 destination ABI. regions.rs classifies MakeClosure/MakeDyn as FreshItems over captures/value: env and data live in the destination region; a closure stored in a record, vec or map that outlives its scope is promoted like any heap-bearing value via per-layout promote helpers (0037/0270). Indirect call summaries are conservative (result may alias all args and env); captures count as aliases for the uniqueness proof (0278). Fuel: each indirect/dyn call charges one at callee entry, like a direct call, so fuel traps match across backends.

Interpreter. Value::Fn { func, env: Rc<[Value]> }, Value::Dyn { ty, value } (impl table keyed by (iface, ty)); equal on them is a compiler bug.

Prior art

Alternatives considered

Consequences

Implementation slices

  1. Fn types, named items as values, indirect calls. parser, resolve, types, lower, ir, mono, cgen, compact.rs + PRIMITIVE_GRAMMAR.md; interp.rs, interp/value_preview.rs. Frozen: yes. Claude Opus.
  2. Capturing closures. Lambda lifting (lower.rs), env layouts, regions.rs, cgen_carry.rs promote helpers, snapshot E-codes; interp.rs, interp/heap.rs. Frozen: yes. Claude Opus.
  3. ? conversion + result.map_err. types.rs, lower.rs (existing IR; no interp change). Frozen: no. Claude Sonnet.
  4. dyn values. types.rs compatibility, ir.rs, mono.rs, cgen.rs vtables; interp.rs, interp/heap.rs, interp/value_preview.rs. Frozen: yes. Claude Opus.
  5. Spec + parity. LANGUAGE.md (with trim), diagnostics.md, IDIOMS.md, bench/ callback and registry fixture on both backends. Frozen: no. Claude Sonnet.
  6. Adoption. tui_keys keymaps as map<str, fn(…)> (not frozen); agent tools as vec<dyn Tool> in plugins/agent* (frozen, separate OK). Gemini (agy Argon High).

Open questions (resolved)

Resolved by maintainer on 2026-11-22: every question takes its stated default.

  1. Closure params: never annotated (default) / optional { x: T -> }?
  2. In closures: ? allowed, return E0703 (default) / allow return?
  3. dyn I(x) explicit (default) / implicit coercion at typed sites?
  4. Field call: (r.f)(x) (default) / r.f(x) when no method matches?
  5. ? conversion: unique wrapping variant (default) / declared conversion function?
  6. Frozen interp edits for slices 1, 2, 4: approve per slice (default) / once for all?
  7. Compact: additive opcodes under ~1 like 0269 (default) / format ~2?