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.
21 /// assert_eq!("a".is_empty(), false);
22 /// assert_ne!("a".is_empty(), true);
25 /// assert!(!"a".is_empty());
27 #[clippy::version = "1.53.0"]
28 pub BOOL_ASSERT_COMPARISON,
30 "Using a boolean as comparison value in an assert_* macro when there is no need"
33 declare_lint_pass!(BoolAssertComparison => [BOOL_ASSERT_COMPARISON]);
35 fn is_bool_lit(e: &Expr<'_>) -> bool {
39 node: LitKind::Bool(_),
42 ) && !e.span.from_expansion()
45 fn is_impl_not_trait_with_bool_out(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
46 let ty = cx.typeck_results().expr_ty(e);
51 .filter(|trait_id| implements_trait(cx, ty, *trait_id, &[]))
52 .and_then(|trait_id| {
53 cx.tcx.associated_items(trait_id).find_by_name_and_kind(
55 Ident::from_str("Output"),
60 .map_or(false, |assoc_item| {
61 let proj = cx.tcx.mk_projection(assoc_item.def_id, cx.tcx.mk_substs_trait(ty, &[]));
62 let nty = cx.tcx.normalize_erasing_regions(cx.param_env, proj);
68 impl<'tcx> LateLintPass<'tcx> for BoolAssertComparison {
69 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
70 let Some(macro_call) = root_macro_call_first_node(cx, expr) else { return };
71 let macro_name = cx.tcx.item_name(macro_call.def_id);
74 "assert_eq" | "debug_assert_eq" | "assert_ne" | "debug_assert_ne"
78 let Some ((a, b, _)) = find_assert_eq_args(cx, expr, macro_call.expn) else { return };
79 if !(is_bool_lit(a) ^ is_bool_lit(b)) {
80 // If there are two boolean arguments, we definitely don't understand
81 // what's going on, so better leave things as is...
83 // Or there is simply no boolean and then we can leave things as is!
87 if !is_impl_not_trait_with_bool_out(cx, a) || !is_impl_not_trait_with_bool_out(cx, b) {
88 // At this point the expression which is not a boolean
89 // literal does not implement Not trait with a bool output,
90 // so we cannot suggest to rewrite our code
94 let macro_name = macro_name.as_str();
95 let non_eq_mac = ¯o_name[..macro_name.len() - 3];
98 BOOL_ASSERT_COMPARISON,
100 &format!("used `{}!` with a literal bool", macro_name),
102 format!("{}!(..)", non_eq_mac),
103 Applicability::MaybeIncorrect,