Skip to content

Commit bcf6cb7

Browse files
Rollup merge of #156949 - bb1yd:detect-missing-else, r=estebank
Detect missing else in let statement Fixes #135857 I add the help message in rustc_resolve. It now will display something like this: ```rust error: expected identifier, found keyword `return` --> ./test.rs:8:24 | 8 | let Some(a) = bar{return;}; | --- ^^^^^^ expected identifier, found keyword | | | while parsing this struct | help: escape `return` to use it as an identifier | 8 | let Some(a) = bar{r#return;}; | ++ error[E0574]: expected struct, variant or union type, found local variable `bar` --> ./test.rs:8:20 | 8 | let Some(a) = bar{return;}; | ^^^ not a struct, variant or union type | help: try adding `else` here: | 8 | let Some(a) = bar else {return;}; | ++++ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0574`. ``` r? estebank
2 parents 6bb1652 + 355aec9 commit bcf6cb7

8 files changed

Lines changed: 105 additions & 6 deletions

File tree

‎compiler/rustc_parse/src/diagnostics.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4651,3 +4651,15 @@ pub(crate) struct SuggestIntroduceTypeParameter {
46514651
pub span: Span,
46524652
pub parameters: String,
46534653
}
4654+
4655+
#[derive(Subdiagnostic)]
4656+
#[suggestion(
4657+
"you might have meant to write a diverging block on a refutable `let` statement by using `let-else`
4658+
for more information, visit <https://doc.rust-lang.org/beta/rust-by-example/flow_control/let_else.html>",
4659+
code = " else ",
4660+
applicability = "maybe-incorrect"
4661+
)]
4662+
pub(crate) struct MissingElseInLet {
4663+
#[primary_span]
4664+
pub span: Span,
4665+
}

‎compiler/rustc_parse/src/parser/expr.rs‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,11 @@ impl<'a> Parser<'a> {
5757
self.current_closure.take();
5858
self.parse_expr_res(Restrictions::empty())
5959
}
60-
60+
#[inline]
61+
pub fn parse_expr_in_let(&mut self) -> PResult<'a, Box<Expr>> {
62+
self.current_closure.take();
63+
self.parse_expr_res(Restrictions::IN_LET)
64+
}
6165
/// Parses an expression, forcing tokens to be collected.
6266
pub fn parse_expr_force_collect(&mut self) -> PResult<'a, Box<Expr>> {
6367
self.current_closure.take();
@@ -3680,11 +3684,12 @@ impl<'a> Parser<'a> {
36803684
Option<ErrorGuaranteed>, /* async blocks are forbidden in Rust 2015 */
36813685
),
36823686
> {
3687+
let open_span = self.prev_token.span; //{
36833688
let mut fields = ThinVec::new();
36843689
let mut base = ast::StructRest::None;
36853690
let mut recovered_async = None;
36863691
let in_if_guard = self.restrictions.contains(Restrictions::IN_IF_GUARD);
3687-
3692+
let in_let = self.restrictions.contains(Restrictions::IN_LET);
36883693
let async_block_err = |e: &mut Diag<'_>, span: Span| {
36893694
crate::diagnostics::AsyncBlockIn2015 { span }.add_to_diag(e);
36903695
crate::diagnostics::HelpUseLatestEdition::new().add_to_diag(e);
@@ -3769,6 +3774,28 @@ impl<'a> Parser<'a> {
37693774
return Err(e);
37703775
}
37713776

3777+
if in_let {
3778+
// Better diagnostic for `foo { return 42; };`
3779+
// We've consumed `foo {` already
3780+
let mut snapshot = self.create_snapshot_for_diagnostic();
3781+
let might_be_stmt = snapshot.token.is_keyword(kw::Return);
3782+
snapshot.consume_block(
3783+
exp!(OpenBrace),
3784+
exp!(CloseBrace),
3785+
super::diagnostics::ConsumeClosingDelim::Yes,
3786+
); //consume to the end of the block, including `}`
3787+
3788+
// make sure the block is at the end by eating a `;`,
3789+
// we shouldn't report such diagnostic for `let a = foo{return 43;}+bar;`
3790+
// also skip the suggestion if the span cross macro boundaries
3791+
if might_be_stmt && snapshot.eat(exp!(Semi)) && pth.span.eq_ctxt(open_span)
3792+
{
3793+
let span = pth.span.between(open_span);
3794+
e.subdiagnostic(crate::diagnostics::MissingElseInLet { span });
3795+
self.restore_snapshot(snapshot);
3796+
return Err(e);
3797+
}
3798+
}
37723799
let guar = e.emit_err();
37733800
if pth == kw::Async {
37743801
recovered_async = Some(guar);

‎compiler/rustc_parse/src/parser/mod.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,9 @@ bitflags::bitflags! {
125125
/// expression, but halts parsing the expression when reaching certain
126126
/// tokens like `=`.
127127
const IS_PAT = 1 << 5;
128+
/// Used to detect a missing `else` in a let statement.
129+
/// e.g. let Some(foo) = bar{return;};
130+
const IN_LET = 1 << 6;
128131
}
129132
}
130133

‎compiler/rustc_parse/src/parser/stmt.rs‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,13 @@ use std::mem;
33
use std::ops::Bound;
44

55
use ast::Label;
6-
use rustc_ast as ast;
76
use rustc_ast::token::{self, Delimiter, InvisibleOrigin, MetaVarKind, TokenKind};
87
use rustc_ast::tokenstream::TokenTree;
98
use rustc_ast::util::classify::{self, TrailingBrace};
109
use rustc_ast::visit::{Visitor, walk_expr};
1110
use rustc_ast::{
12-
AttrStyle, AttrVec, Block, BlockCheckMode, DUMMY_NODE_ID, Expr, ExprKind, HasAttrs, Local,
13-
LocalKind, MacCall, MacCallStmt, MacStmtStyle, Recovered, Stmt, StmtKind,
11+
self as ast, AttrStyle, AttrVec, Block, BlockCheckMode, DUMMY_NODE_ID, Expr, ExprKind,
12+
HasAttrs, Local, LocalKind, MacCall, MacCallStmt, MacStmtStyle, Recovered, Stmt, StmtKind,
1413
};
1514
use rustc_errors::{Applicability, Diag, PResult};
1615
use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym};
@@ -517,7 +516,7 @@ impl<'a> Parser<'a> {
517516
_ => self.eat(exp!(Eq)),
518517
};
519518

