Skip to content
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

[let_chains, 1/6] Remove hir::ExprKind::If #59288

Merged
merged 5 commits into from
May 11, 2019

Conversation

Centril
Copy link
Contributor

@Centril Centril commented Mar 19, 2019

@rust-highfive rust-highfive added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Mar 19, 2019
@petrochenkov petrochenkov self-assigned this Mar 19, 2019
@rust-highfive

This comment has been minimized.

@petrochenkov
Copy link
Contributor

IIRC, I got some lifetime issues after trying to desugar all ifs into matches (rather than those containing is), with RefCells being held for too long (or too little?) and panicking etc.
Don't remember the details right now, perhaps it's fixable.

@petrochenkov
Copy link
Contributor

This seems like a nice simplification even regardless of if-let chains, we only need to make sure that it doesn't regress 1) codegen 2) compile times, and 3) diagnostics.

Similarly, desugaring while into loop is also required for implementing pattern matching expressions, but is also a nice simplification otherwise.

(I'll try to review the code later today.)

@petrochenkov
Copy link
Contributor

petrochenkov commented Mar 19, 2019

On the other hand, the desugaring for pattern matching expressions at the AST/HIR border turned out incredibly hacky, when I tried it.
It also made impossible to support those expressions in pattern guards.

match thing {
    PAT(y) if let Some(x) = y {
        print(x); // Nope
    }
}

So it's a pretty real possibility that it's better done somewhere at HIR->MIR time.

@Centril
Copy link
Contributor Author

Centril commented Mar 19, 2019

This seems like a nice simplification even regardless of if-let chains, we only need to make sure that it doesn't regress 1) codegen 2) compile times, and 3) diagnostics.

I think I fixed all diagnostics issues that I had... some even got improved. :) As for codegen there are issues in #59288 (comment) wrt. mir-opt tests (thus the WIP) that I don't really understand yet.

Similarly, desugaring while into loop is also required for implementing pattern matching expressions, but is also a nice simplification otherwise.

Yup, I'd like to do that as step 4 in the process after having done the if part of the RFC fully. Maybe even remove continue from HIR after step 6...

(I'll try to review the code later today.)

:)

On the other hand, the desugaring for pattern matching expressions at the AST/HIR border turned out incredibly hacky, when I tried it.

When I tried it out with LBV + a fold in lowering it didn't feel so bad. Haven't thought about the implications of if-let-guards + if-let-chains tho wrt. lowering. :)

@rust-highfive

This comment has been minimized.

@Centril
Copy link
Contributor Author

Centril commented Mar 19, 2019

(I believe @oli-obk is looking into the mir-opt stuff)

src/librustc/hir/mod.rs Show resolved Hide resolved
src/librustc_typeck/check/_match.rs Outdated Show resolved Hide resolved
src/librustc_typeck/check/demand.rs Outdated Show resolved Hide resolved
src/librustc_typeck/check/mod.rs Outdated Show resolved Hide resolved
Centril added a commit to Centril/rust that referenced this pull request Mar 19, 2019
Run branch cleanup after copy prop

This is preliminary work for rust-lang#59288 (comment) which gets rid of `if` in the HIR.

cc @rust-lang/wg-mir-opt 	@Centril
@oli-obk
Copy link
Contributor

oli-obk commented Mar 19, 2019

@bors try

@bors
Copy link
Contributor

bors commented Mar 19, 2019

⌛ Trying commit db4452fab28c9374dd6676b702dc36b43e2a45b5 with merge bf82f43c83ada4fffaf93a633dfce5c7f55d57fe...

@rust-highfive

This comment has been minimized.

@bors
Copy link
Contributor

bors commented Mar 19, 2019

☀️ Try build successful - checks-travis
Build commit: bf82f43c83ada4fffaf93a633dfce5c7f55d57fe

@oli-obk
Copy link
Contributor

oli-obk commented Mar 19, 2019

@rust-timer build

@oli-obk
Copy link
Contributor

oli-obk commented Mar 19, 2019

