Skip to content

Commit 76ea566

Browse files
committed
Better error if the user tries to do assignment ... else
1 parent c1aa854 commit 76ea566

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

compiler/rustc_parse/src/parser/stmt.rs

+10
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,16 @@ impl<'a> Parser<'a> {
103103
} else {
104104
self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs))
105105
}?;
106+
if matches!(e.kind, ExprKind::Assign(..)) && self.eat_keyword(kw::Else) {
107+
let bl = self.parse_block()?;
108+
// Destructuring assignment ... else.
109+
// This is not allowed, but point it out in a nice way.
110+
let mut err = self.struct_span_err(
111+
e.span.to(bl.span),
112+
"<assignment> ... else { ... } is not allowed",
113+
);
114+
err.emit();
115+
}
106116
self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))
107117
} else {
108118
self.error_outer_attrs(&attrs.take_for_recovery());
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#![feature(let_else)]
2+
#[derive(Debug)]
3+
enum Foo {
4+
Done,
5+
Nested(Option<&'static Foo>),
6+
}
7+
8+
fn walk(mut value: &Foo) {
9+
loop {
10+
println!("{:?}", value);
11+
&Foo::Nested(Some(value)) = value else { break }; //~ ERROR invalid left-hand side of assignment
12+
//~^ERROR <assignment> ... else { ... } is not allowed
13+
}
14+
}
15+
16+
fn main() {
17+
walk(&Foo::Done);
18+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
error: <assignment> ... else { ... } is not allowed
2+
--> $DIR/let-else-destructuring.rs:11:9
3+
|
4+
LL | &Foo::Nested(Some(value)) = value else { break };
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6+
7+
error[E0070]: invalid left-hand side of assignment
8+
--> $DIR/let-else-destructuring.rs:11:35
9+
|
10+
LL | &Foo::Nested(Some(value)) = value else { break };
11+
| ------------------------- ^
12+
| |
13+
| cannot assign to this expression
14+
15+
error: aborting due to 2 previous errors
16+
17+
For more information about this error, try `rustc --explain E0070`.

0 commit comments

Comments
 (0)