Skip to content

D69 follow-ups: generic and method gen fn, comprehensions and goto over generators, loop-body view borrows - #1747

Merged
ehartford merged 5 commits into
gen-push-implfrom
gen-push-fixes
Sep 27, 2026
Merged

ehartford merged 5 commits into
gen-push-implfrom
gen-push-fixes

Conversation

@ehartford

@ehartford ehartford commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Stack layer 2 on #1731. Fixes #1724 #1727 #1730 #1734; also fixes a comprehension that leaked its collection on ?. Each fix has a test shown failing on #1731's compiler. Filed along the way: #1735–#1740. Draft until the stack's one battery is green.

@ehartford
ehartford added this pull request to stack #1749 September 26, 2026 22:29
@ehartford ehartford changed the title gen push fixes D69 follow-ups: generic and method gen fn, comprehensions and goto over generators, loop-body view borrows Sep 26, 2026
Eric Hartford added 5 commits September 26, 2026 23:10
… labeled break (Fixes #1730)

§13.4, §13.5b. The body of `for x in g` over a Gen[T] lowers as the
closure `each` calls, and a `goto` in it to a label of the enclosing
function was never carried across that call. Root cause, in
lower_goto: goto_target_info always allocates a block for the label
(ensure_goto_label), so the child builder got a fresh block for a label
it never defines; the `target.break_bb < 0` branch meant to catch this
(mark_unsupported) could not fire, and the jump went to an unterminated
block — a run-time "reached unreachable code" trap, not the lowering
error #1730 describes.

A goto is an exit of the consumer's body like the others. The closure
collects its own body's labels (collect_goto_label_depths, which the
owning frame now skips for a gen-loop body); a goto to any other label
leaves the closure through the flag, as a labeled break does, with a
new exit kind (gen_loop_exit_kinds: break, continue, goto). The owning
frame runs the cleanup of the scopes it leaves and jumps to the label,
or, when it is itself a gen-loop closure that does not own the label,
passes the exit on (lower_gen_loop_exit_arm).

The tool that stayed silent: a goto to a label its body never defines
now stops lowering with a phase bug (verify_goto_labels) in every
function, closure and gen-loop body, instead of lowering a trap.

Tests (both trap with "reached unreachable code" under the
gen-push-impl compiler): behav_gen_push_goto_exit — forward, backward
(restart with a fresh generator), out of nested generator loops, a
label inside the body, and a goto in a generator's own consuming loop;
da_gen_push_goto_stops_generator — the stopped generators' defers and
resources run once, inner first, before the label's code, leak count 0.
…a `?` in the element releases it

§13.6. A `?` (or a cancellation) in a comprehension's element leaves
the function while the collection is being built. The collection lived
in a MIR temp no cleanup knew about (lower_array_comprehension's
new_temp, never registered), so the early-return path dropped the
scope's locals but leaked the collection and every element already in
it: `[check(i)? for i in 0..6]` leaked the Vec buffer and its strs.

The collection is now registered as the statement's temporary when it
is created, exactly as a call's result is: emit_drops_for_return
releases it on an early exit, and the finished value moves out through
the usual consume, which cancels the temporary.

