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

Reorder nesting scopes and declare bindings without drop schedule #101410

Merged
merged 6 commits into from
Sep 15, 2022

Conversation

dingxiangfei2009
Copy link
Contributor

Fix #99228
Fix #99975

Storages are previously not declared before entering the else block of a let .. else statement. However, when breaking out of the pattern matching into the else block, those storages are recorded as scheduled for drops. This is not expected.

This MR fixes this issue by not scheduling the drops for those storages.

cc @est31

@rustbot rustbot added the T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. label Sep 4, 2022
@rust-highfive
Copy link
Collaborator

r? @jackh726

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

@rust-highfive rust-highfive added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Sep 4, 2022
@est31
Copy link
Member

est31 commented Sep 4, 2022

The test for #99228 is good, but it should also have a test for #99975. Can you add a test with the file name src/test/ui/let-else/issue-99975.rs with the content from my comment in addition to // compile-flags: -C opt-level=3 at the top of the file?

@est31 est31 mentioned this pull request Sep 5, 2022
@dingxiangfei2009
Copy link
Contributor Author

Right. A test is added for that issue now.

@est31
Copy link
Member

est31 commented Sep 5, 2022

@dingxiangfei2009 thanks! Looks good from the tests point of view now. For the implementation, I can't comment much on that.

@dingxiangfei2009
Copy link
Contributor Author

@est31 I see. Which reviewer do you think has the capacity to review this work at the moment? Hopefully this is not blocking the stabilisation effort.

@est31
Copy link
Member

est31 commented Sep 9, 2022

Yes it is blocking stabilization. Depending on how quickly this PR gets merged it depends whether let else makes it into 1.65 or 1.66. Generally I like let else stable as quickly as possible, but one release give or take won't be the end of it, and rushing things is usually not worth it (little nudges are fine but only up till a limit, you shouldn't stress people or stuff). The train model was designed precisely to prevent such rushing/pressure.

For the reviewers, you might try @oli-obk who has approved your earlier let else PRs but according to their github activity, they don't seem to work on weekends, so a review will probably only happen on monday. The current reviewer jackh726 is actually available as well, they have approved another PR 17 hours ago, but maybe it's not their area of expertise, idk.

@jackh726
Copy link
Member

jackh726 commented Sep 9, 2022

Yeah, not really my area of expertise, but I'll try to review this over the weekend.

initializer: Some(initializer),
lint_level,
else_block: Some(else_block),
} => {
Copy link
Member

Choose a reason for hiding this comment

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

It honestly would be helpful to either have a test with mir output that covers this, or an example with the expected mir output in comments here.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Let me try both. 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Speeking too soon. It seems not possible to dump MIR in ui tests yet. I have added explanatory comments here instead.

Copy link
Member

Choose a reason for hiding this comment

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

There is a list of MIR based tests in src/test/mir-opt. Despite the name of the directory, not all are about optimization. You can check out src/test/mir-opt/storage_ranges.rs for an example that just checks the generated MIR. It is also explained here.

Comment on lines 38 to 39
| - `Rc::new(())` is later dropped here
LL | }
| - `Rc::new(())` is later dropped here
Copy link
Member

Choose a reason for hiding this comment

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

This seems weird to me. I would expect that Rc::new(()) would get dropped at the end of the else block, not the end of the function?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sounds right. Indeed this is not expected as Rc::new(()) should be a temporary value and its lifetime terminates at the end of the else block.

else block should be marked as enclosed in a terminating scope. This should fix this bug.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Okay, now the temporaries are properly contained within the else block now.

Copy link
Member

@jackh726 jackh726 left a comment

Choose a reason for hiding this comment

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

Beautiful diagram :)

@jackh726
Copy link
Member

@bors r+

@bors
Copy link
Contributor

bors commented Sep 13, 2022

📌 Commit d2bde7d has been approved by jackh726

It is now in the queue for this repository.

@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 Sep 13, 2022
Dylan-DPC added a commit to Dylan-DPC/rust that referenced this pull request Sep 13, 2022
…ing, r=jackh726

Reorder nesting scopes and declare bindings without drop schedule

Fix rust-lang#99228
Fix rust-lang#99975

Storages are previously not declared before entering the `else` block of a `let .. else` statement. However, when breaking out of the pattern matching into the `else` block, those storages are recorded as scheduled for drops. This is not expected.

This MR fixes this issue by not scheduling the drops for those storages.

cc `@est31`
@bors
Copy link
Contributor

bors commented Sep 14, 2022

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

@bors bors 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-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. labels Sep 14, 2022
@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-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Sep 15, 2022
@bors
Copy link
Contributor

bors commented Sep 15, 2022

⌛ Testing commit 4a5d2a5 with merge 35a0407...

@bors
Copy link
Contributor

bors commented Sep 15, 2022

☀️ Test successful - checks-actions
Approved by: jackh726
Pushing 35a0407 to master...

