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