Repository navigation
Description
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 inNK_UNSAFE_BLOCKwithUNSAFE_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:8095family; testerr_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 byEFF_RAW_PTR_VALIDITYnoted at SemaCheck.w:2676; testserr_issue366_*). - Callable types:
NK_TYPE_FNandNK_TYPE_EXTERN_FNparsed inParser.parse_type_expr(src/Parser.w:6680and 6640-6653); sema typesTY_FN/TY_EXTERN_FN(src/Sema.w:47, constructed at Sema.w:1856-1878). No unsafe bit anywhere in the callable type representation.unsafein 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 inextern "C" fn(*mut i32)and calling it later is a safe call to code with an unchecked precondition.
Implementation plan
- Syntax: accept
unsafeas a prefix in type position for both forms —unsafe fn(*mut i32) -> Unitandunsafe extern "C" fn(*mut i32). InParser.parse_type_expr(src/Parser.w:6606), onTK_KW_UNSAFEpeek ahead forTK_KW_FN/TK_KW_EXTERNand set anis_unsafeflag passed intoparse_fn_type_node; encode in the type node (spare bit in d2 or a wrapper flag in extras — confirm NK_TYPE_FN layoutd0=extra_start, d1=param_count, d2=return_typeat src/Ast.w:1526; return_type occupies d2, so carry the bit alongside param_count or in the extras header). - Type representation: add the unsafe bit to
TY_FN/TY_EXTERN_FNconstruction (Sema.add_typecall sites Sema.w:1856-1878). Two unsafe variants must unify with themselves and be distinct from safe ones infind_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. - 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). - 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: errorcannot 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.
Usefn_symbol_is_unsafe(SemaCheck.w:2699) at the coercion site where named functions become values (theextern "C" fncoercion already rejects capturing closures — extend that check, see testerr_extern_fn_pointer_capturing_closure.wfor the existing pattern).
- named
- c_import / migrate emission: where
c_importtranslates a C function-pointer member/param whose contract is unmodeled (ci_type_requires_raw_contractreturns 1 for TY_FN/TY_EXTERN_FN at src/SemaDecl.w:466-469), emitunsafe extern "C" fn(...)in the generated surface so callback slots are honest; keep value-only signatures safe.with migratemirrors this for translated callback typedefs. - 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. - 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): declareunsafe fn bump(p: *mut i32); store inlet cb: unsafe extern "C" fn(*mut i32) = bump; call insideunsafe { 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: callcb(p)outside unsafe →//! expect-error: call to unsafe function pointer requires unsafe context.test/compile_errors/err_unsafe_fn_to_safe_fnptr.w: assignunsafe fntoextern "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 safefuncfield 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.wunchanged.
Acceptance criteria
-
unsafe fn(...)andunsafe 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 fnvalues cannot reach safe callable types (assignment, field init, argument, return); safe→unsafe widening allowed. -
c_importemits unsafe callback types for unmodeled raw-pointer callback contracts. -
with build && with build :fixpoint && with build :testpass.
Dependencies
- Align @[effect] with §16.3d (declared effect contracts) #402 (@[effect] — value-level effect contracts complement the unsafe bit).
- Stdlib helpers for boxing/unboxing C callback context (§16.7) #436 (callback context helpers will type their trampolines with these types).
- Overlaps Curated libc contract overlay for c_import modeled surfaces #379 (modeled callback contracts could re-safe specific surfaces).
Traceability
From the raw-pointer safety rework (#366 follow-up); spec §16.6, §16.7, §16.11.
Activity
Represent unsafe function pointer and callback types (#370, §16.6/16.…
ehartford commentedon Jun 17, 2026
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.