From d1ba2d25d483a65f41ca6277c160e2ea6d813e3b Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 27 May 2022 21:58:48 -0700 Subject: Improve parsing errors and suggestions for bad if statements --- compiler/rustc_parse/src/parser/stmt.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) (limited to 'compiler/rustc_parse/src/parser/stmt.rs') diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index 42355dd93a7..51bd9d2d386 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -432,10 +432,23 @@ impl<'a> Parser<'a> { // // which is valid in other languages, but not Rust. match self.parse_stmt_without_recovery(false, ForceCollect::No) { - // If the next token is an open brace (e.g., `if a b {`), the place- - // inside-a-block suggestion would be more likely wrong than right. + // If the next token is an open brace, e.g., we have: + // + // if expr other_expr { + // ^ ^ ^- lookahead(1) is a brace + // | |- current token is not "else" + // |- (statement we just parsed) + // + // the place-inside-a-block suggestion would be more likely wrong than right. + // + // FIXME(compiler-errors): this should probably parse an arbitrary expr and not + // just lookahead one token, so we can see if there's a brace after _that_, + // since we want to protect against: + // `if 1 1 + 1 {` being suggested as `if { 1 } 1 + 1 {` + // + + Ok(Some(_)) - if self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Brace)) + if (!self.token.is_keyword(kw::Else) + && self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Brace))) || do_not_suggest_help => {} // Do not suggest `if foo println!("") {;}` (as would be seen in test for #46836). Ok(Some(Stmt { kind: StmtKind::Empty, .. })) => {} -- cgit 1.4.1-3-g733a5