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