Add tests for the drop behavior of some control flow constructs by Noratrieb · Pull Request #100526 · rust-lang/rust (original) (raw)

Conversation

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters

[ Show hidden characters]({{ revealButtonHref }})

Noratrieb

@rustbot rustbot added the T-compiler

Relevant to the compiler team, which will review and decide on the PR/issue.

label

Aug 14, 2022

5225225

@Noratrieb

In rust-lang#100513 it was shown that the drop behavior of let_chains is not correct currently. Since drop behavior is something pretty subtle, this adds explicit tests for the drop behavior of if, if let and match to make sure that it does not regress in the future.

The println!s were left in to make debugging easier in case something goes wrong, but they are not required for the test.

@bors bors added S-waiting-on-bors

Status: Waiting on bors to run and complete tests. Bors will change the label on completion.

and removed S-waiting-on-review

Status: Awaiting review from the assignee but also interested parties.

labels

Aug 14, 2022

bors added a commit to rust-lang-ci/rust that referenced this pull request

Aug 14, 2022

@bors

…iaskrgr

Rollup of 6 pull requests

Successful merges:

Failed merges:

r? @ghost @rustbot modify labels: rollup

@est31 est31 mentioned this pull request

Aug 22, 2022

Dylan-DPC added a commit to Dylan-DPC/rust that referenced this pull request

Oct 15, 2022

@Dylan-DPC

…r=eholk

Drop temporaries created in a condition, even if it's a let chain

Fixes rust-lang#100513.

During the lowering from AST to HIR we wrap expressions acting as conditions in a DropTemps expression so that any temporaries created in the condition are dropped after the condition is executed. Effectively this means we transform

if Some(1).is_some() { .. }

into (roughly)

if { let _t = Some(1).is_some(); _t } { .. }

so that if we create any temporaries, they're lifted into the new scope surrounding the condition, so for example something along the lines of

if { let temp = Some(1); let _t = temp.is_some(); _t }.

Before this PR, if the condition contained any let expressions we would not introduce that new scope, instead leaving the condition alone. This meant that in a let-chain like

if get_drop("first").is_some() && let None = get_drop("last") {
        println!("second");
} else { .. }

the temporary created for get_drop("first") would be lifted into the surrounding block, which caused it to be dropped after the execution of the entire if expression.

After this PR, we wrap everything but the let expression in terminating scopes. The upside to this solution is that it's minimally invasive, but the downside is that in the worst case, an expression with let exprs interspersed like

if get_drop("first").is_some()
    && let Some(_a) = get_drop("fifth")
    && get_drop("second").is_some()
    && let Some(_b) = get_drop("fourth") { .. }

gets multiple new scopes, roughly

if { let _t = get_drop("first").is_some(); _t }
    && let Some(_a) = get_drop("fifth")
    && { let _t = get_drop("second").is_some(); _t }
    && let Some(_b) = get_drop("fourth") { .. }

so instead of all of the temporaries being dropped at the end of the entire condition, they will be dropped right after they're evaluated (before the subsequent let expr). So while I'd say the drop behavior around let-chains is less surprising after this PR, it still might not exactly match what people might expect.

For tests, I've just extended the drop order tests added in rust-lang#100526. I'm not sure if that's the best way to go about it, though, so suggestions are welcome.

@est31 est31 mentioned this pull request

Oct 16, 2022

@est31 est31 mentioned this pull request

Nov 10, 2024

9 tasks

bors added a commit to rust-lang-ci/rust that referenced this pull request

Apr 22, 2025

@bors

Stabilize let chains in the 2024 edition

Stabilization report

This proposes the stabilization of let_chains (tracking issue, RFC 2497) in the 2024 edition of Rust.

What is being stabilized

The ability to &&-chain let statements inside if and while is being stabilized, allowing intermixture with boolean expressions. The patterns inside the let sub-expressions can be irrefutable or refutable.

struct FnCall<'a> {
    fn_name: &'a str,
    args: Vec<i32>,
}

fn is_legal_ident(s: &str) -> bool {
    s.chars()
        .all(|c| ('a'..='z').contains(&c) || ('A'..='Z').contains(&c))
}

