Skip to content

Broken MIR ICE with let chains #104843

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

Closed
est31 opened this issue Nov 24, 2022 · 13 comments · Fixed by #119077
Closed

Broken MIR ICE with let chains #104843

est31 opened this issue Nov 24, 2022 · 13 comments · Fixed by #119077
Assignees
Labels
-Zvalidate-mir Unstable option: MIR validation A-MIR Area: Mid-level IR (MIR) - https://blog.rust-lang.org/2016/04/19/MIR.html C-bug Category: This is a bug. F-let_chains `#![feature(let_chains)]` glacier ICE tracked in rust-lang/glacier. I-ICE Issue: The compiler panicked, giving an Internal Compilation Error (ICE) ❄️ T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Comments

@est31
Copy link
Member

est31 commented Nov 24, 2022

Originally reported by @flip1995 in #99938 (comment) .

Code

#![feature(let_chains)]

struct F(Box<()>);

impl F {
    fn s(&self) -> Option<&str> {
        None
    }
}

fn cex() -> Option<F> {
    None
}

pub fn main() {
    if false
        && let Some(ce) = cex()
        && let Some(_ce) = ce.s()
    {
    }
}

Error output

error: internal compiler error: no errors encountered even though `delay_span_bug` issued

error: internal compiler error: broken MIR in Item(WithOptConstParam { did: DefId(0:9 ~ a[8fb6]::main), const_param_did: None }) (after phase change to runtime-optimized) at bb3[0]:
                                use of local _1, which has no storage here
  --> /tmp/a.rs:21:1
   |
21 | }
   | ^
   |
   = note: delayed at compiler/rustc_const_eval/src/transform/validate.rs:88:36

error: internal compiler error: broken MIR in Item(WithOptConstParam { did: DefId(0:9 ~ a[8fb6]::main), const_param_did: None }) (after phase change to runtime-optimized) at bb4[0]:
                                use of local _1, which has no storage here
  --> /tmp/a.rs:21:1
   |
21 | }
   | ^
   |
   = note: delayed at compiler/rustc_const_eval/src/transform/validate.rs:88:36

thread 'rustc' panicked at 'Box<dyn Any>', compiler/rustc_errors/src/lib.rs:1594:13

