]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/if_not_else.rs
c56f67df0618f3b6d47e1d2193ae1e613333db55
[rust.git] / clippy_lints / src / if_not_else.rs
1 //! lint on if branches that could be swapped so no `!` operation is necessary
2 //! on the condition
3
4 use clippy_utils::diagnostics::span_lint_and_help;
5 use rustc_ast::ast::{BinOpKind, Expr, ExprKind, UnOp};
6 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
7 use rustc_middle::lint::in_external_macro;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for usage of `!` or `!=` in an if condition with an
12     /// else branch.
13     ///
14     /// **Why is this bad?** Negations reduce the readability of statements.
15     ///
16     /// **Known problems:** None.
17     ///
18     /// **Example:**
19     /// ```rust
20     /// # let v: Vec<usize> = vec![];
21     /// # fn a() {}
22     /// # fn b() {}
23     /// if !v.is_empty() {
24     ///     a()
25     /// } else {
26     ///     b()
27     /// }
28     /// ```
29     ///
30     /// Could be written:
31     ///
32     /// ```rust
33     /// # let v: Vec<usize> = vec![];
34     /// # fn a() {}
35     /// # fn b() {}
36     /// if v.is_empty() {
37     ///     b()
38     /// } else {
39     ///     a()
40     /// }
41     /// ```
42     pub IF_NOT_ELSE,
43     pedantic,
44     "`if` branches that could be swapped so no negation operation is necessary on the condition"
45 }
46
47 declare_lint_pass!(IfNotElse => [IF_NOT_ELSE]);
48
49 impl EarlyLintPass for IfNotElse {
50     fn check_expr(&mut self, cx: &EarlyContext<'_>, item: &Expr) {
51         if in_external_macro(cx.sess(), item.span) {
52             return;
53         }
54         if let ExprKind::If(ref cond, _, Some(ref els)) = item.kind {
55             if let ExprKind::Block(..) = els.kind {
56                 match cond.kind {
57                     ExprKind::Unary(UnOp::Not, _) => {
58                         span_lint_and_help(
59                             cx,
60                             IF_NOT_ELSE,
61                             item.span,
62                             "unnecessary boolean `not` operation",
63                             None,
64                             "remove the `!` and swap the blocks of the `if`/`else`",
65                         );
66                     },
67                     ExprKind::Binary(ref kind, _, _) if kind.node == BinOpKind::Ne => {
68                         span_lint_and_help(
69                             cx,
70                             IF_NOT_ELSE,
71                             item.span,
72                             "unnecessary `!=` operation",
73                             None,
74                             "change to `==` and swap the blocks of the `if`/`else`",
75                         );
76                     },
77                     _ => (),
78                 }
79             }
80         }
81     }
82 }