rust-lang / rust-lang/rust

drop-checking is more permissive when patterns have guards

Open
#142,057 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-MIR C-bug I-lang-radar T-compiler T-lang
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

When pattern bindings are lowered to MIR, they're dropped in reverse-order of declaration (with some caveats when or-patterns are involved). However, by-ref bindings are created eagerly before anything else if guards are present, so that they can be used in guards (#49870). Because that affects the order in which drops are scheduled, this difference is observable through the drop check (playground link):

struct Struct<T>(T);
impl<T> Drop for Struct<T> {
    fn drop(&mut self) {}
}

fn main() {
    // This is an error: `short1` is dead before `long1` is dropped.
    match (Struct(&&0), 1) {
        (mut long1, ref short1) => long1.0 = &short1,
    }
    // This is OK: `short2`'s storage is live until after `long2`'s drop runs.
    match (Struct(&&0), 1) {
        (mut long2, ref short2) if true => long2.0 = &short2,
        _ => unreachable!(),
    }
}

Related: #142056

cc @rust-lang/lang since if this needs fixing it'll involve changing what programs are allowed. I imagine that needs a T-lang decision?

@rustbot label: +T-compiler +T-lang +A-MIR

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the MIR lowering behavior described in the issue and reproduce both examples using the linked Rust Playground. Compare drop scheduling for guarded and unguarded patterns, then read related issue #142056 and the discussion around the required T-lang decision. Done requires an agreed resolution for the language behavior and corresponding compiler changes or documentation of the decision.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.