@rust-timer build bf82f43c83ada4fffaf93a633dfce5c7f55d57fe

@rust-timer
Copy link
Collaborator

Success: Queued bf82f43c83ada4fffaf93a633dfce5c7f55d57fe with parent ef4d1c4, comparison URL.

@rust-timer
Copy link
Collaborator

Finished benchmarking try commit bf82f43c83ada4fffaf93a633dfce5c7f55d57fe

@Centril Centril force-pushed the hir-if-to-match branch 2 times, most recently from 772ab34 to 9a0d37d Compare March 21, 2019 10:11
@rust-highfive

This comment has been minimized.

@bors

This comment has been minimized.

@Centril Centril 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 Mar 22, 2019
@petrochenkov petrochenkov added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Mar 23, 2019
@Manishearth
Copy link
Member

Have you looked into how hard it will be to make clippy migrate to these? We have a lot of lints around ifs, and the lowering may lose some context necessary to make these work. Removing lints because they're no longer possible isn't an option.

IMO for such changes where there's a good chance clippy lints will be unfixably broken we should be notified of this before it merges :/

@Manishearth
Copy link
Member

I appreciate it being split up, though, it's easier to make this evaluation if one thing breaks at a time :)

@Centril
Copy link
Contributor Author

Centril commented May 11, 2019

We have a lot of lints around ifs, and the lowering may lose some context necessary to make these work.

The lowering preserves information about the source; you can check MatchSource::IfDesugar to see whether it originated from an if.

@oli-obk thought it would work for clippy and as you know, he also works on clippy...

@Manishearth
Copy link
Member

Manishearth commented May 11, 2019 via email

@Centril
Copy link
Contributor Author

Centril commented May 11, 2019

For the later steps can you work with us to ensure stuff isn't broken before landing? Mostly just pinging me when the PR is ready to merge so I can work on a patch

Sure. Fwiw, I expected Oliver to be the "work with us" party... ;)

The next steps will be to introduce ast::ExprKind::Let and then to use 'label: { ... break 'label value }. That will probably be less straightforward but I think we can introduce similar desugaring info as needed. I could introduce ast::ExprKind::Let in a separate intermediate step however without connecting the parser (already done in a PR but I could probably split things).

@Manishearth
Copy link
Member

Manishearth commented May 11, 2019 via email

bors added a commit to rust-lang/rust-clippy that referenced this pull request May 11, 2019
Rustup to rustc 1.36.0-nightly (acc7e65 2019-05-10)

Fixes breakages from rust-lang/rust#59288

Not finished yet, help appreciated.

Todo:

 - [x] Needs to build
 - [x] Util should handle DropTemps, #4080 (comment)
 - [x] Author lint should spit out higher::if_block checks
 - [x] Unsure what to do in consts.rs
 - [x] Needs to pass tests
bors added a commit that referenced this pull request May 15, 2019
[let_chains, 2/6] Introduce `Let(..)` in AST, remove IfLet + WhileLet and parse let chains

Here we remove `ast::ExprKind::{IfLet, WhileLet}` and introduce `ast::ExprKind::Let`.
Moreover, we also:
+ connect the parsing logic for let chains
+ introduce the feature gate
+ do some AST validation
+ rewire HIR lowering a bit.

However, this does not connect the new syntax to semantics in HIR.
That will be the subject of a subsequent PR.

Per #53667 (comment).
Next step after #59288.

cc @Manishearth re. Clippy.

r? @oli-obk
bors added a commit that referenced this pull request May 16, 2019
[let_chains, 2/6] Introduce `Let(..)` in AST, remove IfLet + WhileLet and parse let chains

Here we remove `ast::ExprKind::{IfLet, WhileLet}` and introduce `ast::ExprKind::Let`.
Moreover, we also:
+ connect the parsing logic for let chains
+ introduce the feature gate
+ do some AST validation
+ rewire HIR lowering a bit.

However, this does not connect the new syntax to semantics in HIR.
That will be the subject of a subsequent PR.

Per #53667 (comment).
Next step after #59288.

