Skip to content

Detect incorrect chaining of if and if let conditions and recover #103405

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 18, 2022

Conversation

chenyukang
Copy link
Member

Fixes #103381

@rustbot rustbot added A-translation Area: Translation infrastructure, and migrating existing diagnostics to SessionDiagnostic T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Oct 22, 2022
@rust-highfive
Copy link
Contributor

r? @petrochenkov

(rust-highfive has picked a reviewer for you, use r? to override)

@rustbot
Copy link
Collaborator

rustbot commented Oct 22, 2022

rustc_error_messages was changed

cc @davidtwco, @compiler-errors, @JohnTitor, @estebank, @TaKO8Ki

@rust-highfive rust-highfive added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Oct 22, 2022
@chenyukang
Copy link
Member Author

r? @estebank

@rust-log-analyzer

This comment has been minimized.

Copy link
Member

@compiler-errors compiler-errors left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This breaks existing code -- if expressions are allowed to be their own conditions within other if statements.

fn main() {
    if true && if let 1 = 1 { true } else { true } {}
}

Before this PR: compiles

After this PR:

error: unexpected `if` in the condition expression
 --> /home/gh-compiler-errors/test.rs:2:16
  |
2 |     if true && if let 1 = 1 { true } else { true } {}
  |                ^^^
  |
help: remove the `if`
  |
2 -     if true && if let 1 = 1 { true } else { true } {}
2 +     if true && let 1 = 1 { true } else { true } {}
  |

error[E0658]: `let` expressions in this position are unstable
 --> /home/gh-compiler-errors/test.rs:2:19
  |
2 |     if true && if let 1 = 1 { true } else { true } {}
  |                   ^^^^^^^^^
  |
  = note: see issue #53667 <https://github.com/rust-lang/rust/issues/53667> for more information
  = help: add `#![feature(let_chains)]` to the crate attributes to enable

error[E0308]: mismatched types
 --> /home/gh-compiler-errors/test.rs:2:31
  |
2 |     if true && if let 1 = 1 { true } else { true } {}
  |     --------------------------^^^^----------------
  |     |                         |
  |     |                         expected `()`, found `bool`
  |     expected this to be `()`

error[E0308]: mismatched types
 --> /home/gh-compiler-errors/test.rs:2:45
  |
2 |     if true && if let 1 = 1 { true } else { true } {}
  |     ----------------------------------------^^^^--
  |     |                                       |
  |     |                                       expected `()`, found `bool`
  |     expected this to be `()`

error: aborting due to 4 previous errors

Some errors have detailed explanations: E0308, E0658.
For more information about an error, try `rustc --explain E0308`.

@chenyukang
Copy link
Member Author

chenyukang commented Oct 23, 2022

This breaks existing code -- if expressions are allowed to be their own conditions within other if statements.

This code will also compile in current compiler:

fn should_ok() {
    if true && if let x = 1 { true } else { true } {}
}

With this warning:

warning: irrefutable `if let` pattern
  --> /home/cat/code/rust/src/test/ui/parser/issue-103381.rs:13:19
   |
13 |     if true && if let x = 1 { true } else { true } {}
   |                   ^^^^^^^^^
   |
   = note: `#[warn(irrefutable_let_patterns)]` on by default
   = note: this pattern will always match, so the `if let` is useless
   = help: consider replacing the `if let` with a `let`

warning: 1 warning emitted

@compiler-errors
Copy link
Member

Just noting that "irrefutable if let pattern" warning is unrelated to this issue, and is just because let x = 1 is a "irrefutable" binding, i.e. not actually conditional.

@chenyukang
Copy link
Member Author

chenyukang commented Oct 23, 2022

The job x86_64-gnu-llvm-13 failed! Check out the build log: (web) (plain)

Click to see the possible cause of the failure (guessed by this bot)

From the UI testing result, we have this syntax:

fn shoule_match_ok() {
    #[cfg(feature = "full")]
    {
        let a = 1;
        let b = 2;
        if match a {
            1 if b == 1 => true,
            _ => false,
        } && if a > 1 { true } else { false }
        {
            true
        }
    }
}

I think it's not a readable code, but it compiled and runnable 😂
Anyway, I plan to restrict this suggestion to limited scenarios:

            // recovery from `if b && if let Some(x)`
            if op == AssocOp::LAnd
                && self.token.is_keyword(kw::If)
                && self.look_ahead(1, |t| t.is_bool_lit())
                || (self.look_ahead(1, |t| t.is_keyword(kw::Let))
                    && self.look_ahead(2, |t| {
                        t.is_ident_named(sym::Some) || t.is_ident_named(sym::None)
                    }))
            {
                // eat the `if`
                self.bump();
                self.sess.emit_err(UnexpectedIfWithIf(
                    self.prev_token.span.to(self.token.span.shrink_to_lo()),
                ));
            }

Not sure whether there is a better way.

@compiler-errors
Copy link
Member

compiler-errors commented Oct 23, 2022

@chenyukang, this approach still has issues:

fn main() {
    if true && if true { true } else { false } {}
}

This fails to compile with your new changes:

error: unexpected `if` in the condition expression
 --> /home/gh-compiler-errors/test.rs:2:16
  |
2 |     if true && if true { true } else { false } {}
  |                ^^^
  |
help: remove the `if`
  |
2 -     if true && if true { true } else { false } {}
2 +     if true && true { true } else { false } {}
  |

error[E0308]: mismatched types
 --> /home/gh-compiler-errors/test.rs:2:26
  |
2 |     if true && if true { true } else { false } {}
  |     ---------------------^^^^-----------------
  |     |                    |
  |     |                    expected `()`, found `bool`
  |     expected this to be `()`

error[E0308]: mismatched types
 --> /home/gh-compiler-errors/test.rs:2:40
  |
2 |     if true && if true { true } else { false } {}
  |     -----------------------------------^^^^^--
  |     |                                  |
  |     |                                  expected `()`, found `bool`
  |     expected this to be `()`

error: aborting due to 3 previous errors

I'm pretty sure it's impossible to detect #103381 inside of parse_assoc_expr_with -- you need to add a suggestion to remove if only after the parser has already detected an error, probably by passing the correct state down to parse_if_after_cond or some similar function that is involved in parsing if statements.

This may be hard to do, or not worth the changes to the parser to allow this state to be tracked.

@chenyukang
Copy link
Member Author

chenyukang commented Oct 23, 2022 via email

@rust-log-analyzer

This comment has been minimized.

@Noratrieb
Copy link
Member

Hi, I've seen you changed some diagnostic structs in your PR. After #103345, the way we refer to fluent messages changed. They are now in a flat namespace with the same identifier as in the fluent file. For example, parser::cool_thing is now parser_cool_thing and parser::suggestion just suggestion.
You should rebase to the latest master and change your fluent message references as described above. Thanks!

@chenyukang chenyukang force-pushed the yukang/fix-103381-and-if branch from 31bad2e to 3fea71e Compare October 23, 2022 11:47
@chenyukang
Copy link
Member Author

chenyukang commented Oct 23, 2022

This may be hard to do, or not worth the changes to the parser to allow this state to be tracked.

Take some time to investigate it.
Yes, seems it is not easy since we need to rollback too much.
I think we'd better don't try to suggest and fix this case right now, it's easy for developer fix without diagnostics:

 let _ = if true && if true { true } else { false };
 let _ = if true && if false { true } else { false };

Only add check for && if let Option...

@chenyukang chenyukang force-pushed the yukang/fix-103381-and-if branch from 3fea71e to 43269b6 Compare October 23, 2022 12:05
@compiler-errors compiler-errors added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Nov 2, 2022
@chenyukang
Copy link
Member Author

@rustbot ready

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Nov 9, 2022
&& self.token.is_keyword(kw::If)
&& self.look_ahead(1, |t| t.is_keyword(kw::Let))
&& self
.look_ahead(2, |t| t.is_ident_named(sym::Some) || t.is_ident_named(sym::None))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The following code is perfectly valid:

if true
    && if let Some(1) = Some(1) { true } else { true }
{
    todo!()
}

In general, it is always possible to write valid code containing if <some condition> && if let <some pattern>.

I don't think it's possible to detect the scenario you're looking for until after you parse the inner if let .. expression.

@compiler-errors compiler-errors added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Nov 10, 2022
@compiler-errors
Copy link
Member

compiler-errors commented Nov 10, 2022

@chenyukang, camsteffen is correct, and as I noted in my previous comment, I'm pretty sure it's impossible to detect #103381 inside of parse_assoc_expr_with. Marking as S-waiting-on-author until this PR is reformulated.

This check needs to live in another function using a different strategy, after parsing has detected a failure. Be very careful about adding parser recoveries before we've detected an error, since it's very1 easy2 to accidentally introduce changes in parser behavior while improving error messages during parsing...

@chenyukang
Copy link
Member Author

I think we'd better don't recover from these scenarios, but give proper diagnostics 😁
Code updated.

@chenyukang chenyukang force-pushed the yukang/fix-103381-and-if branch from a6ea4bc to 6cd4a2a Compare November 10, 2022 16:36
@estebank
Copy link
Contributor

r? @compiler-errors as you're already familiar with the changes :)

@rustbot rustbot assigned compiler-errors and unassigned estebank Nov 10, 2022
Comment on lines +25 to +34
error: unexpected `if` in the condition expression
--> $DIR/issue-103381.rs:19:15
|
LL | if true && if true { true } else { false };
| ^^^^
|
help: remove the `if`
|
LL - if true && if true { true } else { false };
LL + if true && true { true } else { false };
Copy link
Contributor

@estebank estebank Nov 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens for if true && if true { true } else { false } { true } else { false };?

Given where you call the recovery it should succeed, right? In that case I believe the code changes look fine because the error is only ever precluding another, so there are no changes of regressions.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given where you call the recovery it should succeed, right?

yeah, this is my thinking. I'll give this a better review later, but I much prefer this approach since it's already deep in the "bad path".

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this code will compile successfully, I have added it as a UI.

@compiler-errors
Copy link
Member

@rustbot ready

I will get around to reviewing this soon.

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Nov 15, 2022
@bors
Copy link
Collaborator

bors commented Nov 15, 2022

☔ The latest upstream changes (presumably #104418) made this pull request unmergeable. Please resolve the merge conflicts.

@chenyukang chenyukang force-pushed the yukang/fix-103381-and-if branch from dafa06f to cd2bde1 Compare November 15, 2022 08:46
@chenyukang
Copy link
Member Author

@rustbot ready

conflict resolved.

@compiler-errors
Copy link
Member

@bors r+

@bors
Copy link
Collaborator

bors commented Nov 16, 2022

📌 Commit cd2bde1 has been approved by compiler-errors

It is now in the queue for this repository.

@bors
Copy link
Collaborator

bors commented Nov 16, 2022

🌲 The tree is currently closed for pull requests below priority 1. This pull request will be tested once the tree is reopened.

@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 Nov 16, 2022
bors added a commit to rust-lang-ci/rust that referenced this pull request Nov 18, 2022
…iaskrgr

Rollup of 8 pull requests

Successful merges:

 - rust-lang#101162 (Migrate rustc_resolve to use SessionDiagnostic, part # 1)
 - rust-lang#103386 (Don't allow `CoerceUnsized` into `dyn*` (except for trait upcasting))
 - rust-lang#103405 (Detect incorrect chaining of if and if let conditions and recover)
 - rust-lang#103594 (Fix non-associativity of `Instant` math on `aarch64-apple-darwin` targets)
 - rust-lang#104006 (Add variant_name function to `LangItem`)
 - rust-lang#104494 (Migrate GUI test to use functions)
 - rust-lang#104516 (rustdoc: clean up sidebar width CSS)
 - rust-lang#104550 (fix a typo)

Failed merges:

 - rust-lang#104554 (Use `ErrorGuaranteed::unchecked_claim_error_was_emitted` less)

r? `@ghost`
`@rustbot` modify labels: rollup
@bors bors merged commit 3efbf30 into rust-lang:master Nov 18, 2022
@rustbot rustbot added this to the 1.67.0 milestone Nov 18, 2022
flip1995 pushed a commit to flip1995/rust that referenced this pull request Nov 21, 2022
…iaskrgr

Rollup of 8 pull requests

Successful merges:

 - rust-lang#101162 (Migrate rustc_resolve to use SessionDiagnostic, part # 1)
 - rust-lang#103386 (Don't allow `CoerceUnsized` into `dyn*` (except for trait upcasting))
 - rust-lang#103405 (Detect incorrect chaining of if and if let conditions and recover)
 - rust-lang#103594 (Fix non-associativity of `Instant` math on `aarch64-apple-darwin` targets)
 - rust-lang#104006 (Add variant_name function to `LangItem`)
 - rust-lang#104494 (Migrate GUI test to use functions)
 - rust-lang#104516 (rustdoc: clean up sidebar width CSS)
 - rust-lang#104550 (fix a typo)

Failed merges:

 - rust-lang#104554 (Use `ErrorGuaranteed::unchecked_claim_error_was_emitted` less)

r? `@ghost`
`@rustbot` modify labels: rollup
bors added a commit to rust-lang-ci/rust that referenced this pull request Apr 22, 2025
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.

[tracking issue]: rust-lang#53667
[RFC 2497]: rust-lang/rfcs#2497
[2024 edition]: https://doc.rust-lang.org/nightly/edition-guide/rust-2024/index.html

## 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.

```Rust
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.

[generate correct MIR]: rust-lang#104843
[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

* History from before March 14, 2022 can be found in the [original stabilization PR] that was reverted.
* rust-lang#94927
* rust-lang#94951
* rust-lang#94974
* rust-lang#95008
* rust-lang#97295
* rust-lang#98633
* rust-lang#99731
* rust-lang#102394
* rust-lang#100526
* rust-lang#100538
* rust-lang#102998
* rust-lang#103405
* rust-lang#103293
* rust-lang#107251
* rust-lang#110568
* rust-lang#115677
* rust-lang#117743
* rust-lang#117770
* rust-lang#118191
* rust-lang#119554
* rust-lang#129394
* rust-lang#132828
* rust-lang/reference#1179
* rust-lang/reference#1251
* rust-lang/rustfmt#5910

[original stabilization PR]: rust-lang#94927

## Adoption history

### In the compiler

* History before March 14, 2022 can be found in the [original stabilization PR].
* rust-lang#115983
* rust-lang#116549
* rust-lang#116688

### Outside of the compiler

* rust-lang/rust-clippy#11750
* [rspack](https://github.com/web-infra-dev/rspack)
* [risingwave](https://github.com/risingwavelabs/risingwave)
* [dylint](https://github.com/trailofbits/dylint)
* [convex-backend](https://github.com/get-convex/convex-backend)
* [tikv](https://github.com/tikv/tikv)
* [Daft](https://github.com/Eventual-Inc/Daft)
* [greptimedb](https://github.com/GreptimeTeam/greptimedb)

## Tests

<details>

### Intentional restrictions

[`partially-macro-expanded.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/partially-macro-expanded.rs), [`macro-expanded.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/parens.rs): `if (let pat = expr)` is not allowed in chains
[`ensure-that-let-else-does-not-interact-with-let-chains.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/shadowing.rs): shadowing in if let guards works as expected
[`ast-validate-guards.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/then-else-blocks.rs)
[`ast-lowering-does-not-wrap-let-chains.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/ast-lowering-does-not-wrap-let-chains.rs)
[`issue-90722.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/issue-90722.rs)
[`issue-92145.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/issue-92145.rs)

### Drop order/MIR scoping tests

[`issue-100276.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/drop/issue-100276.rs): let expressions on RHS aren't terminating scopes
[`drop_order.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/drop/drop_order.rs): exhaustive temporary drop order test for various Rust constructs, including let chains
[`scope.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/scope.rs): match guard scoping test
[`drop-scope.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/drop/drop_order_if_let_rescope.rs): if let rescoping on edition 2024, including chains
[`mir_let_chains_drop_order.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/mir/mir_let_chains_drop_order.rs): comprehensive drop order test for let chains, distinguishes editions 2021 and 2024.
[`issue-99938.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/issue-99938.rs), [`issue-99852.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/mir/issue-99852.rs) both bad MIR ICEs fixed by rust-lang#102394

### Linting

[`irrefutable-lets.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/lint/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`](https://github.com/rust-lang/rust/blob/2128d8df0e858edcbe6a0861bac948b88b7fabc3/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.rs): `let` in expression context is rejected everywhere except at the top level
[`invalid-let-in-a-valid-let-context.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/issues/issue-103381.rs): Graceful recovery of incorrect chaining of `if` and `if let`
[`semi-in-let-chain.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/deli-ident-issue-1.rs), [`brace-in-let-chain.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/brace-in-let-chain.rs): Ensure that stray unclosed `{`s in let chains give nice errors and hints

### Misc

