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