Skip to content

Commit 09ca6a4

Browse files
authored
Rollup merge of rust-lang#71976 - mibac138:let-recovery, r=estebank
Improve diagnostics for `let x += 1` Fixes(?) rust-lang#66736 The code responsible for the `E0404` errors is [here](https://github.com/rust-lang/rust/blob/master/src/librustc_parse/parser/ty.rs#L399-L424) which I don't think can be easily modified to prevent emitting an error in one specific case. Because of this I couldn't get rid of `E0404` and instead added `E0067` along with a help message which will fix the problem. r? @estebank
2 parents 2e9e434 + 98532a3 commit 09ca6a4

File tree

3 files changed

+50
-2
lines changed

3 files changed

+50
-2
lines changed

src/librustc_parse/parser/stmt.rs

+22-2
Original file line numberDiff line numberDiff line change
@@ -216,8 +216,28 @@ impl<'a> Parser<'a> {
216216
}
217217

218218
/// Parses the RHS of a local variable declaration (e.g., '= 14;').
219-
fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
220-
if self.eat(&token::Eq) || skip_eq { Ok(Some(self.parse_expr()?)) } else { Ok(None) }
219+
fn parse_initializer(&mut self, eq_optional: bool) -> PResult<'a, Option<P<Expr>>> {
220+
let eq_consumed = match self.token.kind {
221+
token::BinOpEq(..) => {
222+
// Recover `let x <op>= 1` as `let x = 1`
223+
self.struct_span_err(
224+
self.token.span,
225+
"can't reassign to an uninitialized variable",
226+
)
227+
.span_suggestion_short(
228+
self.token.span,
229+
"initialize the variable",
230+
"=".to_string(),
231+
Applicability::MaybeIncorrect,
232+
)
233+
.emit();
234+
self.bump();
235+
true
236+
}
237+
_ => self.eat(&token::Eq),
238+
};
239+
240+
Ok(if eq_consumed || eq_optional { Some(self.parse_expr()?) } else { None })
221241
}
222242

223243
/// Parses a block. No inner attributes are allowed.

src/test/ui/parser/let-binop.rs

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
fn main() {
2+
let a: i8 *= 1; //~ ERROR can't reassign to an uninitialized variable
3+
let _ = a;
4+
let b += 1; //~ ERROR can't reassign to an uninitialized variable
5+
let _ = b;
6+
let c *= 1; //~ ERROR can't reassign to an uninitialized variable
7+
let _ = c;
8+
}

src/test/ui/parser/let-binop.stderr

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
error: can't reassign to an uninitialized variable
2+
--> $DIR/let-binop.rs:2:15
3+
|
4+
LL | let a: i8 *= 1;
5+
| ^^ help: initialize the variable
6+
7+
error: can't reassign to an uninitialized variable
8+
--> $DIR/let-binop.rs:4:11
9+
|
10+
LL | let b += 1;
11+
| ^^ help: initialize the variable
12+
13+
error: can't reassign to an uninitialized variable
14+
--> $DIR/let-binop.rs:6:11
15+
|
16+
LL | let c *= 1;
17+
| ^^ help: initialize the variable
18+
19+
error: aborting due to 3 previous errors
20+

0 commit comments

Comments
 (0)