impl<'a> FnCall<'a> {
    fn parse(s: &'a str) -> Option<Self> {
        if let Some((fn_name, after_name)) = s.split_once("(")
            && !fn_name.is_empty()
            && is_legal_ident(fn_name)
            && let Some((args_str, "")) = after_name.rsplit_once(")")
        {
            let args = args_str
                .split(',')
                .map(|arg| arg.parse())
                .collect::<Result<Vec<_>, _>>();
            args.ok().map(|args| FnCall { fn_name, args })
        } else {
            None
        }
    }
    fn exec(&self) -> Option<i32> {
        let iter = self.args.iter().copied();
        match self.fn_name {
            "sum" => Some(iter.sum()),
            "max" => iter.max(),
            "min" => iter.min(),
            _ => None,
        }
    }
}

fn main() {
    println!("{:?}", FnCall::parse("sum(1,2,3)").unwrap().exec());
    println!("{:?}", FnCall::parse("max(4,5)").unwrap().exec());
}

The feature will only be stabilized for the 2024 edition and future editions. Users of past editions will get an error with a hint to update the edition.

closes rust-lang#53667

Why 2024 edition?

Rust generally tries to ship new features to all editions. So even the oldest editions receive the newest features. However, sometimes a feature requires a breaking change so much that offering the feature without the breaking change makes no sense. This occurs rarely, but has happened in the 2018 edition already with async and await syntax. It required an edition boundary in order for async/await to become keywords, and the entire feature foots on those keywords.

In the instance of let chains, the issue is the drop order of if let chains. If we want if let chains to be compatible with if let, drop order makes it hard for us to generate correct MIR. It would be strange to have different behaviour for if let ... {} and if true && let ... {}. So it's better to [stay consistent with if let].

In edition 2024, [drop order changes] have been introduced to make if let temporaries be lived more shortly. These changes also affected if let chains. These changes make sense even if you don't take the if let chains MIR generation problem into account. But if we want to use them as the solution to the MIR generation problem, we need to restrict let chains to edition 2024 and beyond: for let chains, it's not just a change towards more sensible behaviour, but one required for correct function.

[stay consistent with if let]: rust-lang#103293 (comment) [drop order changes]: rust-lang#124085

Introduction considerations

As edition 2024 is very new, this stabilization PR only makes it possible to use let chains on 2024 without that feature gate, it doesn't mark that feature gate as stable/removed. I would propose to continue offering the let_chains feature (behind a feature gate) for a limited time (maybe 3 months after stabilization?) on older editions to allow nightly users to adopt edition 2024 at their own pace. After that, the feature gate shall be marked as stabilized, not removed, and replaced by an error on editions 2021 and below.

Implementation history

Adoption history

In the compiler

Outside of the compiler

Tests

Intentional restrictions

partially-macro-expanded.rs, macro-expanded.rs: it is possible to use macros to expand to both the pattern and the expression inside a let chain, but not to the entire let pat = expr operand. parens.rs: if (let pat = expr) is not allowed in chains ensure-that-let-else-does-not-interact-with-let-chains.rs: let...else doesn't support chaining.

Overlap with match guards

move-guard-if-let-chain.rs: test for the use moved value error working well in match guards. could maybe be extended with let chains that have more than one let shadowing.rs: shadowing in if let guards works as expected ast-validate-guards.rs: let chains in match guards require the match guards feature gate

Simple cases from the early days

PR rust-lang#88642 has added some tests with very simple usages of let else, mostly as regression tests to early bugs.

then-else-blocks.rs ast-lowering-does-not-wrap-let-chains.rs issue-90722.rs issue-92145.rs

Drop order/MIR scoping tests

issue-100276.rs: let expressions on RHS aren't terminating scopes drop_order.rs: exhaustive temporary drop order test for various Rust constructs, including let chains scope.rs: match guard scoping test drop-scope.rs: another match guard scoping test, ensuring that temporaries in if-let guards live for the arm drop_order_if_let_rescope.rs: if let rescoping on edition 2024, including chains mir_let_chains_drop_order.rs: comprehensive drop order test for let chains, distinguishes editions 2021 and 2024. issue-99938.rs, issue-99852.rs both bad MIR ICEs fixed by rust-lang#102394

Linting

irrefutable-lets.rs: trailing and leading irrefutable let patterns get linted for, others don't. The lint is turned off for else if. issue-121070-let-range.rs: regression test for false positive of the unused parens lint, precedence requires the ()s here

Parser: intentional restrictions

