Skip to content

Sema/MIR: CK_FN loud on a missing fn (#1859); atomics default SeqCst (#1861); callable call observes, not moves (#1858); closure literal to &U auto-borrowed (#1904); scoped type bindings win (#1967); test_* inferred return (#1862); Ok/Err join builds Result[A,B] (#1856); generic fn as a value (#1857) - #1980

Merged
ehartford merged 11 commits into
fix-tool-tmpfrom
wave-sema
Oct 3, 2026

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Campaign wave (issues since modeled-C). One commit per issue, each with its root-cause line and a red→green fixture (#1859 has none: its only path was #1857, now fixed — a reached CK_FN-missing is a named sema_phase_bug). Every fixture clean under --debug-alloc; drop-audit 254/0; deep-debug-tool-tests and gate green. #1903 is NOT here: it needs Eric's ruling (brief on the issue). Joins the next campaign stack.

Eric Hartford added 11 commits October 2, 2026 22:21
…BUG, never undef (#1859)

No Silent Fallbacks. The CK_FN branch of the codegen constant evaluator
printed `warning: [ck-fn] NOT FOUND` and returned wl_get_undef when a
function constant's symbol was in neither fn_values nor the LLVM module:
an undefined function value that compiled and jumped into garbage at run
time. Sema resolved the name and MirLower emitted the constant, so a
missing function here is a compiler defect; it is now a named
sema_phase_bug carrying the symbol and its link name.

Corpus exposure is the battery's to measure (grep its logs for the BUG
line); this branch's #1857 fix routes the one known reacher, a generic
function used as a callable value, to its specialization first.
…the call's own operand (#1861)

Route: codegen/ABI. `with check --dump-mir` on `a.store(3); print(f"x{a.load()}")`
showed `fetch_add(copy _1, const 3)` with two operands and `load(copy _1)`
with one: Sema accepts the ordering as optional (atomic_method_expected_arg_type),
MirLower's lower_intrinsic_call pushed only the written arguments, and both
backends read the ordering by position from the flat operand table
(CodegenDispatch mir_atomic_fiber_intrinsic_call: mir_intrinsic_arg(body,
args_id, 1|2) reads call_arg_operands[arg_start + idx] with no bound against
call_arg_counts). An omitted ordering therefore read the NEXT call's first
operand — the f-string's literal text, "wrong argument type actual=i32
expected=ptr" — or, for a global initializer that is the last call in its
body, ran off the table: "panic: index out of bounds".

The omitted argument is the program's choice of the default (§14.17.1:
SeqCst), fixed in one place: lower_intrinsic_call pads an Atomic intrinsic's
operands to mir_atomic_intrinsic_arg_count with `Order.SeqCst` typed as the
module's Order enum, so every backend sees the full argument list.

behav_1861_atomic_default_ordering.w: the issue's global initializer
(panicked), top-level fetch_add + f-string (codegen error), the in-fn
store/load (codegen error) and the helper fn shape (panicked) now print
4 / x7 / x3 / 2 4, debug-alloc leak count 0.
…es then drops it (#1858)

Route: drop/ownership. `with run --debug-alloc` (and WITH_ALLOC_NO_REUSE=1)
on behav_callable_alias_field_call.w and on a capturing variant
(`h.f.clone()(21)` with `f` closing over a heap str) is clean: leak count 0,
no double free. `--dump-mir` of `nested` showed the inconsistency the
ownership validator reported:

    call const fn sym210(copy _1.*.inner.run) -> _5    // .clone()
    call move _5(const 21)
    drop(_5) @ scope-exit _5

So the audit was right and the MIR fact was wrong. D63 (§12.4): calling a
callable observes it, and codegen's indirect call does not consume the
pair, which is why the allocator saw one free. The wrong line was
MirLower.lower_callable_expr: a callee that is not a place (a call result)
fell through to `lower_expr`, which hands a call result back as OK_MOVE of
its statement temp. A callable callee is now read as OK_COPY of that temp,
so the one scheduled drop is the only consumer.

audit:all on behav_callable_alias_field_call.w: violations=1 FAILED ->
violations=0 ok; the capturing repro: violations=1 -> 0; both print the
same values under the debug allocator with leak count 0.
…uto-borrowed in MIR (#1904)

Route: MIR validator. `with check` on the issue's facade program:
"invalid MIR before codegen: call argument 2 is a value where the callee
parameter is a reference to it (a missing borrow)" at the closure literal
`d.exec(invoke, n => n + 1, 1)`. A facade callback method is generic over
its userdata `U` and lowers through MirLower.lower_method_call's
GENERIC_CALL path, whose argument loop sends every NK_CLOSURE argument
straight to lower_closure and pushes the closure value, skipping
lower_call_arg — the only place the `&U` auto-reference
(lower_auto_ref_call_arg, can_auto_ref_arg_frozen) is applied. A bound
closure (`let f = n => n + 1; d.exec(invoke, f, 1)`) took lower_call_arg
and was borrowed, which is why only the literal spelling failed.

The closure literal is still lowered in place (codegen resolves it through
this body's CK_CLOSURE constant); when the parameter is a `&U` it accepts
by auto-reference, the literal is materialized into its statement temp and
the argument is a shared borrow of it, as lower_auto_ref_call_arg builds.
A by-value closure argument is unchanged and stays registered for the
machinery-dispatch move.

behav_1904_facade_callback_closure_literal_userdata.w: invalid MIR -> 2,
debug-alloc leak count 0.
…ns over a visible module's type (#1967)

Sema.lookup_named_type_filtered walked the module candidates for a name
and returned the first visible one before consulting the scoped tier
(scoped_type_binding: `Self` and generic type parameters, inserted into
named_types directly with no module candidate). A visible module's
`pub type T` therefore shadowed the `T` of `fn d[T: Default]`. Observed on
the installed compiler with `use issue1967.shadow_t`:

    fn d[T: Default](w: T) -> T: T.default()
    error: unknown method 'default' for type 'T'     (T = the module struct)

and without the import the same body prints 0. (The struct-literal
spelling `T { v: 1 }` showed the same misresolution as "return type
mismatch".)

The candidate walk now first notes whether named_types' entry is one of
the recorded candidates, and returns the scoped binding before any module
candidate; the c_import, bridged-std and builtin tiers keep their order
after it.

behav_1967_generic_param_beats_imported_type.w: compile error -> `0 0 4 15`;
the imported struct stays reachable by its short name outside the generic.
…est_* rule (#1862)

`with analyze r.w 'select:stage=sema,kind=signature,name~test_label'`
shows `test_label` with return=14 (Unit): functions.md fixes it —
"`main`, `@[entry]` and `test_*` functions do not infer: their return
contract is fixed and their tail is statement position" — with no
exception for parameters, so the rule applies and the Unit result is
the program's; the defect is that Sema accepted it as an operand.
SemaCheck.check_binary's OP_CONCAT branch rejects an operand whose kind
is int/float/bool/struct/enum/array/tuple/generic-inst and let TY_VOID
through, so `"x " ++ test_label(0)` passed `check` and died in codegen
("wrong argument type actual=i32 expected=ptr", or "call argument 0 is
Unit" in MIR). Arithmetic had the same hole (`u() + 1`). A call argument
and an annotated binding already reported it.

reject_unit_operand now refuses a Unit operand of `++`, `+ - * / %`,
naming the callee that returns Unit and, for `main`/`test_*`, the D43
rule and the remedy (rename a helper: a `test_` name marks a test).

err_1862_test_fn_unit_result_used.w: `ok` + codegen failure -> the
diagnostic.
`with run` on `let r = if c: Ok(s.len()) else: Err("e" ++ "")` died with
"BUG: `:?` reached MIR for type 0" (MirLower.lower_debug_write_place):
post-Sema type 0. With no outer demand each constructor arm is checked
alone, `Ok(a)` fixes only A and `Err(b)` only B, so both arms are the bare
`Result` enum; SemaCheck.resolve_contextual_join's
merge_contextual_owned_join_types agreed on that bare enum (lhs ==
rhs) and the binding held an uninstantiated type. `Some(x)`/`None` joins
because `Some(x)` alone is already an instance and the
instance-beside-base rule takes it.

resolve_contextual_join now, with no outer demand and a bare-`Result`
join, names `Result[A, B]` from the reaching arms
(infer_result_join_from_variant_arms): A is the join of the `Ok` arms'
payload types, B of the `Err` arms', each by the same owned-join rule;
the arm constructor nodes are retyped to the instance. Any arm that is
not a one-payload Ok/Err call, or arms that fix only one side, leave the
join as before. The payload type comes from check_call, which now
records a variant constructor's checked payload type on the payload node:
check_expr does not self-record every node kind, and a `++` payload read
back as 0 (bisected: `Ok(2) | Err("e")` joined, `Ok(2) | Err("e" ++ "")`
did not).

behav_1856_unannotated_ok_err_join.w: the issue's `if` and `match`
spellings, both arms each -> Ok(2) / Err("e") / Ok(2) / Err("x"),
debug-alloc leak count 0.
…pected function type in Sema (#1857)

`with check` on `apply(identity, 3)` (apply: fn(fn(i32) -> i32, i32)) said
"invalid MIR before codegen: call argument 0 is Unit but the callee
parameter is not"; `let g: fn(i32) -> i32 = identity` said "use rvalue type
is incompatible with assign destination". The wrong line was
SemaCheck.check_ident: a visible generic function name in value position
hit `if self.generic_fn_node_for_symbol(sym) != 0 ...: return 0` — no type,
no instantiation, no diagnostic — and MirLower emitted an untyped CK_FN of
the template, which codegen could not find (the #1859 fallback).

§12: the name is instantiated at the expected callable type. check_ident
now, when an expected `fn(P..) -> R` is in force, runs check_generic_call
with the expected parameter types (the one specialization path a call
takes), records the instance on the node (resolved_call_mono_syms), types
the name as the instance's callable type — built from its concrete
signature, since a specialization's sig carries no function type — and
marks it a callable value (D65) after checking assignability. With no
expected function type the name is refused loudly ("needs an expected
function type to instantiate it"), never typed 0. MirLower's identifier
lowering takes the recorded instance for the CK_FN constant, and codegen's
CK_FN branch emits that specialization on demand
(ensure_concrete_mir_function) before the #1859 BUG.

behav_1857_generic_fn_as_callable_value.w: both spellings -> 3 / 7,
debug-alloc leak count 0.
…er listed twice no longer leaks (#1967)

`fn Box.new[T]` binds `T` twice: the owner's `Box[T]` and its own `[T]`
(check_generic_method_body_concrete pushes owner and function parameters,
tp_syms = [T, T, Self]; lldb at SemaCheck.w check_fn_body_concrete's
install loop: `memory read tp_sym` -> 163 163 42). The frame saved each
binding and then installed the concrete one, so the second save read the
first install (Option[str]), and the restore ran first to last: the
caller's `T` came back, then the second save put Option[str] over it.
After `Box.new(Some("maybe".clone()))` the module's `enum T` was bound to
Option[str] in named_types. #1967 rightly put the scoped tier ahead of the
module candidates, which exposed it: lldb on Sema.scoped_type_binding
(condition named_tid != 0, saw_recorded = 1, saw_named_tid = 0) stops at
`let kids: Vec[Box[T]]` in main with sym=163 named_tid=550, and
da_box_pointee_dropped_by_type failed "unknown method 'Leaf' for type
'Option[str]'".

The three frames that install type-parameter bindings into named_types
(SemaCheck.check_fn_body_concrete, ComptimeEvaluator
.restore_generic_substitutions, MirLower's concrete-specialization
lowering) restore last to first, so the first save, the caller's, wins.

behav_1967_type_param_frame_restores_in_reverse.w: "unknown method 'Leaf'
for type 'Option[str]'" -> `some 1 leaf x`. behav_1967 stays `0 0 4 15`;
da_box_pointee_dropped_by_type: leak count=0.
…ter a statement that ends in its own block

CodegenTraits.generate_default_trait_method_for_impl emits the default
body with its own MIR loop, which tested `wl_get_bb_terminator(dtm_llbb)`
— the MIR block's first LLVM block — before emitting the terminator.
Checked arithmetic ends its statement in `arith.ok`, after terminating that
first block with the overflow branch, so the terminator was skipped and
`fn total(self: &Self) -> i32: self.size() + 1` failed LLVM verification
("Basic Block in function 'P.total' does not have terminator! label
%arith.ok"; main's installed compiler too). The loop now reads the insert
block, as the function, closure and global-initializer emitters do.

Found behind the #1862 regression: with a trait's contract return
published before default bodies are checked, `self.size() + 1` reaches
codegen at all.

behav_trait_default_checked_arith_tail.w: LLVM verification failure ->
`3 6`.
…ked; `self.name() ++ "!"` is not a Unit operand (#1862)

#1945 publishes the return a trait declares onto an impl's unannotated
method "before any body is checked", but from check_bodies, while
collect_declarations had already checked each impl's default bodies
(check_trait_default_method_bodies). There `self.name()` read
Person.name's unpublished signature, Unit, and #1862's
reject_unit_operand rightly refused it (lldb: SemaCheck reject_unit_operand
<- check_binary <- check_trait_default_method_body_for_impl <-
check_trait_default_method_bodies <- collect_declarations). The type was
determined, just not yet published; main's compiler typed the same call
Unit without the check, and `self.size() + 1` there was "arithmetic
operator requires numeric operands".

collect_declarations publishes the contract returns once every signature
exists, before the default bodies; check_bodies no longer does.

behav_1862_trait_default_reads_contract_return.w: "operand of `++` is
Unit" / "operand of `+` is Unit" -> `Ada! 3`. err_1862 still reports
"`test_label` returns Unit"; da_trait_default_tail: leak count=0.
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery GREEN on stack top 0f13a62 (seed-driven, with run tools/battery.w; stack #2007 = #2005 → #1980 → #1989, on main 3044b9c): gate rc=0 wall=1040s, battery-checks rc=0 wall=521s. The prior run of #1980+#1989 was RED on two regressions in #1980's own fixes (a type-parameter frame restored in the wrong order — three sites; trait contract returns published after default bodies needed them) plus a codegen terminator bug they exposed; all fixed in-layer. #2005's per-process captures held this run steady under load. Merged by the coordinator per Eric's standing direction.

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