Found while testing #1727 (a comprehension over a generator whose `?`
stops the generator). Test da_comprehension_try_releases_collection:
leak count=10 under the gen-push-impl compiler, 0 now, over a Vec and a
HashSet comprehension that stop early and one that finishes.
…prehension at each yield (Fixes #1727)

§13.4, §13.6. A comprehension clause's `for PATTERN in EXPR` is §13.5's
iteration, and a Gen[T] is consumed through `each` — the D69 lowering
only did that for a `for` statement, so a clause over a generator was a
loud compile error (it hung at run time before D69, stepping the old
pull `next()`).

Sema decides, per clause (check_comprehension_clause_iterable): over a
Gen[T] it records the gen-loop facts keyed by the clause's iterable
(resolve_gen_for, as for a `for` node), consumes the generator value,
and — with every clause binding still in scope — the captures of the
closure the rest of the comprehension runs as: the enclosing bindings
its filter, later clauses and element name
(record_gen_comprehension_captures). A generator whose body may suspend
makes the comprehension may-suspend (gen_loop_may_suspend, shared with
`for`).

MIR (lower_comprehension_gen) lowers the clause's filter, the later
clauses and the leaf as the closure `each` calls, with the collection
being built as one more by-place capture; a refutable pattern skips.
A comprehension consumes the whole generator, so the closure stops it
only for an exit of the enclosing function (`?`, cancellation), through
the flag like a `for` body. lower_for_gen and the clause share the
closure's construction (begin_gen_loop_closure, add_gen_loop_item) and
the `each` call with its flag dispatch (finish_gen_loop).

Tests (both are compile errors citing #1727 under the gen-push-impl
compiler): behav_gen_push_comprehension — element and filter, nested
generator clauses, a generator clause after a range clause and the
reverse, BTreeSet and BTreeMap targets, views of the generator's own
locals cloned in, a refutable pattern, captured bindings, a stored
generator value; da_gen_push_comprehension_stop — owned elements moved
into the Vec, a `?` in the element stopping the generator (its defer
and resource released once before the error returns), leak count 0.
err_generator_comprehension_unimplemented pinned the non-compliance
and is removed.
§13.4 restricts neither, and the D69 lowering made both a loud compile
error. They now compile like any generic function and any method.

Generic gen fns. Everything behind a gen fn — the generator value's
type, its producer and `each` — is registered by one Sema entry,
register_generator, keyed by the symbol whose signature returns the
value: the declaration, or a specialization's symbol, which
check_fn_body_concrete now registers for a gen fn (its concrete
signature returns that specialization's value). check_generic_call
returns the specialization's value type rather than the declared element
type; the body check reads the element type by the signature's symbol;
lower_concrete_specialization lowers a gen specialization as the three
functions (lower_generator_functions, shared with declarations). A
generator whose body may suspend makes its loop may-suspend through a
specialization too, and the no_suspend note names the generator as
declared.

Generator methods. The parser accepted `gen` only on a top-level
declaration; an impl or extend block now takes `gen fn` (before a
`mut`/`move` receiver mode, as `async` does). The generator value holds
the receiver like any other argument: a borrowed receiver (`fn`,
`mut fn`) is the caller's place, so Sema makes the value's field a view
of it (&Self, the value ephemeral), records the fact
(generator_fn_receiver_views), and passes that receiver by place
(value_ref_abi) to the gen fn and its producer whatever the owner type
— a `str` or `i32` receiver included. The constructor stores the place's
address, `each` hands the producer the place the view names, and the
call's view dependencies include the receiver on the method-call paths
(record_generator_call_ref_origins, now reading the value's field types),
so the receiver cannot change or move while the value is live. A `move`
receiver, or a `self` spelled as a reference, is an ordinary argument.

Found on the way: the constructor created the receiver view's temporary
between parameter locals, so the next parameter was read from the
temporary's slot (a `gen mut fn tick(times)` ran zero times); the
parameters are now allocated first. Neither validate-all nor audit:all
noticed the argument/parameter type mismatch (#1735).

Tests (the first three fail to compile under the gen-push-impl
compiler: `gen` in an impl is a parse error there, a generic gen fn is
#1724's error): behav_gen_push_generic_and_methods — generic gen fns
over i32, str, tuples and views of a generic argument, in a pipeline
and a comprehension; read, mut and move receivers, `self: &Tree`, a
generic owner, `extend str` and `extend i32`; da_gen_push_generic_
method_stop — a stopped generic generator, an unconsumed one, a stopped
move-receiver generator (its receiver dropped once when it leaves) and
a borrowed-receiver one (the caller's value dropped once at the caller's
end), leak count 0; err_gen_method_receiver_view_mutated;
err_gen_push_generic_suspending_in_no_suspend.
err_generator_generic_unimplemented pinned the non-compliance and is
removed.
…dy cannot mutate what it views (Fixes #1734)

§13.4, §21.1. The consumer's body runs while the producer is running:
`for l in each_line(&lines): lines.push(..)` grows the Vec the producer
is iterating. Sema refused a mutation of a viewed place between creating
the generator and the loop, but not inside the body: the generator
value is consumed by the loop, so its own borrow ended at the iterable
(its last use), and nothing stood for the running producer.

Sema owns the fact. At a generator call it records the places the view
arguments name (gen_call_view_place_nodes: the operand of `&place`, a
view argument, a borrowed receiver — alongside the view dependencies it
already recorded). A loop over a generator — `for x in g`, or a
comprehension clause — registers those places as shared borrows inside
the loop's scope (register_gen_loop_view_borrows), path-precise as any
view (#1530), so a sibling field stays writable; a generator reached
another way (a binding) borrows the roots of its view dependencies. The
borrows are loop views (for_view_binding_*), never expired at a lexical
last use, and — unlike a collection's loop view — not even when the
loop ends right after the mutation: the stopped generator still leaves
through its own scopes and defers, which may read the place
(for_view_binding_gen_loops). The error is the borrow checker's own
"cannot mutate `x` while `each_line(…)` is a live view into it", with a
note that the generator is still running; a move out of the viewed place
is refused the same way.

Pipeline stages over a view-holding generator are rejected wholesale
today (#1737); lifting that must keep these borrows for the chain.

Tests. Accepted (`ok`) by the pre-fix stage1 (4167b8e), refused now:
err_gen_loop_body_mutates_arg_view, _field_view, _receiver_view (a
mutation right before `break`), _stored_gen_view, err_gen_loop_body_
moves_viewed_place, err_gen_comprehension_mutates_view. The first four
that the gen-push-impl compiler can express (arg, field, stored, moved)
are `ok` there too; the receiver and comprehension forms do not compile
there (#1724, #1727). behav_gen_push_view_borrow_disjoint: a sibling
field write, a read of a borrowed receiver, a write to an unrelated
place, and the viewed Vec free again after the loop — all accepted.
@ehartford

Copy link
Copy Markdown
Contributor Author

Stack battery GREEN on the stack top 5fc8160 (on main 2e8defa; host darwin-aarch64, pinned seed), run once for all six layers with with run tools/battery.w:

5fc8160a /Users/eric/.local/with-staging/battery-target
build rc=0 wall=409s
battery-checks rc=0 wall=1184s
GREEN

battery-checks = fixpoint, drop-audit, move-audit, every test target, user-programs-safe, test-green and last-green evidence. Merge the whole stack in order: gh stack merge 1761 --yes --squash.

@ehartford
ehartford marked this pull request as ready for review September 27, 2026 05:04
@ehartford
ehartford merged commit f50c708 into main Sep 27, 2026
@ehartford
ehartford deleted the gen-push-fixes branch September 27, 2026 05:28
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.

D69: generic generator functions and generator methods (gen fn f[T], gen fn in impl)

1 participant