]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/if_not_else.rs
Merge branch 'master' into move_links
[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;
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 let ExprKind::If(ref cond, _, Some(ref els)) = item.node {
51             if let ExprKind::Block(..) = els.node {
52                 match cond.node {
53                     ExprKind::Unary(UnOp::Not, _) => {
54                         span_help_and_lint(
55                             cx,
56                             IF_NOT_ELSE,
57                             item.span,
58                             "Unnecessary boolean `not` operation",
59                             "remove the `!` and swap the blocks of the if/else",
60                         );
61                     },
62                     ExprKind::Binary(ref kind, _, _) if kind.node == BinOpKind::Ne => {
63                         span_help_and_lint(
64                             cx,
65                             IF_NOT_ELSE,
66                             item.span,
67                             "Unnecessary `!=` operation",
68                             "change to `==` and swap the blocks of the if/else",
69                         );
70                     },
71                     _ => (),
72                 }
73             }
74         }
75     }
76 }