Skip to content

Commit 98ad0af

Browse files
mibac138LeSeulArtichaut
authored andcommitted
Properly suggest deref in else block
1 parent 5662d93 commit 98ad0af

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

compiler/rustc_typeck/src/check/demand.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
366366
false
367367
}
368368

369+
crate fn hir_id_sole_block_element(
370+
&self,
371+
hir_id: hir::HirId,
372+
) -> Option<&'tcx rustc_hir::Expr<'tcx>> {
373+
let node: Option<Node<'_>> = self.tcx.hir().find(hir_id);
374+
match node {
375+
Some(Node::Expr(rustc_hir::Expr {
376+
kind: rustc_hir::ExprKind::Block(block, ..),
377+
..
378+
})) if block.stmts.len() == 0 => block.expr,
379+
_ => None,
380+
}
381+
}
382+
369383
/// This function is used to determine potential "simple" improvements or users' errors and
370384
/// provide them useful help. For example:
371385
///
@@ -652,6 +666,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
652666
};
653667
let suggestion = if is_struct_pat_shorthand_field {
654668
format!("{}: *{}", code, code)
669+
} else if let Some(expr) =
670+
self.hir_id_sole_block_element(expr.hir_id)
671+
{
672+
if let Ok(inner_code) = sm.span_to_snippet(expr.span) {
673+
format!("*{}", inner_code)
674+
} else {
675+
format!("*{}", code)
676+
}
655677
} else {
656678
format!("*{}", code)
657679
};

src/test/ui/deref-suggestion.rs

Lines changed: 10 additions & 0 deletions
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

Lines changed: 10 additions & 1 deletion
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)