]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/if_not_else.rs
rustup https://github.com/rust-lang/rust/pull/61758/files
[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     /// if !v.is_empty() {
21     ///     a()
22     /// } else {
23     ///     b()
24     /// }
25     /// ```
26     ///
27     /// Could be written:
28     ///
29     /// ```rust
30     /// if v.is_empty() {
31     ///     b()
32     /// } else {
33     ///     a()
34     /// }
35     /// ```
36     pub IF_NOT_ELSE,
37     pedantic,
38     "`if` branches that could be swapped so no negation operation is necessary on the condition"
39 }
40
41 declare_lint_pass!(IfNotElse => [IF_NOT_ELSE]);
42
43 impl EarlyLintPass for IfNotElse {
44     fn check_expr(&mut self, cx: &EarlyContext<'_>, item: &Expr) {
45         if in_external_macro(cx.sess(), item.span) {
46             return;
47         }
48         if let ExprKind::If(ref cond, _, Some(ref els)) = item.node {
49             if let ExprKind::Block(..) = els.node {
50                 match cond.node {
51                     ExprKind::Unary(UnOp::Not, _) => {
52                         span_help_and_lint(
53                             cx,
54                             IF_NOT_ELSE,
55                             item.span,
56                             "Unnecessary boolean `not` operation",
57                             "remove the `!` and swap the blocks of the if/else",
58                         );
59                     },
60                     ExprKind::Binary(ref kind, _, _) if kind.node == BinOpKind::Ne => {
61                         span_help_and_lint(
62                             cx,
63                             IF_NOT_ELSE,
64                             item.span,
65                             "Unnecessary `!=` operation",
66                             "change to `==` and swap the blocks of the if/else",
67                         );
68                     },
69                     _ => (),
70                 }
71             }
72         }
73     }
74 }