Skip to content

An ephemeral value a generator yields from its own frame cannot leave the loop body - #3608

Merged
ehartford merged 1 commit into
mainfrom
gen-ephemeral-origin
Nov 25, 2026
Merged

ehartford merged 1 commit into
mainfrom
gen-ephemeral-origin

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

A soundness hole, found while building D216 (#2425).

The hole. Safe code could carry a view of a generator's frame out of the loop that runs the generator:

enum E ephemeral:
    Key(&K)
    Other(i64)

gen fn each() -> E:
    var k = K { code: 1 }
    yield E.Key(&k)

fn first() -> E:
    for e in each():
        return e          // a view of each()'s local, which is gone
    panic("none")

This compiled and ran. So did assigning e to a variable outside the loop and pushing it into a list read after the loop. With a plain &K element the same programs were already refused ("returned view may outlive its origin 'e'"); only an ephemeral value (a struct or a sum holding the view) got through.

Root cause. check_for gives an ephemeral loop binding its origins from the iterated expression (record_for_binding_view_origins). For a generator call that is the call's arguments, or nothing: the generator's own frame is not among them, so the binding depended on nothing that dies.

The fix. D69 (§13.4) already says it: a yielded view, "of the generator's own locals included, is an argument borrowed for that call, never retained past it". When the generator yields a view of its own frame (the fact note_generator_local_view_yield records for the pull rule; the generator's body is checked first if it has not been), the loop binding is itself an origin: a local of the body.

What stays accepted. Using the value in the body, and returning or keeping a yielded value that views only what the caller passed in (gen fn items(xs: &List[K]) -> V yielding V { k: x }).

This changes what safe code may do, by closing a hole: a program that kept such a value compiled before and held a dangling view. Flagged for your veto as a checker change.

Tests: err_gen_yielded_ephemeral_returned, _kept_in_list, _assigned_outward, _param_and_frame (consumer declared before the generator; a parameter and the frame both yielded), and behav_gen_yielded_ephemeral_in_body. The four fail on main.

Evidence at 3ca31f6: both compilers check the source; release build; :unit-return-review, :ceremony-census, :self-audit, :native-compile-error-tests, :behavior-tests green; battery green; :release-checks survey: all targets green (the corpora compile under the stricter rule).

… the loop body: the loop binding is its origin
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