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