Skip to content

Represent unsafe function pointer and callback types #370

Closed

Description

@ehartford

Summary

Give function-pointer and callback types an unsafe bit so a callable value can honestly carry a raw-pointer-validity precondition. Today unsafe fn exists for named declarations and §16.11 makes safe functions with raw-pointer validity preconditions a compile error, but the obligation evaporates the moment the function becomes a value: there is no type spelling for "this callback is unsafe to call", so c_import/migrate and user code cannot represent raw callback surfaces precisely.

Spec

§16.11: "A function that dereferences, retains, mutates through, converts, or otherwise relies on caller-guaranteed validity of a raw pointer parameter has a safety precondition that the raw pointer type does not encode. Such a function is an unsafe fn ..." and "Calls to unsafe fn" require an unsafe context.
§16.6: fn(...) -> T is a With callable value; extern "C" fn(...) -> T is a raw C ABI function pointer; "Named functions and non-capturing closures coerce to extern "C" fn when their signature matches."
§16.7 callback pattern stores extern "C" fn(ctx: *mut c_void, arg: i32) -> i32 in repr(C) structs.

The semantic requirement (spelling TBD, proposed below): a callable type may be marked unsafe; calling a value of such a type requires an unsafe context; an unsafe fn value must not coerce to a safe callable type; safe→unsafe coercion is fine.

Current state

  • Named unsafe fn: parsed by wrapping the body in NK_UNSAFE_BLOCK with UNSAFE_ORIGIN_FN_BODY (src/Parser.w:1111-1115); Sema.fn_symbol_is_unsafe (src/SemaCheck.w:2699) detects it; calling one requires unsafe (src/SemaCheck.w:8095 family; test err_unsafe_fn_call_requires_unsafe.w).
  • Issue Require unsafe fn or proven wrapper for raw-pointer validity preconditions #366 enforcement exists: a safe fn relying on caller-guaranteed raw pointer validity errors (src/SemaCheck.w:926-928, driven by EFF_RAW_PTR_VALIDITY noted at SemaCheck.w:2676; tests err_issue366_*).
  • Callable types: NK_TYPE_FN and NK_TYPE_EXTERN_FN parsed in Parser.parse_type_expr (src/Parser.w:6680 and 6640-6653); sema types TY_FN/TY_EXTERN_FN (src/Sema.w:47, constructed at Sema.w:1856-1878). No unsafe bit anywhere in the callable type representation. unsafe in type position does not parse.
  • Calls through callable values go through Sema.check_callable_value_call (src/SemaCheck.w:7699) — it never requires an unsafe context.
  • Consequence: unsafe fn cb(ctx: *mut i32) cannot be stored in any honest callback slot; storing it in extern "C" fn(*mut i32) and calling it later is a safe call to code with an unchecked precondition.