520-
Ok(if eq_consumed || eq_optional { Some(self.parse_expr()?) } else { None })
519+
Ok(if eq_consumed || eq_optional { Some(self.parse_expr_in_let()?) } else { None })
521520
}
522521

523522
/// Parses a block. No inner attributes are allowed.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// detect missing else in let statement. (issue #135857)
2+
fn main() {
3+
let foo = Some(1);
4+
let Some(a) = foo{return;};
5+
//~^ HELP you might have meant to write a diverging block
6+
//~| HELP escape `return` to use it as an identifier
7+
//~| ERROR expected identifier, found keyword `return`
8+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
error: expected identifier, found keyword `return`
2+
--> $DIR/detect-missing-else-in-let-1.rs:4:23
3+
|
4+
LL | let Some(a) = foo{return;};
5+
| --- ^^^^^^ expected identifier, found keyword
6+
| |
7+
| while parsing this struct
8+
|
9+
help: escape `return` to use it as an identifier
10+
|
11+
LL | let Some(a) = foo{r#return;};
12+
| ++
13+
help: you might have meant to write a diverging block on a refutable `let` statement by using `let-else`
14+
for more information, visit <https://doc.rust-lang.org/beta/rust-by-example/flow_control/let_else.html>
15+
|
16+
LL | let Some(a) = foo else {return;};
17+
| ++++
18+
19+
error: aborting due to 1 previous error
20+
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// the compiler currently will suggest the user to add `else` in this case
2+
// it shouldn't because `bar` is an irrefutable pattern, the else block would never be valid/useful
3+
// it is currently unmitigated
4+
fn main(){
5+
let foo = 12;
6+
let bar = foo{return;};
7+
//~^ HELP you might have meant to write a diverging block
8+
//~| HELP escape `return` to use it as an identifier
9+
//~| ERROR expected identifier, found keyword `return`
10+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
error: expected identifier, found keyword `return`
2+
--> $DIR/detect-missing-else-in-let-2.rs:6:19
3+
|
4+
LL | let bar = foo{return;};
5+
| --- ^^^^^^ expected identifier, found keyword
6+
| |
7+
| while parsing this struct
8+
|
9+
help: escape `return` to use it as an identifier
10+
|
11+
LL | let bar = foo{r#return;};
12+
| ++
13+
help: you might have meant to write a diverging block on a refutable `let` statement by using `let-else`
14+
for more information, visit <https://doc.rust-lang.org/beta/rust-by-example/flow_control/let_else.html>
15+
|
16+
LL | let bar = foo else {return;};
17+
| ++++
18+
19+
error: aborting due to 1 previous error
20+

0 commit comments

Comments
 (0)