Support Python generators and yield from

Closed
JA
9d ago
+2002-75

Superseeded by #1435


Add lazy Python generator functions and yield from delegation to Monty's bytecode VM. Calling a generator function binds its arguments without running its body; next(), send(None), and for resume it until its next yield or completion.

def inner():
    yield 1
    return 42

def outer():
    result = yield from inner()
    yield result

g = outer()
assert next(g) == 1
assert next(g) == 42
assert next(g, None) is None

Execution and ownership

  • Store generators as HeapData::Generator behind the existing Value::Ref, with created, suspended, running, and completed states. Detect generator functions from yield or yield from in their own scope, including unreachable expressions.
  • Execute generator frames on the normal VM stack. A resumption boundary records whether a result goes to next(), for, or an outer generator's yield from.
  • Transfer the frame, locals, operand stack, namespace, and exception state between the VM and generator object. Reuse empty suspension buffers and resumption boundaries across yields.
  • Preserve generator return values through StopIteration.value, reject reentrant execution, and convert an uncaught StopIteration escaping a generator into RuntimeError.
  • Delegate to generators, builtin iterators, and custom iterators. Run custom __next__ methods on normal VM frames so they can suspend at host calls and return arbitrary StopIteration.value objects without losing identity.

Snapshots and resource limits

Serialize suspended frames inside generator objects and active frames with their resumption boundaries. This preserves shared heap references and restores nested delegation, including execution paused during a host call.

Generator references participate in reference counting and cycle collection. Active resumes enforce recursion limits; suspended frame storage remains visible to the existing allocator-backed memory accounting. The bytecode changes bump the dump version to 14 and add a matching compatibility fixture.

Scope and follow-up work

Dropping an unfinished generator releases its references without running pending finally blocks.
Host calls inside a Python __next__ method can suspend normally; assigning an external callable directly to __next__ is explicitly rejected before calling it.

  • Support non-None values in send().
  • Implement throw() and close(), including finalization behavior.
  • Let synchronous consumers (list(), tuple(), sum(), enumerate(), and itertools adaptors) advance generators.
  • Support an external callable assigned directly to a custom iterator's __next__.
  • Preserve the original escaped StopIteration as RuntimeError.__cause__ when exception chaining is implemented.
  • Implement lazy generator expressions.
  • Implement async generators.
  • Expose generator frame attributes (gi_frame, gi_code, gi_running, gi_yieldfrom).

Validation

  • Full monty test suite with memory-model-checks,ref-count-return, including 41 generator tests.
  • Generator coverage includes lazy creation, independent locals, loops, nested delegation, return-value identity, exceptions, reentrancy, closures, suspended and active snapshots, reference cleanup, GC cycles, recursion limits, and execution time limits.
  • Subprocess memory-limit test covers both suspended generators and suspended delegation chains, including session recovery after MemoryError.
  • Clippy with warnings denied, import checks, and git diff --check.