]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/manual_assert.rs
Rollup merge of #90741 - mbartlett21:patch-4, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / manual_assert.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::higher::PanicExpn;
3 use clippy_utils::source::snippet_with_applicability;
4 use clippy_utils::{is_expn_of, sugg};
5 use rustc_errors::Applicability;
6 use rustc_hir::{Block, Expr, ExprKind, StmtKind, UnOp};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9
10 declare_clippy_lint! {
11     /// ### What it does
12     /// Detects `if`-then-`panic!` that can be replaced with `assert!`.
13     ///
14     /// ### Why is this bad?
15     /// `assert!` is simpler than `if`-then-`panic!`.
16     ///
17     /// ### Example
18     /// ```rust
19     /// let sad_people: Vec<&str> = vec![];
20     /// if !sad_people.is_empty() {
21     ///     panic!("there are sad people: {:?}", sad_people);
22     /// }
23     /// ```
24     /// Use instead:
25     /// ```rust
26     /// let sad_people: Vec<&str> = vec![];
27     /// assert!(sad_people.is_empty(), "there are sad people: {:?}", sad_people);
28     /// ```
29     #[clippy::version = "1.57.0"]
30     pub MANUAL_ASSERT,
31     pedantic,
32     "`panic!` and only a `panic!` in `if`-then statement"
33 }
34
35 declare_lint_pass!(ManualAssert => [MANUAL_ASSERT]);
36
37 impl LateLintPass<'_> for ManualAssert {
38     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
39         if_chain! {
40             if let Expr {
41                 kind: ExprKind:: If(cond, Expr {
42                     kind: ExprKind::Block(
43                         Block {
44                             stmts: [stmt],
45                             ..
46                         },
47                         _),
48                     ..
49                 }, None),
50                 ..
51             } = &expr;
52             if is_expn_of(stmt.span, "panic").is_some();
53             if !matches!(cond.kind, ExprKind::Let(_, _, _));
54             if let StmtKind::Semi(semi) = stmt.kind;
55             if !cx.tcx.sess.source_map().is_multiline(cond.span);
56
57             then {
58                 let call = if_chain! {
59                     if let ExprKind::Block(block, _) = semi.kind;
60                     if let Some(init) = block.expr;
61                     then {
62                         init
63                     } else {
64                         semi
65                     }
66                 };
67                 let span = if let Some(panic_expn) = PanicExpn::parse(call) {
68                     match *panic_expn.format_args.value_args {
69                         [] => panic_expn.format_args.format_string_span,
70                         [.., last] => panic_expn.format_args.format_string_span.to(last.span),
71                     }
72                 } else if let ExprKind::Call(_, [format_args]) = call.kind {
73                     format_args.span
74                 } else {
75                     return
76                 };
77                 let mut applicability = Applicability::MachineApplicable;
78                 let sugg = snippet_with_applicability(cx, span, "..", &mut applicability);
79                 let cond_sugg = if let ExprKind::DropTemps(e, ..) = cond.kind {
80                     if let Expr{kind: ExprKind::Unary(UnOp::Not, not_expr), ..} = e {
81                          sugg::Sugg::hir_with_applicability(cx, not_expr, "..", &mut applicability).maybe_par().to_string()
82                     } else {
83                        format!("!{}", sugg::Sugg::hir_with_applicability(cx, e, "..", &mut applicability).maybe_par())
84                     }
85                 } else {
86                    format!("!{}", sugg::Sugg::hir_with_applicability(cx, cond, "..", &mut applicability).maybe_par())
87                 };
88
89                 span_lint_and_sugg(
90                     cx,
91                     MANUAL_ASSERT,
92                     expr.span,
93                     "only a `panic!` in `if`-then statement",
94                     "try",
95                     format!("assert!({}, {});", cond_sugg, sugg),
96                     Applicability::MachineApplicable,
97                 );
98             }
99         }
100     }
101 }