|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::macros::{find_assert_args, root_macro_call_first_node}; |
| 3 | +use rustc_errors::Applicability; |
| 4 | +use rustc_hir::{Expr, ExprKind, UnOp}; |
| 5 | +use rustc_lint::{LateContext, LateLintPass}; |
| 6 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 7 | + |
| 8 | +declare_clippy_lint! { |
| 9 | + /// ### What it does |
| 10 | + /// This lint warns about the use of inverted conditions in assert-like macros. |
| 11 | + /// |
| 12 | + /// ### Why is this bad? |
| 13 | + /// It is all too easy to misread the semantics of an assertion when the |
| 14 | + /// logic of the condition is reversed. Explicitly comparing to a boolean |
| 15 | + /// value is preferable. |
| 16 | + /// |
| 17 | + /// ### Example |
| 18 | + /// ```rust |
| 19 | + /// // Bad |
| 20 | + /// assert!(!"a".is_empty()); |
| 21 | + /// |
| 22 | + /// // Good |
| 23 | + /// assert_eq!("a".is_empty(), false); |
| 24 | + /// |
| 25 | + /// // Okay |
| 26 | + /// assert_ne!("a".is_empty(), true); |
| 27 | + /// ``` |
| 28 | + #[clippy::version = "1.58.0"] |
| 29 | + pub BOOL_ASSERT_INVERTED, |
| 30 | + restriction, |
| 31 | + "Asserting on an inverted condition" |
| 32 | +} |
| 33 | + |
| 34 | +declare_lint_pass!(BoolAssertInverted => [BOOL_ASSERT_INVERTED]); |
| 35 | + |
| 36 | +fn is_inverted(e: &Expr<'_>) -> bool { |
| 37 | + matches!(e.kind, ExprKind::Unary(UnOp::Not, _),) && !e.span.from_expansion() |
| 38 | +} |
| 39 | + |
| 40 | +impl<'tcx> LateLintPass<'tcx> for BoolAssertInverted { |
| 41 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { |
| 42 | + let Some(macro_call) = root_macro_call_first_node(cx, expr) else { return }; |
| 43 | + let macro_name = cx.tcx.item_name(macro_call.def_id); |
| 44 | + if !matches!(macro_name.as_str(), "assert" | "debug_assert") { |
| 45 | + return; |
| 46 | + } |
| 47 | + let Some ((a, _)) = find_assert_args(cx, expr, macro_call.expn) else { return }; |
| 48 | + if !is_inverted(a) { |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + let macro_name = macro_name.as_str(); |
| 53 | + let eq_mac = format!("{}_eq", macro_name); |
| 54 | + span_lint_and_sugg( |
| 55 | + cx, |
| 56 | + BOOL_ASSERT_INVERTED, |
| 57 | + macro_call.span, |
| 58 | + &format!("used `{}!` with an inverted condition", macro_name), |
| 59 | + "replace it with", |
| 60 | + format!("{}!(.., false, ..)", eq_mac), |
| 61 | + Applicability::MaybeIncorrect, |
| 62 | + ); |
| 63 | + } |
| 64 | +} |
0 commit comments