Skip to content

Sema: a closure passed as a direct argument is non-escaping even when the callee stores or returns it — its non-Copy captures are pointers into the caller's frame (§12.1–§12.3) #1566

Closed

Description

@ehartford

Found while fixing #1471 (closure environments in loops).

check_closure classifies a closure as non-escaping when it is a direct call argument and the receiving parameter carries no EFF_ESCAPE_VALUE/EFF_ESCAPE_VIEW. A fn value is Copy (Sema.is_copy: TY_FN → 1), so a plain f: fn() -> i32 parameter never records an escape effect, and every closure argument is non-escaping — including one the callee stores or returns. Non-escaping closures capture non-Copy values by place (a pointer to the outer slot, gen_closure can_capture_by_ref), so the stored closure keeps a pointer into a frame slot that may already be dead.

All three compile and run with with check silent (origin/main f1e3bd2, stage1):

fn keep(f: fn() -> i32) -> fn() -> i32: f
fn main:
    let s = "ab".clone()
    let g = keep(() => s.len() as i32)   // returned: escaping by §12.2
    print(s)                             // s was captured by place, not moved
    print(g())
fn main:
    var fs: Vec[fn() -> i32] = Vec.new()
    let s = "ab".clone()
    fs.push(() => s.len() as i32)        // stored: escaping by §12.2
    print(s)
fn main:
    var fs: Vec[fn() -> i32] = Vec.new()
    for i in 0..3:
        let s = "ab".clone()
        fs.push(() => s.len() as i32 + i)   // pointer to this iteration's `s` slot
    for k in 0..3: print(fs[k]())            // reads a dropped str (prints 2 2 2 by luck)

§12.2: "A closure is escaping if stored, returned, or sent to another thread. Escaping closures may NOT capture ephemeral values." §12.3 makes a direct argument non-escaping — the spec's model puts the burden on the callee: a fn-typed parameter that is stored or returned must be diagnosed (a by-place capture is a view). Neither side is checked today: the callee may store/return its fn parameter freely, and Vec.push (an intrinsic with no signature effects) stores its argument.

What is missing is a ruling on which side carries the check (callee's fn parameter escape, as with &T views, or the call site), then the check. The spec text for fn parameters escaping (§12) does not say. Not fixed in the #1471 stack; #1471's per-iteration environment does not depend on this classification.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions