@@ -2713,6 +2713,36 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
27132713 ) ) ;
27142714 }
27152715
2716+ // Don't try to suggest ref/deref on an `if` expression, because:
2717+ // - The `if` could be part of a desugared `if else` statement,
2718+ // which would create impossible suggestions such as `if ... { ... } else &if { ... } else { ... }`.
2719+ // - In general the suggestions it creates such as `&if ... { ... } else { ... }` are kind of ugly.
2720+ // We try to generate a suggestion such as `if ... { &... } else { &... }` instead.
2721+ if let hir:: ExprKind :: If ( _c, then, els) = expr. kind {
2722+ // If there is no `else`, the return type of this `if` will be (), so suggesting to change the `then` block is useless
2723+ let Some ( els) = els else {
2724+ return None ;
2725+ } ;
2726+ let ( mut then_suggs, help, app, verbose, mutref) =
2727+ self . suggest_deref_or_ref ( then, checked_ty, expected) ?;
2728+ let ( else_suggs, ..) =
2729+ self . suggest_deref_or_ref ( els, checked_ty, expected) ?;
2730+ then_suggs. extend ( else_suggs) ;
2731+ return Some ( ( then_suggs, help, app, verbose, mutref) ) ;
2732+ }
2733+
2734+ // Don't try to suggest ref/deref on a `block` expression, because it is ugly.
2735+ // It creates suggestions such as `&{ ... }`.
2736+ // Instead suggest `{ ...; &... }` ref/deref on the final expression
2737+ if let hir:: ExprKind :: Block ( block, _) = expr. kind {
2738+ // If the block expression does not have a final expression the type will be `()`,
2739+ // in which case there are no good ref/deref suggestions to be made.
2740+ let Some ( expr) = block. expr else {
2741+ return None ;
2742+ } ;
2743+ return self . suggest_deref_or_ref ( expr, checked_ty, expected) ;
2744+ }
2745+
27162746 if let Some ( ( sugg, msg) ) = self . can_use_as_ref ( expr) {
27172747 return Some ( (
27182748 sugg,
0 commit comments