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 clippy_utils::is_else_clause;
6 use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp};
7 use rustc_lint::{LateContext, LateLintPass};
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![];
42 #[clippy::version = "pre 1.29.0"]
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 LateLintPass<'_> for IfNotElse {
51 fn check_expr(&mut self, cx: &LateContext<'_>, item: &Expr<'_>) {
52 // While loops will be desugared to ExprKind::If. This will cause the lint to fire.
53 // To fix this, return early if this span comes from a macro or desugaring.
54 if item.span.from_expansion() {
57 if let ExprKind::If(cond, _, Some(els)) = item.kind {
58 if let ExprKind::Block(..) = els.kind {
59 // Disable firing the lint in "else if" expressions.
60 if is_else_clause(cx.tcx, item) {
64 match cond.peel_drop_temps().kind {
65 ExprKind::Unary(UnOp::Not, _) => {
70 "unnecessary boolean `not` operation",
72 "remove the `!` and swap the blocks of the `if`/`else`",
75 ExprKind::Binary(ref kind, _, _) if kind.node == BinOpKind::Ne => {
80 "unnecessary `!=` operation",
82 "change to `==` and swap the blocks of the `if`/`else`",