Skip to content

Sema/Codegen: every capture of a non-move closure is by place, Copy or not; a consuming call moves the capture out once (#1481, D62) - #1591

Merged
ehartford merged 1 commit into
fix-1486-closure-capture-assignfrom
fix-1481-let-bound-by-place
Sep 24, 2026
Merged

ehartford merged 1 commit into
fix-1486-closure-capture-assignfrom
fix-1481-let-bound-by-place

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Fixes #1481. Stacked on #1584 (base fix-1486-closure-capture-assign).

Spec §12.4: "For non-Copy values, default capture is by place: the closure observes or mutates the original place according to its body." / "Invoking a closure is checked exactly like invoking a function: if a closure consumes, mutates, returns, or returns a view derived from a capture, those effects apply to the originating captured place." — and its let-bound example let f = || xs.push(1); f() // mutates xs.

Root cause SemaCheck.check_closure treated every non-direct-argument closure as consuming its non-Copy captures at creation (MOVED + EFF_CONSUME), gen_closure copied the bytes into the environment (can_capture_by_ref only for non-escaping closures), MirLower saw no move, so main still dropped the original: let f: fn() -> str = () => c; print(f()) → debug-alloc DOUBLE FREE (both drops the str glue). The §15.9 error rejected the spec's own example.

Fix one rule for direct-argument and let-bound closures:

  • only move || consumes at creation; a non-move closure's non-Copy captures are EFF_CAPTURE_BY_PLACE in its summary and view origins of the binding holding it (collect_expr_view_deps / record_view_binding_from_expr), so existing container/view-liveness checks see them; §15.9 retired (return case is the next layer, A closure returned from a function reads its environment from the dead callee frame: fn mk(x: i32) -> fn() -> i32: () => x * 10 gives garbage once mk is not inlined (§12.2 escaping closures) #1567);
  • apply_closure_capture_consumes at every call (callable value, direct argument of a fn or method): a CONSUME/ESCAPE_VALUE capture effect moves the originating binding and spends the holder; a call on an already-moved capture is use of moved value 'c': calling this closure moves c out of its capture, and an earlier call already did;
  • MirLower keeps the scope-exit drop guard of a capture the body consumes (the body blanks the place through the pointer; Stage 4 had elided the guard, so a consumed Drop struct ran its destructor on the blanked place);
  • Codegen: can_capture_by_ref for every non-move closure.

Matrix (stage1 run --debug-alloc, leak 0): let-bound str-returning closure, one call (was DOUBLE FREE); second call rejected; binding use after the consuming call rejected; direct-arg consume of a str and of a Drop struct (destructor once); read-only let-bound closure called twice; xs.push through a let-bound closure mutates xs; direct-arg closure leaves r usable. Fixtures: behav_closure_let_bound_by_place.w, behav_closure_direct_arg_read_after.w, da_closure_consume_by_place_capture.w (debug_drop lane: all fixtures PASS), err_closure_consume_capture_twice.w, err_closure_consume_capture_then_use.w. Retired (old-rule expectations): capture_error.w, err_closure_capture_noncopy.w, err_escape_mutating_closure.w.

Audits three drop_audit cells added (closure_let_bound_assign, closure_consume_direct, closure_consume_let_bound; seed: COMPILE-FAIL / RUN-FAIL / DOUBLE-FREE, all FIXED): 188 cells, 0 non-PASS, 0 regressions vs seed; move_audit 73 cells, 0 failures; analyze audit:all clean; stage1 check src/main.w and build.w ok. Iterate tier only — no battery.

Not changed by-place capture sent to spawn_os unchecked (#974); direct-argument closure the callee stores still non-escaping (#1566).

@ehartford
ehartford added this pull request to stack #1585 September 23, 2026 23:35
@ehartford
ehartford force-pushed the fix-1481-let-bound-by-place branch from e5477a9 to aa7ce5e Compare September 24, 2026 03:24
@ehartford ehartford changed the title Sema/Codegen: a let-bound closure captures a non-Copy local by place; a consuming call moves it out once (#1481) Sema/Codegen: every capture of a non-move closure is by place, Copy or not; a consuming call moves the capture out once (#1481, D62) Sep 24, 2026
@ehartford

Copy link
Copy Markdown
Contributor Author

Reworked under D62 — §12.4: "Captures are by place regardless of whether the type is Copy; a read through a capture of a Copy value copies it. move || transfers ownership, which for a Copy value is a copy."

  • Copy captures take the same by-ref environment path and effect summaries as non-Copy ones; count += 1 in a non-move closure mutates the outer count; move || writes its own copy (behav_closure_copy_capture_modes.w, closure_ref_capture.w, behav_closure_move_copy_snapshot.w).
  • Exclusivity is the existing view-liveness rule: let f = () => n + 1; n = 5; f() → "cannot mutate n while f is a live view" (err_closure_copy_capture_mutated_while_live.w); reassigning after the closure's last use is fine.
  • A pointer-valued capture (&T, *mut T) now reads through its slot too (the audit's mk(2, slot) cells had received the outer slot's address).
  • Eric's note, recorded in the commit: let g = || take(xs) makes g a consuming view — callable once, and xs is still owned and dropped by the outer scope if g is never called; that is the intended behavior.

Evidence (stage1 vs pinned seed): closure/spawn/capture sweep clean; debug_alloc lane all PASS; probe matrix as intended; analyze audit:all 0 violations; drop-audit 188 cells, 0 non-PASS, 0 regressions (12 closure cells FIXED); move-audit 73 cells, 0 failures. Iterate tier only — no battery.

Filed, not fixed: #1594 (a non-move closure of a loop-scoped local stored into an outer container is not diagnosed as a view escape — #1471's non-move spelling now silently reads the last iteration; the fixture spells move), #1598 (a capture used only inside an unsafe block is not collected; pre-existing on the seed).

…r not; a let-bound closure holds its captures by place, a consuming call moves the capture out once (#1481)

Spec §12.4 (D62, Eric 2026-09-23): "Captures are by place regardless of
whether the type is Copy; a read through a capture of a Copy value
copies it. `move ||` transfers ownership, which for a Copy value is a
copy." And: "Invoking a closure is checked exactly like invoking a
function: if a closure consumes, mutates, returns, or returns a view
derived from a capture, those effects apply to the originating captured
place." — with the let-bound example `let f = || xs.push(1); f() //
mutates xs`. Eric's note: `let g = || take(xs)` makes `g` a consuming
view — callable once, and `xs` is still owned and dropped by the outer
scope if `g` is never called; that is the intended behavior.

Root cause: SemaCheck.check_closure treated every closure that is not a
direct argument as consuming its non-Copy captures at creation
("Escaping closures (including move closures) consume non-Copy
captures": scope_set_state MOVED + EFF_CONSUME), and gen_closure copied
the bytes into the environment (`can_capture_by_ref` only for
non-escaping closures) while MirLower never saw a move, so `main` still
dropped the original: `let f: fn() -> str = () => c; print(f())` freed
`c`'s buffer twice (debug-alloc DOUBLE FREE, first_drop and second_drop
both the str glue). Copy captures were value snapshots in every closure
(`() => n += 1` left `n` unchanged, #1486's i32 half). The §15.9 error
("closure that mutates captured place cannot escape its defining
scope") rejected the spec's own example.

Fix, one rule for direct-argument and let-bound closures, Copy or not:
- Sema: only `move ||` consumes at creation; every capture of a non-move
  closure is EFF_CAPTURE_BY_PLACE in its summary with its real effects,
  and is a view origin of the binding that holds it
  (collect_expr_view_deps / record_view_binding_from_expr), so the
  existing view-liveness and container checks see it: assigning `n`
  while `let f = () => n + 1` is still used is the ordinary "cannot
  mutate `n` while `f` is a live view" (exclusivity, no new machinery).
  Direct-argument closures register borrows for every capture. §15.9 is
  retired (the return case is #1567, next layer).
- Sema: apply_closure_capture_consumes runs at every call — a callable
  value, a direct argument of a function or a method — and applies a
  CONSUME/ESCAPE_VALUE capture effect to the originating place: the
  binding is MOVED, the holder binding is spent (marked first, since
  moving the place checks its live views), and a call on an
  already-moved capture is "use of moved value 'c': calling this closure
  moves `c` out of its capture, and an earlier call already did".
- MirLower: a capture the body consumes keeps its scope-exit drop guard
  (mark_local_ever_moved) — the body blanks the place through the
  capture pointer (reset-on-move), and Stage 4 had elided the guard for
  a local it never saw moved (a consumed Drop struct ran its destructor
  on the blanked place: the option cell of the audit crashed in R.drop).
- Codegen: `can_capture_by_ref` for every capture of every non-move
  closure. A capture whose value is itself a pointer (`&T`, `*mut T`)
  reads through its slot too (mir_ref_capture_local_types on the
  scalar-load and place-for-ref paths): with the slot read as the value,
  `mk(2, slot)` received the address of the outer `slot` as the slot.

Matrix (stage1 run --debug-alloc, leak count=0): let-bound closure
returning a str, single call (was DOUBLE FREE); second call rejected;
use of the binding after the consuming call rejected; direct-argument
consume of a str and of a Drop struct (destructor once); let-bound
read-only closure called twice; let-bound `xs.push` mutates xs; a
direct-argument closure leaves `r` usable after the call; `n = n + 1`
in a non-move closure writes the outer n (11), the same in `move ||`
writes its copy (outer 10); `count += 1` through a let-bound closure
twice → 2; `move () => n + 1` snapshots n across a later `n = 5`, the
non-move form is rejected as a live view. Fixtures:
behav_closure_let_bound_by_place.w, behav_closure_direct_arg_read_after.w,
behav_closure_copy_capture_modes.w (rewritten to the ruling),
closure_ref_capture.w (rewritten), behav_closure_capture_copy.w,
behav_closure_move_copy_snapshot.w, da_closure_consume_by_place_capture.w
(debug_drop lane: every fixture PASS), err_closure_consume_capture_twice.w,
err_closure_consume_capture_then_use.w,
err_closure_copy_capture_mutated_while_live.w. Retired, their
expectation was the old rule: capture_error.w,
err_closure_capture_noncopy.w (creation no longer moves),
err_escape_mutating_closure.w (the spec example). `analyze audit:all`:
violations=0; stage1 `check src/main.w`, build.w: ok.

Audit: three drop_audit cells added — closure_let_bound_assign,
closure_consume_direct, closure_consume_let_bound (seed: COMPILE-FAIL,
RUN-FAIL, DOUBLE-FREE; all FIXED). 188 cells, 0 non-PASS, 0 regressions.
move_audit: 73 cells, 0 vs-expected failures.

Not changed: a by-place capture sent to `spawn_os` is unchecked (#974);
a direct-argument closure the callee stores is still classified
non-escaping (#1566); a non-move closure of a loop-scoped local stored
into an outer container is not yet diagnosed as a view escape (#1594);
a capture used only inside an `unsafe` block is not collected (#1598).
@ehartford
ehartford force-pushed the fix-1481-let-bound-by-place branch from 71d756b to b473b91 Compare September 24, 2026 14:59
@ehartford
ehartford merged commit 8a1ca9d into main Sep 24, 2026
@ehartford
ehartford deleted the fix-1481-let-bound-by-place branch September 24, 2026 16:56
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.

A closure returning a captured non-Copy local by value double-frees it (§2.3)

1 participant