Implementation plan

  1. Syntax: accept unsafe as a prefix in type position for both forms — unsafe fn(*mut i32) -> Unit and unsafe extern "C" fn(*mut i32). In Parser.parse_type_expr (src/Parser.w:6606), on TK_KW_UNSAFE peek ahead for TK_KW_FN/TK_KW_EXTERN and set an is_unsafe flag passed into parse_fn_type_node; encode in the type node (spare bit in d2 or a wrapper flag in extras — confirm NK_TYPE_FN layout d0=extra_start, d1=param_count, d2=return_type at src/Ast.w:1526; return_type occupies d2, so carry the bit alongside param_count or in the extras header).
  2. Type representation: add the unsafe bit to TY_FN/TY_EXTERN_FN construction (Sema.add_type call sites Sema.w:1856-1878). Two unsafe variants must unify with themselves and be distinct from safe ones in find_fn_type_of_kind. Keep ABI/layout identical (pointer-sized) — this is a sema-only bit; codegen treats unsafe fn-ptr types exactly like their safe counterparts.
  3. Call rule: in check_callable_value_call (SemaCheck.w:7699) and the field-callable path (SemaCheck.w:7783-7797), if the callee type carries the unsafe bit, require_unsafe_operation("call to unsafe function pointer requires unsafe context", node) — same helper used by NK_ASM_EXPR (SemaCheck.w:3100) and transmute (7777).
  4. Coercion rules in types_compatible/assignment + the named-fn → fn-ptr coercion path:
    • named unsafe fn / unsafe closure → unsafe callable type: OK;
    • named safe fn → unsafe callable type: OK (widening);
    • named unsafe fn → safe callable type: error cannot use unsafe fn where a safe function type is expected; mark the target type 'unsafe fn' or wrap the contract in a safe function;
    • unsafe callable value → safe callable type: same error.
      Use fn_symbol_is_unsafe (SemaCheck.w:2699) at the coercion site where named functions become values (the extern "C" fn coercion already rejects capturing closures — extend that check, see test err_extern_fn_pointer_capturing_closure.w for the existing pattern).
  5. c_import / migrate emission: where c_import translates a C function-pointer member/param whose contract is unmodeled (ci_type_requires_raw_contract returns 1 for TY_FN/TY_EXTERN_FN at src/SemaDecl.w:466-469), emit unsafe extern "C" fn(...) in the generated surface so callback slots are honest; keep value-only signatures safe. with migrate mirrors this for translated callback typedefs.
  6. Effects interplay (Align @[effect] with §16.3d (declared effect contracts) #402): an unsafe callable type is the value-level analogue of EFF_RAW_PTR_VALIDITY; when Align @[effect] with §16.3d (declared effect contracts) #402 lands, a declared-effect summary on a callback type can refine it, but the default for raw C callback types is unsafe.
  7. Pure parser/sema change; no MIR/codegen lowering differences, no rt/Link.w impact.

Test plan

  • test/spec/spec_ss16_11_unsafe_fn_pointer.w (positive): declare unsafe fn bump(p: *mut i32); store in let cb: unsafe extern "C" fn(*mut i32) = bump; call inside unsafe { cb(&raw mut x) }; assert effect. Also safe fn assigned to unsafe slot, callable under unsafe.
  • test/compile_errors/err_unsafe_fnptr_call_requires_unsafe.w: call cb(p) outside unsafe → //! expect-error: call to unsafe function pointer requires unsafe context.
  • test/compile_errors/err_unsafe_fn_to_safe_fnptr.w: assign unsafe fn to extern "C" fn(...)-typed binding/field → //! expect-error: cannot use unsafe fn where a safe function type is expected.
  • test/compile_errors/err_unsafe_fnptr_struct_field.w: §16.7-style @[repr(C)] struct with safe func field given an unsafe fn → error.
  • c_import surface: inline-header import with typedef void (*cb)(int *p); void reg(cb f); — generated binding's callback slot is unsafe; passing a safe wrapper compiles, calling slot requires unsafe.
  • Regression: existing behav_closure_fnptr.w, behav_extern_fn_pointer.w, issue98_struct_field_fn_ptr_call.w unchanged.

Acceptance criteria

  • unsafe fn(...) and unsafe extern "C" fn(...) parse in type position (fields, params, lets, returns).
  • Calling an unsafe callable value requires an unsafe context; safe callable behavior unchanged.
  • unsafe fn values cannot reach safe callable types (assignment, field init, argument, return); safe→unsafe widening allowed.
  • c_import emits unsafe callback types for unmodeled raw-pointer callback contracts.
  • with build && with build :fixpoint && with build :test pass.

Dependencies

Traceability

From the raw-pointer safety rework (#366 follow-up); spec §16.6, §16.7, §16.11.

Activity

  1. added a commit that references this issue on Jun 17, 2026
  2. ehartford commented on Jun 17, 2026

    @ehartford
    ContributorAuthor

    Implemented in eb189c3. unsafe fn(...) and unsafe extern "C" fn(...) now parse in type position; unsafe-ness is part of callable type identity (sema side-set, ABI unchanged). Calling an unsafe callable value or unsafe callback field requires unsafe; a named unsafe fn or unsafe-typed value cannot coerce to a safe callable type (safe→unsafe widening allowed). c_import emits unsafe extern "C" fn(...) for generated callback params/fields whose signature carries a raw pointer (value-only signatures stay safe), so §16.7 callback slots are honest; cache format bumped to v14. Tests: spec_ss16_11_unsafe_fn_pointer, err_unsafe_fnptr_call_requires_unsafe, err_unsafe_fn_to_safe_fnptr, err_c_import_unsafe_callback_field. build + fixpoint + compile-error(579)/spec(163)/behavior(682) suites pass.

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