Skip to content

Commit

Permalink
Fix incorrect suggestion for boxing tail expression in blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
estebank committed Jan 22, 2024
1 parent 88189a7 commit 390ef9b
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 1 deletion.
8 changes: 7 additions & 1 deletion compiler/rustc_hir_typeck/src/demand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
|| self.suggest_non_zero_new_unwrap(err, expr, expected, expr_ty)
|| self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty)
|| self.suggest_no_capture_closure(err, expected, expr_ty)
|| self.suggest_boxing_when_appropriate(err, expr.span, expr.hir_id, expected, expr_ty)
|| self.suggest_boxing_when_appropriate(
err,
expr.peel_blocks().span,
expr.hir_id,
expected,
expr_ty,
)
|| self.suggest_block_to_brackets_peeling_refs(err, expr, expr_ty, expected)
|| self.suggest_copied_cloned_or_as_ref(err, expr, expr_ty, expected)
|| self.suggest_clone_for_ref(err, expr, expr_ty, expected)
Expand Down
14 changes: 14 additions & 0 deletions tests/ui/typeck/suggest-box-on-divergent-if-else-arms.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// run-rustfix
trait Trait {}
struct Struct;
impl Trait for Struct {}
fn foo() -> Box<dyn Trait> {
Box::new(Struct)
}
fn main() {
let _ = if true {
foo()
} else {
Box::new(Struct) //~ ERROR E0308
};
}
14 changes: 14 additions & 0 deletions tests/ui/typeck/suggest-box-on-divergent-if-else-arms.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// run-rustfix
trait Trait {}
struct Struct;
impl Trait for Struct {}
fn foo() -> Box<dyn Trait> {
Box::new(Struct)
}
fn main() {
let _ = if true {
foo()
} else {
Struct //~ ERROR E0308
};
}
24 changes: 24 additions & 0 deletions tests/ui/typeck/suggest-box-on-divergent-if-else-arms.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
error[E0308]: `if` and `else` have incompatible types
--> $DIR/suggest-box-on-divergent-if-else-arms.rs:12:9
|
LL | let _ = if true {
| _____________-
LL | | foo()
| | ----- expected because of this
LL | | } else {
LL | | Struct
| | ^^^^^^ expected `Box<dyn Trait>`, found `Struct`
LL | | };
| |_____- `if` and `else` have incompatible types
|
= note: expected struct `Box<dyn Trait>`
found struct `Struct`
= note: for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html
help: store this in the heap by calling `Box::new`
|
LL | Box::new(Struct)
| +++++++++ +

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0308`.

0 comments on commit 390ef9b

Please sign in to comment.