0275. Function values, closures and interface values
- Status: Accepted (maintainer, 2026-11-22; recommended defaults for all open questions; frozen-file edits listed here approved)
- Date: 2026-11-22
- Plan: D3 (staged: fn types →
?conversion →dynvalues); amends 0025, 0027, 0042 - Review: Design Critic #3
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
- Rust closures and dyn compatibility: https://doc.rust-lang.org/reference/types/closure.html, https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility
- Swift closures/capture lists; typed throws (SE-0413): https://docs.swift.org/swift-book/documentation/the-swift-programming-language/closures/, https://github.com/swiftlang/swift-evolution/blob/main/proposals/0413-typed-throws.md
- Go by-reference function literals; interface layout: https://go.dev/ref/spec#Function_literals, https://research.swtch.com/interfaces
- Zig error sets: https://ziglang.org/documentation/master/#Error-Set-Type
- Kotlin lambdas mutate captured vars: https://kotlinlang.org/docs/lambdas.html
Alternatives considered
- Non-capturing function pointers only —
Maintainer chose full closures; registries need configured
callbacks (
{ ev -> scroll(ev, step) }). - Capture by reference (Go/Kotlin) — reintroduces shared mutable state 0007 removed.
- Rust
move/borrows or Swift capture lists — syntax for a distinction Tenon lacks. fn(x: i64) -> R { … }literals — a second form; typed{ x: i64 ->collides with theIdent { Ident :record lookahead.impl Into for E1— no generic interfaces (0027); one impl per type allows one target.- Implicit coercion to
dyn— breaks "no implicit conversions";dyn I(x)is greppable.
Consequences
- UX: keymaps, middleware and tool registries become data, so
apps are configurable without new dispatchers. DX: removes
dispatch and error-wrapping boilerplate. AX (0009): one closure
form, one capture rule, one
dynform, each with a teaching diagnostic. - Indirect calls defeat some inlining; IDIOMS.md: "prefer
<T: I>; usefn/dyn Ifor heterogeneous registries". - LANGUAGE.md ≈ +9 lines (+230 tokens): Functions +5, Interfaces
+2,
?+1; deletes "Interfaces aren't values (E0663)", "No error conversion" and "function values, nested functions" from Absent; the spec slice trims as much (integer/str match detail → diagnostics.md). - Compact grammar (0268) gains additive opcodes, as 0269 added
T: fn type, dyn type, closure (N;+ block, the block-argument encoding), indirect call,dyn I(x); named items reuseN. - Closures in agent state cannot be journaled (no Json/Reflect). FFI rejects fn/dyn statically.
- Frozen files: crates/tenon/src/interp.rs, crates/tenon/src/interp/heap.rs, crates/tenon/src/interp/value_preview.rs (slices 1, 2, 4); plugins/agent* (slice 6).
Implementation slices
- 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.
- 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.
?conversion +result.map_err. types.rs, lower.rs (existing IR; no interp change). Frozen: no. Claude Sonnet.dynvalues. types.rs compatibility, ir.rs, mono.rs, cgen.rs vtables; interp.rs, interp/heap.rs, interp/value_preview.rs. Frozen: yes. Claude Opus.- Spec + parity. LANGUAGE.md (with trim),
diagnostics.md, IDIOMS.md,
bench/callback and registry fixture on both backends. Frozen: no. Claude Sonnet. - Adoption. tui_keys keymaps as
map<str, fn(…)>(not frozen); agent tools asvec<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.
- Closure params: never annotated (default) / optional
{ x: T -> }? - In closures:
?allowed,returnE0703 (default) / allowreturn? dyn I(x)explicit (default) / implicit coercion at typed sites?- Field call:
(r.f)(x)(default) /r.f(x)when no method matches? ?conversion: unique wrapping variant (default) / declared conversion function?- Frozen interp edits for slices 1, 2, 4: approve per slice (default) / once for all?
- Compact: additive opcodes under
~1like 0269 (default) / format~2?