1 //! lint on if branches that could be swapped so no `!` operation is necessary
4 use clippy_utils::diagnostics::span_lint_and_help;
5 use rustc_ast::ast::{BinOpKind, Expr, ExprKind, UnOp};
6 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
7 use rustc_middle::lint::in_external_macro;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 declare_clippy_lint! {
12 /// Checks for usage of `!` or `!=` in an if condition with an
15 /// ### Why is this bad?
16 /// Negations reduce the readability of statements.
20 /// # let v: Vec<usize> = vec![];
23 /// if !v.is_empty() {
33 /// # let v: Vec<usize> = vec![];
44 "`if` branches that could be swapped so no negation operation is necessary on the condition"
47 declare_lint_pass!(IfNotElse => [IF_NOT_ELSE]);
49 impl EarlyLintPass for IfNotElse {
50 fn check_expr(&mut self, cx: &EarlyContext<'_>, item: &Expr) {
51 if in_external_macro(cx.sess(), item.span) {
54 if let ExprKind::If(ref cond, _, Some(ref els)) = item.kind {
55 if let ExprKind::Block(..) = els.kind {
57 ExprKind::Unary(UnOp::Not, _) => {
62 "unnecessary boolean `not` operation",
64 "remove the `!` and swap the blocks of the `if`/`else`",
67 ExprKind::Binary(ref kind, _, _) if kind.node == BinOpKind::Ne => {
72 "unnecessary `!=` operation",
74 "change to `==` and swap the blocks of the `if`/`else`",