Skip to content

Closures that assign a captured variable: str capture segfaults, i32 capture's mutation is lost (§15.9) #1486

Closed

Description

@ehartford

Found while testing D60 closure tails; the store is a statement here, so D60 does not change it. Reproduced on origin/main 5848ae9 (stage1 built from it); the D60 branch behaves the same.

A non-escaping closure argument that assigns a captured str crashes the program:

fn compute(s: &str): s.clone() ++ "!"
fn run_unit(f: fn() -> Unit): f()
fn main:
    var c = "".clone()
    run_unit(() => c = compute("x"))
    print(c)

with build succeeds; the binary exits 139 (SIGSEGV) before printing. run_unit(() => { c = compute("x") }) is the same.

A closure that mutates a captured i32 does not write it back:

fn run_unit(f: fn() -> Unit): f()
fn main:
    var n = 1
    run_unit(() => n += 1)
    print(n)          // 1
    let g = () => n += 5
    g()
    print(n)          // 1

Expected 2 and 7: a closure that mutates a captured place mutates that place (§15.9 rejects only the escaping case). Checked without error, so the mutation is silently lost.

Activity

  1. ehartford commented on Sep 23, 2026

    @ehartford
    ContributorAuthor

    The str half (segfault) is fixed in #1584 (stacked on #1583): the drop of a by-place capture freed the closure's pointer slot instead of the captured place. Matrix, fixture and nine new drop-audit cells in the PR.

    The i32 half is stopped for a ruling. §12.4 says both "For Copy values, default capture copies the value" and "if a closure consumes, mutates, returns, or returns a view derived from a capture, those effects apply to the originating captured place." For run_unit(() => n += 1) these disagree: the first makes n a snapshot (today: n stays 1, the write is silently lost — no diagnostic), the second writes it back (this issue's expectation, 2 and 7). The spec's example covers only a read (let g = || n + 1 … n remains unchanged). Question: is an assigned Copy capture by place or by copy? If by copy, the silent lost write still needs a diagnostic.

  2. ehartford commented on Sep 23, 2026

    @ehartford
    ContributorAuthor

    i32 half implemented per the §12.4 decision (a Copy capture is a copy; a write to it is now a compile error with the declare-inside / non-Copy-cell fix-it): PR #1584 (squashed with the str half). The spelling gap is filed as #1586.

  3. ehartford commented on Sep 26, 2026

    @ehartford
    ContributorAuthor

    Verified fixed on main 55739d4 (release binary): str capture x! leak 0; i32 capture 2 then 7.

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