]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/if_not_else.rs
Merge pull request #3076 from mbrubeck/patch-1
[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::{EarlyContext, EarlyLintPass, LintArray, LintPass, in_external_macro, LintContext};
5 use rustc::{declare_lint, lint_array};
6 use syntax::ast::*;
7
8 use crate::utils::span_help_and_lint;
9
10 /// **What it does:** Checks for usage of `!` or `!=` in an if condition with an
11 /// else branch.
12 ///
13 /// **Why is this bad?** Negations reduce the readability of statements.
14 ///
15 /// **Known problems:** None.
16 ///
17 /// **Example:**
18 /// ```rust
19 /// if !v.is_empty() {
20 ///     a()
21 /// } else {
22 ///     b()
23 /// }
24 /// ```
25 ///
26 /// Could be written:
27 ///
28 /// ```rust
29 /// if v.is_empty() {
30 ///     b()
31 /// } else {
32 ///     a()
33 /// }
34 /// ```
35 declare_clippy_lint! {
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
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.node {
55             if let ExprKind::Block(..) = els.node {
56                 match cond.node {
57                     ExprKind::Unary(UnOp::Not, _) => {
58                         span_help_and_lint(
59                             cx,
60                             IF_NOT_ELSE,
61                             item.span,
62                             "Unnecessary boolean `not` operation",
63                             "remove the `!` and swap the blocks of the if/else",
64                         );
65                     },
66                     ExprKind::Binary(ref kind, _, _) if kind.node == BinOpKind::Ne => {
67                         span_help_and_lint(
68                             cx,
69                             IF_NOT_ELSE,
70                             item.span,
71                             "Unnecessary `!=` operation",
72                             "change to `==` and swap the blocks of the if/else",
73                         );
74                     },
75                     _ => (),
76                 }
77             }
78         }
79     }
80 }