]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs
Rollup merge of #90741 - mbartlett21:patch-4, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / bool_assert_comparison.rs
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};
6 use rustc_middle::ty;
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::symbol::Ident;
9
10 declare_clippy_lint! {
11     /// ### What it does
12     /// This lint warns about boolean comparisons in assert-like macros.
13     ///
14     /// ### Why is this bad?
15     /// It is shorter to use the equivalent.
16     ///
17     /// ### Example
18     /// ```rust
19     /// // Bad
20     /// assert_eq!("a".is_empty(), false);
21     /// assert_ne!("a".is_empty(), true);
22     ///
23     /// // Good
24     /// assert!(!"a".is_empty());
25     /// ```
26     #[clippy::version = "1.53.0"]
27     pub BOOL_ASSERT_COMPARISON,
28     style,
29     "Using a boolean as comparison value in an assert_* macro when there is no need"
30 }
31
32 declare_lint_pass!(BoolAssertComparison => [BOOL_ASSERT_COMPARISON]);
33
34 fn is_bool_lit(e: &Expr<'_>) -> bool {
35     matches!(
36         e.kind,
37         ExprKind::Lit(Lit {
38             node: LitKind::Bool(_),
39             ..
40         })
41     ) && !e.span.from_expansion()
42 }
43
44 fn is_impl_not_trait_with_bool_out(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> bool {
45     let ty = cx.typeck_results().expr_ty(e);
46
47     cx.tcx
48         .lang_items()
49         .not_trait()
50         .filter(|trait_id| implements_trait(cx, ty, *trait_id, &[]))
51         .and_then(|trait_id| {
52             cx.tcx.associated_items(trait_id).find_by_name_and_kind(
53                 cx.tcx,
54                 Ident::from_str("Output"),
55                 ty::AssocKind::Type,
56                 trait_id,
57             )
58         })
59         .map_or(false, |assoc_item| {
60             let proj = cx.tcx.mk_projection(assoc_item.def_id, cx.tcx.mk_substs_trait(ty, &[]));
61             let nty = cx.tcx.normalize_erasing_regions(cx.param_env, proj);
62
63             nty.is_bool()
64         })
65 }
66
67 impl<'tcx> LateLintPass<'tcx> for BoolAssertComparison {
68     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
69         let macros = ["assert_eq", "debug_assert_eq"];
70         let inverted_macros = ["assert_ne", "debug_assert_ne"];
71
72         for mac in macros.iter().chain(inverted_macros.iter()) {
73             if let Some(span) = is_direct_expn_of(expr.span, mac) {
74                 if let Some(args) = higher::extract_assert_macro_args(expr) {
75                     if let [a, b, ..] = args[..] {
76                         let nb_bool_args = usize::from(is_bool_lit(a)) + usize::from(is_bool_lit(b));
77
78                         if nb_bool_args != 1 {
79                             // If there are two boolean arguments, we definitely don't understand
80                             // what's going on, so better leave things as is...
81                             //
82                             // Or there is simply no boolean and then we can leave things as is!
83                             return;
84                         }
85
86                         if !is_impl_not_trait_with_bool_out(cx, a) || !is_impl_not_trait_with_bool_out(cx, b) {
87                             // At this point the expression which is not a boolean
88                             // literal does not implement Not trait with a bool output,
89                             // so we cannot suggest to rewrite our code
90                             return;
91                         }
92
93                         let non_eq_mac = &mac[..mac.len() - 3];
94                         span_lint_and_sugg(
95                             cx,
96                             BOOL_ASSERT_COMPARISON,
97                             span,
98                             &format!("used `{}!` with a literal bool", mac),
99                             "replace it with",
100                             format!("{}!(..)", non_eq_mac),
101                             Applicability::MaybeIncorrect,
102                         );
103                         return;
104                     }
105                 }
106             }
107         }
108     }
109 }