Repository navigation
Variadic definitions (D75): va_start()/ap.arg[T]() per target; migrator translates C variadic bodies (#1678) - #1844
Merged
Merged
Conversation
ehartford
force-pushed
the
impl-variadic
branch
from
September 28, 2026 09:26
c68baa3 to
ecccc1e
Compare
This was referenced Sep 28, 2026
Merged
Contributor
Author
|
Battery GREEN on the stack top |
ehartford
marked this pull request as ready for review
September 28, 2026 10:05
added 5 commits
September 28, 2026 15:15
…T]()`, the list ends with its scope; C convention; unsafe to call A function defined with a trailing `...` now has the C calling convention for its whole signature (FnAbi: fn_abi_definition_convention, the one compute_fn_abi input; WITH_ABI_VERSION 7) and is unsafe to call. - Sema: `va_start()` is an intrinsic valid only as a `let`/`var` initializer in the body of a `...` definition (not a closure in it); it yields c_va_list. `ap.arg[T]()` reads the next argument: T is a default-promoted C scalar (an integer of at least int's width, f64, a raw pointer, an extern "C" fn) — a narrower integer, bool or f32 is refused with the promotion named; the list is a mutable place (a `let` list is refused, a c_va_list parameter reads its caller's list); the read is an unsafe operation. A `...` definition cannot be used as a value, nor be async or a generator. Sema records both calls (va_start_calls, va_arg_calls); MirLower honors them. - MIR: VA_START writes the list into its binding's storage, VA_ARG reads through the list place, and DK_VA_END ends the list at every exit of the binding's scope (return, break, loop iteration). - LLVM: llvm.va_start/llvm.va_end on the binding; va_arg expanded per target the way clang does — char* slots (Darwin arm64, Windows, wasm), SysV x86_64 gp/fp offsets, AAPCS64 gr/vr offsets. - TypeLayout: Darwin x86_64's va_list is SysV's 24-byte tag with caller-place parameters (it was 8 bytes); wasm's is a pointer (its LLVM type was an empty struct). - C backend: `, ...` prototypes, <stdarg.h> va_start/va_arg/va_end, and va_list for c_va_list. Verified: behav_variadic_definitions runs every promoted type, register overflow into the stack, a restarted list, early return, a va_list parameter, vsnprintf forwarding and an aggregate before `...` on darwin arm64; the same shapes linked against a gcc C caller on linux x86_64 (eric-5090); per-target IR (behav_variadic_definition_target_abi) matches clang's expansion for each target.
#1678) A variadic C definition is no longer omitted or bridged through the with_va_start/with_va_end seam: - `va_list ap; ... va_start(ap, last);` becomes `var ap: c_va_list = va_start()` where the list starts (the declaration is deferred to it); a list started again after its va_end is a fresh binding the scope then names; `va_end(ap)` is the list's scope end; `va_arg(ap, T)` is `ap.arg[T]()`. Every other shape fails loudly with its reason (a list that is not a local, va_start nested in another statement or used as a value, va_copy, goto bodies, an unnamed function-pointer T). - A static inline variadic definition keeps its `...` and is unsafe; a migrated `...` definition is `unsafe fn`, and its callers wrap the call. - libclang calls every unprototyped function type variadic; a K&R definition (`void stop()`) takes exactly the parameters it lists, so it is not a `...` definition (it had become `fn stop(...)`). - The preamble no longer declares with_va_start/with_va_end, and the corpus extern allowlist no longer permits them. Tests: behav_migrate_variadic_definitions migrates sum/mean/a restarted list/vsnprintf forwarding/a K&R definition and runs them; the c_import `static inline` probe that pinned the omission (#1678) now runs as behav_c_import_static_inline_variadic; the c-migrator-basic check expects the new form.
`void stop()`, `int main()` (TommyDS check.c) and
`void test_hash_iterator_key_pair()` (c-algorithms test-hash-table.c) are
K&R definitions; the migrator made them `fn f(...)`, which D75 makes
unsafe to call and unusable as a value. Re-migrated with this tree's
migrator (`:tommyds-migrate`, `:c-algorithms-migrate-tests`):
- lib/std/tommyds: check_.w and defs.w are the migrator's output whole
(defs.w drops the retired with_va_start/with_va_end externs; check_.w
also carries the current migrator's removal of nested `unsafe` prefixes
inside `unsafe { }` calls). The tommycheck harness builds and passes.
- c-algorithms: only programs/hash-table/test_hash_table.w, whose
regeneration differs by this one signature. The full re-migration of the
test programs also drops macro constants from every program's defs.w
(BINARY_HEAP_NULL, ALLOC_TEST_MAGIC, ...), which unchanged modules still
reference — drift that predates this change, left for its own re-promote.
test-hash-table builds and passes.
A generic variadic definition specialized without its `...`: the call reported "expects 2 argument(s), found 5" and the instantiated body "this body has none" for va_start. A `...` definition has the C calling convention — one C signature — so a type parameter on it is refused at the declaration, as async and generator ones are.
ehartford
force-pushed
the
impl-variadic
branch
from
September 28, 2026 19:15
ecccc1e to
04a1b4b
Compare
ehartford
pushed a commit
that referenced
this pull request
Sep 29, 2026
…finition convention that merged first (#1844) Both changes bumped WITH_ABI_VERSION to 7 in parallel; the variadic layer landed on main as v7, so the `&str` {ptr, len} view (its with-abi.md entry already renumbered v8 in the rebase) takes 8. docs/with-abi.sha256 is re-recorded on the stack top.
ehartford
pushed a commit
that referenced
this pull request
Sep 29, 2026
…#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
ehartford
added a commit
that referenced
this pull request
Sep 29, 2026
…e links its own generation's runtime (#1810 #1587 #1815) (#1869) * Build/Link: a stage links and embeds only runtime objects its own compiler generation compiled, and a link checks the build's say-so instead of trusting it (D30, #761 class) stage2's code is stage1's codegen, but stage1 linked it against the seed-built out/bootstrap-lib (prepare-bootstrap-link-root empties out/lib and out/lib is compiled by stage2), and stage-embedded-objects gave stage2 and stage3 the same seed-built blobs. It never failed only because no runtime seam changed representation since the pinned seed; the &str view ABI (#1810) changes every `with_*`/`wl_*` &str parameter. The D30 check could not see it: WITH_OUT_DIR vouched for any root the build pointed at. - A generation is the tree a compiler is built from: sha256 over its src/ and rt/ sources (build/compiler.w compiler_generation, one owner; the .wo keys reuse the same compiler_tree_sha/compiler_sha256_text, moved out of build/wo.w). Every stamped compiler carries its generation and the generation of the runtime it embeds in two post-link slots beside the ABI stamp (compiler.AbiStamp; `with version --generation`, `--runtime-generation`). - Every runtime/bridge object set records its producer's generation in <dir>/.producer (`version --generation`, else `foreign:<sha256>` — the pinned seed predates the flag): out/bootstrap-lib (seed), NEW out/bootstrap/lib (stage1: runtime, bridges, link metadata), out/lib (stage2). - stage2 links out/bootstrap/lib and stage2/stage3 embed it; stage3 and the release link out/lib. Each stage link names its root (runtime-root= -> WITH_RUNTIME_ROOT) and its embedded set's producer (runtime-producer=). `:dev` builds out/bootstrap/lib. - Link.w: WITH_RUNTIME_ROOT is the only root and must be this generation, else a loud error and no fallback. WITH_OUT_DIR no longer vouches: a candidate is taken only when its .producer is this generation (or, with none recorded, byte-identical to an embedded runtime of this generation); the embedded runtime is taken only when it is this generation's, else "run `with build :dev`". stage1 run by hand links through out/bootstrap/lib (<compiler_dir>/../lib). An unstamped compiler keeps the old rule. - runtime-generation-regression (part of :test): the release is one generation with out/lib and its embedded runtime, links through out/lib by WITH_RUNTIME_ROOT, and refuses a root of another generation with the message and no output. Evidence (this worktree, seed cffa4a40): - .producer: out/bootstrap-lib foreign:cffa4a40…, out/bootstrap/lib and out/lib e4b881d8…; stage1 gen e4b881d8 rtgen foreign:cffa4a40; stage2, stage3 and release gen = rtgen = e4b881d8. - out/command/stage2/worker.effects: stage1 linked stage2 with WITH_RUNTIME_ROOT = sha256(<root>/out/bootstrap/lib) c593c2ed…; link-compiler and stage3 with sha256(<root>/out/lib) 20c31de1…. - The objdump marker of #1815 (rt_f64_fixed_digits' frame) cannot tell the sets apart here: this seed compiles rt_core.o byte-identical to stage1 (cmp out/bootstrap-lib/rt_core.o out/bootstrap/lib/rt_core.o), so the roots are shown by the recorded env and by the refusals below. - stage1 by hand: links test/hello.w (prints hello); with out/bootstrap/lib moved away: "error: no runtime objects of this compiler's generation (e4b881d8…) to link: its embedded runtime is generation foreign:cffa4a40… … run `with build :dev` …", no binary; WITH_RUNTIME_ROOT=<root>/out/bootstrap-lib: "… holds runtime objects of compiler generation foreign:cffa4a40…, but this compiler is generation e4b881d8…; linking them would mix compiler generations (D30, #1815)", no binary. - release by hand: hello in the checkout and outside it (embedded); WITH_RUNTIME_ROOT=<root>/out/bootstrap-lib refused as above. - src/main build: green; src/main build :fixpoint: stage2 == stage3 over all 16 units; :stage3, :runtime-generation-regression, :embedded-runtime-regression, :deep-debug-tool-tests --no-deps: green. `version --generation` and `--runtime-generation` are build plumbing, internal flags in the spec inventory like `--link-bundle`. The wo_bundles.md sentence this changes is proposed in the next commit. Fixes #1815 * PROPOSED (needs Eric's blessing): wo_bundles.md — stage2's and stage3's embedded runtime is the one stage1 compiled (#1815) docs/spec/toolchain/wo_bundles.md said the stage-embedded object "reuses the bootstrap runtime inputs" — the seed-built set. Since the previous commit it embeds out/bootstrap/lib, the runtime stage1 compiled, because stage2's code is stage1's codegen. Kept in its own commit so the exact words can go to Eric before they land. * rt/std/compiler: read a `&str`'s bytes through `s as *const str`, which means the same under either `&str` representation `unsafe **(&s as *const *const *const u8)` reached a `&str`'s data pointer by dereferencing the reference's own slot twice: right only while a `&str` is a pointer to a str header. #1810 makes a `&str` its own `{ptr, len}`, and on the way through the stage chain the runtime and the LLVM/Clang bridges are compiled by both representations — by the pinned seed for stage1 (pointer) and by stage1 for stage2 and its programs (view) — so every such read must mean one thing under both. `*(s as *const str as *const *const u8)` does: a `&str` cast to `*const str` names a str header either way (the seed passes the reference through, #747; a view is its own header — its storage, or a copy in the frame). 56 sites: rt_core (str_data, with_str_eq_ref/cmp_ref, with_parse_i64_ref, with_lines_out_ref), panic_runtime.str_data and each platform's rt_str_data/posix_str_to_c_buf/win_str_data/rt_net_str_data/wasm_str_data, LlvmBridge (to_cstr, path_to_cstr and 18 wl_* string parameters), ClangBridge (10), ClangDriver.cc_c_string, both intern pools, std.regex, std.internal.str_abi, std.collections.trie (the same idiom through `*const *mut u8`), and Sema.sema_str_has_data (which read the text's first eight bytes as a pointer under a view). Evidence: the seed compiles these sources into out/bootstrap-lib (pointer `&str`) and stage1 links and runs against them (`src/main build :dev`); stage1 compiles them into out/bootstrap/lib (view `&str`) and the #1810 matrix programs linked through it pass. `grep` for the idiom in rt/ src/ lib/ tools/ build/: none left. * PROPOSED (needs Eric's blessing): with-abi v7 — a shared `&str` is a view value with str's own `{ptr, len}` layout, passed like a slice docs/spec/abi/with-abi.md describes the ABI the compiler implements; this is the wording for the #1810 change that follows, kept in its own commit so the exact words can go to Eric before they land. - §1: a shared `&str` (or `&T` of a distinct type over str) is a view value `{ ptr: *const u8, len: i64 }`, not the address of a str header, so a range view `s[a..b]` exists without a header (spec §4.8a); `&mut str` stays a pointer. The fact's one owner is `TypeLayout.type_layout_is_str_view`. - §3: the layout row (16 bytes, align 8); `Option[&str]` is an ordinary tagged enum, not the D22 nullable pointer (its payload is not an address). - §4: `&str` views pass Fat, `{ptr, len}` by value, indirect under the existing Windows x86_64 rule, like `[]T`. - Header and status line: version 7 (they still said v4 after v5 and v6 were recorded); v7 history entry. The spec already rules the language question (§4.8a: a str range is a `&str` view of its bytes, with the origin of any view); this commit only describes its ABI consequence. * FnAbi/TypeLayout/Codegen/CCodegen: a shared `&str` is its own `{ptr, len}` view, passed by value like a slice, so a str range needs no header (D71 §4.8a, #1810) Spec §4.8a makes `s[a..b]` a `&str` view of its bytes, with the origin of any view. While `&str` was the address of a str header, a range view had no header to point at: #1587 built one in a hidden frame local and Sema refused every return of it. A `&str` is now the view itself. One owner: `Sema.type_layout_is_str_view` (TypeLayout.w) says a shared `&str` (or `&` of a distinct type over str) has str's layout, 16 bytes, align 8; `&mut str` stays a pointer. Everything else reads it: - FnAbi: a view classifies through its LLVM type (the str struct), so compute_fn_abi gives it PM_DIRECT by value (PM_INDIRECT under the windows-x86_64 rule), for With functions and every runtime `_ref` seam alike; `sig_param_is_explicit_ref` no longer calls it a reference. WITH_ABI_VERSION 6 -> 7; docs/with-abi.sha256 re-recorded. - LLVM codegen: `*view` is the view's own storage (no load); a shared borrow of a str place loads the header's bits; `*const str -> &str` loads, `&str -> *const T` names the view's storage. Every hand-built runtime declaration (str methods, fmt, concat, join, panic, cstr lend) now goes through `call_internal_runtime_fn`/the str type, so caller and callee read one FnAbi. `Option[&str]` is a tagged enum: slot lookups (Map.get, SlotMap.get, Vec element and iterator views, map traversal) read the view out of the slot (`mir_ref_from_slot_ptr`, `option_ref_from_slot_ptr`). - MirLower: a str range is the view itself, like `[]T`; the hidden header local is gone. - C backend: `&str` is `with_str` by value; `WITH_STR_REF` and every `const with_str *` for a `&str` parameter in runtime/with_runtime.h and build/package.w are gone; a str or view lent to `const char *` goes through `with_cstr_lend`/`with_cstr_release` as the LLVM backend lends it (D47; a range view is not NUL-terminated at its end), keyed on Sema's `sema_type_is_c_char_pointer` (Codegen's copy of that predicate is gone too). Evidence (compiler facts, `with analyze … matrix:`; the `&str` rows of the matrix programs, before -> after): m1 params: params pointer 84 -> 0, value 0 -> 84; args existing-pointer -> direct-value, all m2 consumers: params 84 ptr -> 84 value; args 107 existing-pointer + 100 direct-value -> 207 direct-value m3 Option: 84 -> 84 value; 105 + 97 -> 202 direct-value m6 c_import: 83 -> 83 value; 104 + 88 -> 192 direct-value m9 join/fmt: 83 -> 83 value; 103 + 91 -> 194 direct-value Behavior (build + run, before -> after; the programs that do not return a range view): params, consumers (compare, concat, match, hash, fmt, Display/Debug), Option lookups, places (iteration, closures, `&&str`, raw pointers), c_import lending: pass -> pass; `[&str; N]` element concat: codegen "wrong argument type actual=str expected=ptr" -> pass; `join(&str sep)` over a Vec: SIGBUS -> pass; `&dyn Display` over a str: the same phase BUG before and after (#1818, filed). New tests: behav_1810_str_view_{params,consumers,lookups,c_lend}.w. `src/main build` green; `src/main build :fixpoint`: stage2 == stage3 over all 16 units. `:emit-c-smoke` green (every test/emit_c fixture, run by both backends). `:deep-debug-tool-tests --no-deps` green; `:drop-audit` 213 cells, 0 non-PASS, 0 regressions; `:move-audit` 105 cells, 0 FAIL, 0 DIFF; `with analyze … audit:all` violations=0 on every matrix program and new test except the `mut fn` str receiver false positive (#1822, the same on the baseline; debug-alloc leak count 0). * Sema: a str range view carries only its base's origins, so `fn tail(s: &str) -> &str: s[1..]` returns a view of the caller's string (D71 §4.8a, §21.1 Rule 6) #1587 gave every str range view a second, frame-local origin (`syms.str_range_view`) because its header lived in a hidden local of the frame, and refused every return of one by name. Since the previous commit a `&str` is its own `{ptr, len}`: there is no header, so the sentinel described nothing. Check_slice now records only the base's origins, exactly as for `[]T`; a returned range view is checked by the same Rule 6 as every other returned view. Tests: - err_1587_str_range_returned.w becomes behav_1810_str_range_returned.w: `tail`, `tail_bound`, a range view through an inner function, in `Option`, and in a tuple, all read the caller's bytes. err_1587_…_via_binding.w is covered there and removed. - behav_1810_str_view_aggregates.w: range views in tuples, structs with a view field, and arrays, returned and printed with Debug. - test/emit_c/str_view_representation.w: the same in the C backend (range return, runtime seams, `const char *` lending, map lookups). - The origin rules still refuse what they must: err_1810_returned_view_of_consumed_param.w (a view of a consumed `str` parameter: "returned view may outlive its origin 's'") and err_1810_returned_view_invalidated.w (mutating a string under a live range view). - err_1810_global_view_across_mutating_callee.w: a view of a global str live across a callee that reassigns the global. §9.1c and §21.1 refuse it; the checker accepts it until #1819, which lands in the layer below this one, and under a `{ptr, len}` view the accepted program reads freed bytes. This test is red on this layer alone and green on the stack; it proves the order. Matrix (build + run, before this stack -> after): returned range view refused (#1587) -> "bc"; range views in a returned tuple / struct Debug refused -> pass; #1819 cell: accepted before and after this layer (refusal expected from #1819). Fixes #1810 Fixes #1587 * FnAbi: the &str view representation is ABI v8 — v7 is the variadic-definition convention that merged first (#1844) Both changes bumped WITH_ABI_VERSION to 7 in parallel; the variadic layer landed on main as v7, so the `&str` {ptr, len} view (its with-abi.md entry already renumbered v8 in the rebase) takes 8. docs/with-abi.sha256 is re-recorded on the stack top. * docs/with-abi.sha256: re-recorded for ABI v8 (the &str view; FnAbi.w and TypeLayout.w as stacked) * build.w: stage1-llvm-link-metadata declares its out/command capture dir — #1840's SDK probe (merged after this layer was written) writes there * test: behav_1810 returns the &str view its cast through &Name yields (§4.5, D75) Under D75 a cast through a reference borrows, so `n as str` with `n: &Name` is a `&str` view; returning it from `-> str` is refused (d95cd0c). The fixture predates D75; it now returns `&str`, keeping what it demonstrates (a view parameter's bytes reach the caller). --------- Co-authored-by: Eric Hartford <[email protected]>
ehartford
added a commit
that referenced
this pull request
Sep 29, 2026
…, inline unsafety, variadic fn pointers, migrator prototypes, c_export conflicts (#1829 #1831 #1830 #1833 #1832 #1848 #1849 #1850) (#1870) * Sema: a fn-pointer type whose parameter is a reference is not ephemeral (#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 * Sema: a function whose call needs unsafe is an unsafe callable as a value (#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 * c_import: an inline function whose body calls a raw C function is an 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 * c_import: an unprototyped call passes promoted arguments with the fixed-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 * Variadic calls pass each `...` argument after the default argument promotions (#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 * The C variadic function-pointer type: extern "C" fn(A, ..., ...) -> R (#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 * PROPOSED spec sentence: the type of a variadic C function as a value (§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. * @[c_export] of a declared symbol: a conflicting definition is refused; 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 * C migrator: a declaration without a prototype becomes the prototype its 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 * test: behav_unit_and_c_void_surface binds a raw c_import function to 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. --------- Co-authored-by: Eric Hartford <[email protected]>
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 💬