@bors bors added the merged-by-bors This PR was explicitly merged by bors. label Sep 15, 2022
@bors bors merged commit 35a0407 into rust-lang:master Sep 15, 2022
@rustbot rustbot added this to the 1.65.0 milestone Sep 15, 2022
@rust-highfive
Copy link
Collaborator

📣 Toolstate changed by #101410!

Tested on commit 35a0407.
Direct link to PR: #101410

💔 miri on windows: test-pass → test-fail (cc @RalfJung @oli-obk).
💔 miri on linux: test-pass → test-fail (cc @RalfJung @oli-obk).

rust-highfive added a commit to rust-lang-nursery/rust-toolstate that referenced this pull request Sep 15, 2022
Tested on commit rust-lang/rust@35a0407.
Direct link to PR: <rust-lang/rust#101410>

💔 miri on windows: test-pass → test-fail (cc @RalfJung @oli-obk).
💔 miri on linux: test-pass → test-fail (cc @RalfJung @oli-obk).
@rust-timer
Copy link
Collaborator

Finished benchmarking commit (35a0407): comparison URL.

Overall result: no relevant changes - no action needed

@rustbot label: -perf-regression

Instruction count

This benchmark run did not return any relevant results for this metric.

Max RSS (memory usage)

Results

This is a less reliable metric that may be of interest but was not used to determine the overall result at the top of this comment.

mean1 range count2
Regressions ❌
(primary)
3.1% [3.1%, 3.1%] 1
Regressions ❌
(secondary)
4.0% [2.7%, 5.3%] 2
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) 3.1% [3.1%, 3.1%] 1

Cycles

Results

This is a less reliable metric that may be of interest but was not used to determine the overall result at the top of this comment.

mean1 range count2
Regressions ❌
(primary)
2.3% [2.3%, 2.3%] 1
Regressions ❌
(secondary)
2.1% [2.1%, 2.1%] 1
Improvements ✅
(primary)
-6.1% [-10.0%, -2.2%] 2
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) -3.3% [-10.0%, 2.3%] 3

Footnotes

  1. the arithmetic mean of the percent change 2

  2. number of relevant changes 2

@jackh726
Copy link
Member

It's No Tools Breakage Week and this seems to have broken miri. So likely unlikely we can get a fix for miri fast, we'll need to revert this for now.

@jackh726
Copy link
Member

@Mark-Simulacrum can you confirm the above?

@est31
Copy link
Member

est31 commented Sep 15, 2022

@jackh726 miri is a nightly only tool, no? And according to your link they are exempt?

@jackh726
Copy link
Member

I'm not sure, maybe!

@saethlin
Copy link
Member

This definitely breaks Miri. But the way it breaks Miri is strange to me. Miri now reports this on any program:

error: Undefined Behavior: StorageLive on a local that was already live
    --> /home/ben/.rustup/toolchains/miri/lib/rustlib/src/rust/library/std/src/thread/mod.rs:1058:30
     |
