Skip to content

c_import/migrate/emit-c: no -> Unit on void C fns (#1838); header fns are their importer's (#1882); failed-state facade holds its resource (#1834); emit-c array-returning fn values (#1817); implicit .iter() on any Iter[T] collection (#1837) - #1976

Merged
ehartford merged 7 commits into
mainfrom
wave-cimport
Oct 3, 2026

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Campaign wave (issues since modeled-C). One commit per issue on main 9307016; each red→green with fixtures named in its commit. #1933 needed no change (closed: fixed by bfa0201). Gate green (225.7 s), c-migrator-basic-tests green, emit-c-smoke 23/23, contract-view-tests 13/13, drop-audit 254/0. Will join the campaign stack for one battery.

Eric Hartford added 7 commits October 2, 2026 21:17
…1838)

An absent return type is Unit, so the compiler already knows what `-> Unit`
says, and unit-return-review flags every re-migrated signature that keeps
it (the D75 re-migration of TommyDS check.c and c-algorithms
test-hash-table.c had to be recorded in docs/unit-return-reviews.tsv as
migrator output). docs/spec/guide/with-migration-guide.md already states
the rule: "`void` -> omit return type".

One rule, read by every signature renderer: CImport.ci_ret_suffix(ret)
renders "" for Unit and " -> T" otherwise. Its readers: the extern
declaration (CImport extern render, CiMigrate's migrate-mode extern), the
migrated definition (CiMigrate ret_suffix), the static-inline body, the
buf_in/buf_out wrapper and its raw extern, the struct method and
associated-fn sugar, the translated macro fn, and CiPrint's IR printer
(fn and extern). The empty-macro fn and both with_free preamble lines drop
their hard-coded `-> Unit`. Fn-pointer TYPES keep `-> Unit`: that is type
syntax, not a signature.

Evidence: `with-stage1 migrate` of
  void stop(void); void noop(void) {}
  static inline void tick(int *p) { *p += 1; } int bump(int *p) {...}
printed `extern fn stop() -> Unit`, `pub fn noop() -> Unit:`,
`unsafe fn tick(__param_p: *mut c_int) -> Unit:` before; after: `extern fn
stop()`, `pub fn noop():`, `unsafe fn tick(__param_p: *mut c_int):`, zero
`-> Unit` in the file, and the output checks. The case is pinned as
bs_check_migrate_void_omits_unit in c-migrator-basic-tests.

No checked-in expectation spells a function's `-> Unit` (test/contract's are
fn-pointer types). The corpora (pcre2, zlib, tommyds, c_algorithms) still
carry the old spelling until their next promote, which removes it; the two
docs/unit-return-reviews.tsv rows citing #1838 go with that promote.
…l name (#1882)

§18.2 / D70 (every import is a namespace): a function a c_import header
DEFINES (a `static inline` body, a rendered wrapper) took the flat name. The
.wo bundles' shared defs reach every compilation over the prelude edge, so
a header defining `u128_mul_would_overflow(int)` captured
lib/std/re/defs.w's own calls:

  error: function 'u128_mul_would_overflow' expects 1 argument(s), found 2
   --> lib/std/re/defs.w:235:8

With the bundle's exact signature Sema saw no error and two bodies shared
one symbol: "invalid MIR before codegen: body index map mismatch for fn
symbol 961". A user module defining `fn twice` beside a header's `twice`
failed the same way (symbol 13431).

Fix, at the frontend merge where #1350/#1362/#1703 already give colliding
declarations their module-qualified identity:
- Frontend.displace_colliding_c_import_fns (src/compiler/Frontend.w, run
  after displace_c_import_wrappers): non-import declarations take their
  short names first, whatever the merge order; a c_import-defined fn whose
  name another owner holds is displaced to `name$in$<importer>` (each
  c_import an owner of its own, #1753). A header's extern stays the one
  global C symbol (D29); methods and interface fns are untouched.
- Sema.resolve_displaced_fn_ident (src/Sema.w): a displaced c_import
  definition carries its importer's path but is the importer's IMPORT
  (tier 3), not its own declaration (tier 2): the module's own fn of that
  name wins; otherwise the importer's calls bind to its import's
  definition. `hdr.twice` reaches the header's through its namespace
  (namespace_c_import_member already walks the displaced chain).

The #1877 workaround goes with it: the import's overflow helpers had a
separate `__c_import_*` spelling only so they could not collide with the
bundles' `__with_builtin_*` / `u128_mul_would_overflow`. They now carry the
migrator's spelling (CiMigrate.ci_overflow_helper_name,
ci_u128_mul_helper_name) and are displaced like any import definition.

Evidence (with-stage1, before -> after):
  behav_1882_c_import_fn_scoped_to_importer   arity error in defs.w -> 2
  behav_1882_c_import_fn_same_signature       body index map mismatch -> true / false
  behav_1882_c_import_fn_beside_own_fn        body index map mismatch -> 10 / 11
  behav_1882_c_import_overflow_helpers_beside_bundle (new spelling, i32 and
  u128 helpers beside the bundle's)           -> 42 -1 1 0
Unchanged and green: behav_c_import_builtin_overflow, behav_d70_import_as,
behav_1830/1820/1831 c_import fixtures; `with-stage1 check src/main.w` ok.
…1834)

`with analyze <prog> audit:all` failed on every program using the SQLite
facade: "the rendered call of 'sqlite3_errmsg' invalidates views of its
parameter 0, which holds no modeled resource" (#1674, §16.2b.14). The
rendered call is `FailedDatabase.errmsg`, the `valid on failed` rendering;
`facade_type_holds_resource` (SemaFacade.w) knew only the resource's own
name, so the `Failed<R>` receiver read as holding nothing.

Decided by the ruling: spec §16.2b.4 (projection of D51 §18) — "A resource
owned by an error admits raw access only, unless the facade marks an
operation as valid on the failure state; it is carried as a distinct type
(`FailedDatabase`)" — and Amendment 1 (Eric, 2026-09-27): the operation "is
presented on the failed-state type as well". The failed state is the
resource itself under another name; the effect on the receiver is correct
(§38: no `preserves`, so invalidate), and the holds predicate — Sema's
fact, which the audit reads (D65) — now counts `Failed<R>`.

Lines: src/SemaFacade.w facade_type_holds_resource — after the
facade_resource_index check, `facade_failed_state_resource(name) >= 0`
also holds.

contract-view-tests runs audit:all over test/contract ok_ fixtures only, so
the battery never saw this (the audit stayed silent on the behavior
fixtures): test/contract/ok_valid_on_failed.w is a SQLite-shaped `valid on
failed` facade whose main calls `failed.errmsg()`; red under the pre-fix
stage1, green now, snapshot in ok_valid_on_failed.expected.

Evidence: pre-fix stage1 `analyze … audit:all` reported violations=1 on
behav_sqlite_facade_exec_no_callback.w, behav_sqlite_facade_failed_open_errmsg.w,
behav_sqlite_facade_end_to_end.w and the new fixture; fixed stage1 reports
violations=0 ok on all four; `:contract-view-tests` 13 fixtures agreed;
`:dev` green.
…s the destination out-pointer after the context (#1817)

C returns no arrays. #1775 gave a named function returning [N]T a leading
`void* __with_ret`; every fn VALUE of such a type was refused instead. One
rule now covers every shape, read from one place in src/CCodegen.w:

- array_out_param(ret_tid, named, after) (new, beside returns_array):
  renders the out-pointer parameter, after the context for fat shapes,
  leading for a named function, empty for any other return.
- return_decl(ret_tid, declarator) (new): `void` for an array return,
  pointer-to-array declarator, or plain type; replaces four copies of the
  type_is_pointer_to_array/c_type branch.
- emit_fn_type_defs: the fat TY_FN typedef is
  `void (*fn_ptr)(void* ctx, void* __with_ret, params)`; the refusal is
  gone. A TY_EXTERN_FN (C function pointer) returning an array stays a
  loud refusal: C has no such type and a foreign pointer carries no
  out-pointer convention.
- emit_fat_thunk_defs: the thunk is
  `static void thunk(void* __with_ctx, void* __with_ret, params)
  { (void)__with_ctx; target(__with_ret, args); }`; the refusal is gone.
- collect closures: the refusal is gone; closure_fn_sig takes
  `void* __with_ret` after `__with_ctx`. TK_RETURN's memcpy already
  covers the closure (sig_idx < 0 falls to local_type_ids[0]).
- emit_term TK_CALL: the leading arguments are built in signature order:
  ctx, then dest, then args for a fat call, and dest, then args for a
  direct one. Before, the array branch prepended dest ahead of the ctx
  that had already been prepended.
- emit_fn_decl: the named-function out-pointer goes through
  array_out_param/return_decl.

Evidence (test/emit_c/fn_value_array_return.w: the issue's `let f = arr`,
a closure `() => [1u8, 2u8]`, and `call_it(arr)` calling a
`fn() -> [u16; 2]` parameter indirectly):
- red, unmodified stage1: `--emit-c` rc=1, "a closure returning an array
  has no C lowering"; the issue repro rc=1, "a fn value whose type returns
  an array has no C lowering".
- green, fixed stage1: emit rc=0, cc rc=0, run prints 9 / 2 / 7; issue
  repro prints 9. Emitted: `typedef struct { void (*fn_ptr)(void*, void*);
  void* ctx; }`, the thunk forwards `arr__N(__with_ret)`, and the indirect
  call is `_1.fn_ptr(_1.ctx, _2)`.
- `src/main build :emit-c-smoke`: EMIT-C SMOKE OK (23 cases).
- An `extern "C" fn() -> [u16; 2]` value: emit-c refuses with the new
  message, rc=1.
…r[T] (#1837)

§13.5: "When it does not implement `Iter[T]` but has an `.iter()` method
that returns an `Iter[T]`, the compiler inserts `.iter()` automatically."

Only Vec/HashMap/BTreeMap had it. `for x in s` over a SortedVec (or any
user collection) got the interim #1837 diagnostic; before #1828 it failed
in MIR lowering.

Sema decides the callee (D65):
- SemaCheck.resolve_implicit_iter_for (15350): the iterable, or the T of
  a &T, has no next(), is no Gen[T] and no built-in traversal (tried
  first, unchanged), and has an iter() taking only self whose result has
  a next() returning Option[T]. The call is resolved as the spelled one:
  a generic impl's specialization through check_generic_method_call
  (demand_generic_implicit_iter, 15429, saves/restores the key node's
  call tables like demand_generic_gen_each); a `mut fn iter()` needs a
  mutable place; a `move fn iter()` consumes the collection; the call's
  global effects are noted. Recorded under the loop key in for_iter_fn_syms,
  for_iter_sigs, for_iter_monos and for_iter_types (Sema.w), plus
  for_iter_next_fns for a concrete iterator's next().
- check_for (15054) and check_comprehension_clause_iterable (15215) call
  it after the existing paths fail. The generic next() is demanded on the
  iterator type, and yields_views asks whether the inserted iter() is
  @[iter_of_self] (implicit_iter_yields_views, 15459).
- report_not_iterable (15232) takes the loop key. The "not implemented
  yet (#1837)" arm is gone. When iter() exists but its result is no
  Iter[T], it now says so and names the result type.

MIR lowers only what Sema recorded:
- MirLower.lower_for_implicit_iter_call (8175): the recorded call.
  A move-self receiver is moved and consumed; any other receiver goes
  through lower_generic_receiver_arg. The recorded contract is used
  (GENERIC_CALL for a specialization). The iterator lands in a statement
  temp that drops after the loop.
- lower_for (8080) and lower_comprehension_generic_iter (8960) step that
  iterator with the existing next() protocol, using the recorded
  specialization or for_iter_next_fns.

Vec/HashMap/BTreeMap/Receiver/range/slice paths are untouched.

Evidence (stage1 = out/bootstrap/bin/with-stage1):
- red before the fix, all three fixtures:
  error: `for` over `SortedVec[i32]` needs the implicit `.iter()` of
  §13.5, which is not implemented yet for this type (#1837); write `.iter()`
  (likewise `Deck`, `&Deck`, `Bag[Tok]`, `&Bag[Tok]`)
- green after: behav_1837_implicit_iter_sorted_vec (SortedVec),
  _user (non-generic Deck/DeckIter, &Deck, a comprehension clause),
  _generic_bag (Bag[T]/BagIter[T], &Bag, Drop-class Tok elements bind as
  views: each dropped exactly once with the bag). Output matches the
  explicit `.iter()` spelling byte for byte. `with test` ok on all three.
- run --debug-alloc on _generic_bag: leak count=0
- 81/81 existing for/iter/comprehension behavior fixtures pass on stage1
- with-stage1 check src/main.w: ok
- `mut fn iter()` on a let binding behaves as the spelled `s.iter()` does
  (both accepted); a non-Iter iter() result is refused with the new message
- src/main build (full), :deep-debug-tool-tests --no-deps: green
- :drop-audit: 254 cells, 0 non-PASS, 0 regressions vs baseline
…fers Unit; a discarded pure read is no statement (#1838)

515721c dropped `-> Unit` from every C `void` definition, but an omitted
return type is the body tail's type (D43). `static void callback(void *p)
{ (void)p; }` rendered `unsafe fn callback(__param_p: *mut c_void):
__param_p`, whose type became `fn(*mut c_void) -> *mut c_void`, and
`return &callback` from a `void (*)(void *)` function was a "return type
mismatch" (c-migrator-core-tests check-noop-pointer-casts). Worse, the
same rule silently gave `void d(void) { f(); }` (int f) the type
`fn() -> c_int`: no error unless something took it as a fn value.

Two fixes, each at its owner:

1. The return clause of a translated definition is decided from the
   rendered body. ci_trans_stmt_ir now reports whether the statement it
   printed infers Unit as a body tail (CiPrint ci_stmt_ir_tail_is_unit,
   which follows the printer's layout: return/break/continue, a
   declaration, a loop, an `if` with no else, a top-level non-memcpy
   assignment, a CIS_EXPR flagged CI_STMT_EXPR_VOID because its C
   expression is `void`, and blocks/arms recursively). The body
   translator hands that out (ci_take_body_tail_unit) and both definition
   renderers (CiMigrate, c_import's static inline) use ci_def_ret_suffix,
   which keeps `-> Unit` when the tail is not shown to be Unit. Keeping it
   is never wrong (the migration guide: "omit return type (or `-> Unit`)").

2. C's `(void)x` means "x is unused". A discarded read of a variable,
   function, enumerator or literal now lowers to no statement; a discarded
   field or element read lowers to its operands' effects (`(void)f()->x`
   still calls f); a volatile read is kept; a discarded conversion of any
   type is its operand's effects. A discarded expression with effects
   (`(void)f()`) keeps them as before (#1911/#1933). The `{ (void)p; }`
   body is now `return` (d55a6aa). merge_both_or_fail_ir no longer reads
   two empty parts as a failure (`(void)(a + b)` was refused once both
   operands became empty).

Test: c-migrator-basic-tests bs_check_migrate_void_tail_is_unit migrates
`(void)p;` alone, before and after an assignment, `(void)(a + b); (void)a;`,
`(void)f();`, a bare `f();` tail and `return &fn` of each callback; it
asserts the bodies, that the pure casts left no `__param_*` statement, that
the value tails keep `-> Unit`, and that the file checks. It failed on the
515721c release binary ("missing expected output for void_tail_is_unit:
unsafe fn only_cast(...):") and passes on this tree, as do the whole
c-migrator-basic-tests and c-migrator-core-tests suites; every standalone
.w those suites generate checks (45 of 48; the other 3 are modules of the
cross-module project the suite checks as a project).
…stop():` (#1838)

The test asserted `fn stop() -> Unit`, the spelling before #1838; a void
function whose tail infers Unit (here the assignment `calls = calls + 1`)
is now rendered without it, as docs/spec/guide/with-migration-guide.md
says ("`void` -> omit return type"). The assertion follows the spelling
and a new one pins that the old one is gone; `not fn stop(...)` still
pins that a K&R definition is not variadic.

Test: passes on stage1 (the migrated file has `pub fn stop():`); it was
the battery red on the previous tip.
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery GREEN on stack top 029574d (seed-driven, with run tools/battery.w; stack #1979 = #1976 → #1978, on main ac522dc): gate rc=0 wall=843s, battery-checks rc=0 wall=748s — fixpoint, drop and move audits, every corpus. The prior run was RED on three reds from these layers: #1838 dropped -> Unit where the rendered body's tail inferred a value (a silent meaning change, two shapes found) — now kept unless the tail provably infers Unit, and a discarded pure read lowers to nothing; plus two tests tracking this stack's own spelling/signature changes. Merged by the coordinator per Eric's standing direction.

@ehartford
ehartford marked this pull request as ready for review October 3, 2026 04:45
@ehartford
ehartford merged commit 7b56d3f into main Oct 3, 2026
@ehartford
ehartford deleted the wave-cimport branch October 3, 2026 04:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant