1 //! lint on if branches that could be swapped so no `!` operation is necessary
4 use rustc_ast::ast::{BinOpKind, Expr, ExprKind, UnOp};
5 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
6 use rustc_middle::lint::in_external_macro;
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use crate::utils::span_lint_and_help;
11 declare_clippy_lint! {
12 /// **What it does:** Checks for usage of `!` or `!=` in an if condition with an
15 /// **Why is this bad?** Negations reduce the readability of statements.
17 /// **Known problems:** None.
21 /// # let v: Vec<usize> = vec![];
24 /// if !v.is_empty() {
34 /// # let v: Vec<usize> = vec![];
45 "`if` branches that could be swapped so no negation operation is necessary on the condition"
48 declare_lint_pass!(IfNotElse => [IF_NOT_ELSE]);
50 impl EarlyLintPass for IfNotElse {
51 fn check_expr(&mut self, cx: &EarlyContext<'_>, item: &Expr) {
52 if in_external_macro(cx.sess(), item.span) {
55 if let ExprKind::If(ref cond, _, Some(ref els)) = item.kind {
56 if let ExprKind::Block(..) = els.kind {
58 ExprKind::Unary(UnOp::Not, _) => {
63 "Unnecessary boolean `not` operation",
65 "remove the `!` and swap the blocks of the `if`/`else`",
68 ExprKind::Binary(ref kind, _, _) if kind.node == BinOpKind::Ne => {
73 "Unnecessary `!=` operation",
75 "change to `==` and swap the blocks of the `if`/`else`",