]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/if_not_else.rs
Auto merge of #4551 - mikerite:fix-ice-reporting, r=llogiq
[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::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
5 use rustc::{declare_lint_pass, declare_tool_lint};
6 use syntax::ast::*;
7
8 use crate::utils::span_help_and_lint;
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for usage of `!` or `!=` in an if condition with an
12     /// else branch.
13     ///
14     /// **Why is this bad?** Negations reduce the readability of statements.
15     ///
16     /// **Known problems:** None.
17     ///
18     /// **Example:**
19     /// ```rust
20     /// # let v: Vec<usize> = vec![];
21     /// # fn a() {}
22     /// # fn b() {}
23     /// if !v.is_empty() {
24     ///     a()
25     /// } else {
26     ///     b()
27     /// }
28     /// ```
29     ///
30     /// Could be written:
31     ///
32     /// ```rust
33     /// # let v: Vec<usize> = vec![];
34     /// # fn a() {}
35     /// # fn b() {}
36     /// if v.is_empty() {
37     ///     b()
38     /// } else {
39     ///     a()
40     /// }
41     /// ```
42     pub IF_NOT_ELSE,
43     pedantic,
44     "`if` branches that could be swapped so no negation operation is necessary on the condition"
45 }
46
47 declare_lint_pass!(IfNotElse => [IF_NOT_ELSE]);
48
49 impl EarlyLintPass for IfNotElse {
50     fn check_expr(&mut self, cx: &EarlyContext<'_>, item: &Expr) {
51         if in_external_macro(cx.sess(), item.span) {
52             return;
53         }
54         if let ExprKind::If(ref cond, _, Some(ref els)) = item.node {
55             if let ExprKind::Block(..) = els.node {
56                 match cond.node {
57                     ExprKind::Unary(UnOp::Not, _) => {
58                         span_help_and_lint(
59                             cx,
60                             IF_NOT_ELSE,
61                             item.span,
62                             "Unnecessary boolean `not` operation",
63                             "remove the `!` and swap the blocks of the if/else",
64                         );
65                     },
66                     ExprKind::Binary(ref kind, _, _) if kind.node == BinOpKind::Ne => {
67                         span_help_and_lint(
68                             cx,
69                             IF_NOT_ELSE,
70                             item.span,
71                             "Unnecessary `!=` operation",
72                             "change to `==` and swap the blocks of the if/else",
73                         );
74                     },
75                     _ => (),
76                 }
77             }
78         }
79     }
80 }