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