Skip to content

Commit 390ef9b

Browse files
committed
Fix incorrect suggestion for boxing tail expression in blocks
1 parent 88189a7 commit 390ef9b

File tree

4 files changed

+59
-1
lines changed

4 files changed

+59
-1
lines changed

compiler/rustc_hir_typeck/src/demand.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
4444
|| self.suggest_non_zero_new_unwrap(err, expr, expected, expr_ty)
4545
|| self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty)
4646
|| self.suggest_no_capture_closure(err, expected, expr_ty)
47-
|| self.suggest_boxing_when_appropriate(err, expr.span, expr.hir_id, expected, expr_ty)
47+
|| self.suggest_boxing_when_appropriate(
48+
err,
49+
expr.peel_blocks().span,
50+
expr.hir_id,
51+
expected,
52+
expr_ty,
53+
)
4854
|| self.suggest_block_to_brackets_peeling_refs(err, expr, expr_ty, expected)
4955
|| self.suggest_copied_cloned_or_as_ref(err, expr, expr_ty, expected)
5056
|| self.suggest_clone_for_ref(err, expr, expr_ty, expected)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// run-rustfix
2+
trait Trait {}
3+
struct Struct;
4+
impl Trait for Struct {}
5+
fn foo() -> Box<dyn Trait> {
6+
Box::new(Struct)
7+
}
8+
fn main() {
9+
let _ = if true {
10+
foo()
11+
} else {
12+
Box::new(Struct) //~ ERROR E0308
13+
};
14+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// run-rustfix
2+
trait Trait {}
3+
struct Struct;
4+
impl Trait for Struct {}
5+
fn foo() -> Box<dyn Trait> {
6+
Box::new(Struct)
7+
}
8+
fn main() {
9+
let _ = if true {
10+
foo()
11+
} else {
12+
Struct //~ ERROR E0308
13+
};
14+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
error[E0308]: `if` and `else` have incompatible types
2+
--> $DIR/suggest-box-on-divergent-if-else-arms.rs:12:9
3+
|
4+
LL | let _ = if true {
5+
| _____________-
6+
LL | | foo()
7+
| | ----- expected because of this
8+
LL | | } else {
9+
LL | | Struct
10+
| | ^^^^^^ expected `Box<dyn Trait>`, found `Struct`
11+
LL | | };
12+
| |_____- `if` and `else` have incompatible types
13+
|
14+
= note: expected struct `Box<dyn Trait>`
15+
found struct `Struct`
16+
= 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
17+
help: store this in the heap by calling `Box::new`
18+
|
19+
LL | Box::new(Struct)
20+
| +++++++++ +
21+
22+
error: aborting due to 1 previous error
23+
24+
For more information about this error, try `rustc --explain E0308`.

0 commit comments

Comments
 (0)