1 use clippy_utils::macros::{find_assert_eq_args, root_macro_call_first_node};
2 use clippy_utils::{diagnostics::span_lint_and_sugg, ty::implements_trait};
3 use rustc_ast::ast::LitKind;
4 use rustc_errors::Applicability;
5 use rustc_hir::{Expr, ExprKind, Lit};
6 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::symbol::Ident;
11 declare_clippy_lint! {
13 /// This lint warns about boolean comparisons in assert-like macros.
15 /// ### Why is this bad?
16 /// It is shorter to use the equivalent.
20 /// assert_eq!("a".is_empty(), false);
21 /// assert_ne!("a".is_empty(), true);
26 /// assert!(!"a".is_empty());
28 #[clippy::version = "1.53.0"]
29 pub BOOL_ASSERT_COMPARISON,
31 "Using a boolean as comparison value in an assert_* macro when there is no need"
34 declare_lint_pass!(BoolAssertComparison => [BOOL_ASSERT_COMPARISON]);
36 fn is_bool_lit(e: &Expr<'_>) -> bool {
40 node: LitKind::Bool(_),
43 ) && !e.span.from_expansion()
46 fn is_impl_not_trait_with_bool_out(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
47 let ty = cx.typeck_results().expr_ty(e);
52 .filter(|trait_id| implements_trait(cx, ty, *trait_id, &[]))
53 .and_then(|trait_id| {
54 cx.tcx.associated_items(trait_id).find_by_name_and_kind(
56 Ident::from_str("Output"),
61 .map_or(false, |assoc_item| {
62 let proj = cx.tcx.mk_projection(assoc_item.def_id, cx.tcx.mk_substs_trait(ty, &[]));
63 let nty = cx.tcx.normalize_erasing_regions(cx.param_env, proj);
69 impl<'tcx> LateLintPass<'tcx> for BoolAssertComparison {
70 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
71 let Some(macro_call) = root_macro_call_first_node(cx, expr) else { return };
72 let macro_name = cx.tcx.item_name(macro_call.def_id);
75 "assert_eq" | "debug_assert_eq" | "assert_ne" | "debug_assert_ne"
79 let Some ((a, b, _)) = find_assert_eq_args(cx, expr, macro_call.expn) else { return };
80 if !(is_bool_lit(a) ^ is_bool_lit(b)) {
81 // If there are two boolean arguments, we definitely don't understand
82 // what's going on, so better leave things as is...
84 // Or there is simply no boolean and then we can leave things as is!
88 if !is_impl_not_trait_with_bool_out(cx, a) || !is_impl_not_trait_with_bool_out(cx, b) {
89 // At this point the expression which is not a boolean
90 // literal does not implement Not trait with a bool output,
91 // so we cannot suggest to rewrite our code
95 let macro_name = macro_name.as_str();
96 let non_eq_mac = ¯o_name[..macro_name.len() - 3];
99 BOOL_ASSERT_COMPARISON,
101 &format!("used `{}!` with a literal bool", macro_name),
103 format!("{}!(..)", non_eq_mac),
104 Applicability::MaybeIncorrect,