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![];
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 LateLintPass<'_> for IfNotElse {
50 fn check_expr(&mut self, cx: &LateContext<'_>, item: &Expr<'_>) {
51 // While loops will be desugared to ExprKind::If. This will cause the lint to fire.
52 // To fix this, return early if this span comes from a macro or desugaring.
53 if item.span.from_expansion() {
56 if let ExprKind::If(cond, _, Some(els)) = item.kind {
57 if let ExprKind::Block(..) = els.kind {
58 // Disable firing the lint in "else if" expressions.
59 if is_else_clause(cx.tcx, item) {
63 match cond.peel_drop_temps().kind {
64 ExprKind::Unary(UnOp::Not, _) => {
69 "unnecessary boolean `not` operation",
71 "remove the `!` and swap the blocks of the `if`/`else`",
74 ExprKind::Binary(ref kind, _, _) if kind.node == BinOpKind::Ne => {
79 "unnecessary `!=` operation",
81 "change to `==` and swap the blocks of the `if`/`else`",