disallowed-positions.rs: let in expression context is rejected everywhere except at the top level invalid-let-in-a-valid-let-context.rs: nested let is not allowed (let's are no legal expressions just because they are allowed in if and while).

Parser: recovery

issue-103381.rs: Graceful recovery of incorrect chaining of if and if let semi-in-let-chain.rs: Ensure that stray ;s in let chains give nice errors (if_chain! users might be accustomed to ;s) deli-ident-issue-1.rs, brace-in-let-chain.rs: Ensure that stray unclosed {s in let chains give nice errors and hints

Misc

conflicting_bindings.rs: the conflicting bindings check also works in let chains. Personally, I'd extend it to chains with multiple let's as well. let-chains-attr.rs: attributes work on let chains

Tangential tests with #![feature(let_chains)]

if-let.rs: MC/DC coverage tests for let chains logical_or_in_conditional.rs: not really about let chains, more about dropping/scoping behaviour of || stringify.rs: exhaustive test of the stringify macro expanded-interpolation.rs, expanded-exhaustive.rs: Exhaustive test of -Zunpretty diverges-not.rs: Never type, mostly tangential to let chains

Possible future work

Open questions / blockers

github-actions bot pushed a commit to rust-lang/miri that referenced this pull request

Apr 23, 2025

@bors

Stabilize let chains in the 2024 edition

Stabilization report

This proposes the stabilization of let_chains (tracking issue, RFC 2497) in the 2024 edition of Rust.

What is being stabilized

The ability to &&-chain let statements inside if and while is being stabilized, allowing intermixture with boolean expressions. The patterns inside the let sub-expressions can be irrefutable or refutable.

struct FnCall<'a> {
    fn_name: &'a str,
    args: Vec<i32>,
}

fn is_legal_ident(s: &str) -> bool {
    s.chars()
        .all(|c| ('a'..='z').contains(&c) || ('A'..='Z').contains(&c))
}

impl<'a> FnCall<'a> {
    fn parse(s: &'a str) -> Option<Self> {
        if let Some((fn_name, after_name)) = s.split_once("(")
            && !fn_name.is_empty()
            && is_legal_ident(fn_name)
            && let Some((args_str, "")) = after_name.rsplit_once(")")
        {
            let args = args_str
                .split(',')
                .map(|arg| arg.parse())
                .collect::<Result<Vec<_>, _>>();
            args.ok().map(|args| FnCall { fn_name, args })
        } else {
            None
        }
    }
    fn exec(&self) -> Option<i32> {
        let iter = self.args.iter().copied();
        match self.fn_name {
            "sum" => Some(iter.sum()),
            "max" => iter.max(),
            "min" => iter.min(),
            _ => None,
        }
    }
}

fn main() {
    println!("{:?}", FnCall::parse("sum(1,2,3)").unwrap().exec());
    println!("{:?}", FnCall::parse("max(4,5)").unwrap().exec());
}

The feature will only be stabilized for the 2024 edition and future editions. Users of past editions will get an error with a hint to update the edition.

closes #53667

Why 2024 edition?

Rust generally tries to ship new features to all editions. So even the oldest editions receive the newest features. However, sometimes a feature requires a breaking change so much that offering the feature without the breaking change makes no sense. This occurs rarely, but has happened in the 2018 edition already with async and await syntax. It required an edition boundary in order for async/await to become keywords, and the entire feature foots on those keywords.

In the instance of let chains, the issue is the drop order of if let chains. If we want if let chains to be compatible with if let, drop order makes it hard for us to generate correct MIR. It would be strange to have different behaviour for if let ... {} and if true && let ... {}. So it's better to [stay consistent with if let].

In edition 2024, [drop order changes] have been introduced to make if let temporaries be lived more shortly. These changes also affected if let chains. These changes make sense even if you don't take the if let chains MIR generation problem into account. But if we want to use them as the solution to the MIR generation problem, we need to restrict let chains to edition 2024 and beyond: for let chains, it's not just a change towards more sensible behaviour, but one required for correct function.

[stay consistent with if let]: rust-lang/rust#103293 (comment) [drop order changes]: rust-lang/rust#124085

Introduction considerations

As edition 2024 is very new, this stabilization PR only makes it possible to use let chains on 2024 without that feature gate, it doesn't mark that feature gate as stable/removed. I would propose to continue offering the let_chains feature (behind a feature gate) for a limited time (maybe 3 months after stabilization?) on older editions to allow nightly users to adopt edition 2024 at their own pace. After that, the feature gate shall be marked as stabilized, not removed, and replaced by an error on editions 2021 and below.

Implementation history

Adoption history

In the compiler

Outside of the compiler

Tests

Intentional restrictions

partially-macro-expanded.rs, macro-expanded.rs: it is possible to use macros to expand to both the pattern and the expression inside a let chain, but not to the entire let pat = expr operand. parens.rs: if (let pat = expr) is not allowed in chains ensure-that-let-else-does-not-interact-with-let-chains.rs: let...else doesn't support chaining.

Overlap with match guards

move-guard-if-let-chain.rs: test for the use moved value error working well in match guards. could maybe be extended with let chains that have more than one let shadowing.rs: shadowing in if let guards works as expected ast-validate-guards.rs: let chains in match guards require the match guards feature gate

Simple cases from the early days

PR #88642 has added some tests with very simple usages of let else, mostly as regression tests to early bugs.

then-else-blocks.rs ast-lowering-does-not-wrap-let-chains.rs issue-90722.rs issue-92145.rs

Drop order/MIR scoping tests

issue-100276.rs: let expressions on RHS aren't terminating scopes drop_order.rs: exhaustive temporary drop order test for various Rust constructs, including let chains scope.rs: match guard scoping test drop-scope.rs: another match guard scoping test, ensuring that temporaries in if-let guards live for the arm drop_order_if_let_rescope.rs: if let rescoping on edition 2024, including chains mir_let_chains_drop_order.rs: comprehensive drop order test for let chains, distinguishes editions 2021 and 2024. issue-99938.rs, issue-99852.rs both bad MIR ICEs fixed by #102394

Linting

irrefutable-lets.rs: trailing and leading irrefutable let patterns get linted for, others don't. The lint is turned off for else if. issue-121070-let-range.rs: regression test for false positive of the unused parens lint, precedence requires the ()s here

Parser: intentional restrictions

disallowed-positions.rs: let in expression context is rejected everywhere except at the top level invalid-let-in-a-valid-let-context.rs: nested let is not allowed (let's are no legal expressions just because they are allowed in if and while).

Parser: recovery

issue-103381.rs: Graceful recovery of incorrect chaining of if and if let semi-in-let-chain.rs: Ensure that stray ;s in let chains give nice errors (if_chain! users might be accustomed to ;s) deli-ident-issue-1.rs, brace-in-let-chain.rs: Ensure that stray unclosed {s in let chains give nice errors and hints

Misc

conflicting_bindings.rs: the conflicting bindings check also works in let chains. Personally, I'd extend it to chains with multiple let's as well. let-chains-attr.rs: attributes work on let chains

Tangential tests with #![feature(let_chains)]

if-let.rs: MC/DC coverage tests for let chains logical_or_in_conditional.rs: not really about let chains, more about dropping/scoping behaviour of || stringify.rs: exhaustive test of the stringify macro expanded-interpolation.rs, expanded-exhaustive.rs: Exhaustive test of -Zunpretty diverges-not.rs: Never type, mostly tangential to let chains

Possible future work

Open questions / blockers

github-actions bot pushed a commit to rust-lang/rustc-dev-guide that referenced this pull request

Apr 24, 2025

@bors

Stabilize let chains in the 2024 edition

Stabilization report

This proposes the stabilization of let_chains (tracking issue, RFC 2497) in the 2024 edition of Rust.

What is being stabilized

The ability to &&-chain let statements inside if and while is being stabilized, allowing intermixture with boolean expressions. The patterns inside the let sub-expressions can be irrefutable or refutable.

struct FnCall<'a> {
    fn_name: &'a str,
    args: Vec<i32>,
}

fn is_legal_ident(s: &str) -> bool {
    s.chars()
        .all(|c| ('a'..='z').contains(&c) || ('A'..='Z').contains(&c))
}

impl<'a> FnCall<'a> {
    fn parse(s: &'a str) -> Option<Self> {
        if let Some((fn_name, after_name)) = s.split_once("(")
            && !fn_name.is_empty()
            && is_legal_ident(fn_name)
            && let Some((args_str, "")) = after_name.rsplit_once(")")
        {
            let args = args_str
                .split(',')
                .map(|arg| arg.parse())
                .collect::<Result<Vec<_>, _>>();
            args.ok().map(|args| FnCall { fn_name, args })
        } else {
            None
        }
    }
    fn exec(&self) -> Option<i32> {
        let iter = self.args.iter().copied();
        match self.fn_name {
            "sum" => Some(iter.sum()),
            "max" => iter.max(),
            "min" => iter.min(),
            _ => None,
        }
    }
}

fn main() {
    println!("{:?}", FnCall::parse("sum(1,2,3)").unwrap().exec());
    println!("{:?}", FnCall::parse("max(4,5)").unwrap().exec());
}

The feature will only be stabilized for the 2024 edition and future editions. Users of past editions will get an error with a hint to update the edition.

closes #53667

Why 2024 edition?

Rust generally tries to ship new features to all editions. So even the oldest editions receive the newest features. However, sometimes a feature requires a breaking change so much that offering the feature without the breaking change makes no sense. This occurs rarely, but has happened in the 2018 edition already with async and await syntax. It required an edition boundary in order for async/await to become keywords, and the entire feature foots on those keywords.

In the instance of let chains, the issue is the drop order of if let chains. If we want if let chains to be compatible with if let, drop order makes it hard for us to generate correct MIR. It would be strange to have different behaviour for if let ... {} and if true && let ... {}. So it's better to [stay consistent with if let].

In edition 2024, [drop order changes] have been introduced to make if let temporaries be lived more shortly. These changes also affected if let chains. These changes make sense even if you don't take the if let chains MIR generation problem into account. But if we want to use them as the solution to the MIR generation problem, we need to restrict let chains to edition 2024 and beyond: for let chains, it's not just a change towards more sensible behaviour, but one required for correct function.

[stay consistent with if let]: rust-lang/rust#103293 (comment) [drop order changes]: rust-lang/rust#124085

Introduction considerations

As edition 2024 is very new, this stabilization PR only makes it possible to use let chains on 2024 without that feature gate, it doesn't mark that feature gate as stable/removed. I would propose to continue offering the let_chains feature (behind a feature gate) for a limited time (maybe 3 months after stabilization?) on older editions to allow nightly users to adopt edition 2024 at their own pace. After that, the feature gate shall be marked as stabilized, not removed, and replaced by an error on editions 2021 and below.

Implementation history

Adoption history

In the compiler

Outside of the compiler

Tests

Intentional restrictions

partially-macro-expanded.rs, macro-expanded.rs: it is possible to use macros to expand to both the pattern and the expression inside a let chain, but not to the entire let pat = expr operand. parens.rs: if (let pat = expr) is not allowed in chains ensure-that-let-else-does-not-interact-with-let-chains.rs: let...else doesn't support chaining.

Overlap with match guards

move-guard-if-let-chain.rs: test for the use moved value error working well in match guards. could maybe be extended with let chains that have more than one let shadowing.rs: shadowing in if let guards works as expected ast-validate-guards.rs: let chains in match guards require the match guards feature gate

Simple cases from the early days

PR #88642 has added some tests with very simple usages of let else, mostly as regression tests to early bugs.

then-else-blocks.rs ast-lowering-does-not-wrap-let-chains.rs issue-90722.rs issue-92145.rs

Drop order/MIR scoping tests

issue-100276.rs: let expressions on RHS aren't terminating scopes drop_order.rs: exhaustive temporary drop order test for various Rust constructs, including let chains scope.rs: match guard scoping test drop-scope.rs: another match guard scoping test, ensuring that temporaries in if-let guards live for the arm drop_order_if_let_rescope.rs: if let rescoping on edition 2024, including chains mir_let_chains_drop_order.rs: comprehensive drop order test for let chains, distinguishes editions 2021 and 2024. issue-99938.rs, issue-99852.rs both bad MIR ICEs fixed by #102394

Linting

irrefutable-lets.rs: trailing and leading irrefutable let patterns get linted for, others don't. The lint is turned off for else if. issue-121070-let-range.rs: regression test for false positive of the unused parens lint, precedence requires the ()s here

Parser: intentional restrictions

disallowed-positions.rs: let in expression context is rejected everywhere except at the top level invalid-let-in-a-valid-let-context.rs: nested let is not allowed (let's are no legal expressions just because they are allowed in if and while).

Parser: recovery

issue-103381.rs: Graceful recovery of incorrect chaining of if and if let semi-in-let-chain.rs: Ensure that stray ;s in let chains give nice errors (if_chain! users might be accustomed to ;s) deli-ident-issue-1.rs, brace-in-let-chain.rs: Ensure that stray unclosed {s in let chains give nice errors and hints

Misc

conflicting_bindings.rs: the conflicting bindings check also works in let chains. Personally, I'd extend it to chains with multiple let's as well. let-chains-attr.rs: attributes work on let chains

Tangential tests with #![feature(let_chains)]

if-let.rs: MC/DC coverage tests for let chains logical_or_in_conditional.rs: not really about let chains, more about dropping/scoping behaviour of || stringify.rs: exhaustive test of the stringify macro expanded-interpolation.rs, expanded-exhaustive.rs: Exhaustive test of -Zunpretty diverges-not.rs: Never type, mostly tangential to let chains

Possible future work

Open questions / blockers