|
1 | 1 | use clippy_utils::diagnostics::span_lint_and_then; |
2 | 2 | use clippy_utils::macros::{is_panic, root_macro_call}; |
| 3 | +use clippy_utils::source::{indent_of, reindent_multiline}; |
3 | 4 | use clippy_utils::{higher, is_else_clause, is_parent_stmt, peel_blocks_with_stmt, span_extract_comment, sugg}; |
4 | 5 | use rustc_errors::Applicability; |
5 | 6 | use rustc_hir::{Expr, ExprKind}; |
@@ -50,32 +51,32 @@ impl<'tcx> LateLintPass<'tcx> for ManualAssert { |
50 | 51 | // Should this have a config value? |
51 | 52 | && !is_else_clause(cx.tcx, expr) |
52 | 53 | { |
53 | | - let mut applicability = Applicability::MachineApplicable; |
54 | | - let mut comments = span_extract_comment(cx.sess().source_map(), expr.span); |
55 | | - if !comments.is_empty() { |
56 | | - comments += "\n"; |
57 | | - } |
58 | | - let cond_sugg = !sugg::Sugg::hir_with_context(cx, cond, expr.span.ctxt(), "..", &mut applicability); |
59 | | - let semicolon = if is_parent_stmt(cx, expr.hir_id) { ";" } else { "" }; |
60 | | - let sugg = format!("assert!({cond_sugg}, {format_args_snip}){semicolon}"); |
61 | | - // we show to the user the suggestion without the comments, but when applying the fix, include the |
62 | | - // comments in the block |
63 | 54 | span_lint_and_then( |
64 | 55 | cx, |
65 | 56 | MANUAL_ASSERT, |
66 | 57 | expr.span, |
67 | 58 | "only a `panic!` in `if`-then statement", |
68 | 59 | |diag| { |
69 | | - // comments can be noisy, do not show them to the user |
| 60 | + let mut applicability = Applicability::MachineApplicable; |
| 61 | + let mut comments = span_extract_comment(cx.sess().source_map(), expr.span); |
70 | 62 | if !comments.is_empty() { |
71 | | - diag.tool_only_span_suggestion( |
72 | | - expr.span.shrink_to_lo(), |
73 | | - "add comments back", |
74 | | - comments, |
75 | | - applicability, |
76 | | - ); |
| 63 | + comments += "\n"; |
77 | 64 | } |
78 | | - diag.span_suggestion(expr.span, "try instead", sugg, applicability); |
| 65 | + let cond_sugg = !sugg::Sugg::hir_with_context(cx, cond, expr.span.ctxt(), "..", &mut applicability); |
| 66 | + let semicolon = if is_parent_stmt(cx, expr.hir_id) { ";" } else { "" }; |
| 67 | + |
| 68 | + let indent = indent_of(cx, expr.span); |
| 69 | + let full_sugg = reindent_multiline( |
| 70 | + format!("{comments}assert!({cond_sugg}, {format_args_snip}){semicolon}").as_str(), |
| 71 | + true, |
| 72 | + indent, |
| 73 | + ); |
| 74 | + diag.span_suggestion_verbose( |
| 75 | + expr.span, |
| 76 | + "replace `if`-then-`panic!` with `assert!`", |
| 77 | + full_sugg, |
| 78 | + applicability, |
| 79 | + ); |
79 | 80 | }, |
80 | 81 | ); |
81 | 82 | } |
|
0 commit comments