cc @Manishearth re. Clippy.

r? @oli-obk
bors added a commit that referenced this pull request May 19, 2019
[let_chains, 2/6] Introduce `Let(..)` in AST, remove IfLet + WhileLet and parse let chains

Here we remove `ast::ExprKind::{IfLet, WhileLet}` and introduce `ast::ExprKind::Let`.
Moreover, we also:
+ connect the parsing logic for let chains
+ introduce the feature gate
+ do some AST validation
+ rewire HIR lowering a bit.

However, this does not connect the new syntax to semantics in HIR.
That will be the subject of a subsequent PR.

Per #53667 (comment).
Next step after #59288.

cc @Manishearth re. Clippy.

r? @oli-obk
@nnethercote
Copy link
Contributor

This ended up being a non-trivial perf regression.

@Centril
Copy link
Contributor Author

Centril commented Jun 3, 2019

Yep; this was expected. #60730 will hopefully reduce some of those regressions.

bors added a commit that referenced this pull request Jun 23, 2019
[let_chains, 2/6] Introduce `Let(..)` in AST, remove IfLet + WhileLet and parse let chains

Here we remove `ast::ExprKind::{IfLet, WhileLet}` and introduce `ast::ExprKind::Let`.
Moreover, we also:
+ connect the parsing logic for let chains
+ introduce the feature gate
+ rewire HIR lowering a bit.

However, this does not connect the new syntax to semantics in HIR.
That will be the subject of a subsequent PR.

Per #53667 (comment).
Next step after #59288.

cc @Manishearth re. Clippy.

r? @oli-obk
bors added a commit that referenced this pull request Jul 5, 2019
[let_chains, 3/6] And then there was only Loop

Here we remove `hir::ExprKind::While`.
Instead, we desugar: `'label: while $cond $body` into:

```rust
'label: loop {
    match DropTemps($cond) {
        true => $body,
        _ => break,
    }
}
```

Per #53667 (comment).
This is a follow up to #59288 which did the same for `if` expressions.

r? @matthewjasper
bors added a commit that referenced this pull request Jul 6, 2019
[let_chains, 3/6] And then there was only Loop

Here we remove `hir::ExprKind::While`.
Instead, we desugar: `'label: while $cond $body` into:

```rust
'label: loop {
    match DropTemps($cond) {
        true => $body,
        _ => break,
    }
}
```

Per #53667 (comment).
This is a follow up to #59288 which did the same for `if` expressions.

r? @matthewjasper
@Centril Centril added the F-let_chains `#![feature(let_chains)]` label Oct 10, 2019
@c410-f3r c410-f3r mentioned this pull request Nov 23, 2020
6 tasks
bors added a commit to rust-lang-ci/rust that referenced this pull request Jan 14, 2021
Reintroduce hir::ExprKind::If

Basically copied and paste rust-lang#59288/rust-lang/rust-clippy#4080 with some modifications.

The vast majority of tests were fixed and now there are only a few remaining. Since I am still unable to figure out the missing pieces, any help with the following list is welcome.

