Skip to content

Commit

Permalink
Properly suggest deref in else block
Browse files Browse the repository at this point in the history
  • Loading branch information
mibac138 authored and LeSeulArtichaut committed Apr 2, 2021
1 parent 5662d93 commit 98ad0af
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
22 changes: 22 additions & 0 deletions compiler/rustc_typeck/src/check/demand.rs
Expand Up @@ -366,6 +366,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
false
}

crate fn hir_id_sole_block_element(
&self,
hir_id: hir::HirId,
) -> Option<&'tcx rustc_hir::Expr<'tcx>> {
let node: Option<Node<'_>> = self.tcx.hir().find(hir_id);
match node {
Some(Node::Expr(rustc_hir::Expr {
kind: rustc_hir::ExprKind::Block(block, ..),
..
})) if block.stmts.len() == 0 => block.expr,
_ => None,
}
}

/// This function is used to determine potential "simple" improvements or users' errors and
/// provide them useful help. For example:
///
Expand Down Expand Up @@ -652,6 +666,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
};
let suggestion = if is_struct_pat_shorthand_field {
format!("{}: *{}", code, code)
} else if let Some(expr) =
self.hir_id_sole_block_element(expr.hir_id)
{
if let Ok(inner_code) = sm.span_to_snippet(expr.span) {
format!("*{}", inner_code)
} else {
format!("*{}", code)
}
} else {
format!("*{}", code)
};
Expand Down
10 changes: 10 additions & 0 deletions src/test/ui/deref-suggestion.rs
Expand Up @@ -45,4 +45,14 @@ fn main() {
//~^ ERROR mismatched types
let r = R { i: i };
//~^ ERROR mismatched types


let a = &1;
let b = &2;
let val: i32 = if true {
a + 1
} else {
b
//~^ ERROR mismatched types
};
}
11 changes: 10 additions & 1 deletion src/test/ui/deref-suggestion.stderr
Expand Up @@ -89,6 +89,15 @@ LL | let r = R { i: i };
| expected `u32`, found `&{integer}`
| help: consider dereferencing the borrow: `*i`

error: aborting due to 10 previous errors
error[E0308]: mismatched types
--> $DIR/deref-suggestion.rs:55:9
|
LL | b
| ^
| |
| expected `i32`, found `&{integer}`
| help: consider dereferencing the borrow: `*b`

error: aborting due to 11 previous errors

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

0 comments on commit 98ad0af

Please sign in to comment.