Provide suggestion when encountering match () { () => 1 } + match () { () => 1 }

```
error[E0308]: mismatched types
  --> $DIR/expr-as-stmt.rs:69:5
   |
LL |     match () { () => 1 } + match () { () => 1 }
   |     ^^^^^^^^^^^^^^^^^^^^ expected `()`, found integer
   |
help: consider using a semicolon here
   |
LL |     match () { () => 1 }; + match () { () => 1 }
   |                         +
help: alternatively, parentheses are required to parse this as an expression
   |
LL |     (match () { () => 1 }) + match () { () => 1 }
   |     +                    +
```

Parentheses are needed for the `match` to be unambiguously parsed as an expression and not a statement when chaining with binops that are also unops.
This commit is contained in:
Esteban Küber 2025-08-31 00:42:58 +00:00
parent fe55364329
commit a7e32a5319
3 changed files with 35 additions and 6 deletions

View file

@ -1914,6 +1914,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.check_expr_has_type_or_error(expr, self.tcx.types.unit, |err| {
if expr.can_have_side_effects() {
self.suggest_semicolon_at_end(expr.span, err);
if let hir::ExprKind::Match(..) = expr.kind {
err.multipart_suggestion(
"alternatively, parentheses are required to parse this as an \
expression",
vec![
(expr.span.shrink_to_lo(), "(".to_string()),
(expr.span.shrink_to_hi(), ")".to_string()),
],
Applicability::MaybeIncorrect,
);
}
}
});
}

View file

@ -227,9 +227,16 @@ error[E0308]: mismatched types
--> $DIR/expr-as-stmt.rs:69:5
|
LL | match () { () => 1 } + match () { () => 1 }
| ^^^^^^^^^^^^^^^^^^^^- help: consider using a semicolon here
| |
| expected `()`, found integer
| ^^^^^^^^^^^^^^^^^^^^ expected `()`, found integer
|
help: consider using a semicolon here
|
LL | match () { () => 1 }; + match () { () => 1 }
| +
help: alternatively, parentheses are required to parse this as an expression
|
LL | (match () { () => 1 }) + match () { () => 1 }
| + +
error[E0308]: mismatched types
--> $DIR/expr-as-stmt.rs:75:14

View file

@ -28,9 +28,20 @@ LL | | 4 => 1,
LL | | 3 => 2,
LL | | _ => 2
LL | | }
| | ^- help: consider using a semicolon here
| |_____|
| expected `()`, found integer
| |_____^ expected `()`, found integer
|
help: consider using a semicolon here
|
LL | };
| +
help: alternatively, parentheses are required to parse this as an expression
|
LL ~ (match 3 {
LL | 4 => 1,
LL | 3 => 2,
LL | _ => 2
LL ~ })
|
error: aborting due to 2 previous errors