]> git.lizzy.rs Git - rust.git/blob - src/if_not_else.rs
add known problems
[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::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:** if !v.is_empty() { a() } else { b() }
15 declare_lint! {
16     pub IF_NOT_ELSE, Allow,
17     "finds if branches that could be swapped so no negation operation is necessary on the condition"
18 }
19
20 pub struct IfNotElse;
21
22 impl LintPass for IfNotElse {
23     fn get_lints(&self) -> LintArray {
24         lint_array!(IF_NOT_ELSE)
25     }
26 }
27
28 impl EarlyLintPass for IfNotElse {
29     fn check_expr(&mut self, cx: &EarlyContext, item: &Expr) {
30         if let ExprKind::If(ref cond, _, Some(ref els)) = item.node {
31             if let ExprKind::Block(..) = els.node {
32                 match cond.node {
33                     ExprKind::Unary(UnOp::Not, _) => {
34                         span_help_and_lint(cx,
35                                            IF_NOT_ELSE,
36                                            item.span,
37                                            "Unnecessary boolean `not` operation",
38                                            "remove the `!` and swap the blocks of the if/else");
39                     }
40                     ExprKind::Binary(ref kind, _, _) if kind.node == BinOpKind::Ne => {
41                         span_help_and_lint(cx,
42                                            IF_NOT_ELSE,
43                                            item.span,
44                                            "Unnecessary `!=` operation",
45                                            "change to `==` and swap the blocks of the if/else");
46                     }
47                     _ => (),
48                 }
49             }
50         }
51     }
52 }