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