Skip to content

Stdlib helpers for boxing/unboxing C callback context (§16.7) #436

Closed

Description

@ehartford

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 no ffi.w; c_void lives in lib/std/builtins.w:9 (pub type c_void = opaque).
  • Raw building blocks exist: std.mem exposes alloc/alloc_zeroed/free_mem/mem_copy (lib/std/mem.w:18-45); extern "C" fn types parse and named non-capturing functions coerce (tests behav_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 trampoline extern-ABI function casting *mut c_void back, manual std.mem.alloc/free_mem, all unsafe-by-hand.

Implementation plan

  1. New module lib/std/ffi.w (this is also the spec-preferred home for c_void per 16.3.3.9 — re-export c_void here 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), move value in, return the type-erased pointer. The value's Drop is deferred until drop_ctx.
    • pub unsafe fn ctx_ref[T](ctx: *mut c_void) -> &T and pub 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 a T and 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) — run T's drop and free, for wiring into destroy slots.
      Implementation notes: needs sizeof/alignof intrinsics (exist, §16.12) and a way to run drop glue for T — 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 by let _ = unbox_ctx[T](ctx)-style implementation, avoiding a direct drop-glue intrinsic).
  2. Destroy trampoline helper: since each T needs an extern "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 to extern "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).
  3. 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 via ctx_mut[State](ctx).
  4. 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.mem externs. No bootstrap hazard.
  5. Type discipline: helpers must reject ephemeral T (context outlives the call; storing ephemerals would be an escape) — add the ephemeral bound check if box_ctx doesn'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 under unsafe — no real C needed), mutate via ctx_mut, observe the mutation after the call, then drop_ctx; assert a Drop-counter type's drop ran exactly once. //! expect-stdout: ok.
  • test/behavior/behav_ffi_box_roundtrip.w: box_ctx/unbox_ctx round-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) outside unsafe → //! expect-error: (unsafe fn call).
  • test/compile_errors/err_ffi_box_ephemeral.w: boxing an ephemeral type → escape/ephemeral error.
  • If destroy_trampoline ships: behavior test wiring it into the Callback struct and invoking destroy actually drops the context.

Acceptance criteria

  • std.ffi (new lib/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" fn coercion isn't sound yet, the trampoline helper is omitted and the omission documented, not stubbed.
  • with build && with build :fixpoint && with build :test pass.

Dependencies

Traceability

From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 16.7.1.1.

Activity

  1. ehartford commented on Jun 17, 2026

    @ehartford
    ContributorAuthor

    Implemented in 4f09da9 (lib/std/ffi.w).

    Helpers (§16.7): box_ctx[T](value) -> *mut c_void plus unsafe recovery ctx_ref/unbox_ctx/drop_ctx. box_ctx is Box.new(value) as *mut c_void — Box.new moves the value to the heap without dropping it and the cast surrenders ownership without running the box's Drop. Recovery reads the value back and frees the same allocation, so the value's Drop runs exactly once, at unbox_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 from ctx as *mut State) rather than the turbofish unbox_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)] Callback record — fn-pointer + ctx + destroy — invoked under unsafe, 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):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions