Skip to content

Commit fb7cf09

Browse files
Don't suggest dereferencing an else if expression
1 parent 0887944 commit fb7cf09

File tree

2 files changed

+19
-15
lines changed

2 files changed

+19
-15
lines changed

compiler/rustc_typeck/src/check/demand.rs

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
374374
}
375375
}
376376

377+
/// Returns whether the given expression is an `else if`.
378+
crate fn is_else_if_block(&self, expr: &hir::Expr<'_>) -> bool {
379+
if let hir::ExprKind::If(..) = expr.kind {
380+
let parent_id = self.tcx.hir().get_parent_node(expr.hir_id);
381+
if let Some(Node::Expr(hir::Expr {
382+
kind: hir::ExprKind::If(_, _, Some(else_expr)),
383+
..
384+
})) = self.tcx.hir().find(parent_id)
385+
{
386+
return else_expr.hir_id == expr.hir_id;
387+
}
388+
}
389+
false
390+
}
391+
377392
/// This function is used to determine potential "simple" improvements or users' errors and
378393
/// provide them useful help. For example:
379394
///
@@ -660,12 +675,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
660675
};
661676
let suggestion = if is_struct_pat_shorthand_field {
662677
format!("{}: *{}", code, code)
678+
} else if self.is_else_if_block(expr) {
679+
// Don't suggest nonsense like `else *if`
680+
return None;
663681
} else if let Some(expr) = self.maybe_get_block_expr(expr.hir_id) {
664-
if let Ok(inner_code) = sm.span_to_snippet(expr.span) {
665-
format!("*{}", inner_code)
666-
} else {
667-
format!("*{}", code)
668-
}
682+
format!("*{}", sm.span_to_snippet(expr.span).unwrap_or(code))
669683
} else {
670684
format!("*{}", code)
671685
};

src/test/ui/deref-suggestion.stderr

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -125,16 +125,6 @@ LL | || };
125125
| ||_____|
126126
| |______`if` and `else` have incompatible types
127127
| expected `i32`, found `&{integer}`
128-
|
129-
help: consider dereferencing the borrow
130-
|
131-
LL | } else *if true {
132-
LL |
133-
LL | b
134-
LL | } else {
135-
LL | &0
136-
LL | };
137-
|
138128

139129
error: aborting due to 13 previous errors
140130

0 commit comments

Comments
 (0)