ADR 0072: Generators as state machines¶
Status: Final
Type: Feature
Created: 2026-11-06
Amends: 0064 (a generator the inlining cannot take is lowered as a state machine, so a recursive generator and one held in a name leave the refused list)
Related-ADRs: 0023 and 0024 (the frame is an instance, released as one), 0007 (an exception leaving the generator), 0053 (a yield defeats a loop's proof, notes/accept-then-wrong.md §76)
Context¶
ADR 0064 lowers a generator by writing its body into the loop that consumes it, which needs no frame and costs nothing at run time. It refuses the shapes it cannot write in: a generator held in a name and consumed later, or one that consumes itself, which would be written into itself without end. ADR 0064's alternatives named the answer, a frame per generator object holding the locals and the yield it stopped at. They also named the programs that would need it: sudoku5's solve and mwmatching's blossomLeaves, both recursive. The owner chose it (A187).
Decision¶
- The inlining stays the first answer. A call ADR 0064 lowers is lowered as before. A frame is made only where the inlining cannot be used: a generator consuming itself, directly or through another, or a frame held in a name, a local or a module global, and consumed by a later loop.
- Which generators. A module-level generator function qualifies when all parameters are annotated, with constant defaults and no
*args,**kwargsor keyword-only parameter, when it defines no function or class and has noyieldinside atryor awith, and when the return is annotatedIterator[T],Iterable[T]orGenerator[T, None, None].Tis what the frame produces. Any other generator keeps ADR 0064's refusals, which now say which of these it misses. - The frame is an instance of a class the compiler makes for the generator. The fields are the state, the arguments, and every value live across a
yield. The live values are found from the IR once the body is lowered, so a loop's hidden counter, arange's bound and an inlined generator's own state are kept with the locals. The frame is counted and released as any instance is (ADR 0024). A value the frame's function owned moves into a field at theyieldand back at the resume. A value it only borrowed is held by the field while the generator is suspended, as CPython's frame holds it. - Two functions. The constructor, named as the generator, so a call of it is an ordinary call: it allocates the frame and stores the arguments. The resume function has the generator's body. Its entry dispatches on the state: to the start, to the point after the
yieldit stopped at, or, finished, to the end. A frame resumed while it runs raises CPython'sValueError: generator already executing. Ayield vreturnsvand records where to resume; the end of the body, areturnand an exception leaving it finish the generator. - What consumes a frame. A
for, a comprehension, andlist,sorted,sum,min,max,set,any,allorjoinof it, each resuming it until it finishes. An exception it raises leaves through the consumer's handlers. Abreakleaves it suspended; a later loop over the same frame resumes it where it stopped, as CPython's does. - How the rest of the program sees a frame. The repr is CPython's,
<generator object g at 0x…>, with this runtime's address (A179).==and hashing are identity, as CPython's. It has no attribute a program can read.copy.copyandcopy.deepcopyof one are refused, where the compiler sees the frame, and stop the program where it does not, as a file's copy does (CPython raisesTypeError: cannot pickle 'generator' object). - What a frame does not do yet is listed on the compatibility page. Two of those items wait on more than work:
next()raisesStopIteration, which PEP 479 turns intoRuntimeErroras it leaves a generator. A generator written into its consumer has no edge to turn it at. Ayieldinside atryor awithneeds itsfinallyor__exit__run when a suspended frame is dropped.
Consequences¶
- A module whose generators are all inlined compiles to the IR it compiled to before: a machine is lowered only when a lowered function calls it.
- A frame costs a heap allocation per call and a dispatch per value. A recursion
ddeep passes each value up throughdframes, as CPython's nestedfor/yielddoes. - Designing this found three defects in the inlining it keeps, each fixed: a proven loop read a list the consumer had cleared (
notes/accept-then-wrong.md§76); a name the generator bound inside a block was not renamed apart from the consumer's (§77); and ayieldbefore a loop made the loop's bound undominated, which crashed the verifier.
Alternatives considered¶
- The consumer's body as a callback the generator calls at each
yield, for a recursive generator consumed in place: smaller, but a second partial mechanism, with mutable captures and a stop flag forbreak; it has no answer for a held generator. - The frame's fields from the source's locals: misses the values the lowering itself keeps across a
yield: a generator suspended inside a loop keeps its place in them. - Every generator as a state machine: an allocation per call where the inlining is exact and free.