1 use clippy_utils::{diagnostics::span_lint_and_sugg, higher, is_direct_expn_of, ty::implements_trait};
2 use rustc_ast::ast::LitKind;
3 use rustc_errors::Applicability;
4 use rustc_hir::{Expr, ExprKind, Lit};
5 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::symbol::Ident;
10 declare_clippy_lint! {
12 /// This lint warns about boolean comparisons in assert-like macros.
14 /// ### Why is this bad?
15 /// It is shorter to use the equivalent.
20 /// assert_eq!("a".is_empty(), false);
21 /// assert_ne!("a".is_empty(), true);
24 /// assert!(!"a".is_empty());
26 pub BOOL_ASSERT_COMPARISON,
28 "Using a boolean as comparison value in an assert_* macro when there is no need"
31 declare_lint_pass!(BoolAssertComparison => [BOOL_ASSERT_COMPARISON]);
33 fn is_bool_lit(e: &Expr<'_>) -> bool {
37 node: LitKind::Bool(_),
40 ) && !e.span.from_expansion()
43 fn is_impl_not_trait_with_bool_out(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> bool {
44 let ty = cx.typeck_results().expr_ty(e);
49 .filter(|trait_id| implements_trait(cx, ty, *trait_id, &[]))
50 .and_then(|trait_id| {
51 cx.tcx.associated_items(trait_id).find_by_name_and_kind(
53 Ident::from_str("Output"),
58 .map_or(false, |assoc_item| {
59 let proj = cx.tcx.mk_projection(assoc_item.def_id, cx.tcx.mk_substs_trait(ty, &[]));
60 let nty = cx.tcx.normalize_erasing_regions(cx.param_env, proj);
66 impl<'tcx> LateLintPass<'tcx> for BoolAssertComparison {
67 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
68 let macros = ["assert_eq", "debug_assert_eq"];
69 let inverted_macros = ["assert_ne", "debug_assert_ne"];
71 for mac in macros.iter().chain(inverted_macros.iter()) {
72 if let Some(span) = is_direct_expn_of(expr.span, mac) {
73 if let Some(args) = higher::extract_assert_macro_args(expr) {
74 if let [a, b, ..] = args[..] {
75 let nb_bool_args = is_bool_lit(a) as usize + is_bool_lit(b) as usize;
77 if nb_bool_args != 1 {
78 // If there are two boolean arguments, we definitely don't understand
79 // what's going on, so better leave things as is...
81 // Or there is simply no boolean and then we can leave things as is!
85 if !is_impl_not_trait_with_bool_out(cx, a) || !is_impl_not_trait_with_bool_out(cx, b) {
86 // At this point the expression which is not a boolean
87 // literal does not implement Not trait with a bool output,
88 // so we cannot suggest to rewrite our code
92 let non_eq_mac = &mac[..mac.len() - 3];
95 BOOL_ASSERT_COMPARISON,
97 &format!("used `{}!` with a literal bool", mac),
99 format!("{}!(..)", non_eq_mac),
100 Applicability::MaybeIncorrect,