1058 |                     let Some(id) = last.checked_add(1) else {
     |                              ^^ StorageLive on a local that was already live
     |
     = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
     = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
     = note: BACKTRACE:
     = note: inside `std::thread::ThreadId::new` at /home/ben/.rustup/toolchains/miri/lib/rustlib/src/rust/library/std/src/thread/mod.rs:1058:30
     = note: inside `std::thread::Thread::new` at /home/ben/.rustup/toolchains/miri/lib/rustlib/src/rust/library/std/src/thread/mod.rs:1159:43
     = note: inside `std::rt::init` at /home/ben/.rustup/toolchains/miri/lib/rustlib/src/rust/library/std/src/rt.rs:104:22
     = note: inside closure at /home/ben/.rustup/toolchains/miri/lib/rustlib/src/rust/library/std/src/rt.rs:147:42
     = note: inside `std::panicking::try::do_call::<[closure@std::rt::lang_start_internal::{closure#1}], ()>` at /home/ben/.rustup/toolchains/miri/lib/rustlib/src/rust/library/std/src/panicking.rs:492:40
     = note: inside `std::panicking::try::<(), [closure@std::rt::lang_start_internal::{closure#1}]>` at /home/ben/.rustup/toolchains/miri/lib/rustlib/src/rust/library/std/src/panicking.rs:456:19
     = note: inside `std::panic::catch_unwind::<[closure@std::rt::lang_start_internal::{closure#1}], ()>` at /home/ben/.rustup/toolchains/miri/lib/rustlib/src/rust/library/std/src/panic.rs:137:14
     = note: inside `std::rt::lang_start_internal` at /home/ben/.rustup/toolchains/miri/lib/rustlib/src/rust/library/std/src/rt.rs:147:5
     = note: inside `std::rt::lang_start::<()>` at /home/ben/.rustup/toolchains/miri/lib/rustlib/src/rust/library/std/src/rt.rs:165:17

error: aborting due to previous error

@est31
Copy link
Member

est31 commented Sep 16, 2022

Hmm that's interesting. I hope that it's miri being wrong and it's not UB...

@saethlin
Copy link
Member

I'm pretty sure this is UB. Consider this program:

#![feature(let_else)]
fn main() {
    let x: Option<u8> = Some(1);
    let Some(y) = x else {
        panic!();
    };
}

After this PR, it compiles to this MIR:

fn main() -> () {
    let mut _0: ();                      // return place in scope 0 at main.rs:2:11: 2:11
    let _1: std::option::Option<u8>;     // in scope 0 at main.rs:3:9: 3:10
    let mut _2: !;                       // in scope 0 at main.rs:4:26: 6:6
    let _3: ();                          // in scope 0 at /home/ben/rust-master/library/std/src/panic.rs:19:9: 19:50
    let mut _4: !;                       // in scope 0 at /home/ben/rust-master/library/std/src/panic.rs:19:9: 19:50
    let mut _6: isize;                   // in scope 0 at main.rs:4:9: 4:16
    scope 1 {
        debug x => _1;                   // in scope 1 at main.rs:3:9: 3:10
        let _5: u8;                      // in scope 1 at main.rs:4:14: 4:15
        scope 2 {
            debug y => _5;               // in scope 2 at main.rs:4:14: 4:15
        }
    }

    bb0: {
        StorageLive(_1);                 // scope 0 at main.rs:3:9: 3:10
        Deinit(_1);                      // scope 0 at main.rs:3:25: 3:32
        ((_1 as Some).0: u8) = const 1_u8; // scope 0 at main.rs:3:25: 3:32
        discriminant(_1) = 1;            // scope 0 at main.rs:3:25: 3:32
        StorageLive(_5);                 // scope 1 at main.rs:4:14: 4:15
        _6 = discriminant(_1);           // scope 1 at main.rs:4:19: 4:20
        switchInt(move _6) -> [1_isize: bb1, otherwise: bb2]; // scope 1 at main.rs:4:9: 4:16
    }

    bb1: {
        StorageLive(_5);                 // scope 1 at main.rs:4:14: 4:15
        _5 = ((_1 as Some).0: u8);       // scope 1 at main.rs:4:14: 4:15
        _0 = const ();                   // scope 0 at main.rs:2:11: 7:2
        StorageDead(_5);                 // scope 1 at main.rs:7:1: 7:2
        StorageDead(_1);                 // scope 0 at main.rs:7:1: 7:2
        return;                          // scope 0 at main.rs:7:2: 7:2
    }

    bb2: {
        StorageDead(_5);                 // scope 1 at main.rs:7:1: 7:2
        StorageLive(_3);                 // scope 1 at /home/ben/rust-master/library/std/src/panic.rs:18:12: 20:6
        StorageLive(_4);                 // scope 1 at /home/ben/rust-master/library/std/src/panic.rs:19:9: 19:50
        _4 = begin_panic::<&str>(const "explicit panic"); // scope 1 at /home/ben/rust-master/library/std/src/panic.rs:19:9: 19:50
                                         // mir::Constant
                                         // + span: /home/ben/rust-master/library/std/src/panic.rs:19:9: 19:32
                                         // + literal: Const { ty: fn(&str) -> ! {begin_panic::<&str>}, val: Value(<ZST>) }
                                         // mir::Constant
                                         // + span: /home/ben/rust-master/library/std/src/panic.rs:19:33: 19:49
                                         // + literal: Const { ty: &str, val: Value(Slice(..)) }
    }
}

If we branch from bb0 to bb1, we StorageLive(_5) twice, and that's UB.

@est31
Copy link
Member

est31 commented Sep 16, 2022

Mhh yeah that's convincing.

@thomcc
Copy link
Member

thomcc commented Sep 16, 2022

Someone should probably cut a PR reverting this.

@est31
Copy link
Member

est31 commented Sep 16, 2022

I would revert only after there has been a more thorough look on the problem. Maybe the fix is simple. Such a simple fix can then be backported to beta. The revert, if needed, can also easily be backported.

@dingxiangfei2009 dingxiangfei2009 deleted the fix-let-else-scoping branch September 16, 2022 09:33
@dingxiangfei2009
Copy link
Contributor Author

dingxiangfei2009 commented Sep 16, 2022

@est31 Ah okay, I did not know that we cannot declare storages live twice. I have one idea, but it needs to touch the bind_matched_candidate_for_arm_body. I am taking a look.

GuillaumeGomez added a commit to GuillaumeGomez/rust that referenced this pull request Sep 16, 2022
…plett

Stabilize `let else`

:tada:  **Stabilizes the `let else` feature, added by [RFC 3137](rust-lang/rfcs#3137 🎉

Reference PR: rust-lang/reference#1156

closes rust-lang#87335 (`let else` tracking issue)

FCP: rust-lang#93628 (comment)

----------

## Stabilization report

### Summary

The feature allows refutable patterns in `let` statements if the expression is
followed by a diverging `else`:

```Rust
fn get_count_item(s: &str) -> (u64, &str) {
    let mut it = s.split(' ');
    let (Some(count_str), Some(item)) = (it.next(), it.next()) else {
        panic!("Can't segment count item pair: '{s}'");
    };
    let Ok(count) = u64::from_str(count_str) else {
        panic!("Can't parse integer: '{count_str}'");
    };
    (count, item)
}
assert_eq!(get_count_item("3 chairs"), (3, "chairs"));
```

### Differences from the RFC / Desugaring

Outside of desugaring I'm not aware of any differences between the implementation and the RFC. The chosen desugaring has been changed from the RFC's [original](https://rust-lang.github.io/rfcs/3137-let-else.html#reference-level-explanations). You can read a detailed discussion of the implementation history of it in `@cormacrelf` 's [summary](rust-lang#93628 (comment)) in this thread, as well as the [followup](rust-lang#93628 (comment)). Since that followup, further changes have happened to the desugaring, in rust-lang#98574, rust-lang#99518, rust-lang#99954. The later changes were mostly about the drop order: On match, temporaries drop in the same order as they would for a `let` declaration. On mismatch, temporaries drop before the `else` block.

### Test cases

In chronological order as they were merged.

Added by df9a2e0 (rust-lang#87688):

* [`ui/pattern/usefulness/top-level-alternation.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/pattern/usefulness/top-level-alternation.rs) to ensure the unreachable pattern lint visits patterns inside `let else`.

Added by 5b95df4 (rust-lang#87688):

* [`ui/let-else/let-else-bool-binop-init.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-bool-binop-init.rs) to ensure that no lazy boolean expressions (using `&&` or `||`) are allowed in the expression, as the RFC mandates.
* [`ui/let-else/let-else-brace-before-else.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-brace-before-else.rs) to ensure that no `}` directly preceding the `else` is allowed in the expression, as the RFC mandates.
* [`ui/let-else/let-else-check.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-check.rs) to ensure that `#[allow(...)]` attributes added to the entire `let` statement apply for the `else` block.
* [`ui/let-else/let-else-irrefutable.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-irrefutable.rs) to ensure that the `irrefutable_let_patterns` lint fires.
* [`ui/let-else/let-else-missing-semicolon.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-missing-semicolon.rs) to ensure the presence of semicolons at the end of the `let` statement.
* [`ui/let-else/let-else-non-diverging.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-non-diverging.rs) to ensure the `else` block diverges.
* [`ui/let-else/let-else-run-pass.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-run-pass.rs) to ensure the feature works in some simple test case settings.
* [`ui/let-else/let-else-scope.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-scope.rs) to ensure the bindings created by the outer `let` expression are not available in the `else` block of it.

Added by bf7c32a (rust-lang#89965):

* [`ui/let-else/issue-89960.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/issue-89960.rs) as a regression test for the ICE-on-error bug rust-lang#89960 . Later in 102b912 this got removed in favour of more comprehensive tests.

Added by 8565419 (rust-lang#89974):

* [`ui/let-else/let-else-if.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-if.rs) to test for the improved error message that points out that `let else if` is not possible.

Added by 9b45713:

* [`ui/let-else/let-else-allow-unused.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-allow-unused.rs) as a regression test for rust-lang#89807, to ensure that `#[allow(...)]` attributes added to the entire `let` statement apply for bindings created by the `let else` pattern.

Added by 61bcd8d (rust-lang#89841):

* [`ui/let-else/let-else-non-copy.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-non-copy.rs) to ensure that a copy is performed out of non-copy wrapper types. This mirrors `if let` behaviour. The test case bases on rustc internal changes originally meant for rust-lang#89933 but then removed from the PR due to the error prior to the improvements of rust-lang#89841.
* [`ui/let-else/let-else-source-expr-nomove-pass.rs `](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-source-expr-nomove-pass.rs) to ensure that while there is a move of the binding in the successful case, the `else` case can still access the non-matching value. This mirrors `if let` behaviour.

Added by 102b912 (rust-lang#89841):

* [`ui/let-else/let-else-ref-bindings.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-ref-bindings.rs) and [`ui/let-else/let-else-ref-bindings-pass.rs `](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-ref-bindings-pass.rs) to check `ref` and `ref mut` keywords in the pattern work correctly and error when needed.

Added by 2715c5f (rust-lang#89841):

* Match ergonomic tests adapted from the `rfc2005` test suite.

Added by fec8a50 (rust-lang#89841):

* [`ui/let-else/let-else-deref-coercion-annotated.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-deref-coercion-annotated.rs) and [`ui/let-else/let-else-deref-coercion.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-deref-coercion.rs) to check deref coercions.

#### Added since this stabilization report was originally written (2022-02-09)

Added by 76ea566 (rust-lang#94211):

* [`ui/let-else/let-else-destructuring.rs`](https://github.com/rust-lang/rust/blob/1.63.0/src/test/ui/let-else/let-else-destructuring.rs) to give a nice error message if an user tries to do an assignment with a (possibly refutable) pattern and an `else` block, like asked for in rust-lang#93995.

Added by e7730dc (rust-lang#94208):

* [`ui/let-else/let-else-allow-in-expr.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-allow-in-expr.rs) to test whether `#[allow(unused_variables)]` works in the expr, as well as its non presence, as well as putting it on the entire `let else` *affects* the expr, too. This was adding a missing test as pointed out by the stabilization report.
* Expansion of `ui/let-else/let-else-allow-unused.rs` and `ui/let-else/let-else-check.rs` to ensure that non-presence of `#[allow(unused)]` does issue the unused lint. This was adding a missing test case as pointed out by the stabilization report.

Added by 5bd7106 (rust-lang#94208):

* [`ui/let-else/let-else-slicing-error.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-slicing-error.rs), a regression test for rust-lang#92069, which got fixed without addition of a regression test. This resolves a missing test as pointed out by the stabilization report.

Added by 5374688 (rust-lang#98574):

* [`src/test/ui/async-await/async-await-let-else.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/async-await/async-await-let-else.rs) to test the interaction of async/await with `let else`

Added by 6c529de (rust-lang#98574):

* [`src/test/ui/let-else/let-else-temporary-lifetime.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-temporary-lifetime.rs) as a (partial) regression test for rust-lang#98672

Added by 9b56640 (rust-lang#99518):

* [`src/test/ui/let-else/let-else-temp-borrowck.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-temporary-lifetime.rs) as a regression test for rust-lang#93951
* Extension of `src/test/ui/let-else/let-else-temporary-lifetime.rs` to include a partial regression test for rust-lang#98672 (especially regarding `else` drop order)

Added by baf9a7c (rust-lang#99518):

* Extension of `src/test/ui/let-else/let-else-temporary-lifetime.rs` to include a partial regression test for rust-lang#93951, similar to `let-else-temp-borrowck.rs`

Added by 60be2de (rust-lang#99518):

* Extension of `src/test/ui/let-else/let-else-temporary-lifetime.rs` to include a program that can now be compiled thanks to borrow checker implications of rust-lang#99518

Added by 47a7a91 (rust-lang#100132):

* [`src/test/ui/let-else/issue-100103.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/issue-100103.rs), as a regression test for rust-lang#100103, to ensure that there is no ICE when doing `Err(...)?` inside else blocks.

Added by e3c5bd6 (rust-lang#100443):

* [`src/test/ui/let-else/let-else-then-diverge.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-then-diverge.rs), to verify that there is no unreachable code error with the current desugaring.

Added by 9818526 (rust-lang#100443):

* [`src/test/ui/let-else/issue-94176.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/issue-94176.rs), to make sure that a correct span is emitted for a missing trailing expression error. Regression test for rust-lang#94176.

Added by e182d12 (rust-lang#100434):

* [src/test/ui/unpretty/pretty-let-else.rs](https://github.com/rust-lang/rust/blob/master/src/test/ui/unpretty/pretty-let-else.rs), as a regression test to ensure pretty printing works for `let else` (this bug surfaced in many different ways)

Added by e262856 (rust-lang#99954):

* [`src/test/ui/let-else/let-else-temporary-lifetime.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-temporary-lifetime.rs) extended to contain & borrows as well, as this was identified as an earlier issue with the desugaring: rust-lang#98672 (comment)

Added by 2d8460e (rust-lang#99291):

* [`src/test/ui/let-else/let-else-drop-order.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-drop-order.rs) a matrix based test for various drop order behaviour of `let else`. Especially, it verifies equality of `let` and `let else` drop orders, [resolving](rust-lang#93628 (comment)) a [stabilization blocker](rust-lang#93628 (comment)).

Added by 1b87ce0 (rust-lang#101410):

* Edit to `src/test/ui/let-else/let-else-temporary-lifetime.rs` to add the `-Zvalidate-mir` flag, as a regression test for rust-lang#99228

Added by af591eb (rust-lang#101410):

* [`src/test/ui/let-else/issue-99975.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/issue-99975.rs) as a regression test for the ICE rust-lang#99975.

Added by this PR:

* `ui/let-else/let-else.rs`, a simple run-pass check, similar to `ui/let-else/let-else-run-pass.rs`.

### Things not currently tested

* ~~The `#[allow(...)]` tests check whether allow works, but they don't check whether the non-presence of allow causes a lint to fire.~~ → *test added by e7730dc*
* ~~There is no `#[allow(...)]` test for the expression, as there are tests for the pattern and the else block.~~ → *test added by e7730dc*
* ~~`let-else-brace-before-else.rs` forbids the `let ... = {} else {}` pattern and there is a rustfix to obtain `let ... = ({}) else {}`. I'm not sure whether the `.fixed` files are checked by the tooling that they compile. But if there is no such check, it would be neat to make sure that `let ... = ({}) else {}` compiles.~~ → *test added by e7730dc*
* ~~rust-lang#92069 got closed as fixed, but no regression test was added. Not sure it's worth to add one.~~ → *test added by 5bd7106*
* ~~consistency between `let else` and `if let` regarding lifetimes and drop order: rust-lang#93628 (comment) → *test added by 2d8460e*

Edit: they are all tested now.

### Possible future work / Refutable destructuring assignments

[RFC 2909](https://rust-lang.github.io/rfcs/2909-destructuring-assignment.html) specifies destructuring assignment, allowing statements like `FooBar { a, b, c } = foo();`.
As it was stabilized, destructuring assignment only allows *irrefutable* patterns, which before the advent of `let else` were the only patterns that `let` supported.
So the combination of `let else` and destructuring assignments gives reason to think about extensions of the destructuring assignments feature that allow refutable patterns, discussed in rust-lang#93995.

A naive mapping of `let else` to destructuring assignments in the form of `Some(v) = foo() else { ... };` might not be the ideal way. `let else` needs a diverging `else` clause as it introduces new bindings, while assignments have a default behaviour to fall back to if the pattern does not match, in the form of not performing the assignment. Thus, there is no good case to require divergence, or even an `else` clause at all, beyond the need for having *some* introducer syntax so that it is clear to readers that the assignment is not a given (enums and structs look similar). There are better candidates for introducer syntax however than an empty `else {}` clause, like `maybe` which could be added as a keyword on an edition boundary:

```Rust
let mut v = 0;
maybe Some(v) = foo(&v);
maybe Some(v) = foo(&v) else { bar() };
```

Further design discussion is left to an RFC, or the linked issue.
Dylan-DPC added a commit to Dylan-DPC/rust that referenced this pull request Sep 17, 2022
…plett

Stabilize `let else`

:tada:  **Stabilizes the `let else` feature, added by [RFC 3137](rust-lang/rfcs#3137 🎉

Reference PR: rust-lang/reference#1156

closes rust-lang#87335 (`let else` tracking issue)

FCP: rust-lang#93628 (comment)

----------

## Stabilization report

### Summary

The feature allows refutable patterns in `let` statements if the expression is
followed by a diverging `else`:

```Rust
fn get_count_item(s: &str) -> (u64, &str) {
    let mut it = s.split(' ');
    let (Some(count_str), Some(item)) = (it.next(), it.next()) else {
        panic!("Can't segment count item pair: '{s}'");
    };
    let Ok(count) = u64::from_str(count_str) else {
        panic!("Can't parse integer: '{count_str}'");
    };
    (count, item)
}
assert_eq!(get_count_item("3 chairs"), (3, "chairs"));
```

### Differences from the RFC / Desugaring

Outside of desugaring I'm not aware of any differences between the implementation and the RFC. The chosen desugaring has been changed from the RFC's [original](https://rust-lang.github.io/rfcs/3137-let-else.html#reference-level-explanations). You can read a detailed discussion of the implementation history of it in `@cormacrelf` 's [summary](rust-lang#93628 (comment)) in this thread, as well as the [followup](rust-lang#93628 (comment)). Since that followup, further changes have happened to the desugaring, in rust-lang#98574, rust-lang#99518, rust-lang#99954. The later changes were mostly about the drop order: On match, temporaries drop in the same order as they would for a `let` declaration. On mismatch, temporaries drop before the `else` block.

### Test cases

In chronological order as they were merged.

Added by df9a2e0 (rust-lang#87688):

* [`ui/pattern/usefulness/top-level-alternation.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/pattern/usefulness/top-level-alternation.rs) to ensure the unreachable pattern lint visits patterns inside `let else`.

Added by 5b95df4 (rust-lang#87688):

* [`ui/let-else/let-else-bool-binop-init.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-bool-binop-init.rs) to ensure that no lazy boolean expressions (using `&&` or `||`) are allowed in the expression, as the RFC mandates.
* [`ui/let-else/let-else-brace-before-else.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-brace-before-else.rs) to ensure that no `}` directly preceding the `else` is allowed in the expression, as the RFC mandates.
* [`ui/let-else/let-else-check.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-check.rs) to ensure that `#[allow(...)]` attributes added to the entire `let` statement apply for the `else` block.
* [`ui/let-else/let-else-irrefutable.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-irrefutable.rs) to ensure that the `irrefutable_let_patterns` lint fires.
* [`ui/let-else/let-else-missing-semicolon.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-missing-semicolon.rs) to ensure the presence of semicolons at the end of the `let` statement.
* [`ui/let-else/let-else-non-diverging.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-non-diverging.rs) to ensure the `else` block diverges.
* [`ui/let-else/let-else-run-pass.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-run-pass.rs) to ensure the feature works in some simple test case settings.
* [`ui/let-else/let-else-scope.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-scope.rs) to ensure the bindings created by the outer `let` expression are not available in the `else` block of it.

Added by bf7c32a (rust-lang#89965):

* [`ui/let-else/issue-89960.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/issue-89960.rs) as a regression test for the ICE-on-error bug rust-lang#89960 . Later in 102b912 this got removed in favour of more comprehensive tests.

Added by 8565419 (rust-lang#89974):

* [`ui/let-else/let-else-if.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-if.rs) to test for the improved error message that points out that `let else if` is not possible.

Added by 9b45713:

* [`ui/let-else/let-else-allow-unused.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-allow-unused.rs) as a regression test for rust-lang#89807, to ensure that `#[allow(...)]` attributes added to the entire `let` statement apply for bindings created by the `let else` pattern.

Added by 61bcd8d (rust-lang#89841):

* [`ui/let-else/let-else-non-copy.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-non-copy.rs) to ensure that a copy is performed out of non-copy wrapper types. This mirrors `if let` behaviour. The test case bases on rustc internal changes originally meant for rust-lang#89933 but then removed from the PR due to the error prior to the improvements of rust-lang#89841.
* [`ui/let-else/let-else-source-expr-nomove-pass.rs `](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-source-expr-nomove-pass.rs) to ensure that while there is a move of the binding in the successful case, the `else` case can still access the non-matching value. This mirrors `if let` behaviour.

Added by 102b912 (rust-lang#89841):

* [`ui/let-else/let-else-ref-bindings.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-ref-bindings.rs) and [`ui/let-else/let-else-ref-bindings-pass.rs `](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-ref-bindings-pass.rs) to check `ref` and `ref mut` keywords in the pattern work correctly and error when needed.

Added by 2715c5f (rust-lang#89841):

* Match ergonomic tests adapted from the `rfc2005` test suite.

Added by fec8a50 (rust-lang#89841):

* [`ui/let-else/let-else-deref-coercion-annotated.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-deref-coercion-annotated.rs) and [`ui/let-else/let-else-deref-coercion.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-deref-coercion.rs) to check deref coercions.

#### Added since this stabilization report was originally written (2022-02-09)

Added by 76ea566 (rust-lang#94211):

* [`ui/let-else/let-else-destructuring.rs`](https://github.com/rust-lang/rust/blob/1.63.0/src/test/ui/let-else/let-else-destructuring.rs) to give a nice error message if an user tries to do an assignment with a (possibly refutable) pattern and an `else` block, like asked for in rust-lang#93995.

Added by e7730dc (rust-lang#94208):

* [`ui/let-else/let-else-allow-in-expr.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-allow-in-expr.rs) to test whether `#[allow(unused_variables)]` works in the expr, as well as its non presence, as well as putting it on the entire `let else` *affects* the expr, too. This was adding a missing test as pointed out by the stabilization report.
* Expansion of `ui/let-else/let-else-allow-unused.rs` and `ui/let-else/let-else-check.rs` to ensure that non-presence of `#[allow(unused)]` does issue the unused lint. This was adding a missing test case as pointed out by the stabilization report.

Added by 5bd7106 (rust-lang#94208):

* [`ui/let-else/let-else-slicing-error.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-slicing-error.rs), a regression test for rust-lang#92069, which got fixed without addition of a regression test. This resolves a missing test as pointed out by the stabilization report.

Added by 5374688 (rust-lang#98574):

* [`src/test/ui/async-await/async-await-let-else.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/async-await/async-await-let-else.rs) to test the interaction of async/await with `let else`

Added by 6c529de (rust-lang#98574):

* [`src/test/ui/let-else/let-else-temporary-lifetime.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-temporary-lifetime.rs) as a (partial) regression test for rust-lang#98672

Added by 9b56640 (rust-lang#99518):

* [`src/test/ui/let-else/let-else-temp-borrowck.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-temporary-lifetime.rs) as a regression test for rust-lang#93951
* Extension of `src/test/ui/let-else/let-else-temporary-lifetime.rs` to include a partial regression test for rust-lang#98672 (especially regarding `else` drop order)

Added by baf9a7c (rust-lang#99518):

* Extension of `src/test/ui/let-else/let-else-temporary-lifetime.rs` to include a partial regression test for rust-lang#93951, similar to `let-else-temp-borrowck.rs`

Added by 60be2de (rust-lang#99518):

* Extension of `src/test/ui/let-else/let-else-temporary-lifetime.rs` to include a program that can now be compiled thanks to borrow checker implications of rust-lang#99518

Added by 47a7a91 (rust-lang#100132):

* [`src/test/ui/let-else/issue-100103.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/issue-100103.rs), as a regression test for rust-lang#100103, to ensure that there is no ICE when doing `Err(...)?` inside else blocks.

Added by e3c5bd6 (rust-lang#100443):

* [`src/test/ui/let-else/let-else-then-diverge.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-then-diverge.rs), to verify that there is no unreachable code error with the current desugaring.

Added by 9818526 (rust-lang#100443):

* [`src/test/ui/let-else/issue-94176.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/issue-94176.rs), to make sure that a correct span is emitted for a missing trailing expression error. Regression test for rust-lang#94176.

Added by e182d12 (rust-lang#100434):

* [src/test/ui/unpretty/pretty-let-else.rs](https://github.com/rust-lang/rust/blob/master/src/test/ui/unpretty/pretty-let-else.rs), as a regression test to ensure pretty printing works for `let else` (this bug surfaced in many different ways)

Added by e262856 (rust-lang#99954):

* [`src/test/ui/let-else/let-else-temporary-lifetime.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-temporary-lifetime.rs) extended to contain & borrows as well, as this was identified as an earlier issue with the desugaring: rust-lang#98672 (comment)

Added by 2d8460e (rust-lang#99291):

* [`src/test/ui/let-else/let-else-drop-order.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-drop-order.rs) a matrix based test for various drop order behaviour of `let else`. Especially, it verifies equality of `let` and `let else` drop orders, [resolving](rust-lang#93628 (comment)) a [stabilization blocker](rust-lang#93628 (comment)).

Added by 1b87ce0 (rust-lang#101410):

* Edit to `src/test/ui/let-else/let-else-temporary-lifetime.rs` to add the `-Zvalidate-mir` flag, as a regression test for rust-lang#99228

Added by af591eb (rust-lang#101410):

* [`src/test/ui/let-else/issue-99975.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/issue-99975.rs) as a regression test for the ICE rust-lang#99975.

Added by this PR:

* `ui/let-else/let-else.rs`, a simple run-pass check, similar to `ui/let-else/let-else-run-pass.rs`.

### Things not currently tested

* ~~The `#[allow(...)]` tests check whether allow works, but they don't check whether the non-presence of allow causes a lint to fire.~~ → *test added by e7730dc*
* ~~There is no `#[allow(...)]` test for the expression, as there are tests for the pattern and the else block.~~ → *test added by e7730dc*
* ~~`let-else-brace-before-else.rs` forbids the `let ... = {} else {}` pattern and there is a rustfix to obtain `let ... = ({}) else {}`. I'm not sure whether the `.fixed` files are checked by the tooling that they compile. But if there is no such check, it would be neat to make sure that `let ... = ({}) else {}` compiles.~~ → *test added by e7730dc*
* ~~rust-lang#92069 got closed as fixed, but no regression test was added. Not sure it's worth to add one.~~ → *test added by 5bd7106*
* ~~consistency between `let else` and `if let` regarding lifetimes and drop order: rust-lang#93628 (comment) → *test added by 2d8460e*

Edit: they are all tested now.

### Possible future work / Refutable destructuring assignments

[RFC 2909](https://rust-lang.github.io/rfcs/2909-destructuring-assignment.html) specifies destructuring assignment, allowing statements like `FooBar { a, b, c } = foo();`.
As it was stabilized, destructuring assignment only allows *irrefutable* patterns, which before the advent of `let else` were the only patterns that `let` supported.
So the combination of `let else` and destructuring assignments gives reason to think about extensions of the destructuring assignments feature that allow refutable patterns, discussed in rust-lang#93995.

A naive mapping of `let else` to destructuring assignments in the form of `Some(v) = foo() else { ... };` might not be the ideal way. `let else` needs a diverging `else` clause as it introduces new bindings, while assignments have a default behaviour to fall back to if the pattern does not match, in the form of not performing the assignment. Thus, there is no good case to require divergence, or even an `else` clause at all, beyond the need for having *some* introducer syntax so that it is clear to readers that the assignment is not a given (enums and structs look similar). There are better candidates for introducer syntax however than an empty `else {}` clause, like `maybe` which could be added as a keyword on an edition boundary:

```Rust
let mut v = 0;
maybe Some(v) = foo(&v);
maybe Some(v) = foo(&v) else { bar() };
```

Further design discussion is left to an RFC, or the linked issue.
@RalfJung
Copy link
Member

I did not know that we cannot declare storages live twice.

See https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/mir/enum.StatementKind.html#variant.StorageLive for more details, and #99160 for further discussion.

bors added a commit to rust-lang-ci/rust that referenced this pull request Sep 19, 2022
…icate-storage-live, r=oli-obk

Avoid duplicating StorageLive in let-else

cc `@est31`

Fix rust-lang#101867
Fix rust-lang#101932

rust-lang#101410 introduced directives to activate storages of bindings in let-else earlier. However, since it is using the machinery of `match` and friends for pattern matching and binding, those storages are activated for the second time. This PR adjusts this behavior and avoid the duplicated activation for let-else statements.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
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. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
10 participants