[`conflicting_bindings.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/pattern/usefulness/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/expr/if/attrs/let-chains-attr.rs): attributes work on let chains

### Tangential tests with `#![feature(let_chains)]`

[`if-let.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/coverage/branch/if-let.rs): MC/DC coverage tests for let chains
[`logical_or_in_conditional.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/mir-opt/building/logical_or_in_conditional.rs): not really about let chains, more about dropping/scoping behaviour of `||`
[`stringify.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/macros/stringify.rs): exhaustive test of the `stringify` macro
[`expanded-interpolation.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/unpretty/expanded-interpolation.rs), [`expanded-exhaustive.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/unpretty/expanded-exhaustive.rs): Exhaustive test of `-Zunpretty`
[`diverges-not.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-0000-never_patterns/diverges-not.rs): Never type, mostly tangential to let chains

</details>

## Possible future work

* There is proposals to allow `if let Pat(bindings) = expr {}` to be written as `if expr is Pat(bindings) {}` ([RFC 3573]). `if let` chains are a natural extension of the already existing `if let` syntax, and I'd argue orthogonal towards `is` syntax.
  * rust-lang/lang-team#297
* One could have similar chaining inside `let ... else` statements. There is no proposed RFC for this however, nor is it implemented on nightly.
* Match guards have the `if` keyword as well, but on stable Rust, they don't support `let`. The functionality is available via an unstable feature ([`if_let_guard` tracking issue]). Stabilization of let chains affects this feature in so far as match guards containing let chains now only need the `if_let_guard` feature gate be present instead of also the `let_chains` feature (NOTE: this PR doesn't implement this simplification, it's left for future work).

[RFC 3573]: rust-lang/rfcs#3573
[`if_let_guard` tracking issue]: rust-lang#51114

## Open questions / blockers

- [ ] bad recovery if you don't put a `let` (I don't think this is a blocker): [rust-lang#117977](rust-lang#117977)
- [x] An instance where a temporary lives shorter than with nested ifs, breaking compilation: [rust-lang#103476](rust-lang#103476). Personally I don't think this is a blocker either, as it's an edge case. Edit: turns out to not reproduce in edition 2025 any more, due to let rescoping. regression test added in rust-lang#133093
- [x] One should probably extend the tests for `move-guard-if-let-chain.rs` and `conflicting_bindings.rs` to have chains with multiple let's: done in 133093
- [x] Parsing rejection tests: addressed by rust-lang#132828
- [x] [Style](https://rust-lang.zulipchat.com/#narrow/channel/346005-t-style/topic/let.20chains.20stabilization.20and.20formatting): rust-lang#139456
- [x] rust-lang#86730 explicitly mentions `let_else`. I think we can live with `let pat = expr` not evaluating as `expr` for macro_rules macros, especially given that `let pat = expr` is not a legal expression anywhere except inside `if` and `while`.
- [x] Documentation in the reference: rust-lang/reference#1740
- [x] Add chapter to the Rust 2024 [edition guide]: rust-lang/edition-guide#337
- [x] Resolve open questions on desired drop order.

[original reference PR]: rust-lang/reference#1179
[edition guide]: https://github.com/rust-lang/edition-guide
github-actions bot pushed a commit to rust-lang/miri that referenced this pull request Apr 23, 2025
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.

[tracking issue]: rust-lang/rust#53667
[RFC 2497]: rust-lang/rfcs#2497
[2024 edition]: https://doc.rust-lang.org/nightly/edition-guide/rust-2024/index.html

## 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.

```Rust
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.

[generate correct MIR]: rust-lang/rust#104843
[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

* History from before March 14, 2022 can be found in the [original stabilization PR] that was reverted.
* rust-lang/rust#94927
* rust-lang/rust#94951
* rust-lang/rust#94974
* rust-lang/rust#95008
* rust-lang/rust#97295
* rust-lang/rust#98633
* rust-lang/rust#99731
* rust-lang/rust#102394
* rust-lang/rust#100526
* rust-lang/rust#100538
* rust-lang/rust#102998
* rust-lang/rust#103405
* rust-lang/rust#103293
* rust-lang/rust#107251
* rust-lang/rust#110568
* rust-lang/rust#115677
* rust-lang/rust#117743
* rust-lang/rust#117770
* rust-lang/rust#118191
* rust-lang/rust#119554
* rust-lang/rust#129394
* rust-lang/rust#132828
* rust-lang/reference#1179
* rust-lang/reference#1251
* rust-lang/rustfmt#5910

[original stabilization PR]: rust-lang/rust#94927

## Adoption history

### In the compiler

* History before March 14, 2022 can be found in the [original stabilization PR].
* rust-lang/rust#115983
* rust-lang/rust#116549
* rust-lang/rust#116688

### Outside of the compiler

* rust-lang/rust-clippy#11750
* [rspack](https://github.com/web-infra-dev/rspack)
* [risingwave](https://github.com/risingwavelabs/risingwave)
* [dylint](https://github.com/trailofbits/dylint)
* [convex-backend](https://github.com/get-convex/convex-backend)
* [tikv](https://github.com/tikv/tikv)
* [Daft](https://github.com/Eventual-Inc/Daft)
* [greptimedb](https://github.com/GreptimeTeam/greptimedb)

## Tests

<details>

### Intentional restrictions

[`partially-macro-expanded.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/partially-macro-expanded.rs), [`macro-expanded.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/parens.rs): `if (let pat = expr)` is not allowed in chains
[`ensure-that-let-else-does-not-interact-with-let-chains.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/shadowing.rs): shadowing in if let guards works as expected
[`ast-validate-guards.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/then-else-blocks.rs)
[`ast-lowering-does-not-wrap-let-chains.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/ast-lowering-does-not-wrap-let-chains.rs)
[`issue-90722.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/issue-90722.rs)
[`issue-92145.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/issue-92145.rs)

### Drop order/MIR scoping tests

[`issue-100276.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/drop/issue-100276.rs): let expressions on RHS aren't terminating scopes
[`drop_order.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/drop/drop_order.rs): exhaustive temporary drop order test for various Rust constructs, including let chains
[`scope.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/scope.rs): match guard scoping test
[`drop-scope.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/drop/drop_order_if_let_rescope.rs): if let rescoping on edition 2024, including chains
[`mir_let_chains_drop_order.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/mir/mir_let_chains_drop_order.rs): comprehensive drop order test for let chains, distinguishes editions 2021 and 2024.
[`issue-99938.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/issue-99938.rs), [`issue-99852.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/mir/issue-99852.rs) both bad MIR ICEs fixed by #102394

### Linting

[`irrefutable-lets.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/lint/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`](https://github.com/rust-lang/rust/blob/2128d8df0e858edcbe6a0861bac948b88b7fabc3/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.rs): `let` in expression context is rejected everywhere except at the top level
[`invalid-let-in-a-valid-let-context.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/issues/issue-103381.rs): Graceful recovery of incorrect chaining of `if` and `if let`
[`semi-in-let-chain.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/deli-ident-issue-1.rs), [`brace-in-let-chain.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/brace-in-let-chain.rs): Ensure that stray unclosed `{`s in let chains give nice errors and hints

### Misc

[`conflicting_bindings.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/pattern/usefulness/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/expr/if/attrs/let-chains-attr.rs): attributes work on let chains

### Tangential tests with `#![feature(let_chains)]`

[`if-let.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/coverage/branch/if-let.rs): MC/DC coverage tests for let chains
[`logical_or_in_conditional.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/mir-opt/building/logical_or_in_conditional.rs): not really about let chains, more about dropping/scoping behaviour of `||`
[`stringify.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/macros/stringify.rs): exhaustive test of the `stringify` macro
[`expanded-interpolation.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/unpretty/expanded-interpolation.rs), [`expanded-exhaustive.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/unpretty/expanded-exhaustive.rs): Exhaustive test of `-Zunpretty`
[`diverges-not.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-0000-never_patterns/diverges-not.rs): Never type, mostly tangential to let chains

</details>

## Possible future work

* There is proposals to allow `if let Pat(bindings) = expr {}` to be written as `if expr is Pat(bindings) {}` ([RFC 3573]). `if let` chains are a natural extension of the already existing `if let` syntax, and I'd argue orthogonal towards `is` syntax.
  * rust-lang/lang-team#297
* One could have similar chaining inside `let ... else` statements. There is no proposed RFC for this however, nor is it implemented on nightly.
* Match guards have the `if` keyword as well, but on stable Rust, they don't support `let`. The functionality is available via an unstable feature ([`if_let_guard` tracking issue]). Stabilization of let chains affects this feature in so far as match guards containing let chains now only need the `if_let_guard` feature gate be present instead of also the `let_chains` feature (NOTE: this PR doesn't implement this simplification, it's left for future work).

[RFC 3573]: rust-lang/rfcs#3573
[`if_let_guard` tracking issue]: rust-lang/rust#51114

## Open questions / blockers

- [ ] bad recovery if you don't put a `let` (I don't think this is a blocker): [#117977](rust-lang/rust#117977)
- [x] An instance where a temporary lives shorter than with nested ifs, breaking compilation: [#103476](rust-lang/rust#103476). Personally I don't think this is a blocker either, as it's an edge case. Edit: turns out to not reproduce in edition 2025 any more, due to let rescoping. regression test added in #133093
- [x] One should probably extend the tests for `move-guard-if-let-chain.rs` and `conflicting_bindings.rs` to have chains with multiple let's: done in 133093
- [x] Parsing rejection tests: addressed by rust-lang/rust#132828
- [x] [Style](https://rust-lang.zulipchat.com/#narrow/channel/346005-t-style/topic/let.20chains.20stabilization.20and.20formatting): rust-lang/rust#139456
- [x] rust-lang/rust#86730 explicitly mentions `let_else`. I think we can live with `let pat = expr` not evaluating as `expr` for macro_rules macros, especially given that `let pat = expr` is not a legal expression anywhere except inside `if` and `while`.
- [x] Documentation in the reference: rust-lang/reference#1740
- [x] Add chapter to the Rust 2024 [edition guide]: rust-lang/edition-guide#337
- [x] Resolve open questions on desired drop order.

[original reference PR]: rust-lang/reference#1179
[edition guide]: https://github.com/rust-lang/edition-guide
github-actions bot pushed a commit to rust-lang/rustc-dev-guide that referenced this pull request Apr 24, 2025
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.

[tracking issue]: rust-lang/rust#53667
[RFC 2497]: rust-lang/rfcs#2497
[2024 edition]: https://doc.rust-lang.org/nightly/edition-guide/rust-2024/index.html

## 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.

```Rust
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.

[generate correct MIR]: rust-lang/rust#104843
[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

* History from before March 14, 2022 can be found in the [original stabilization PR] that was reverted.
* rust-lang/rust#94927
* rust-lang/rust#94951
* rust-lang/rust#94974
* rust-lang/rust#95008
* rust-lang/rust#97295
* rust-lang/rust#98633
* rust-lang/rust#99731
* rust-lang/rust#102394
* rust-lang/rust#100526
* rust-lang/rust#100538
* rust-lang/rust#102998
* rust-lang/rust#103405
* rust-lang/rust#103293
* rust-lang/rust#107251
* rust-lang/rust#110568
* rust-lang/rust#115677
* rust-lang/rust#117743
* rust-lang/rust#117770
* rust-lang/rust#118191
* rust-lang/rust#119554
* rust-lang/rust#129394
* rust-lang/rust#132828
* rust-lang/reference#1179
* rust-lang/reference#1251
* rust-lang/rustfmt#5910

[original stabilization PR]: rust-lang/rust#94927

## Adoption history

### In the compiler

* History before March 14, 2022 can be found in the [original stabilization PR].
* rust-lang/rust#115983
* rust-lang/rust#116549
* rust-lang/rust#116688

### Outside of the compiler

* rust-lang/rust-clippy#11750
* [rspack](https://github.com/web-infra-dev/rspack)
* [risingwave](https://github.com/risingwavelabs/risingwave)
* [dylint](https://github.com/trailofbits/dylint)
* [convex-backend](https://github.com/get-convex/convex-backend)
* [tikv](https://github.com/tikv/tikv)
* [Daft](https://github.com/Eventual-Inc/Daft)
* [greptimedb](https://github.com/GreptimeTeam/greptimedb)

## Tests

<details>

### Intentional restrictions

[`partially-macro-expanded.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/partially-macro-expanded.rs), [`macro-expanded.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/parens.rs): `if (let pat = expr)` is not allowed in chains
[`ensure-that-let-else-does-not-interact-with-let-chains.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/shadowing.rs): shadowing in if let guards works as expected
[`ast-validate-guards.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/then-else-blocks.rs)
[`ast-lowering-does-not-wrap-let-chains.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/ast-lowering-does-not-wrap-let-chains.rs)
[`issue-90722.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/issue-90722.rs)
[`issue-92145.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/issue-92145.rs)

### Drop order/MIR scoping tests

[`issue-100276.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/drop/issue-100276.rs): let expressions on RHS aren't terminating scopes
[`drop_order.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/drop/drop_order.rs): exhaustive temporary drop order test for various Rust constructs, including let chains
[`scope.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/scope.rs): match guard scoping test
[`drop-scope.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2294-if-let-guard/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/drop/drop_order_if_let_rescope.rs): if let rescoping on edition 2024, including chains
[`mir_let_chains_drop_order.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/mir/mir_let_chains_drop_order.rs): comprehensive drop order test for let chains, distinguishes editions 2021 and 2024.
[`issue-99938.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/issue-99938.rs), [`issue-99852.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/mir/issue-99852.rs) both bad MIR ICEs fixed by #102394

### Linting

[`irrefutable-lets.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/lint/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`](https://github.com/rust-lang/rust/blob/2128d8df0e858edcbe6a0861bac948b88b7fabc3/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.rs): `let` in expression context is rejected everywhere except at the top level
[`invalid-let-in-a-valid-let-context.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-2497-if-let-chains/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/issues/issue-103381.rs): Graceful recovery of incorrect chaining of `if` and `if let`
[`semi-in-let-chain.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/deli-ident-issue-1.rs), [`brace-in-let-chain.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/parser/brace-in-let-chain.rs): Ensure that stray unclosed `{`s in let chains give nice errors and hints

### Misc

[`conflicting_bindings.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/pattern/usefulness/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`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/expr/if/attrs/let-chains-attr.rs): attributes work on let chains

### Tangential tests with `#![feature(let_chains)]`

[`if-let.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/coverage/branch/if-let.rs): MC/DC coverage tests for let chains
[`logical_or_in_conditional.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/mir-opt/building/logical_or_in_conditional.rs): not really about let chains, more about dropping/scoping behaviour of `||`
[`stringify.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/macros/stringify.rs): exhaustive test of the `stringify` macro
[`expanded-interpolation.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/unpretty/expanded-interpolation.rs), [`expanded-exhaustive.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/unpretty/expanded-exhaustive.rs): Exhaustive test of `-Zunpretty`
[`diverges-not.rs`](https://github.com/rust-lang/rust/blob/4adafcf40aa6064d2bbcb44bc1a50b3b1e86e5e0/tests/ui/rfcs/rfc-0000-never_patterns/diverges-not.rs): Never type, mostly tangential to let chains

</details>

## Possible future work

* There is proposals to allow `if let Pat(bindings) = expr {}` to be written as `if expr is Pat(bindings) {}` ([RFC 3573]). `if let` chains are a natural extension of the already existing `if let` syntax, and I'd argue orthogonal towards `is` syntax.
  * rust-lang/lang-team#297
* One could have similar chaining inside `let ... else` statements. There is no proposed RFC for this however, nor is it implemented on nightly.
* Match guards have the `if` keyword as well, but on stable Rust, they don't support `let`. The functionality is available via an unstable feature ([`if_let_guard` tracking issue]). Stabilization of let chains affects this feature in so far as match guards containing let chains now only need the `if_let_guard` feature gate be present instead of also the `let_chains` feature (NOTE: this PR doesn't implement this simplification, it's left for future work).

[RFC 3573]: rust-lang/rfcs#3573
[`if_let_guard` tracking issue]: rust-lang/rust#51114

## Open questions / blockers

- [ ] bad recovery if you don't put a `let` (I don't think this is a blocker): [#117977](rust-lang/rust#117977)
- [x] An instance where a temporary lives shorter than with nested ifs, breaking compilation: [#103476](rust-lang/rust#103476). Personally I don't think this is a blocker either, as it's an edge case. Edit: turns out to not reproduce in edition 2025 any more, due to let rescoping. regression test added in #133093
- [x] One should probably extend the tests for `move-guard-if-let-chain.rs` and `conflicting_bindings.rs` to have chains with multiple let's: done in 133093
- [x] Parsing rejection tests: addressed by rust-lang/rust#132828
- [x] [Style](https://rust-lang.zulipchat.com/#narrow/channel/346005-t-style/topic/let.20chains.20stabilization.20and.20formatting): rust-lang/rust#139456
- [x] rust-lang/rust#86730 explicitly mentions `let_else`. I think we can live with `let pat = expr` not evaluating as `expr` for macro_rules macros, especially given that `let pat = expr` is not a legal expression anywhere except inside `if` and `while`.
- [x] Documentation in the reference: rust-lang/reference#1740
- [x] Add chapter to the Rust 2024 [edition guide]: rust-lang/edition-guide#337
- [x] Resolve open questions on desired drop order.

[original reference PR]: rust-lang/reference#1179
[edition guide]: https://github.com/rust-lang/edition-guide
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-translation Area: Translation infrastructure, and migrating existing diagnostics to SessionDiagnostic S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Detect incorrect chaining of if and if let conditions and recover gracefully
10 participants