Skip to content

A block whose only statement is a let drops that value at the end of the function, not the block (§2.4) #1851

Closed

Description

@ehartford

Spec

§2.4 (drop points): a value is dropped at the end of the scope that owns it; a { ... } block is a scope.

Repro

type Tok:
    n: i32

impl Drop for Tok:
    move fn drop(): print(f"drop {self.n}")

fn main:
    {
        let t = Tok { n: 1 }
    }
    print("end")

with run --debug-alloc (installed main, and fix-globals stage1): prints end then drop 1. Expected drop 1 then end.

A block with a statement after the let drops on time ({ let u = Tok { n: 2 }; print("in") } prints in, drop 2 before the code after it), and so does an if body holding only a let.

Evidence

check --dump-mir, main:

bb0: {
    StorageLive(_1);
    _2 = aggregate(kind=0, variant=0, fields=[const 1ty3]);
    _1 = move _2;
    _2 = const zst(ty239);
    _3 = const "sym388";
    ...call print...
}
bb1: {
    drop(_3) @ drop#6 scope-exit _3;
    drop(_1) @ drop#7 scope-exit _1;
    return;
}

t (_1) is scheduled at main's scope exit: the block's scope never closes, so its only binding lives to the end of the function. A Drop with an effect (a lock guard, a file, a global write) runs late.

Found while fixing #1847. Not yet located at the line (parser shape vs MirLower scope close).

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions