]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/if_not_else.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[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 rustc::lint::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
5 use rustc::{declare_tool_lint, lint_array};
6 use syntax::ast::*;
7
8 use crate::utils::span_help_and_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     /// if !v.is_empty() {
21     ///     a()
22     /// } else {
23     ///     b()
24     /// }
25     /// ```
26     ///
27     /// Could be written:
28     ///
29     /// ```rust
30     /// if v.is_empty() {
31     ///     b()
32     /// } else {
33     ///     a()
34     /// }
35     /// ```
36     pub IF_NOT_ELSE,
37     pedantic,
38     "`if` branches that could be swapped so no negation operation is necessary on the condition"
39 }
40
41 pub struct IfNotElse;
42
43 impl LintPass for IfNotElse {
44     fn get_lints(&self) -> LintArray {
45         lint_array!(IF_NOT_ELSE)
46     }
47
48     fn name(&self) -> &'static str {
49         "IfNotElse"
50     }
51 }
52
53 impl EarlyLintPass for IfNotElse {
54     fn check_expr(&mut self, cx: &EarlyContext<'_>, item: &Expr) {
55         if in_external_macro(cx.sess(), item.span) {
56             return;
57         }
58         if let ExprKind::If(ref cond, _, Some(ref els)) = item.node {
59             if let ExprKind::Block(..) = els.node {
60                 match cond.node {
61                     ExprKind::Unary(UnOp::Not, _) => {
62                         span_help_and_lint(
63                             cx,
64                             IF_NOT_ELSE,
65                             item.span,
66                             "Unnecessary boolean `not` operation",
67                             "remove the `!` and swap the blocks of the if/else",
68                         );
69                     },
70                     ExprKind::Binary(ref kind, _, _) if kind.node == BinOpKind::Ne => {
71                         span_help_and_lint(
72                             cx,
73                             IF_NOT_ELSE,
74                             item.span,
75                             "Unnecessary `!=` operation",
76                             "change to `==` and swap the blocks of the if/else",
77                         );
78                     },
79                     _ => (),
80                 }
81             }
82         }
83     }
84 }