]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/manual_assert.rs
Implement assertions and fixes to not emit empty spans without suggestions
[rust.git] / clippy_lints / src / manual_assert.rs
1 use crate::rustc_lint::LintContext;
2 use clippy_utils::diagnostics::span_lint_and_then;
3 use clippy_utils::macros::{root_macro_call, FormatArgsExpn};
4 use clippy_utils::source::snippet_with_applicability;
5 use clippy_utils::{peel_blocks_with_stmt, span_extract_comment, sugg};
6 use rustc_errors::Applicability;
7 use rustc_hir::{Expr, ExprKind, UnOp};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::sym;
11
12 declare_clippy_lint! {
13     /// ### What it does
14     /// Detects `if`-then-`panic!` that can be replaced with `assert!`.
15     ///
16     /// ### Why is this bad?
17     /// `assert!` is simpler than `if`-then-`panic!`.
18     ///
19     /// ### Example
20     /// ```rust
21     /// let sad_people: Vec<&str> = vec![];
22     /// if !sad_people.is_empty() {
23     ///     panic!("there are sad people: {:?}", sad_people);
24     /// }
25     /// ```
26     /// Use instead:
27     /// ```rust
28     /// let sad_people: Vec<&str> = vec![];
29     /// assert!(sad_people.is_empty(), "there are sad people: {:?}", sad_people);
30     /// ```
31     #[clippy::version = "1.57.0"]
32     pub MANUAL_ASSERT,
33     pedantic,
34     "`panic!` and only a `panic!` in `if`-then statement"
35 }
36
37 declare_lint_pass!(ManualAssert => [MANUAL_ASSERT]);
38
39 impl<'tcx> LateLintPass<'tcx> for ManualAssert {
40     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) {
41         if_chain! {
42             if let ExprKind::If(cond, then, None) = expr.kind;
43             if !matches!(cond.kind, ExprKind::Let(_));
44             if !expr.span.from_expansion();
45             let then = peel_blocks_with_stmt(then);
46             if let Some(macro_call) = root_macro_call(then.span);
47             if cx.tcx.item_name(macro_call.def_id) == sym::panic;
48             if !cx.tcx.sess.source_map().is_multiline(cond.span);
49             if let Some(format_args) = FormatArgsExpn::find_nested(cx, then, macro_call.expn);
50             then {
51                 let mut applicability = Applicability::MachineApplicable;
52                 let format_args_snip = snippet_with_applicability(cx, format_args.inputs_span(), "..", &mut applicability);
53                 let cond = cond.peel_drop_temps();
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, not) = match cond.kind {
59                     ExprKind::Unary(UnOp::Not, e) => (e, ""),
60                     _ => (cond, "!"),
61                 };
62                 let cond_sugg = sugg::Sugg::hir_with_applicability(cx, cond, "..", &mut applicability).maybe_par();
63                 let sugg = format!("assert!({not}{cond_sugg}, {format_args_snip});");
64                 // we show to the user the suggestion without the comments, but when applicating the fix, include the comments in the block
65                 span_lint_and_then(
66                     cx,
67                     MANUAL_ASSERT,
68                     expr.span,
69                     "only a `panic!` in `if`-then statement",
70                     |diag| {
71                         // comments can be noisy, do not show them to the user
72                         if !comments.is_empty() {
73                             diag.tool_only_span_suggestion(
74                                         expr.span.shrink_to_lo(),
75                                         "add comments back",
76                                         comments,
77                                         applicability);
78                         }
79                         diag.span_suggestion(
80                                     expr.span,
81                                     "try instead",
82                                     sugg,
83                                     applicability);
84                                      }
85
86                 );
87             }
88         }
89     }
90 }