Don't suggest boxing an empty if/else arm

This commit is contained in:
Michael Goulet 2023-06-11 00:19:56 +00:00
parent 5dfc17f045
commit d80440263c
3 changed files with 44 additions and 1 deletions

View File

@ -847,7 +847,25 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
) {
err.subdiagnostic(subdiag);
}
if let Some(ret_sp) = opt_suggest_box_span {
// don't suggest wrapping either blocks in `if .. {} else {}`
let is_empty_arm = |id| {
let hir::Node::Block(blk) = self.tcx.hir().get(id)
else {
return false;
};
if blk.expr.is_some() || !blk.stmts.is_empty() {
return false;
}
let Some((_, hir::Node::Expr(expr))) = self.tcx.hir().parent_iter(id).nth(1)
else {
return false;
};
matches!(expr.kind, hir::ExprKind::If(..))
};
if let Some(ret_sp) = opt_suggest_box_span
&& !is_empty_arm(then_id)
&& !is_empty_arm(else_id)
{
self.suggest_boxing_for_return_impl_trait(
err,
ret_sp,

View File

@ -0,0 +1,9 @@
fn test() -> impl std::fmt::Debug {
if true {
"boo2"
} else {
//~^ ERROR `if` and `else` have incompatible types
}
}
fn main() {}

View File

@ -0,0 +1,16 @@
error[E0308]: `if` and `else` have incompatible types
--> $DIR/dont-suggest-box-on-empty-else-arm.rs:4:12
|
LL | if true {
| ------- `if` and `else` have incompatible types
LL | "boo2"
| ------ expected because of this
LL | } else {
| ____________^
LL | |
LL | | }
| |_____^ expected `&str`, found `()`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.