Skip to content

Commit c7a31e1

Browse files
committed
Properly suggest deref in else block
1 parent 26438b4 commit c7a31e1

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

compiler/rustc_typeck/src/check/demand.rs

+22
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
360360
false
361361
}
362362

363+
crate fn hir_id_sole_block_element(
364+
&self,
365+
hir_id: hir::HirId,
366+
) -> Option<&'tcx rustc_hir::Expr<'tcx>> {
367+
let node: Option<Node<'_>> = self.tcx.hir().find(hir_id);
368+
match node {
369+
Some(Node::Expr(rustc_hir::Expr {
370+
kind: rustc_hir::ExprKind::Block(block, ..),
371+
..
372+
})) if block.stmts.len() == 0 => block.expr,
373+
_ => None,
374+
}
375+
}
376+
363377
/// This function is used to determine potential "simple" improvements or users' errors and
364378
/// provide them useful help. For example:
365379
///
@@ -626,6 +640,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
626640
};
627641
let suggestion = if is_struct_pat_shorthand_field {
628642
format!("{}: *{}", code, code)
643+
} else if let Some(expr) =
644+
self.hir_id_sole_block_element(expr.hir_id)
645+
{
646+
if let Ok(inner_code) = sm.span_to_snippet(expr.span) {
647+
format!("*{}", inner_code)
648+
} else {
649+
format!("*{}", code)
650+
}
629651
} else {
630652
format!("*{}", code)
631653
};

src/test/ui/deref-suggestion.rs

+10
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,14 @@ fn main() {
4545
//~^ ERROR mismatched types
4646
let r = R { i: i };
4747
//~^ ERROR mismatched types
48+
49+
50+
let a = &1;
51+
let b = &2;
52+
let val: i32 = if true {
53+
a + 1
54+
} else {
55+
b
56+
//~^ ERROR mismatched types
57+
};
4858
}

src/test/ui/deref-suggestion.stderr

+10-1
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,15 @@ LL | let r = R { i: i };
8989
| expected `u32`, found `&{integer}`
9090
| help: consider dereferencing the borrow: `*i`
9191

92-
error: aborting due to 10 previous errors
92+
error[E0308]: mismatched types
93+
--> $DIR/deref-suggestion.rs:55:9
94+
|
95+
LL | b
96+
| ^
97+
| |
98+
| expected `i32`, found `&{integer}`
99+
| help: consider dereferencing the borrow: `*b`
100+
101+
error: aborting due to 11 previous errors
93102

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

0 commit comments

Comments
 (0)