]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs
Rollup merge of #92642 - avborhanian:master, r=Dylan-DPC
[rust.git] / src / tools / clippy / clippy_lints / src / bool_assert_comparison.rs
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};
7 use rustc_middle::ty;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::symbol::Ident;
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// This lint warns about boolean comparisons in assert-like macros.
14     ///
15     /// ### Why is this bad?
16     /// It is shorter to use the equivalent.
17     ///
18     /// ### Example
19     /// ```rust
20     /// // Bad
21     /// assert_eq!("a".is_empty(), false);
22     /// assert_ne!("a".is_empty(), true);
23     ///
24     /// // Good
25     /// assert!(!"a".is_empty());
26     /// ```
27     #[clippy::version = "1.53.0"]
28     pub BOOL_ASSERT_COMPARISON,
29     style,
30     "Using a boolean as comparison value in an assert_* macro when there is no need"
31 }
32
33 declare_lint_pass!(BoolAssertComparison => [BOOL_ASSERT_COMPARISON]);
34
35 fn is_bool_lit(e: &Expr<'_>) -> bool {
36     matches!(
37         e.kind,
38         ExprKind::Lit(Lit {
39             node: LitKind::Bool(_),
40             ..
41         })
42     ) && !e.span.from_expansion()
43 }
44
45 fn is_impl_not_trait_with_bool_out(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
46     let ty = cx.typeck_results().expr_ty(e);
47
48     cx.tcx
49         .lang_items()
50         .not_trait()
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(
54                 cx.tcx,
55                 Ident::from_str("Output"),
56                 ty::AssocKind::Type,
57                 trait_id,
58             )
59         })
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);
63
64             nty.is_bool()
65         })
66 }
67
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);
72         if !matches!(
73             macro_name.as_str(),
74             "assert_eq" | "debug_assert_eq" | "assert_ne" | "debug_assert_ne"
75         ) {
76             return;
77         }
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...
82             //
83             // Or there is simply no boolean and then we can leave things as is!
84             return;
85         }
86
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
91             return;
92         }
93
94         let macro_name = macro_name.as_str();
95         let non_eq_mac = &macro_name[..macro_name.len() - 3];
96         span_lint_and_sugg(
97             cx,
98             BOOL_ASSERT_COMPARISON,
99             macro_call.span,
100             &format!("used `{}!` with a literal bool", macro_name),
101             "replace it with",
102             format!("{}!(..)", non_eq_mac),
103             Applicability::MaybeIncorrect,
104         );
105     }
106 }