Skip to content

Commit d804402

Browse files
Don't suggest boxing an empty if/else arm
1 parent 5dfc17f commit d804402

File tree

3 files changed

+44
-1
lines changed

3 files changed

+44
-1
lines changed

compiler/rustc_infer/src/infer/error_reporting/mod.rs

+19-1
Original file line numberDiff line numberDiff line change
@@ -847,7 +847,25 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
847847
) {
848848
err.subdiagnostic(subdiag);
849849
}
850-
if let Some(ret_sp) = opt_suggest_box_span {
850+
// don't suggest wrapping either blocks in `if .. {} else {}`
851+
let is_empty_arm = |id| {
852+
let hir::Node::Block(blk) = self.tcx.hir().get(id)
853+
else {
854+
return false;
855+
};
856+
if blk.expr.is_some() || !blk.stmts.is_empty() {
857+
return false;
858+
}
859+
let Some((_, hir::Node::Expr(expr))) = self.tcx.hir().parent_iter(id).nth(1)
860+
else {
861+
return false;
862+
};
863+
matches!(expr.kind, hir::ExprKind::If(..))
864+
};
865+
if let Some(ret_sp) = opt_suggest_box_span
866+
&& !is_empty_arm(then_id)
867+
&& !is_empty_arm(else_id)
868+
{
851869
self.suggest_boxing_for_return_impl_trait(
852870
err,
853871
ret_sp,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
fn test() -> impl std::fmt::Debug {
2+
if true {
3+
"boo2"
4+
} else {
5+
//~^ ERROR `if` and `else` have incompatible types
6+
}
7+
}
8+
9+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error[E0308]: `if` and `else` have incompatible types
2+
--> $DIR/dont-suggest-box-on-empty-else-arm.rs:4:12
3+
|
4+
LL | if true {
5+
| ------- `if` and `else` have incompatible types
6+
LL | "boo2"
7+
| ------ expected because of this
8+
LL | } else {
9+
| ____________^
10+
LL | |
11+
LL | | }
12+
| |_____^ expected `&str`, found `()`
13+
14+
error: aborting due to previous error
15+
16+
For more information about this error, try `rustc --explain E0308`.

0 commit comments

Comments
 (0)