Skip to content

D69: generators lower as calls — push generators, std.generators pipelines - #1731

Merged
ehartford merged 3 commits into
mainfrom
gen-push-impl
Sep 27, 2026
Merged

ehartford merged 3 commits into
mainfrom
gen-push-impl

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Implements spec v7.3 §13.4 (D69, #1723). Fixes #1534.

  • gen fn lowers to a constructor + producer + Gen[T].each; each yield calls the consumer's body, and a stop leaves the generator at its yield as if by return (defers, scope drops, temporaries released once — debug-alloc tests).
  • for x in g: over a Gen[T] (Sema's decision) lowers its body to a closure; break/continue/return/?/labeled jumps are carried across each.
  • Views of the generator's own locals may be yielded; .await is allowed in generator bodies; the old state machine, TK_YIELD, is_generator_next and codegen's generator side tables are removed.
  • std.generators: map, filter, take, collect over Gen[T].
  • Pre-existing bugs fixed on the way: nested-closure captures, closure params defaulting to i32 in method/generic calls, callable-field calls moving the field, silently dropped break/continue with a missing target.

Still NON-COMPLIANT (loud errors with issues): g.pull() #1725; generic/method gen fn #1724; comprehensions over generators #1727; goto out of a generator loop #1730. Pipelines need use std.generators.{...} until #752.

Local gate green (build, build.w, lib/std/build.w, abi-hash-check, all corpora, examples). Drop-scheduling change: battery alone with :drop-audit and :move-audit. Draft until green.

Eric Hartford added 3 commits September 26, 2026 23:10
…ody at each yield

§13.4 (D69). A `gen fn f(p) -> T` is three functions: `f` evaluates its
arguments into the generator value (a compiler-generated struct of the
parameters that implements the new std trait Gen[T]); the value's
`move fn each(body: fn(T) -> bool)` hands them to the producer; the
producer is f's body lowered with a last parameter `body`, where each
`yield e` calls `body(e)` and, when it answers false, leaves the
generator as if by `return` — defers, scopes and statement temporaries
released on that path. #1534 (a `for` in a generator lost its counter)
is gone with the state machine.

`for x in g` over a Gen[T] (Sema decides: resolve_gen_for records T,
the body's callable type, the `each` callee and its specialization)
lowers the loop body to a closure passed to `each` (lower_for_gen):
finishing or `continue` answers true, `break` answers false; `return`,
`?`, cancellation and a break/continue of an outer label answer false
after setting the owning frame's flag, which acts on it once `each`
returns — Go 1.23's range-over-func rewrite with the stop automatic.
A returned value is written straight into the owning function's return
slot through a capture; nested generator loops and a `yield` inside a
loop over another generator (recursion) compose. Yielded views of the
generator's own locals are call arguments; the no-references-across-
yield rule and the `.await` prohibition are retired, and a generator
whose body may suspend makes its consuming loop may-suspend (Sema and
MirSuspendCheck, which now counts a suspending closure passed to a call).

Retired: Sema's state-struct collection (finalize_generator_state_type,
generator_collect_state_fields), MirLower's next-body transform and its
save/restore/blank helpers, TK_YIELD, MirCore's is_generator_next
exemption, codegen's generator field side tables, AsyncMir's Generator
flavor and Yield suspension.

Loud errors for what is not implemented: `g.pull()` (#1725), generic gen
fns and gen methods (#1724), a comprehension clause over a generator
(#1727, which hung at run time before).

Found on the way and fixed at the owner:
- closure captures are resolved by the creating body's local id
  (anonymous_capture_sources), not by name at codegen: a closure inside a
  closure captured the capture's pointer slot (writes were lost, a str
  capture crashed), and a same-named later local could be taken; a
  capture of a view binding with no local goes through a &T of its place;
- the ownership validator's leak rule no longer counts a closure's
  capture (the creating frame owns it), which rejected any closure that
  reassigns a captured str;
- `(self.run)(body)` reads the callable in place like `self.run(...)`;
- a closure with unannotated parameters passed to a generic function is
  typed from its parameter once the other arguments bind (`map(g, it*2)`,
  `apply(v, it > 4)` typed `it` as i32 before), fn(A) -> R parameters
  bind type parameters, a method's callable parameter types a closure
  argument (user methods defaulted it to i32), and an `impl Trait`
  parameter's concrete type is part of the specialization key;
- a break/continue whose target MIR cannot find is a phase bug, not a
  silently dropped jump.
The ordered pipeline stages take any Gen[T] and are Gens themselves
(GenStage[T] owns the stage before it inside the callable that runs it),
so `g |> map(f) |> filter(p) |> take(n) |> collect[Vec]()` is as lazy as
the generator it starts from, and `take` stops the whole chain at the
generator's yield by answering false. Until §18.2's fallback tier lands
(#752) the stages are imported: `use std.generators.{map, filter, take,
collect}`.
…ines, await

New: #1534's repro and loops over a range, a Vec and a slice inside a
generator; break/return/?/labeled break/continue from the consumer, each
stopping a generator that holds an owned resource and a defer (debug
allocator: released once, no leak); nested generator loops with returns
and labels; views of the generator's own locals and a view retained past
the body (rejected); a generator value stored in a struct and consumed
later; a recursive walk; pipeline stages; .await in a generator and in
the consuming body; the no_suspend check through a generator; nested
closure by-place captures; loud errors for pull (#1725), generic gen fns
(#1724) and comprehensions over generators (#1727).

Rewritten to the D69 rules (the spec changed): spec_ss13_4_generators
stepped generators with next(), which D69 moves to g.pull() — it now
consumes them with `for` and checks the same values plus #1534 and an
early break; spec_ss13_4_no_references_across_yield pinned the retired
rule and becomes spec_ss13_4_generator_views (views of the generator's
own locals and of its arguments). err_generator_await and
err_generator_yield_local_ref pinned the retired prohibitions and are
removed; behav_gen_push_await and spec_ss13_4_generator_views are their
positive successors.
@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 55b7230 into main Sep 27, 2026
@ehartford
ehartford deleted the gen-push-impl 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.

A for loop in a generator loses its iteration state at every yield (range counter, index, iterator not carried)

1 participant