- [ ] **Unnecessary `typeck` exception**: [Cheated on this one to make CI green.](https://github.com/rust-lang/rust/pull/79328/files#diff-3faee9ba23fc54a12b7c43364ba81f8c5660045c7e1d7989a02a0cee1c5b2051)
- [x] **Incorrect span**: [Span should reference `then` and `else` separately.](https://github.com/rust-lang/rust/pull/79328/files#diff-cf2c46e82222ee4b1037a68fff8a1af3c4f1de7a6b3fd798aacbf3c0475abe3d)
- [x] **New note regarding `assert!`**: [Modified but not "wrong". Maybe can be a good thing?](https://github.com/rust-lang/rust/pull/79328/files#diff-9e0d7c89ed0224e2b62060c957177c27db43c30dfe3c2974cb6b5091cda9cfb5)
- [x] **Inverted report location**: [Modified but not "wrong". Locations were inverted.](https://github.com/rust-lang/rust/pull/79328/files#diff-f637ce7c1f68d523a165aa9651765df05e36c4d7d279194b1a6b28b48a323691)
- [x] **`src/test/ui/point-to-type-err-cause-on-impl-trait-return.rs` has weird errors**: [Not sure why this is happening.](https://github.com/rust-lang/rust/pull/79328/files#diff-c823c09660f5b112f95e97e8ff71f1797b6c7f37dbb3d16f8e98bbaea8072e95)
- [x] **Missing diagnostic**: [???](https://github.com/rust-lang/rust/pull/79328/files#diff-6b8ab09360d725ba4513933827f9796b42ff9522b0690f80b76de067143af2fc)
flip1995 pushed a commit to flip1995/rust that referenced this pull request Jan 15, 2021
Reintroduce hir::ExprKind::If

Basically copied and paste rust-lang#59288/rust-lang/rust-clippy#4080 with some modifications.

The vast majority of tests were fixed and now there are only a few remaining. Since I am still unable to figure out the missing pieces, any help with the following list is welcome.

- [ ] **Unnecessary `typeck` exception**: [Cheated on this one to make CI green.](https://github.com/rust-lang/rust/pull/79328/files#diff-3faee9ba23fc54a12b7c43364ba81f8c5660045c7e1d7989a02a0cee1c5b2051)
- [x] **Incorrect span**: [Span should reference `then` and `else` separately.](https://github.com/rust-lang/rust/pull/79328/files#diff-cf2c46e82222ee4b1037a68fff8a1af3c4f1de7a6b3fd798aacbf3c0475abe3d)
- [x] **New note regarding `assert!`**: [Modified but not "wrong". Maybe can be a good thing?](https://github.com/rust-lang/rust/pull/79328/files#diff-9e0d7c89ed0224e2b62060c957177c27db43c30dfe3c2974cb6b5091cda9cfb5)
- [x] **Inverted report location**: [Modified but not "wrong". Locations were inverted.](https://github.com/rust-lang/rust/pull/79328/files#diff-f637ce7c1f68d523a165aa9651765df05e36c4d7d279194b1a6b28b48a323691)
- [x] **`src/test/ui/point-to-type-err-cause-on-impl-trait-return.rs` has weird errors**: [Not sure why this is happening.](https://github.com/rust-lang/rust/pull/79328/files#diff-c823c09660f5b112f95e97e8ff71f1797b6c7f37dbb3d16f8e98bbaea8072e95)
- [x] **Missing diagnostic**: [???](https://github.com/rust-lang/rust/pull/79328/files#diff-6b8ab09360d725ba4513933827f9796b42ff9522b0690f80b76de067143af2fc)
JohnTitor added a commit to JohnTitor/rust that referenced this pull request Jul 17, 2022
…shtriplett

Stabilize `let_chains` in Rust 1.64

# Stabilization proposal

This PR proposes the stabilization of `#![feature(let_chains)]` in a future-compatibility way that will allow the **possible** addition of the `EXPR is PAT` syntax.

Tracking issue: rust-lang#53667
Version: 1.64 (beta => 2022-08-11, stable => 2022-10-22).

## What is stabilized

The ability to chain let expressions along side local variable declarations or ordinary conditional expressions. For example:

```rust
pub enum Color {
    Blue,
    Red,
    Violet,
}

pub enum Flower {
    Rose,
    Tulip,
    Violet,
}

pub fn roses_are_red_violets_are_blue_printer(
    (first_flower, first_flower_color): (Flower, Color),
    (second_flower, second_flower_color): (Flower, Color),
    pick_up_lines: &[&str],
) {
    if let Flower::Rose = first_flower
        && let Color::Red = first_flower_color
        && let Flower::Violet = second_flower
        && let Color::Blue = second_flower_color
        && let &[first_pick_up_line, ..] = pick_up_lines
    {
        println!("Roses are red, violets are blue, {}", first_pick_up_line);
    }
}

fn main() {
    roses_are_red_violets_are_blue_printer(
        (Flower::Rose, Color::Red),
        (Flower::Violet, Color::Blue),
        &["sugar is sweet and so are you"],
    );
}
```

## Motivation

The main motivation for this feature is improving readability, ergonomics and reducing paper cuts.

For more examples, see the [RFC](https://github.com/rust-lang/rfcs/blob/master/text/2497-if-let-chains.md).

## What isn't stabilized

* Let chains in match guards (`if_let_guard`)

* Resolution of divergent non-terminal matchers

* The `EXPR is PAT` syntax

## History

* On 2017-12-24, [RFC: if- and while-let-chains](rust-lang/rfcs#2260)
* On 2018-07-12, [eRFC: if- and while-let-chains, take 2](rust-lang/rfcs#2497)
* On 2018-08-24, [Tracking issue for eRFC 2497, "if- and while-let-chains, take 2](rust-lang#53667)
* On 2019-03-19, [Run branch cleanup after copy prop](rust-lang#59290)
* On 2019-03-26, [Generalize diagnostic for x = y where bool is the expected type](rust-lang#59439)
* On 2019-04-24, [Introduce hir::ExprKind::Use and employ in for loop desugaring](rust-lang#60225)
* On 2019-03-19, [[let_chains, 1/6] Remove hir::ExprKind::If](rust-lang#59288)
* On 2019-05-15, [[let_chains, 2/6] Introduce Let(..) in AST, remove IfLet + WhileLet and parse let chains](rust-lang#60861)
* On 2019-06-20, [[let_chains, 3/6] And then there was only Loop](rust-lang#61988)
* On 2020-11-22, [Reintroduce hir::ExprKind::If](rust-lang#79328)
* On 2020-12-24, [Introduce hir::ExprKind::Let - Take 2](rust-lang#80357)
* On 2021-02-19, [Lower condition of if expression before it's "then" block](rust-lang#82308)
* On 2021-09-01, [Fix drop handling for `if let` expressions](rust-lang#88572)
* On 2021-09-04, [Formally implement let chains](rust-lang#88642)
* On 2022-01-19, [Add tests to ensure that let_chains works with if_let_guard](rust-lang#93086)
* On 2022-01-18, [Introduce `enhanced_binary_op` feature](rust-lang#93049)
* On 2022-01-22, [Fix `let_chains` and `if_let_guard` feature flags](rust-lang#93213)
* On 2022-02-25, [Initiate the inner usage of `let_chains`](rust-lang#94376)
* On 2022-01-28, [[WIP] Introduce ast::StmtKind::LetElse to allow the usage of `let_else` with `let_chains`](rust-lang#93437)
* On 2022-02-26, [1 - Make more use of `let_chains`](rust-lang#94396)
* On 2022-02-26, [2 - Make more use of `let_chains`](rust-lang#94400)
* On 2022-02-27, [3 - Make more use of `let_chains`](rust-lang#94420)
* On 2022-02-28, [4 - Make more use of `let_chains`](rust-lang#94445)
* On 2022-02-28, [5 - Make more use of `let_chains`](rust-lang#94448)
* On 2022-02-28, [6 - Make more use of `let_chains`](rust-lang#94465)
* On 2022-03-01, [7 - Make more use of `let_chains`](rust-lang#94476)
* On 2022-03-01, [8 - Make more use of `let_chains`](rust-lang#94484)
* On 2022-03-01, [9 - Make more use of `let_chains`](rust-lang#94498)
* On 2022-03-08, [Warn users about `||` in let chain expressions](rust-lang#94754)

From the first RFC (2017-12-24) to the theoretical future stabilization day (2022-10-22), it can be said that this feature took 4 years, 9 months and 28 days of research, development, discussions, agreements and headaches to be settled.

## Divergent non-terminal matchers

More specifically, rust-lang#86730.

```rust
macro_rules! mac {
    ($e:expr) => {
        if $e {
            true
        } else {
            false
        }
    };
}

fn main() {
    // OK!
    assert_eq!(mac!(true && let 1 = 1), true);

    // ERROR! Anything starting with `let` is not considered an expression
    assert_eq!(mac!(let 1 = 1 && true), true);
}
```

To the best of my knowledge, such error or divergence is orthogonal, does not prevent stabilization and can be tackled independently in the near future or effectively in the next Rust 2024 edition. If not, then https://github.com/c410-f3r/rust/tree/let-macro-blah contains a set of changes that will consider `let` an expression.

It is possible that none of the solutions above satisfies all applicable constraints but I personally don't know of any other plausible answers.

## Alternative syntax

Taking into account the usefulness of this feature and the overwhelming desire to use both now and in the past, `let PAT = EXPR` will be utilized for stabilization but it doesn't or shall create any obstacle for a **possible** future addition of `EXPR is PAT`.

The introductory snippet would then be written as the following.

```rust
if first_flower is Flower::Rose
    && first_flower_color is Color::Red
    && second_flower is Flower::Violet
    && second_flower_color is Color::Blue
    && pick_up_lines is &[first_pick_up_line, ..]
{
    println!("Roses are red, violets are blue, {}", first_pick_up_line);
}
```

Just to reinforce, this PR only unblocks a **possible** future road for `EXPR is PAT` and does emphasize what is better or what is worse.

## Tests

* [Verifies the drop order of let chains and ensures it won't change in the future in an unpredictable way](https://github.com/rust-lang/rust/blob/master/src/test/ui/mir/mir_let_chains_drop_order.rs)

* [AST lowering does not wrap let chains in an `DropTemps` expression](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/ast-lowering-does-not-wrap-let-chains.rs)

* [Checks pretty printing output](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/ast-pretty-check.rs)

* [Verifies uninitialized variables due to MIR modifications](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/chains-without-let.rs)

* [A collection of statements where `let` expressions are forbidden](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/disallowed-positions.rs)

* [All or at least most of the places where let chains are allowed](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/feature-gate.rs)

* [Ensures that irrefutable lets are allowed in let chains](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/irrefutable-lets.rs)

* [issue-88498.rs](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/issue-88498.rs), [issue-90722.rs](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/issue-90722.rs), [issue-92145.rs](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/issue-92145.rs) and [issue-93150.rs](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/issue-93150.rs) were bugs found by third parties and fixed overtime.

* [Indexing was triggering a ICE due to a wrongly constructed MIR graph](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/no-double-assigments.rs)

* [Protects the precedence of `&&` in relation to other things](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/protect-precedences.rs)

* [`let_chains`, as well as `if_let_guard`, has a valid MIR graph that evaluates conditional expressions correctly](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/then-else-blocks.rs)

Most of the infra-structure used by let chains is also used by `if` expressions in stable compiler versions since rust-lang#80357 and rust-lang#88572. As a result, no bugs were found since the integration of rust-lang#88642.

## Possible future work

* Let chains in match guards is implemented and working but stabilization is blocked by `if_let_guard`.

* The usage of `let_chains` with `let_else` is possible but not implemented. Regardless, one attempt was introduced and closed in rust-lang#93437.

Thanks `@Centril` for creating the RFC and huge thanks (again) to `@matthewjasper` for all the reviews, mentoring and MIR implementations.

Fixes rust-lang#53667
workingjubilee pushed a commit to tcdi/postgrestd that referenced this pull request Sep 15, 2022
Stabilize `let_chains` in Rust 1.64

# Stabilization proposal

This PR proposes the stabilization of `#![feature(let_chains)]` in a future-compatibility way that will allow the **possible** addition of the `EXPR is PAT` syntax.

Tracking issue: #53667
Version: 1.64 (beta => 2022-08-11, stable => 2022-10-22).

## What is stabilized

The ability to chain let expressions along side local variable declarations or ordinary conditional expressions. For example:

```rust
pub enum Color {
    Blue,
    Red,
    Violet,
}

pub enum Flower {
    Rose,
    Tulip,
    Violet,
}

pub fn roses_are_red_violets_are_blue_printer(
    (first_flower, first_flower_color): (Flower, Color),
    (second_flower, second_flower_color): (Flower, Color),
    pick_up_lines: &[&str],
) {
    if let Flower::Rose = first_flower
        && let Color::Red = first_flower_color
        && let Flower::Violet = second_flower
        && let Color::Blue = second_flower_color
        && let &[first_pick_up_line, ..] = pick_up_lines
    {
        println!("Roses are red, violets are blue, {}", first_pick_up_line);
    }
}

fn main() {
    roses_are_red_violets_are_blue_printer(
        (Flower::Rose, Color::Red),
        (Flower::Violet, Color::Blue),
        &["sugar is sweet and so are you"],
    );
}
```

## Motivation

The main motivation for this feature is improving readability, ergonomics and reducing paper cuts.

For more examples, see the [RFC](https://github.com/rust-lang/rfcs/blob/master/text/2497-if-let-chains.md).

## What isn't stabilized

* Let chains in match guards (`if_let_guard`)

* Resolution of divergent non-terminal matchers

* The `EXPR is PAT` syntax

## History

* On 2017-12-24, [RFC: if- and while-let-chains](rust-lang/rfcs#2260)
* On 2018-07-12, [eRFC: if- and while-let-chains, take 2](rust-lang/rfcs#2497)
* On 2018-08-24, [Tracking issue for eRFC 2497, "if- and while-let-chains, take 2](rust-lang/rust#53667)
* On 2019-03-19, [Run branch cleanup after copy prop](rust-lang/rust#59290)
* On 2019-03-26, [Generalize diagnostic for x = y where bool is the expected type](rust-lang/rust#59439)
* On 2019-04-24, [Introduce hir::ExprKind::Use and employ in for loop desugaring](rust-lang/rust#60225)
* On 2019-03-19, [[let_chains, 1/6] Remove hir::ExprKind::If](rust-lang/rust#59288)
* On 2019-05-15, [[let_chains, 2/6] Introduce Let(..) in AST, remove IfLet + WhileLet and parse let chains](rust-lang/rust#60861)
* On 2019-06-20, [[let_chains, 3/6] And then there was only Loop](rust-lang/rust#61988)
* On 2020-11-22, [Reintroduce hir::ExprKind::If](rust-lang/rust#79328)
* On 2020-12-24, [Introduce hir::ExprKind::Let - Take 2](rust-lang/rust#80357)
* On 2021-02-19, [Lower condition of if expression before it's "then" block](rust-lang/rust#82308)
* On 2021-09-01, [Fix drop handling for `if let` expressions](rust-lang/rust#88572)
* On 2021-09-04, [Formally implement let chains](rust-lang/rust#88642)
* On 2022-01-19, [Add tests to ensure that let_chains works with if_let_guard](rust-lang/rust#93086)
* On 2022-01-18, [Introduce `enhanced_binary_op` feature](rust-lang/rust#93049)
* On 2022-01-22, [Fix `let_chains` and `if_let_guard` feature flags](rust-lang/rust#93213)
* On 2022-02-25, [Initiate the inner usage of `let_chains`](rust-lang/rust#94376)
* On 2022-01-28, [[WIP] Introduce ast::StmtKind::LetElse to allow the usage of `let_else` with `let_chains`](rust-lang/rust#93437)
* On 2022-02-26, [1 - Make more use of `let_chains`](rust-lang/rust#94396)
* On 2022-02-26, [2 - Make more use of `let_chains`](rust-lang/rust#94400)
* On 2022-02-27, [3 - Make more use of `let_chains`](rust-lang/rust#94420)
* On 2022-02-28, [4 - Make more use of `let_chains`](rust-lang/rust#94445)
* On 2022-02-28, [5 - Make more use of `let_chains`](rust-lang/rust#94448)
* On 2022-02-28, [6 - Make more use of `let_chains`](rust-lang/rust#94465)
* On 2022-03-01, [7 - Make more use of `let_chains`](rust-lang/rust#94476)
* On 2022-03-01, [8 - Make more use of `let_chains`](rust-lang/rust#94484)
* On 2022-03-01, [9 - Make more use of `let_chains`](rust-lang/rust#94498)
* On 2022-03-08, [Warn users about `||` in let chain expressions](rust-lang/rust#94754)

From the first RFC (2017-12-24) to the theoretical future stabilization day (2022-10-22), it can be said that this feature took 4 years, 9 months and 28 days of research, development, discussions, agreements and headaches to be settled.

## Divergent non-terminal matchers

More specifically, rust-lang/rust#86730.

```rust
macro_rules! mac {
    ($e:expr) => {
        if $e {
            true
        } else {
            false
        }
    };
}

fn main() {
    // OK!
    assert_eq!(mac!(true && let 1 = 1), true);

    // ERROR! Anything starting with `let` is not considered an expression
    assert_eq!(mac!(let 1 = 1 && true), true);
}
```

To the best of my knowledge, such error or divergence is orthogonal, does not prevent stabilization and can be tackled independently in the near future or effectively in the next Rust 2024 edition. If not, then https://github.com/c410-f3r/rust/tree/let-macro-blah contains a set of changes that will consider `let` an expression.

It is possible that none of the solutions above satisfies all applicable constraints but I personally don't know of any other plausible answers.

## Alternative syntax

Taking into account the usefulness of this feature and the overwhelming desire to use both now and in the past, `let PAT = EXPR` will be utilized for stabilization but it doesn't or shall create any obstacle for a **possible** future addition of `EXPR is PAT`.

The introductory snippet would then be written as the following.

```rust
if first_flower is Flower::Rose
    && first_flower_color is Color::Red
    && second_flower is Flower::Violet
    && second_flower_color is Color::Blue
    && pick_up_lines is &[first_pick_up_line, ..]
{
    println!("Roses are red, violets are blue, {}", first_pick_up_line);
}
```

Just to reinforce, this PR only unblocks a **possible** future road for `EXPR is PAT` and does emphasize what is better or what is worse.

## Tests

* [Verifies the drop order of let chains and ensures it won't change in the future in an unpredictable way](https://github.com/rust-lang/rust/blob/master/src/test/ui/mir/mir_let_chains_drop_order.rs)

* [AST lowering does not wrap let chains in an `DropTemps` expression](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/ast-lowering-does-not-wrap-let-chains.rs)

* [Checks pretty printing output](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/ast-pretty-check.rs)

* [Verifies uninitialized variables due to MIR modifications](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/chains-without-let.rs)

* [A collection of statements where `let` expressions are forbidden](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/disallowed-positions.rs)

* [All or at least most of the places where let chains are allowed](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/feature-gate.rs)

* [Ensures that irrefutable lets are allowed in let chains](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/irrefutable-lets.rs)

* [issue-88498.rs](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/issue-88498.rs), [issue-90722.rs](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/issue-90722.rs), [issue-92145.rs](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/issue-92145.rs) and [issue-93150.rs](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/issue-93150.rs) were bugs found by third parties and fixed overtime.

* [Indexing was triggering a ICE due to a wrongly constructed MIR graph](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/no-double-assigments.rs)

* [Protects the precedence of `&&` in relation to other things](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/protect-precedences.rs)

* [`let_chains`, as well as `if_let_guard`, has a valid MIR graph that evaluates conditional expressions correctly](https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2497-if-let-chains/then-else-blocks.rs)

Most of the infra-structure used by let chains is also used by `if` expressions in stable compiler versions since rust-lang/rust#80357 and rust-lang/rust#88572. As a result, no bugs were found since the integration of rust-lang/rust#88642.

## Possible future work

* Let chains in match guards is implemented and working but stabilization is blocked by `if_let_guard`.

* The usage of `let_chains` with `let_else` is possible but not implemented. Regardless, one attempt was introduced and closed in rust-lang/rust#93437.

Thanks `@Centril` for creating the RFC and huge thanks (again) to `@matthewjasper` for all the reviews, mentoring and MIR implementations.

Fixes #53667
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
F-let_chains `#![feature(let_chains)]` merged-by-bors This PR was explicitly merged by bors. S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

10 participants