1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::{ast_utils, is_direct_expn_of};
3 use rustc_ast::ast::{Expr, ExprKind, Lit, LitKind};
4 use rustc_errors::Applicability;
5 use rustc_lint::{EarlyContext, EarlyLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 /// **What it does:** This lint warns about boolean comparisons in assert-like macros.
11 /// **Why is this bad?** It is shorter to use the equivalent.
13 /// **Known problems:** None.
19 /// assert_eq!("a".is_empty(), false);
20 /// assert_ne!("a".is_empty(), true);
23 /// assert!(!"a".is_empty());
25 pub BOOL_ASSERT_COMPARISON,
27 "Using a boolean as comparison value in an assert_* macro when there is no need"
30 declare_lint_pass!(BoolAssertComparison => [BOOL_ASSERT_COMPARISON]);
32 fn is_bool_lit(e: &Expr) -> bool {
36 kind: LitKind::Bool(_),
39 ) && !e.span.from_expansion()
42 impl EarlyLintPass for BoolAssertComparison {
43 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
44 let macros = ["assert_eq", "debug_assert_eq"];
45 let inverted_macros = ["assert_ne", "debug_assert_ne"];
47 for mac in macros.iter().chain(inverted_macros.iter()) {
48 if let Some(span) = is_direct_expn_of(e.span, mac) {
49 if let Some([a, b]) = ast_utils::extract_assert_macro_args(e) {
50 let nb_bool_args = is_bool_lit(a) as usize + is_bool_lit(b) as usize;
52 if nb_bool_args != 1 {
53 // If there are two boolean arguments, we definitely don't understand
54 // what's going on, so better leave things as is...
56 // Or there is simply no boolean and then we can leave things as is!
60 let non_eq_mac = &mac[..mac.len() - 3];
63 BOOL_ASSERT_COMPARISON,
65 &format!("used `{}!` with a literal bool", mac),
67 format!("{}!(..)", non_eq_mac),
68 Applicability::MaybeIncorrect,