Backtrace

   0:     0x7f4776d010da - std::backtrace_rs::backtrace::libunwind::trace::h06e8f32b98d440be
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/std/src/../../backtrace/src/backtrace/libunwind.rs:93:5
   1:     0x7f4776d010da - std::backtrace_rs::backtrace::trace_unsynchronized::h8a56795adafc3159
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/std/src/../../backtrace/src/backtrace/mod.rs:66:5
   2:     0x7f4776d010da - std::sys_common::backtrace::_print_fmt::h7ba19acb3601abb5
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/std/src/sys_common/backtrace.rs:65:5
   3:     0x7f4776d010da - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::ha37df576307c1a49
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/std/src/sys_common/backtrace.rs:44:22
   4:     0x7f4772c6fbae - core::fmt::write::hd3f2e7e755b45b01
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/core/src/fmt/mod.rs:1208:17
   5:     0x7f4776cf53a5 - std::io::Write::write_fmt::hc1388e059aac0a41
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/std/src/io/mod.rs:1682:15
   6:     0x7f4776d00ea5 - std::sys_common::backtrace::_print::h429db1082d921ab8
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/std/src/sys_common/backtrace.rs:47:5
   7:     0x7f4776d00ea5 - std::sys_common::backtrace::print::h8d611e0005d3ccb9
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/std/src/sys_common/backtrace.rs:34:9
   8:     0x7f4776d0320f - std::panicking::default_hook::{{closure}}::h07380c607f829a79
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/std/src/panicking.rs:267:22
   9:     0x7f4776d02f4b - std::panicking::default_hook::h78998b3f3926502a
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/std/src/panicking.rs:286:9
  10:     0x7f4775f5b284 - <rustc_driver[153e38e44d5410f9]::DEFAULT_HOOK::{closure#0}::{closure#0} as core[1d8afb50f4e7a45]::ops::function::FnOnce<(&core[1d8afb50f4e7a45]::panic::panic_info::PanicInfo,)>>::call_once::{shim:vtable#0}
  11:     0x7f4776d03a0d - <alloc::boxed::Box<F,A> as core::ops::function::Fn<Args>>::call::hbe7c77b7cbfe1f21
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/alloc/src/boxed.rs:2032:9
  12:     0x7f4776d03a0d - std::panicking::rust_panic_with_hook::hda16cab0ff009a11
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/std/src/panicking.rs:692:13
  13:     0x7f4775f93ab1 - std[2b5db76a972e300f]::panicking::begin_panic::<rustc_errors[6e875e03adfb8e66]::ExplicitBug>::{closure#0}
  14:     0x7f4775f923e6 - std[2b5db76a972e300f]::sys_common::backtrace::__rust_end_short_backtrace::<std[2b5db76a972e300f]::panicking::begin_panic<rustc_errors[6e875e03adfb8e66]::ExplicitBug>::{closure#0}, !>
  15:     0x7f4775f8ab76 - std[2b5db76a972e300f]::panicking::begin_panic::<rustc_errors[6e875e03adfb8e66]::ExplicitBug>
  16:     0x7f4775f8e306 - std[2b5db76a972e300f]::panic::panic_any::<rustc_errors[6e875e03adfb8e66]::ExplicitBug>
  17:     0x7f4775465556 - <rustc_errors[6e875e03adfb8e66]::HandlerInner>::flush_delayed::<alloc[eb468f42ab80a7c0]::vec::Vec<rustc_errors[6e875e03adfb8e66]::diagnostic::Diagnostic>, &str>
  18:     0x7f477546485b - <rustc_errors[6e875e03adfb8e66]::HandlerInner as core[1d8afb50f4e7a45]::ops::drop::Drop>::drop
  19:     0x7f477521271e - core[1d8afb50f4e7a45]::ptr::drop_in_place::<rustc_session[729ed7505232e216]::parse::ParseSess>
  20:     0x7f47751cb42f - core[1d8afb50f4e7a45]::ptr::drop_in_place::<rustc_session[729ed7505232e216]::session::Session>
  21:     0x7f47751cb160 - core[1d8afb50f4e7a45]::ptr::drop_in_place::<rustc_interface[d2ac3f3b3bfa4614]::interface::Compiler>
  22:     0x7f47751ca26e - rustc_span[cdf434c68ce75247]::with_source_map::<core[1d8afb50f4e7a45]::result::Result<(), rustc_errors[6e875e03adfb8e66]::ErrorGuaranteed>, rustc_interface[d2ac3f3b3bfa4614]::interface::run_compiler<core[1d8afb50f4e7a45]::result::Result<(), rustc_errors[6e875e03adfb8e66]::ErrorGuaranteed>, rustc_driver[153e38e44d5410f9]::run_compiler::{closure#1}>::{closure#0}::{closure#1}>
  23:     0x7f47751c9ba5 - <scoped_tls[2ec6d95ce5fd8213]::ScopedKey<rustc_span[cdf434c68ce75247]::SessionGlobals>>::set::<rustc_interface[d2ac3f3b3bfa4614]::interface::run_compiler<core[1d8afb50f4e7a45]::result::Result<(), rustc_errors[6e875e03adfb8e66]::ErrorGuaranteed>, rustc_driver[153e38e44d5410f9]::run_compiler::{closure#1}>::{closure#0}, core[1d8afb50f4e7a45]::result::Result<(), rustc_errors[6e875e03adfb8e66]::ErrorGuaranteed>>
  24:     0x7f47751c9192 - std[2b5db76a972e300f]::sys_common::backtrace::__rust_begin_short_backtrace::<rustc_interface[d2ac3f3b3bfa4614]::util::run_in_thread_pool_with_globals<rustc_interface[d2ac3f3b3bfa4614]::interface::run_compiler<core[1d8afb50f4e7a45]::result::Result<(), rustc_errors[6e875e03adfb8e66]::ErrorGuaranteed>, rustc_driver[153e38e44d5410f9]::run_compiler::{closure#1}>::{closure#0}, core[1d8afb50f4e7a45]::result::Result<(), rustc_errors[6e875e03adfb8e66]::ErrorGuaranteed>>::{closure#0}::{closure#0}, core[1d8afb50f4e7a45]::result::Result<(), rustc_errors[6e875e03adfb8e66]::ErrorGuaranteed>>
  25:     0x7f47751c8ea8 - <<std[2b5db76a972e300f]::thread::Builder>::spawn_unchecked_<rustc_interface[d2ac3f3b3bfa4614]::util::run_in_thread_pool_with_globals<rustc_interface[d2ac3f3b3bfa4614]::interface::run_compiler<core[1d8afb50f4e7a45]::result::Result<(), rustc_errors[6e875e03adfb8e66]::ErrorGuaranteed>, rustc_driver[153e38e44d5410f9]::run_compiler::{closure#1}>::{closure#0}, core[1d8afb50f4e7a45]::result::Result<(), rustc_errors[6e875e03adfb8e66]::ErrorGuaranteed>>::{closure#0}::{closure#0}, core[1d8afb50f4e7a45]::result::Result<(), rustc_errors[6e875e03adfb8e66]::ErrorGuaranteed>>::{closure#1} as core[1d8afb50f4e7a45]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0}
  26:     0x7f4776d0ac43 - <alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once::h0c8cfd64ff347c2f
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/alloc/src/boxed.rs:2000:9
  27:     0x7f4776d0ac43 - <alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once::h5243ef33e0bc55ac
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/alloc/src/boxed.rs:2000:9
  28:     0x7f4776d0ac43 - std::sys::unix::thread::Thread::new::thread_start::h248bc665ee6b9bda
                               at /rustc/70f8737b2f5d3bf7d6b784fad00b663b7ff9feda/library/std/src/sys/unix/thread.rs:108:17
  29:     0x7f4772985ff2 - start_thread
  30:     0x7f4772a08bfc - clone3
  31:                0x0 - <unknown>

The ICE requires -O to be passed to rustc, or --release be passed to cargo, the param to validate MIR is not enough. It's also a regression, on nightly-2022-07-30 it does not reproduce.

cc #99938 and #99852 related issues with similar error messages, but they are fixed and this is reproducible.

@rustbot label E-needs-bisection

@est31 est31 added C-bug Category: This is a bug. I-ICE Issue: The compiler panicked, giving an Internal Compilation Error (ICE) ❄️ T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Nov 24, 2022
@rustbot rustbot added the E-needs-bisection Call for participation: This issue needs bisection: https://github.com/rust-lang/cargo-bisect-rustc label Nov 24, 2022
@est31
Copy link
Member Author

est31 commented Nov 24, 2022

@rustbot label F-let_chains

@rustbot rustbot added the F-let_chains `#![feature(let_chains)]` label Nov 24, 2022
@lukas-code
Copy link
Member

searched nightlies: from nightly-2022-07-20 to nightly-2022-11-23
regressed nightly: nightly-2022-10-20
searched commit range: a24a020...4b8f431
regressed commit: d7dd01f

bisected with cargo-bisect-rustc v0.6.4

Host triple: x86_64-unknown-linux-gnu
Reproduce with:

cargo bisect-rustc --end=2022-11-23 --regress=ice -- rustc -- -Zvalidate-mir -O 

@Noratrieb
Copy link
Member

Noratrieb commented Nov 24, 2022

Looks like #103034 didn't fix everything after all..... @nathanwhit
this feature just keeps on giving

@est31
Copy link
Member Author

est31 commented Nov 24, 2022

@rustbot label -E-needs-bisection

@rustbot rustbot removed the E-needs-bisection Call for participation: This issue needs bisection: https://github.com/rust-lang/cargo-bisect-rustc label Nov 24, 2022
@flip1995
Copy link
Member

Thanks for opening an issue for this! I put that on my todo list, but my todo list is just way to long...

@dingxiangfei2009
Copy link
Contributor

@rustbot claim

@dingxiangfei2009
Copy link
Contributor

I have a feeling that the if-then scope tracking could be relevant to this issue. Zooming onto that.

@dingxiangfei2009
Copy link
Contributor

dingxiangfei2009 commented Jan 15, 2023

Here is a summary of the cause. The scrutinees of the let expressions has a temporary lifetime of the whole if expression, enclosing the IfThen scope as well. The consequence is that when the condition test fails and the control continues to the block built by break_for_else, it is breaking out of the scope of IfThen but the scrutinees are still considered living, even though some of them are still dead.

I am going to try moving their temporary lifetimes to IfThens and see it solves this issue or breaks anything else.

The following example passes -Z validate-mir checks with -O optimization level, but inspection of the dumped MIR shows that the "temporary" from calling ce.s() is dropped even though its storage _4 was never live.

The issue that the MIR validation does not catch this shall be addressed separately and I am very intrigued.

#![feature(let_chains)]

struct F(Box<()>);
struct G;
impl Drop for G {
    fn drop(&mut self) {}
}

impl F {
    fn s(&self) -> Option<G> {
        None
    }
}

fn cex() -> Option<F> {
    None
}

pub fn main() {
    if let Some(ce) = cex() && let Some(ce2) = ce.s()
    {
    }
}

@est31
Copy link
Member Author

est31 commented Jan 15, 2023

Note that regarding drop order, for now, until #103108 is addressed, we should drop all the let temporaries after the else has terminated. This is for consistency with if let. See #103248 and especially the message I linked at the end that closed the issue. Not sure how one can represent that with scopes though.

@BlueskyFR
Copy link

This is still happening on the nightly release, @dingxiangfei2009 did you came up with something? This seems to be blocking the let-chaining features from stabilizing

@est31
Copy link
Member Author

est31 commented Sep 29, 2023

There is #107251 which would solve this. I haven't had the time to push it forward, but the next logical step would be to file PRs to the repos broken by the PR, not suggesting that this will break eventually, as the only time when this is 100% sure is when this PR is merged, but that there is the chance it might break. See the thread of #107251.

The other blocker is formatting support, which depends on the style team.

Edit: feel free to file the PRs if you want.

@dingxiangfei2009
Copy link
Contributor

I will update the draft that @est31 mentioned.

@tmiasko tmiasko added A-MIR Area: Mid-level IR (MIR) - https://blog.rust-lang.org/2016/04/19/MIR.html -Zvalidate-mir Unstable option: MIR validation labels Dec 9, 2023
@bors bors closed this as completed in 7dd0955 Dec 23, 2023
rust-timer added a commit to rust-lang-ci/rust that referenced this issue Dec 23, 2023
Rollup merge of rust-lang#119077 - tmiasko:lint, r=cjgillot

Separate MIR lints from validation

Add a MIR lint pass, enabled with -Zlint-mir, which identifies undefined or
likely erroneous behaviour.

The initial implementation mostly migrates existing checks of this nature from
MIR validator, where they did not belong (those checks have false positives and
there is nothing inherently invalid about MIR with undefined behaviour).

Fixes rust-lang#104736
Fixes rust-lang#104843
Fixes rust-lang#116079
Fixes rust-lang#116736
Fixes rust-lang#118990
@est31
Copy link
Member Author

est31 commented Nov 9, 2024

Btw, this still ICEs if you pass -Zlint-mir to the compiler. It passes if you set the edition to 2024 however, so #124085 has worked.

bors added a commit to rust-lang-ci/rust that referenced this issue 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
-Zvalidate-mir Unstable option: MIR validation A-MIR Area: Mid-level IR (MIR) - https://blog.rust-lang.org/2016/04/19/MIR.html C-bug Category: This is a bug. F-let_chains `#![feature(let_chains)]` glacier ICE tracked in rust-lang/glacier. I-ICE Issue: The compiler panicked, giving an Internal Compilation Error (ICE) ❄️ T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

9 participants