Repository navigation
C functions as values and calls: unsafe callables, unprototyped calls, inline unsafety, variadic fn pointers, migrator prototypes, c_export conflicts (#1829 #1831 #1830 #1833 #1832 #1848 #1849 #1850) - #1870
Merged
Conversation
ehartford
added a commit
that referenced
this pull request
Sep 28, 2026
Eric, 2026-09-28: "(a), sentence approved, notation not" — the literal variadic token must be visually distinct from a meta-ellipsis, so the sentence spells `extern "C" fn(A, B, ...) -> R` with a prose note. Calling through it is raw and its `unsafe` is implied; only an `extern "C"` function type may end in `...`; variadic and fixed-arity function types never coerce. Implemented on stack #1871 (#1870). Co-authored-by: Eric Hartford <[email protected]>
added 10 commits
September 29, 2026 14:40
…al (#1833) A struct field of type `extern "C" fn(&T) -> R` (or `fn(&T) -> R`) was refused as "ephemeral references cannot be stored in structs". type_expr_contains_ref (SemaCheck.w) descended into a callable type's parameter and result types; type_expr_is_collection_with_ref did the same. A callable takes a view per call and holds none (§16.6, §22.1 rule 1): what a closure captures is value-level (§22), and the TypeId predicate type_is_ephemeral_value never looked inside a fn type either. Both type-expression predicates now answer 0 for NK_TYPE_FN and NK_TYPE_EXTERN_FN, so a field, a Vec element and a let of such a type are accepted. Test: test/behavior/behav_1833_fn_field_takes_reference.w (a struct with an `extern "C" fn(&i32) -> i32` and a `fn(&i32) -> i32` field, and a `Vec[extern "C" fn(&i32) -> i32]`), refused before, prints 5 6 7 now. Fixes #1833
…alue (#1829) §16.11: an `unsafe fn` may not coerce to a safe callable type, and a call through an unsafe callable needs an unsafe context. check_ident (SemaCheck.w) gave a function used as a value its signature's own TY_FN type (sig_type_ids), which is never in unsafe_fn_type_set, and ran the §16.11 coercion check only when an `extern "C" fn` type was expected. So `let f = danger; f(1)` and `apply(danger, 1)` with `g: fn(i32) -> i32` compiled with no `unsafe`, and so did a raw c_import function or a manual extern with a pointer parameter used the same way. Sema now states the rule once: fn_symbol_unsafe_call_reason decides whether a direct call to a function needs `unsafe` (an `unsafe fn`, a raw c_import function, a manual extern with an unmodeled contract), and both the direct call and the value use read it. As a value such a function has unsafe_callable_type (Sema.w): the same parameters and result, unsafe to call — so the existing "call to unsafe function pointer requires unsafe context" check applies to the call through the value, and the coercion to a safe `fn` or `extern "C" fn` type is refused with the existing §16.11 message. A presented facade call (§16.2b.8) stays safe at its call site; the function's value is not presented. The stage1 self-check (compiler plus embedded stdlib) needed no change. Tests: test/compile_errors/err_1829_unsafe_fn_value_call.w, err_1829_unsafe_fn_to_safe_fn_type.w, err_1829_manual_extern_value_call.w (each compiled and ran before); test/behavior/behav_1829_unsafe_fn_value.w (the value called under `unsafe` and through an `unsafe fn` parameter; rejected before as "unsafe block contains no unsafe operations"). Fixes #1829
…unsafe fn (#1830) ci_translate_function (CImport.w) decided a `static inline` function's `unsafe fn` from its own signature only. A body that calls a raw function (`return vd_sum(4, 10, 20, 12, 18);` over a variadic prototype) was printed as a safe `fn` whose raw call is unwrapped — the migrate path's g_migrate_unsafe_extern_fn_names, which wraps such calls, is never filled by c_import — so the generated text failed Sema with "raw c_import function call requires unsafe context" and took the whole c_import down. D51: the wrapper must not become safe by inference. The static-inline branch now asks ci_cursor_calls_raw_function of the definition before it prints the body: a direct call whose callee is raw by the same test the extern path applies (variadic, a raw-ABI parameter or result), or an inline callee whose own body is raw (depth-bounded; past the bound the answer is raw, which can only remove the safe surface). Such a function is an `unsafe fn` and its body is printed in that context. A libc call the body translator rewrites to its own With form (calloc to with_alloc_zeroed, free, strlen, libm, builtins) is not a call to the C function and does not count: the translator already states that form's context, and the facade tests' safe `log_new`/`log_free` helpers stay safe. Tests: test/behavior/behav_1830_c_import_inline_calls_raw.w (an inline over the variadic snprintf and an inline over that inline, called under `unsafe`: 6, 7) and test/compile_errors/err_1830_c_import_inline_calls_raw.w (the call needs `unsafe`); both failed before on the generated body. Fixes #1830
…ed-argument convention (#1831) libclang reports every FunctionNoProto type variadic, so `int knr();` was imported as `extern fn knr(...) -> c_int` and every call used the variadic convention. On darwin arm64 that puts each argument on the stack while the definition reads x0/x1 (d0 for a double): `knr(4, 2)` printed 0 instead of 42, and `jn(-1, 0.5)` printed 1. C11 6.5.2.2p6: a call to a function with no prototype passes each argument after the default argument promotions (an integer narrower than int -> int keeping its sign, float -> double) with the fixed-argument convention. The fact now flows from its source to its owners: - ClangBridge.w with_cimport_fn_is_unprototyped: a FunctionNoProto declaration whose definition the unit does not show (a K&R definition lists its parameters and stays with the definition path). - CImport.w still spells it `extern fn knr(...)` — any arguments, a raw call — and states the fact in the generated text's manifest (`// @with-cimport-unprototyped|knr`, beside the omitted-symbol manifest). The Frontend, which parses that text, sets flag bit 1 on the NK_EXTERN_FN it names; SemaDecl marks the signature (unprototyped_sigs). Only c_import's generated text can state it: there is no attribute a person could write, so no language surface (the first cut used an `@[c_unprototyped]` attribute; spec-inventory-check rightly refused an unspec'd attribute). - Sema (record_c_promoted_args) states, per call, the type each argument is passed as after the promotions (c_default_promoted_type), reading a materialized Copy view's pointee from materialize_variadic_value_arg; an argument with no C form (a `str`, a With struct) is refused loudly. Using the function as a value is refused: it has no function type. - CodegenDispatch builds the call's FnAbi from exactly those types with compute_fn_abi (FN_ABI_C, not variadic), the one classifier; the declaration's variadic descriptor never reaches the call. The operand coercion takes each promoted type (sign-extend i8, fpext f32). - CCodegen declares it `T knr();` so the C compiler applies the same promotions and convention (a C23 compiler refuses a call with arguments: loud, never a wrong ABI). `with analyze … audit:all` on the test program: 0 violations. Tests: test/behavior/behav_1831_c_import_unprototyped_call.w (`double jn();` with an i8 and an f32, and `long strtol();`: printed 1 and 0 before, -0.242268 0.030604 -12 now, matching C); test/compile_errors/err_1831_unprototyped_as_value.w and err_1831_unprototyped_str_argument.w (compiled before). The C migrator emits the same `extern fn knr(...)` for a declaration-only unprototyped function in migrated source, which has no c_import manifest (#1848). Fixes #1831
…omotions (#1849) C11 6.5.2.2p7: an argument a `...` receives gets the default argument promotions — an integer narrower than int becomes int (keeping its sign or value), a bool int, an f32 f64. Codegen passed an `i8`/`i16` as is into the LLVM vararg call, whose upper bits LLVM leaves undefined: the i8 constant -3 was materialized as `mov w9, #0xfd` into the stack slot and `snprintf(buf, 16, "%d", b)` wrote 253; an i16 -1000 read 64536. Runtime-computed values often sat already extended in the register, so the bug hid. The fact is #1831's: Sema's record_c_promoted_args now also states, for a variadic callee, the promoted type of each `...` argument the promotion changes (c_default_promoted_type; 0 for the fixed arguments and for an argument it leaves alone, so nothing new is refused). Codegen converts such an argument to that type, sign- or zero-extending by the argument's own type, as clang does (`sext i8 … to i32`, `fpext`). The FnAbi of a variadic call is unchanged: the `...` arguments were never in it. Test: test/behavior/behav_1849_variadic_default_promotions.w (an i8, u8, i16, bool and f32 through snprintf's `...`): printed 253 and 64536 before, -3 200 -1000 1 1.5 now. Fixes #1849
…#1832) c_import renders a C variadic function-pointer type as `extern "C" fn(c_int, ...) -> c_int`, but the type grammar had no `...` (parse_fn_type_node: "expected type"), so any header with a variadic callback typedef failed to import; and TY_FN/TY_EXTERN_FN carried no variadic bit, so nothing could call through such a pointer with the variadic convention. Per the decision on #1832 (the spelling c_import already emits, D75's `...`): - Parser: `extern "C" fn(A, ...) -> R` (and `unsafe extern "C" fn(...)`) parses; the node is marked in the AST's variadic_fn_type_nodes (copied by ComptimeTransform like the unsafe mark). `...` in a With `fn(...)` type is refused: a closure has no C variadic convention. - Sema: variadic-ness is part of a callable type's identity (variadic_fn_type_set beside unsafe_fn_type_set; find/ensure take the identity flags CALLABLE_UNSAFE | CALLABLE_VARIADIC; types_identical and fn_types_compatible[_frozen] compare them), so a fixed and a variadic function type never coerce. A variadic type is always unsafe to call (§16.3c: the call is raw): `unsafe` is implied, and both spellings resolve to one type. - A variadic extern used as a value has this type (variadic_callable_type: its fixed parameters, then `...`) instead of a fixed-arity TY_FN. - A call through such a pointer — a binding, a field, a parameter — takes its fixed arguments and any more; the extra ones are passed as a `...` argument is: value context, a Copy view materialized, and the default argument promotions (#1849's record_c_promoted_args). - Codegen: callable_fn_abi gives a variadic TY_EXTERN_FN the variadic convention through compute_fn_abi; the promoted-type conversion reads Sema's record for any call node, not only a named callee's. - The C backend declares the typedef `R (*)(A, ...)`; diagnostics and .wi interfaces spell the `...`. A With `...` definition (D75, #1844) used as a value is not changed here: on main it still has the With convention; once #1844 lands it can take the same type. Tests: test/behavior/behav_1832_variadic_fn_pointer.w (snprintf as a value and through a typed binding, a struct field and c_import's own `fmt_fn` typedef, with a promoted i8 and f32: failed to parse before; prints 7/-2, 12-345, 1.5); test/compile_errors/err_1832_variadic_with_fn_type.w, err_1832_fixed_to_variadic_fn_type.w, err_1832_variadic_pointer_call_requires_unsafe.w (all "expected type" before). Fixes #1832
…(§16.2b.5, #1832) Proposed normative text for Eric's blessing, appended to §16.2b.5's "Variadic definitions" paragraph (docs/spec/ffi.md); not blessed yet: > The type of a variadic C function as a value is `extern "C" fn(A, > ..., ...) -> R`: calling through it is raw and its `unsafe` is implied, > only an `extern "C"` function type may end in `...`, and a variadic and > a fixed-arity function type are distinct types that never coerce to one > another. It states the rule the #1832 implementation follows: the spelling c_import already emits and D75's `...`; §16.3c's raw variadic call; no closure form; variadic-ness as part of the type's identity.
…; a compatible one takes the declaration's references (#1850) When a c_imported header (or a manual extern) declares the C symbol a `@[c_export]` fn defines, C code — and With code calling that extern — calls the definition through the declaration. Codegen's declare-then- define step (Codegen.w, the c_export branch) found the declaration with another LLVM type, renamed it `<name>__stale_decl`, added the definition under a fresh name, and left every call on the renamed declaration: `int zz_sum(int n, ...)` defined by `fn sum_impl(n, a, b)` linked against an undefined `_sum_impl__stale_decl`, and so did the legitimate C pairing of `int zz_knr();` with a definition taking (int, double). §16.5 and C11 6.7.6.3p15 decide which it is, in Sema (check_c_export_against_declarations, beside validate_c_export_signature): the definition must be the C function the declaration describes — the same result, parameter count, parameters and variadic-ness (any two pointers are one C argument type), or, for a declaration without a prototype (#1831), parameters that are what the default argument promotions pass. Anything else is refused at the definition, naming both types: @[c_export("zz_sum")] fn 'sum_impl' is `extern "C" fn(i32, i32, i32) -> i32`, but 'zz_sum' is declared `extern "C" fn(i32, ...) -> i32`, and C calls it through that declaration: one is variadic and the other is not A compatible definition whose LLVM type still differs (the unprototyped case) now owns the symbol for real: codegen replaces every use of the displaced declaration with the definition (wl_replace_all_uses_with) and rebinds each symbol that held it (redirect_fn_value), so calls emitted before or after the definition reach it. Tests: test/behavior/behav_1850_c_export_defines_unprototyped.w (an unprototyped prototype defined in With and called with promoted i8/f32 arguments: undefined `__stale_decl` before, 42 and 25 now); test/compile_errors/err_1850_c_export_conflicts_with_prototype.w and err_1850_c_export_unpromoted_parameter.w (both linked to an undefined `__stale_decl` before). No other `@[c_export]` in test/, lib/, tools/, build/ or examples/ trips the check. Fixes #1850
…ts calls use (#1848) The migrator emitted a declaration-only unprototyped function (`int knr();`, defined in no migrated unit) as `extern fn knr(...) -> c_int`: libclang calls every unprototyped type variadic, so every migrated call used the variadic convention — on darwin arm64 its arguments on the stack while the definition reads x0/d0, #1831's miscompile in migrated code. The fact is #1831's (with_cimport_fn_is_unprototyped). Migrated source is ordinary With, which has no spelling for an unprototyped call, so the migrator writes what C does: each call passes its arguments after the default argument promotions with the fixed-argument convention. The declaration becomes the prototype every call in the unit agrees on, read off clang's own promoted argument types (ci_migrate_unprototyped_call_shape, CImport.w): `int twice(signed char c, float f) { return knr(c, f) * 2 + knr(1, 2.5); }` now declares `extern fn knr(a0: c_int, a1: f64) -> c_int`. Calls that disagree, an argument with no With type, or the function used as a value refuse the migration loudly, naming the function (No Silent Fallbacks); a declaration nothing calls is not emitted. Verified against a K&R definition compiled by clang: the migrated `twice(-3, 1.5)` returns -445, as C does. Test: build/selfhost.w bs_check_migrate_unprototyped_declaration in :c-migrator-basic-tests (the promoted prototype, no `(...)`, the output type-checks, and disagreeing calls are refused); it failed on the pre-fix release binary ("missing expected output … extern fn knr(a0: c_int, a1: f64) -> c_int"). Fixes #1848
…an unsafe extern "C" fn type (#1829) §16.11 lists a call to a raw c_import function (a pointer contract) among the operations that need an unsafe context, and #1829 (a708cd9) made such a function an unsafe callable as a value: it may not coerce to a safe callable type. Only the variadic type extern "C" fn(A, ...) -> R has its unsafe implied (§16.2b.5, v7.9); a fixed-arity extern "C" fn type is safe. The fixture predates the rule and bound with_issue546_identity (void *(void *)) to a safe extern "C" fn type, so the fresh stage1 refused it. It now binds to unsafe extern "C" fn(*mut c_void) -> *mut c_void, the spelling the rule requires; with_issue546_noop has no pointer contract and stays a safe callable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack created with GitHub Stacks CLI • Give Feedback 💬