Skip to content

print[T: Display](v: &T): any Display value prints; a mixed-arm match's fix-it is the f-string (§18.2, D55) - #1325

Merged
ehartford merged 7 commits into
mainfrom
print-display
Sep 22, 2026
Merged

ehartford merged 7 commits into
mainfrom
print-display

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Implements D55 ruling 6 (§18.2, spec words in #1277) with the reference spelled as v: &T (the coordinator is putting that one-word correction to Eric on #1277: §3.8 says an observing function takes &T, and D52 forbids moving out of a global, which the literal v: T did for every print(TRACE) in the test corpus).

The print/Display change (last commit)

  • print[T: Display](v: &T) and eprint are plain generics that observe. The str instance is byte-identical MIR to today's print(s: &str) (with_println_str(copy _1), no temp, no drop); every other instance goes through Display.to_str.
  • The primitives implement Display (rendering as the f-string does); &T: Display/Debug when T is (formatting observes, as an f-string formats a view's pointee).
  • The arms of a match/if argument join under the ordinary join rule; when nothing joins, the diagnostic names the arm and the fix-it is the f-string, never a boxing join:
    error: match arms have types str and i32; no Display type joins them
     --> examples/fizzbuzz.w:7:23
    7 |             _      => i
      |                       ^
      = help: format the arm as an f-string, print(f"{x}") style: f"{i}"
    
  • The generic arg-count diagnostic names the function like the non-generic path (err_output_multiple_args kept its text).

Five compiler bugs the generic exposed, each its own commit with a repro test

  1. MirLower: a specialization recheck that runs a comptime eval (comptime if T.name() == ..) wrote back a Sema with emptied eager caches; the refresh keyed on the type count never fired (is_copy_frozen miss). Refresh by cache extent.
  2. ComptimeEval: a bound type parameter T was shadowed by a module global named T (var T = "" is the drop-order test idiom).
  3. derive(Display): the generated to_str was move self against a trait that declares &Self; a T: Display view consumed and the specialization's ABI disagreed with its call.
  4. MirLower: a variant constructor rvalue (show(Color.Red) into &Color) was routed to the field-place path and failed to lower.
  5. Frontend: the pre-sema and the comptime-transform Sema lacked the tier flags, so a --no-std program's async fn was judged against the std tier (err_no_std_async_fn_leak was the repro).

Verification (bootstrap stage1 from the branch, out/bootstrap/bin/with-stage1)

  • New tests: behav_print_display (42, 3.5, true, derived enum, "lit", owned str twice, &str, a global, a Display struct, &n, for v in xs, shared-i32 match, if, eprint), err_print_mixed_match_arms (fizzbuzz shape, asserts the fix-it text), behav_comptime_if_type_name_in_generic, behav_comptime_type_param_shadows_global, behav_autoref_variant_constructor_arg.
  • Per-file sweeps of test/behavior, compile_errors, spec, debug_alloc, codegen, d_acceptance: every failure (215 + 51 files) also fails on a baseline stage1 built from the untouched tree (bootstrap-lane differences); none is new.
  • examples/: main's rewritten fizzbuzz runs; the only sweep difference vs baseline (json-parser is_digit visibility) fails on the baseline stage1 too and passes on the installed compiler.
  • :dev wall: 188.4 s before, 193.4 s after on the rebased tree (same laptop, mid-session noise; stage1 162.7 s → ~175 s across runs while sweeps were also running).
  • No :fixpoint/:test/battery run here — the coordinator batches it.

@ehartford

Copy link
Copy Markdown
Contributor Author

Interleaved :dev timing on an idle box (fresh origin/main worktree, then this branch with out/bootstrap removed, back to back): main wall 190.0 s / stage1 163.7 s; branch wall 179.7 s / stage1 178.5 s. Across the eight branch builds this session stage1 ranged 137–221 s on the same tree, so the 15 s stage1 delta is inside the laptop noise; the str print instance is byte-identical MIR to before.

Eric Hartford added 7 commits September 22, 2026 14:57
…nt, not type count

A `comptime if T.name() == ..` in a generic body is evaluated during the
recheck that precedes MIR lowering. That evaluation writes back a Sema
whose eager caches prepare_comptime_eval_copy emptied, and the refresh
keyed on the type count never fired, so the frozen twins phase-bugged
("is_copy_frozen miss — type not preregistered: i32"). The copy-ness
table covers every type or it is refreshed.
…ame name

`T.name()` inside `fn f[T]` named the caller's `var T` global and the
`comptime if` was reported as not comptime-evaluable.
`Display.to_str(self: &Self)` observes; the derived enum method was
`move self`, so a `T: Display` bound reached through a view consumed the
value and the specialization's ABI disagreed with its call ("wrong
argument type actual=ptr expected=Color"). The method matches `*self`.
`show(Color.Red)` with `fn show(c: &Color)` routed the rvalue to the
field-place path and failed to lower; it is materialized like a struct
literal.
… flags

Both collect and diagnose declarations before the module's checker runs;
without no_std/alloc/runtime_available a `--no-std` program's `async fn`
was judged against the std tier ("requires the fiber runtime" instead of
"requires std/fiber runtime"). Exposed by the first `comptime if` in the
prelude.
…MIR body (#681)

CodegenUnits packs every MIR body, concrete specializations included, into
one unit, but ensure_concrete_mir_function generated a specialization's
LLVM body only on demand, in whichever unit reached a call to it.
unit_demote_foreign_definitions then deleted the body in every non-owner
unit >= 1. A specialization whose callers all sat in other units was
therefore defined by nobody: its owner never called it, the caller
demoted it.

Evidence (WITH_CODEGEN_UNITS=8, the new behavior test, stage1 without
this change; unit objects captured under lldb at
compilation_cleanup_build_products, since WITH_KEEP_UNIT_OBJECTS keeps
them only on a green link):

  t.o       T _print__sema__140:759:141=3
  t.o.u4.o  T _eprint__sema__144:778:141=16
  t.o.u7.o  T ___wcu$431$caller
            U _eprint__sema__144:778:141=16
            U _print__sema__140:759:141=16   <- defined by no unit

The stage-2 link of the compiler failed the same way once print became
generic (ld64.lld: undefined symbol: _eprint__sema__144:778:141=16). The
pinned seed has the defect too: a plain user `fn show[T](v: &T)` called
from one function fails to link under eight units.

Fix: ensure_concrete_mir_function only declares a specialization its unit
does not own, and gen_owned_specializations defines, in the owner, every
specialization packed there that no call has generated yet. After:

  t.o       T _eprint__sema__144:778:141=16
            T _print__sema__140:759:141=16
            T _show__sema__775:7687:141=16
  t.o.u4.o  T ___wcu$182$caller
            U _eprint__sema__144:778:141=16
            U _print__sema__140:759:141=16
            U _show__sema__775:7687:141=16
…'s fix-it is the f-string (§18.2, D55)

`print` and `eprint` are plain generics that observe (§3.8): the `str`
instance hands the bytes to the runtime exactly as `print(&str)` did
(byte-identical MIR), every other instance formats through
`Display.to_str`. The primitives implement Display (rendering as the
f-string does), and a `&T` is Display/Debug when `T` is — formatting
observes, as an f-string formats a view's pointee.

The arms of a `match`/`if` argument join under the ordinary rule where
the checker already joins arms; when they share no Display type the
diagnostic names the arm and the fix-it is the f-string:

    match arms have types str and i32; no Display type joins them
    = help: format the arm as an f-string, print(f"{x}") style: f"{i}"

never an implicit boxing join. The generic arg-count diagnostic names the
function like the non-generic one.
@ehartford
ehartford merged commit 00bab6e into main Sep 22, 2026
ehartford added a commit that referenced this pull request Sep 22, 2026
…kes &T (§3.8); v: T consumed owned strings and refused globals (D52) (#1326)

Implementing D55 ruling 6 (PR #1325) showed the literal v: T consumes its
argument: print(s); print(s) on an owned str is a use-after-move and
print(GLOBAL) is a move out of a global. §3.8 says an observing function
takes &T; the &str instance is byte-identical to the previous print. One
word, proposed on #1277 and implemented in #1325; Eric's blessing is the
merge.

Co-authored-by: Eric Hartford <[email protected]>
@ehartford

Copy link
Copy Markdown
Contributor Author

Fixes for the battery's three regressions (de356de): the arity wording now satisfies both main contracts (no expectation edited); err_no_std_alloc_async_leak / err_no_std_await_leak return to their original tier-correct expectation from afdcb48 ('Close no_std tier leaks') — 2abfa18 had rewritten them to the leaked wording; the spec's no_std table requires std for async fn and --alloc stays in the no_std tier. Battery re-running.

@ehartford

Copy link
Copy Markdown
Contributor Author

Battery on de356de4 (seed-driven): build, :fixpoint rc=0; :test red only in behav_distinct_compat — main's known red (the D43 narrowing PR fixes it). All three earlier regressions pass. Marking ready.

ehartford pushed a commit that referenced this pull request Sep 22, 2026
…nstead of wiping them — `print(e.key)` erased the `for` binding's borrow of `xs` (#1317)

Root cause: check_fn_body_with_sig_at (src/SemaCheck.w) opened every body
with `while self.borrow_kinds.len() > 0: self.remove_borrow_at(...)`,
treating the borrow table as free at body entry. It is not: the first call
of a generic function reaches it mid-body, through check_call ->
check_generic_call -> check_fn_body_concrete -> check_fn_body_with_sig_at,
while the caller's rows are live. check_fn_body_concrete saves the
caller's scope-stack family but not the borrow columns, so the caller's
borrows were discarded. Since #1325 made print generic
(print[T: Display](v: &T)), the first `print(x)` of each T erased every
live view of the calling body.

Evidence (lldb, with-stage2 check err_for_binding_iterable_clear.w,
function breakpoints): register_for_binding_borrow -> check_borrow_create_direct
appended the row; the next remove_borrow_at hit came from
check_fn_body_with_sig_at <- check_fn_body_concrete <- check_generic_call
<- check_call (the body's `print(e.key)`); check_mutation_against_views
then ran on an empty table, so for_view_binding_depth was never reached.
The same wipe accepted `let e = xs.get(0); print(e.key); xs.push(..);
print(e.key)`, which the installed v0.15.2.1 (before print was generic)
rejects.

Fix: set the caller's borrow columns and loop view bindings aside at body
entry and restore them after the body's pop_scope; the body's own rows
die with it. borrow_path_data is append-only, so saved path indices stay
valid.

Fixtures: err_for_binding_push_body_tail (push as the body tail, no later
use of `e`), err_for_binding_mutate_then_statement (clear, then a
non-exiting statement), err_view_live_across_generic_instantiation (a
let view across the first call of a local generic fn). All three, and
err_for_binding_iterable_clear, checked ok before this change.
ehartford added a commit that referenced this pull request Sep 22, 2026
…ead; no_std --alloc async fixtures pin the tier message (#1340)

* Sema: the generic arity diagnostic keeps its "wrong argument count" lead

59b27fc reworded the generic check to name the function (`print("x", "y")`
reaches it now that print is generic, and err_output_multiple_args pins
"expects 1 argument(s), found 2"), dropping the wording
err_unit_elision_unconstrained_generic pins ("wrong argument count"). Both
fixtures are main's contracts; the message now carries both:

    wrong argument count: function 'id' expects 1 argument(s), found 0

* test: the --no-std --alloc async fixtures pin the no_std tier message again

afdcb48 ("Close no_std tier leaks") authored both fixtures with
"requires std/fiber runtime": require_async_runtime emits that whenever
Sema.no_std is set, and --alloc does not leave the no_std tier (spec
no_std table: `async fn`, `.await` require std). 2abfa18 rewrote them to
"requires the fiber runtime" to match what the compiler then printed, which
was the tier leak 14cc033 closes: under --alloc the prelude's comptime
transform ran a pre-sema with no_std unset, and that Sema's std-tier
wording reached the user before the module checker (no_std = 1) ran. With
the pre-sema and transform Sema carrying the tier flags, all three no_std
async fixtures read the one tier-correct message, as originally authored.

---------

Co-authored-by: Eric Hartford <[email protected]>
ehartford pushed a commit that referenced this pull request Sep 22, 2026
…nstead of wiping them — `print(e.key)` erased the `for` binding's borrow of `xs` (#1317)

Root cause: check_fn_body_with_sig_at (src/SemaCheck.w) opened every body
with `while self.borrow_kinds.len() > 0: self.remove_borrow_at(...)`,
treating the borrow table as free at body entry. It is not: the first call
of a generic function reaches it mid-body, through check_call ->
check_generic_call -> check_fn_body_concrete -> check_fn_body_with_sig_at,
while the caller's rows are live. check_fn_body_concrete saves the
caller's scope-stack family but not the borrow columns, so the caller's
borrows were discarded. Since #1325 made print generic
(print[T: Display](v: &T)), the first `print(x)` of each T erased every
live view of the calling body.

Evidence (lldb, with-stage2 check err_for_binding_iterable_clear.w,
function breakpoints): register_for_binding_borrow -> check_borrow_create_direct
appended the row; the next remove_borrow_at hit came from
check_fn_body_with_sig_at <- check_fn_body_concrete <- check_generic_call
<- check_call (the body's `print(e.key)`); check_mutation_against_views
then ran on an empty table, so for_view_binding_depth was never reached.
The same wipe accepted `let e = xs.get(0); print(e.key); xs.push(..);
print(e.key)`, which the installed v0.15.2.1 (before print was generic)
rejects.

Fix: set the caller's borrow columns and loop view bindings aside at body
entry and restore them after the body's pop_scope; the body's own rows
die with it. borrow_path_data is append-only, so saved path indices stay
valid.

Fixtures: err_for_binding_push_body_tail (push as the body tail, no later
use of `e`), err_for_binding_mutate_then_statement (clear, then a
non-exiting statement), err_view_live_across_generic_instantiation (a
let view across the first call of a local generic fn). All three, and
err_for_binding_iterable_clear, checked ok before this change.
ehartford added a commit that referenced this pull request Sep 22, 2026
#1333)

* Sema: a `for` binding borrows the iterated place for the whole loop — `for e in xs: xs.push(..)` is rejected as the live-view mutation it is (#1317)

Fixes #1317.

`for e in xs` is `xs.iter()` (§13, D44) and `e` is a view into `xs`
(§3.4), but check_for registered no borrow for the binding, so
`xs.push(..)`, `xs.clear()`, `xs.remove(0)` and `m.insert(..)` inside the
body compiled and the next iteration read the reallocated or shifted
buffer through `e` — the same use-after-free §21.1 rule 1 already
rejects for `let e = xs.get(0); xs.push(..); use e`.

register_for_binding_borrow records a SHARED borrow keyed on the field
path of the iterated place (for_iterated_place: the place itself, or the
receiver of a spelled `@[iter_of_self]` call such as `xs.iter()` /
`m.keys()`), with the binding as its ref, through the same
check_borrow_create_direct / check_mutation_against_views mechanism the
let-bound views use. Keying on the path, not the root, keeps
`for e in self.items: self.count += 1` accepted (disjoint paths) while
`self.items.push(..)` conflicts. A pattern binding (`for (k, v) in m`)
registers the same borrow for each of its ephemeral bindings.

The borrow never expires at a lexical last use of the binding: the loop
reads the place again on its next iteration, so check_mutation_against_views
keeps a borrow whose ref is in for_view_binding_syms (a stack check_for
maintains) and adds a note saying so. It expires with the loop's scope.

record_pattern_view_bindings now walks pattern_binding_syms, the one
pattern-binding collector both paths use, and for_iterable_yields_views'
method tail is factored into iter_of_self_call_receiver.

Rejected (new fixtures): push, clear, remove on the iterated Vec, push on
`self.items`, insert on the iterated map. Accepted
(behav_for_binding_disjoint_mutation): `self.count += e.n`, pushing the
element's clone onto another Vec, `for e in xs.iter()`, mutating `xs`
after the loop. `with check src/main.w`, tools/*.w and examples/ compile
under the rule; a scan of src/, lib/, rt/, build/, tools/, examples/ and
test/ for a `for` whose body mutates its own iterable found no site. A
Copy-element loop (`for i in idxs: idxs.push(..)`) binds no view and is
not covered here.

* Sema: a mutation that ends the loop does not conflict with the loop binding's view; index loops stay accepted (#1317)

The loop-binding borrow never expires at a lexical last use, because the
next iteration reads the iterated place again. When the mutation's next
statement is `return`, or an unlabeled `break` of the very `for` that
binds the view (loop_depth equals the body's depth recorded in
for_view_binding_depths), no iteration follows: find-then-grow and
find-then-clear are sound and now check, as Rust's NLL accepts them.
The borrow is kept, not removed, since other paths through the body may
still loop. `continue`, a labeled break, and a break of an inner loop
still conflict (new fixtures).

behav_for_index_loop_mutates_collection pins what migrated C does: a
range over `xs.len()` pushing onto `xs`, a bounded `while` over an index,
and reading `xs[j]` in the iteration that pushes (as the argument, through
a Copy-annotated binding, and through a view dead before the push). The
binding is an i32, not a view, so the rule does not reach them. An
unannotated `let v = zs[j]` used as the pushed argument is rejected by the
existing D27 let-view rule (seed and stage1 alike), not by this change.

* Sema: a generic callee's body check sets the caller's borrows aside instead of wiping them — `print(e.key)` erased the `for` binding's borrow of `xs` (#1317)

Root cause: check_fn_body_with_sig_at (src/SemaCheck.w) opened every body
with `while self.borrow_kinds.len() > 0: self.remove_borrow_at(...)`,
treating the borrow table as free at body entry. It is not: the first call
of a generic function reaches it mid-body, through check_call ->
check_generic_call -> check_fn_body_concrete -> check_fn_body_with_sig_at,
while the caller's rows are live. check_fn_body_concrete saves the
caller's scope-stack family but not the borrow columns, so the caller's
borrows were discarded. Since #1325 made print generic
(print[T: Display](v: &T)), the first `print(x)` of each T erased every
live view of the calling body.

Evidence (lldb, with-stage2 check err_for_binding_iterable_clear.w,
function breakpoints): register_for_binding_borrow -> check_borrow_create_direct
appended the row; the next remove_borrow_at hit came from
check_fn_body_with_sig_at <- check_fn_body_concrete <- check_generic_call
<- check_call (the body's `print(e.key)`); check_mutation_against_views
then ran on an empty table, so for_view_binding_depth was never reached.
The same wipe accepted `let e = xs.get(0); print(e.key); xs.push(..);
print(e.key)`, which the installed v0.15.2.1 (before print was generic)
rejects.

Fix: set the caller's borrow columns and loop view bindings aside at body
entry and restore them after the body's pop_scope; the body's own rows
die with it. borrow_path_data is append-only, so saved path indices stay
valid.

Fixtures: err_for_binding_push_body_tail (push as the body tail, no later
use of `e`), err_for_binding_mutate_then_statement (clear, then a
non-exiting statement), err_view_live_across_generic_instantiation (a
let view across the first call of a local generic fn). All three, and
err_for_binding_iterable_clear, checked ok before this change.

---------

Co-authored-by: Eric Hartford <[email protected]>
ehartford added a commit that referenced this pull request Sep 23, 2026
…s cross-unit specialization ownership); linux pinned to v0.15.2.0 (#1359) (#1401)

The darwin seed is a nightly-channel prerelease cut from main 8c859a7:
build, :fixpoint, :test, :test-green, :last-green green under the old
seed; release UAT functional targets all green; :user-programs-safe red
(#1376), published past by maintainer decision. The asset is the verified
out/release/bin/with (sha256 7c3ed983...), unstripped because
:package-darwin-aarch64 depends on :release-uat.

v0.15.2.0 predates #1325, so a seed-built stage1 can leave a cross-unit
receiver specialization with no owning unit (_Vec.clone__receiver__94_3
undefined in batch B, 2026-09-22). #1360 is the first change that needs
this seed and lands after this bump.

Co-authored-by: Eric Hartford <[email protected]>
ehartford pushed a commit that referenced this pull request Sep 23, 2026
… codegen units pin the receiver-specialization case (#681, #1359)

The copy loops in mir_drop_state_blocks_new and MirDropStateBlocks.input
worked around a stage1 link failure: `undefined symbol:
_Vec.clone__receiver__94_3`. The source compiler does not have this
defect. The pinned seed (v0.15.2.0) does, because it predates #1325's
gen_owned_specializations. At v0.15.2.0, src/Codegen.w:6021
(ensure_concrete_mir_function) generates a specialization's body in
whichever unit reaches a call to it, and unit_demote_foreign_definitions
(:1356) deletes the body in every unit that doesn't own it. An instance
whose callers all sit outside its owning unit is then defined by no unit.

Evidence: the new behavior test under the seed fails to link at 3, 7, 8,
12 and 16 units ("_Vec.clone__receiver__94_3", referenced from
___wcu$146$Holder.dup in ...o.u6.o). Stage1 built from this tree prints
4/376 at each of those counts. On a program where several functions clone
a Vec[i32], nm on stage1's WITH_KEEP_UNIT_OBJECTS output shows one
definer (u4.o: T _Vec.clone__receiver__224_3) and the other units
referencing it (u1.o, u7.o: U).

With `.clone()` restored at both sites, the seed-built stage1 links
(`:dev` green; stage1 defines T _Vec.clone__receiver__94_3). That only
works because of how the 16-unit packing falls for this tree, not
because the seed is fixed. #1359 tracks cutting a seed that contains
#1325.
ehartford pushed a commit that referenced this pull request Sep 23, 2026
…1331)

compilation_execute_binary_link_plan deleted t.o and t.o.u<k>.o on a failed
link before it checked WITH_KEEP_UNIT_OBJECTS. A failed link is exactly
when those objects are needed: nm on them names which unit defines and
which unit references an undefined or duplicate symbol across codegen
units. #1325 and #1359 both had to be chased by breaking in lldb at
compilation_cleanup_build_products. With the variable set, a failed link
now keeps the objects, removes only the partial binary, and prints where
the objects are.

Checked with stage1 on a program that calls an undefined extern at 4
units: WITH_KEEP_UNIT_OBJECTS=1 leaves u.o and u.o.u1.o..u3.o in place and
prints the note. Without the variable, nothing is left behind, as before.

Fixes #1331
ehartford pushed a commit that referenced this pull request Sep 23, 2026
… codegen units pin the receiver-specialization case (#681, #1359)

The copy loops in mir_drop_state_blocks_new and MirDropStateBlocks.input
worked around a stage1 link failure: `undefined symbol:
_Vec.clone__receiver__94_3`. The source compiler does not have this
defect. The pinned seed (v0.15.2.0) does, because it predates #1325's
gen_owned_specializations. At v0.15.2.0, src/Codegen.w:6021
(ensure_concrete_mir_function) generates a specialization's body in
whichever unit reaches a call to it, and unit_demote_foreign_definitions
(:1356) deletes the body in every unit that doesn't own it. An instance
whose callers all sit outside its owning unit is then defined by no unit.

Evidence: the new behavior test under the seed fails to link at 3, 7, 8,
12 and 16 units ("_Vec.clone__receiver__94_3", referenced from
___wcu$146$Holder.dup in ...o.u6.o). Stage1 built from this tree prints
4/376 at each of those counts. On a program where several functions clone
a Vec[i32], nm on stage1's WITH_KEEP_UNIT_OBJECTS output shows one
definer (u4.o: T _Vec.clone__receiver__224_3) and the other units
referencing it (u1.o, u7.o: U).

With `.clone()` restored at both sites, the seed-built stage1 links
(`:dev` green; stage1 defines T _Vec.clone__receiver__94_3). That only
works because of how the 16-unit packing falls for this tree, not
because the seed is fixed. #1359 tracks cutting a seed that contains
#1325.
ehartford pushed a commit that referenced this pull request Sep 23, 2026
…1331)

compilation_execute_binary_link_plan deleted t.o and t.o.u<k>.o on a failed
link before it checked WITH_KEEP_UNIT_OBJECTS. A failed link is exactly
when those objects are needed: nm on them names which unit defines and
which unit references an undefined or duplicate symbol across codegen
units. #1325 and #1359 both had to be chased by breaking in lldb at
compilation_cleanup_build_products. With the variable set, a failed link
now keeps the objects, removes only the partial binary, and prints where
the objects are.

Checked with stage1 on a program that calls an undefined extern at 4
units: WITH_KEEP_UNIT_OBJECTS=1 leaves u.o and u.o.u1.o..u3.o in place and
prints the note. Without the variable, nothing is left behind, as before.

Fixes #1331
ehartford added a commit that referenced this pull request Sep 23, 2026
…specialization; keep unit objects on a failed link (#1359, #1331) (#1360)

* Patterns: a struct pattern tests its literal fields; exhaustiveness reads whole patterns (#1388)

`Point { x: 0, y }` matched any `x` in match, if let, let-else and `for`:
MirLower.lower_pattern_match had no NK_PAT_STRUCT branch, so a named-field
struct pattern fell into the final "conservatively accepted" default,
`self.terminate(TermKind.TK_GOTO, arm_bb, 0, 0, 0)` — no test of any field.
Observed on a stage2 of origin/main: AstPool.kind = 0x6b (NK_PAT_STRUCT) reaches
the shared goto tail with w1 = TK_GOTO, w2 = arm_bb (bb2); --dump-mir of the
repro shows `bb0: goto -> bb2` with no read of `_1.x`.

MirLower:
- NK_PAT_STRUCT tests every refutable field sub-pattern, as the positional
  and tuple forms do; field places carry the field's type (read from the
  subject, so generic struct instances lower — `Pair { a, b }` over
  `Pair[i32]` was an invalid-MIR ICE).
- The default is loud: a pattern kind with no test lowering reports and
  marks the function unsupported instead of matching every value. A slice
  pattern over a dynamic slice (`match s: [] => ...` on `[]i32`), which also
  took the first arm silently, now fails there (#1389).

Sema (§9.7, expression-position matches must be exhaustive):
- Exhaustiveness is a pattern-matrix usefulness check (Maranget) over the
  whole pattern: bool, enum variants with their payloads, tuples, structs,
  bounded integers split into literal/range segments; str, floats and wider
  types need a catch-all. It names a witness: "non-exhaustive match on
  'Point': `Point { x: 1, .. }` is not covered". `Some(5), None` no longer
  counts as exhaustive over Option[i32], nor `0, 1` over i32 (#994's check
  half); `0..=127, 128..=255` over u8 does. D43's missing-arm test uses the
  same answer.
- A struct pattern requires a struct subject, names the subject's type, and
  names only its fields; an enum subject (`Circle { r }`) reached codegen
  untyped.

A refutable `for` pattern keeps its filter semantics (behav_for_full_patterns);
with the lowering fixed, `for Point { x: 0, y } in ps` now skips points whose
x is not 0. Comprehension clauses never test their pattern at all — filed as
#1403.

Sweep: `check` over the 423 test/examples files that contain a match, a
pattern `for` or a struct/slice pattern, and `test` over the 34 with struct or
slice patterns, stage1 of this branch against stage1 of 00408eb: no existing
program changed result; only the new fixtures differ.

Fixes #1388

* Sema: a value `if`/`match` arm that yields a whole binding moves it (#1380)

Route: silent wrong value, a move the checker never modeled — MIR dump,
then the checker's own move trace (WITH_DEBUG_MOVE), then the branch.

`let p = if c: a else: b; let q = if c: a else: b` compiled and printed
`[xy] []`, leak count 0.

Evidence (installed v0.15.2.1, repro r.w):
- `--dump-mir`, main: `bb3: _9 = move _1; _1 = const zst(ty16)` and
  `bb4: _9 = move _2; _2 = const zst(ty16)` for the first `if`; the second
  `if` moves the blanked `_1`/`_2` again (`bb6: _11 = move _1`). MirLower's
  lower_if moves an arm's whole-binding tail into the join temp; only
  projected place reads join as a view (#747 03g: `operand_is_view_read`
  requires `place_proj_counts > 0`).
- `WITH_DEBUG_MOVE=1 with check`: `let p = a` logs `[move] sym=a`; the
  `if` version logs no move for `a` or `b`.

Exact line: SemaCheck.check_if_expr (and check_match_expr) check a value
arm through check_expr_value_context and never mark its tail consumed; the
consumer's mark_moved_if_consumed(value) then sees NK_IF_EXPR / NK_MATCH
and does nothing. So Sema's move state never recorded what MIR does.

Fix (§2.2): mark_arm_tail_consumed marks a value arm's whole-binding tail
(through blocks and parens) consumed in the arm's own move state, before
the branch merge — exactly what `let p = a` does. Only a binding that
outlives the arm is marked (§29.8 forbids shadowing, so a live name is the
outer one). The second read is now "use of moved value"; in a loop,
"moved inside a loop". This is the issue's first option. The other (a view
join for whole bindings) would change MIR's ownership, not only the
checker, and is Eric's call.

Every place the new rule rejected in the tree was reading a value the
program had already moved — each a real bug, fixed here:
- CImport ci_translate_anon_record_cursor: `raw_name` moved into
  `actual_name`, so a named field of anonymous-record type inside an
  anonymous record came out as `anon_0` (`o.mid.deep` did not resolve;
  test/behavior/behav_c_import_nested_anon_record_field_name.w, which
  fails on the seed). Clone.
- CImport ci_translate_macros: `offsetof_result` and `cast_expr_result`
  were moved before the branches that re-read them, so the offsetof
  `c_int` branch and the "expression translation" fallback never ran.
  Running them would be wrong (offsetof is size_t, which clang's semantic
  type already gives; the fallback typed `{ .a = 3 }` as a `c_int` global,
  breaking behav_c_import_macro_probe_recovery). Removed, with the
  extern-var pre-scans and ci_expr_references_var that only fed them:
  behavior unchanged.
- ComptimeEval: effect_tool_identity moved `resolved` into the cache key,
  so a tool's identity was always `<exe>:unresolved`, never its sha256;
  glob moved `pattern` (error text lost it) and `rel_file` (a glob based at
  `.` returned "" for every match). Clone.
- BundleInterfaceEmit: `trait_name` moved into the export name, so the
  impl row (and the bundle fingerprint) had an empty trait field. Clone.
- Codegen.declare_function_at_inner: `sema_name_str` / `parsed_name` moved
  into `name_str` / `alias_text`; later reads saw "". Behavior-neutral
  (Backend hands Codegen the Sema pool, so the recovered alias and
  effective name are the same text). Clone.
- std.build tool actions (scratch dir error text) and
  build/release_publish.w (every provenance sidecar after the first said
  `builder=unknown`). Clone.

Matrix (installed v0.15.2.1 vs stage1): if / else-if / match × arm is an
owned str / Vec local, a param, a block tail; consumer is let, assign, call
arg, struct field, method receiver, `++`/f-string; then-used-after, in a
loop, diverging other arm, cloned arms, last use. Before: every
used-after cell compiled and read "" (or Vec len 0); after: each is "use
of moved value" (the loop cell "moved inside a loop"), cloned and last-use
cells compile and print the text. Field arms (`if c: x.s else: y.s`) are
not whole bindings and are unchanged here: MIR treats them as a view join
and still blanks the field — #1409.

Sweep: every file under test/ examples/ lib/ tools/ build/ with a
candidate arm shape (655 files) checked with stage1; the only new
diagnostics were the sites above. `with-stage1 check src/main.w` ok;
`:stage2` (stage1 builds stage2 and the pcre2/zlib/tommyds/c_algorithms
bundles) green; stage2 checks src/main.w. c_import behavior tests: 0
regressions (the six stage1 failures fail the same on main's stage1).
move-audit (stage1 vs seed): 15 cells, 0 FAIL, 0 DIFF.

Fixtures: test/compile_errors/err_if_arm_moves_binding.w,
err_match_arm_moves_binding.w, err_if_arm_move_in_loop.w,
err_if_arm_moved_by_observer.w; test/behavior/behav_if_arm_binding_join.w,
behav_c_import_nested_anon_record_field_name.w.

Ownership (move checking) change: batch alone.

Fixes #1380.

* Spell the field moves the #1395 check finds: .clone() to keep the owner whole, var + move to vacate

A field that reaches an owned `if`/`match`/`??` join, a block tail or a
break value was an implicit field move the D32 funnel never saw (#1395).
Every site the fixed compiler reports in src/, lib/ and test/, respelled
with the fix-it the D32 error offers:

- `.clone()` where the owner stays whole: Sema's current_module_path in
  record_named_type_with_pub / record_displaced_fn / embed_file / MirLower's
  src intrinsics (a `mut fn` blanked it mid-collection — the #1350 bug),
  ProjectConfig/Compilation root_dir, CImport bail location, ComptimeEval
  target_name/final_output/location, Codegen analysis_query,
  CodegenDispatch source paths, Frontend source_dir, Analysis diag facts,
  BuildGraph target.entry, std.build ToolFs target_name.
- `var` + `move` where the owner dies right after: ComptimeEval's
  control-signal value and write_binary bytes; the raw-slot takes in
  std.collections (binary_heap, hash_index, sorted_vec, trie) and
  behav_generic_drop_only_use, which hid `(*slot).value` in `unsafe { }`
  (the unwrapped spelling was already the D32 error).
- derive(Builder)'s generated `build` rebinds the consumed builder to a
  `var` and vacates each `??` operand explicitly, as the SoA push does.

Every spelling is valid under the current rule, so this lands first.

* Sema: a field that reaches an owned join, block tail or break value is an implicit field move (#1395)

§2.2 (D32): "A field never moves out implicitly — anywhere, in any
context." §3.8's join rules make every arm of an `if`/`match`/`??` whose
result is owned an owned-value demand (rules 2 and 5: "A reference to a
non-Copy value cannot satisfy an owned demand; producing an independent
value requires an explicit owning operation such as clone"). Only an
unannotated `let x = place.field` binds a view.

Root cause: the D32 funnel (mark_moved_if_consumed) is reached with the
consumed expression — the `if`/`match`/block node — and never looked at
the arms, so `let path = if c: self.p else: ""` passed check while
MirLower's lower_expr NK_FIELD_ACCESS arm emitted OK_MOVE of the field
place: a `mut fn` reset the receiver's field to "" (the #1350 symptom), a
read `fn` byte-copied a Vec field that both owners then freed. The
inferred-return tail check never fired either: check_fn_body keyed it on
`ret_type == 0`, but an unannotated fn's signature still reads Unit there.

Now the if- and match-join, `??`, and break-value sites check each arm of
an owned result, and a consumed block checks its tail, through one helper
(d32_check_owned_value_field) that feeds the existing funnel: D32's error
with its `move`/`.clone()` fix-its, or D22 §13.6's borrowed-field error
through a view. The inferred-return tail check keys on the annotation.

move_audit gains 58 field cells (str/Vec x mut fn/read fn/owned local x
plain, if, match, ??, block, break, argument, inferred return, clone,
move); the baseline accepted all 42 error cells. An all-field join with no
owned anchor is rejected too, where §3.8 rule 3 would bind a view — the
safe direction, filed as #1408.

Fixes #1395.

* Option.filter's predicate observes `&T`; filter / inspect / context retire the subject they decompose (#1379)

Route: memory bug — debug allocator, WITH_ALLOC_NO_REUSE, the address
trap, lldb, then the MIR of the block.

`o.filter((v) => v.len() > 0)` over `Option[Vec[i32]]` printed `true`
and then `debug-alloc: DOUBLE FREE ... second_drop=drop#enum
__drop_enum_448`, rc=134.

Evidence (installed v0.15.2.1, repro r.w):
- `WITH_DEBUG_ALLOC=1 WITH_ALLOC_NO_REUSE=1`: the report persists (a
  genuine double free), `first_drop=drop#enum __drop_enum_448`.
- `WITH_DEBUG_ALLOC_TRAP_FREE=<addr>` under lldb: `trap-alloc hit=1`,
  `trap-free hit=1 origin=drop#enum __drop_enum_448`, `trap-free hit=2`
  (same origin). With TRAP_FREE_HIT=1 and a breakpoint on _exit, the first
  free is `with_vec_free_drop_origin <- main at r.w:5:5`: the enum glue at
  the filter line.
- `--dump-mir`, main:
    bb3: call copy _8(move _7<as v0>.f0)            (predicate, by value)
    bb7: _9 = aggregate(kind=1, tag=0, fields=[move _7<as v0>.f0])
    bb5: _6 = move _9; drop(_7) @ drop#15 scope-exit _7
    bb9: drop(_6) @ drop#23 scope-exit _6
  `_7` is lower_owned_receiver_place's materialized subject. The kept
  payload moves into `_9`, but a move out of a variant payload registers
  no reset-on-move, so drop#15 frees it and drop#23 frees it again.

Exact lines (src/MirLower.w, lower_option_combinator_method, the filter
branch):
- `filter_args.push(self.operand_for_place(payload_place, payload_ty))`
  moved the payload into the predicate. §10.5 says the predicate is
  `fn(&T) -> bool`, and Sema (method_arg_expected_type) typed it `fn(T)`.
  On main a closure does not drop its owned parameter, so this was a
  spec violation, not the first free. Once closures drop owned params
  (#1398) it is a third free.
- the kept `Some` moved the same payload, and the join left `_7`'s
  scope-exit drop live.

Fix:
- Sema: the filter predicate's expected type is `fn(&T) -> bool`.
  Option.filter now validates its argument like inspect does (a
  one-argument function whose parameter is `&T`).
- MIR: the predicate gets the payload's address (operand_for_place_arg,
  like inspect). A rejected payload is dropped once, on its path. At the
  join the subject is retired: retire_decomposed_carrier cancels its
  statement temp and scheduled drop.
- The same retire applies to the other combinators whose every path moves
  a payload into the result without a consuming closure. Each was a
  DOUBLE FREE on the seed and on main's stage1: Option.inspect, and
  Result.inspect / inspect_err / context / with_context.
  map / and_then / map_err / or_else move a payload into a consuming
  closure whose body does not yet drop its parameter. They are #1363's
  and are unchanged here.
- observer_param_accepts: an observing callback's parameter must be a
  reference. types_compatible alone accepted `(q: P) =>` for `&P`, so
  Sema said nothing and codegen died on "wrong argument type actual=ptr
  expected=P". That is a silent tool, fixed for filter, inspect and
  inspect_err.

Matrix (test/debug_alloc/da_option_filter_observes_payload.w, leak count
0, exact stdout): Vec / str / struct / i32 payloads × keep / reject /
None; a call-result subject; a named `fn(&T) -> bool` predicate; a typed
`(q: &P)` closure; an Option[&T] payload; filter feeding map; and
Option.inspect Some/None, Result.inspect / inspect_err / context /
with_context on both paths. main's stage1: DOUBLE FREE. After: all cells
pass. test/compile_errors/err_option_filter_owned_param.w pins the typed
owned-parameter rejection. spec §10.3 / §10.5 / §10.6 fixtures and
codegen_option_methods pass on stage1.

A generic closure annotation (`(v: &Vec[i32]) =>`) types `v` as `i32`.
That is a separate parser bug, #1402. The fixture's typed cell uses a
non-generic payload.

Ownership/drop change: batch alone. move-audit (stage1 vs seed): 15
cells, 0 FAIL, 0 DIFF. drop-audit (stage1 vs seed): 136 cells, 0 non-PASS, 0 regressions. debug-alloc fixture lane on stage1: all PASS.

Fixes #1379.

* MirCore: the drop-state scratch and input maps clone their chunk ids; codegen units pin the receiver-specialization case (#681, #1359)

The copy loops in mir_drop_state_blocks_new and MirDropStateBlocks.input
worked around a stage1 link failure: `undefined symbol:
_Vec.clone__receiver__94_3`. The source compiler does not have this
defect. The pinned seed (v0.15.2.0) does, because it predates #1325's
gen_owned_specializations. At v0.15.2.0, src/Codegen.w:6021
(ensure_concrete_mir_function) generates a specialization's body in
whichever unit reaches a call to it, and unit_demote_foreign_definitions
(:1356) deletes the body in every unit that doesn't own it. An instance
whose callers all sit outside its owning unit is then defined by no unit.

Evidence: the new behavior test under the seed fails to link at 3, 7, 8,
12 and 16 units ("_Vec.clone__receiver__94_3", referenced from
___wcu$146$Holder.dup in ...o.u6.o). Stage1 built from this tree prints
4/376 at each of those counts. On a program where several functions clone
a Vec[i32], nm on stage1's WITH_KEEP_UNIT_OBJECTS output shows one
definer (u4.o: T _Vec.clone__receiver__224_3) and the other units
referencing it (u1.o, u7.o: U).

With `.clone()` restored at both sites, the seed-built stage1 links
(`:dev` green; stage1 defines T _Vec.clone__receiver__94_3). That only
works because of how the 16-unit packing falls for this tree, not
because the seed is fixed. #1359 tracks cutting a seed that contains
#1325.

* WITH_KEEP_UNIT_OBJECTS keeps the unit objects on a failed link too (#1331)

compilation_execute_binary_link_plan deleted t.o and t.o.u<k>.o on a failed
link before it checked WITH_KEEP_UNIT_OBJECTS. A failed link is exactly
when those objects are needed: nm on them names which unit defines and
which unit references an undefined or duplicate symbol across codegen
units. #1325 and #1359 both had to be chased by breaking in lldb at
compilation_cleanup_build_products. With the variable set, a failed link
now keeps the objects, removes only the partial binary, and prints where
the objects are.

Checked with stage1 on a program that calls an undefined extern at 4
units: WITH_KEEP_UNIT_OBJECTS=1 leaves u.o and u.o.u1.o..u3.o in place and
prints the note. Without the variable, nothing is left behind, as before.

Fixes #1331

---------

Co-authored-by: Eric Hartford <[email protected]>
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