Repository navigation
Closed
Description
Summary
Provide the §16.7-promised standard-library helpers for boxing/unboxing closure context across C callback boundaries. The callback pattern (C function pointer + void* ctx + destroy hook) is the single most common FFI shape; today users hand-roll the context allocation, the unsafe casts, and the cleanup for every callback, with nothing in lib/std/ to make it correct-by-construction.
Spec
§16.7 Callback Pattern:
@[repr(C)]
type Callback {
func: extern "C" fn(ctx: *mut c_void, arg: i32) -> i32,
ctx: *mut c_void,
destroy: extern "C" fn(ctx: *mut c_void),
}
"Standard library provides helpers for boxing/unboxing closure context."
Supporting facts: §16.6 — capturing closures do not coerce to extern "C" fn (no place for context); c_void is the opaque pointee type (§16.3b).
Current state
- Requirement 16.7.1.1 verdict: absent — "no std boxing helpers".
lib/std/has noffi.w;c_voidlives inlib/std/builtins.w:9(pub type c_void = opaque). - Raw building blocks exist:
std.memexposesalloc/alloc_zeroed/free_mem/mem_copy(lib/std/mem.w:18-45);extern "C" fntypes parse and named non-capturing functions coerce (testsbehav_extern_fn_pointer.w,behav_closure_fnptr.w; capturing-closure rejection:err_extern_fn_pointer_capturing_closure.w). - The compiler correctly refuses to pass a capturing closure where a C fn pointer is expected, so users currently write: a
@[repr(C)]context struct, a named trampolineextern-ABI function casting*mut c_voidback, manualstd.mem.alloc/free_mem, all unsafe-by-hand.
Implementation plan
- New module
lib/std/ffi.w(this is also the spec-preferred home forc_voidper 16.3.3.9 — re-exportc_voidhere without moving the builtin to avoid prelude churn; see Tests: extern c void coverage (§16) #499's note). Provide a typed context box:pub fn box_ctx[T](value: T) -> *mut c_void— heap-allocate (sizeof[T] via the intrinsic,std.mem.alloc), movevaluein, return the type-erased pointer. The value'sDropis deferred untildrop_ctx.pub unsafe fn ctx_ref[T](ctx: *mut c_void) -> &Tandpub unsafe fn ctx_mut[T](ctx: *mut c_void) -> &mut T— unboxing views for use inside the callback (unsafe: caller asserts the ctx really is aTand is live — exactly the §16.11 raw-pointer-to-reference boundary).pub unsafe fn unbox_ctx[T](ctx: *mut c_void) -> T— move the value out and free the allocation (consuming unbox).pub unsafe fn drop_ctx[T](ctx: *mut c_void)— runT's drop and free, for wiring intodestroyslots.
Implementation notes: needs sizeof/alignof intrinsics (exist, §16.12) and a way to run drop glue forT— verify MirLower drop-glue is reachable from a generic body when a value goes out of scope (unbox_ctx's return + scope end covers drop_ctx bylet _ = unbox_ctx[T](ctx)-style implementation, avoiding a direct drop-glue intrinsic).
- Destroy trampoline helper: since each
Tneeds anextern "C" fn(*mut c_void)destroy hook and generic functions cannot be C fn pointers directly, provide a per-instantiation named trampoline pattern:pub fn destroy_trampoline[T]() -> extern "C" fn(*mut c_void)returning a monomorphized non-capturing wrapper. Verify monomorphized generic fns coerce toextern "C" fn; if codegen does not yet give each instantiation a C-ABI-compatible symbol, fall back to documenting the two-line user-side named function and ship only box/unbox/drop helpers (scope honestly — do not ship a helper that returns a wrong-ABI pointer). - Docs/example: a worked §16.7 example in the module doc comment: register a capturing With closure's state with a C API (
Callback { func: trampoline, ctx: box_ctx(state), destroy: ... }), unbox in the trampoline viactx_mut[State](ctx). - Pure stdlib addition (lib/std/ + embedded stdlib regen via normal build); no rt/Link.w changes, no new runtime symbols — helpers bottom out in existing
std.memexterns. No bootstrap hazard. - Type discipline: helpers must reject ephemeral
T(context outlives the call; storing ephemerals would be an escape) — add the ephemeral bound check ifbox_ctxdoesn't naturally trip the existing ephemeral-escape rules; write the negative test either way.
Test plan
test/spec/spec_ss16_7_callback_context.w: define a@[repr(C)]Callback struct exactly as the spec's example; box a struct context, invoke through the C-shaped fn pointer (call the slot directly from With underunsafe— no real C needed), mutate viactx_mut, observe the mutation after the call, thendrop_ctx; assert a Drop-counter type's drop ran exactly once.//! expect-stdout: ok.test/behavior/behav_ffi_box_roundtrip.w:box_ctx/unbox_ctxround-trip preserves value (non-Copy type with Drop counter: drop runs once, at unbox-value scope end, not at box time).test/compile_errors/err_ffi_ctx_ref_requires_unsafe.w:ctx_ref[T](p)outsideunsafe→//! expect-error:(unsafe fn call).test/compile_errors/err_ffi_box_ephemeral.w: boxing an ephemeral type → escape/ephemeral error.- If
destroy_trampolineships: behavior test wiring it into the Callback struct and invokingdestroyactually drops the context.
Acceptance criteria
-
std.ffi(newlib/std/ffi.w) exists with box/unbox/view/drop context helpers, with the unsafe boundary exactly on unbox/view/drop (the validity assertion), not on boxing. - Drop correctness: boxed values drop exactly once, at unbox/drop_ctx, never at box.
- The §16.7 Callback example compiles and runs as written (modulo the documented trampoline pattern).
- No silent wrong-ABI surface: if generic→
extern "C" fncoercion isn't sound yet, the trampoline helper is omitted and the omission documented, not stubbed. -
with build && with build :fixpoint && with build :testpass.
Dependencies
- Represent unsafe function pointer and callback types #370 (unsafe function-pointer types — callback slots whose callee has raw-pointer preconditions will adopt those spellings; helpers should compose).
- Implement Box[T] (§3.7, §3.9, §8, §18.7) #475 (Box[T] — once it exists,
box_ctxcan be reimplemented over it; not a blocker). - Tests: extern c void coverage (§16) #499 (notes the c_void std.builtins-vs-std.ffi placement; resolve consistently).
Traceability
From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 16.7.1.1.
Metadata
Metadata
Assignees
Labels
No labels
Activity
Add std.ffi callback-context helpers (#436)
ehartford commentedon Jun 17, 2026
Implemented in 4f09da9 (
lib/std/ffi.w).Helpers (§16.7):
box_ctx[T](value) -> *mut c_voidplusunsaferecoveryctx_ref/unbox_ctx/drop_ctx.box_ctxisBox.new(value) as *mut c_void—Box.newmoves the value to the heap without dropping it and the cast surrenders ownership without running the box'sDrop. Recovery reads the value back and frees the same allocation, so the value'sDropruns exactly once, atunbox_ctx/drop_ctx, never at box time (asserted by the Drop-counter in the spec test).Unsafe boundary is exactly on recovery (the caller asserts the pointer is a live
T), not on boxing — matching the acceptance criteria.destroy_trampoline omitted: generic functions cannot coerce to
extern "C" fn, so shipping a generic trampoline would hand out a wrong-ABI pointer. The two-line per-type named-trampoline pattern is documented in the module instead (scoped honestly per the issue).Recovery API shape: helpers take
*mut T(T inferred fromctx as *mut State) rather than the turbofishunbox_ctx[State](ctx)form, because explicit type arguments on a free generic function with value args are not yet supported — filed as #598.Tests:
spec_ss16_7_callback_context(the spec's exact@[repr(C)] Callbackrecord — fn-pointer + ctx + destroy — invoked underunsafe, mutation observed across calls, Drop asserted once),behav_ffi_box_roundtrip,err_ffi_ctx_ref_requires_unsafe.with build,:fixpoint,:native-spec-tests(170),:behavior-tests,:native-compile-error-tests(597) all pass.Follow-ups discovered while implementing this (worked around, not blocking):
Box.new).T(shared withBox.new; theerr_ffi_box_ephemeralnegative test is deferred to that fix rather than enforced inconsistently forbox_ctxalone).