Skip to content

Sema: a non-move closure stored into an outer container is a view of a loop-scoped local that outlives it — fs.push(() => n * 10) compiles and prints the last iteration (§12.4 captures are by place) #1594

Closed

Description

@ehartford

Found while implementing Eric's §12.4 ruling ("Captures are by place regardless of whether the type is Copy") in stack #1585 (branch fix-1481-let-bound-by-place, stage1).

Under the ruling #1471's original repro is a view escape, not a copy bug: the closure holds n (a per-iteration local) by place and fs — a container declared outside the loop — keeps it after n dies. Sema accepts it silently and the program prints the last iteration's value (all three closures point at one stack slot):

fn main:
    var fs: Vec[fn() -> i32] = Vec.new()
    for i in 0..3:
        let n = i
        fs.push(() => n * 10)      // view of n stored into fs, which outlives n
    for k in 0..3: print(fs[k]())  // 20 20 20, expected a compile error

Capturing the for binding directly (fs.push(() => i * 10)) is the same. The correct spelling is fs.push(move () => n * 10) (§12.4: "move || transfers ownership, which for a Copy value is a copy"), which test/behavior/behav_closure_loop_env_per_iteration.w pins.

What exists: a non-move closure's captures are recorded as view origins (EFF_CAPTURE_BY_PLACE, collect_expr_view_deps), and let f = () => n + 1; n = 5; f() is rejected as a live view (test/compile_errors/err_closure_copy_capture_mutated_while_live.w). The #625 viral-escape rule (Vec.push / HashMap.insert adding the pushed element's origins to the container binding via add_binding_view_deps) should make fs depend on n, and the end of the iteration (n's scope pop → check_live_views_for_origin(n)) should then report "view 'fs' may outlive its origin 'n'". It does not fire: either the push path does not add a closure argument's deps, or binding_has_active_borrow_from(fs, n) finds no borrow record for a dep added by a store. Same for a closure stored in a struct field or returned inside a container.

Expected: a compile error at the push naming n, with the move () => ... fix-it. Not fixed in #1585.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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