|
1 | 1 | use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::source::{indent_of, reindent_multiline}; |
2 | 3 | use clippy_utils::sugg::Sugg; |
3 | 4 | use clippy_utils::ty::option_arg_ty; |
4 | | -use clippy_utils::{is_res_lang_ctor, path_res, peel_blocks, span_contains_comment}; |
| 5 | +use clippy_utils::{get_parent_expr, is_res_lang_ctor, path_res, peel_blocks, span_contains_comment}; |
5 | 6 | use rustc_ast::BindingMode; |
6 | 7 | use rustc_errors::Applicability; |
7 | 8 | use rustc_hir::LangItem::{OptionNone, OptionSome, ResultErr}; |
@@ -132,13 +133,23 @@ fn apply_lint(cx: &LateContext<'_>, expr: &Expr<'_>, scrutinee: &Expr<'_>, is_ok |
132 | 133 | Applicability::MachineApplicable |
133 | 134 | }; |
134 | 135 | let scrut = Sugg::hir_with_applicability(cx, scrutinee, "..", &mut app).maybe_par(); |
| 136 | + let sugg = format!("{scrut}.{method}()"); |
| 137 | + // If the expression being expanded is the `if …` part of an `else if …`, it must be blockified. |
| 138 | + let sugg = if let Some(parent_expr) = get_parent_expr(cx, expr) |
| 139 | + && let ExprKind::If(_, _, Some(else_part)) = parent_expr.kind |
| 140 | + && else_part.hir_id == expr.hir_id |
| 141 | + { |
| 142 | + reindent_multiline(&format!("{{\n {sugg}\n}}"), true, indent_of(cx, parent_expr.span)) |
| 143 | + } else { |
| 144 | + sugg |
| 145 | + }; |
135 | 146 | span_lint_and_sugg( |
136 | 147 | cx, |
137 | 148 | MANUAL_OK_ERR, |
138 | 149 | expr.span, |
139 | 150 | format!("manual implementation of `{method}`"), |
140 | 151 | "replace with", |
141 | | - format!("{scrut}.{method}()"), |
| 152 | + sugg, |
142 | 153 | app, |
143 | 154 | ); |
144 | 155 | } |
0 commit comments