]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/bool_assert_comparison.rs
Always include a position span in rustc_parse_format::Argument
[rust.git] / 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     /// assert_eq!("a".is_empty(), false);
21     /// assert_ne!("a".is_empty(), true);
22     /// ```
23     ///
24     /// Use instead:
25     /// ```rust
26     /// assert!(!"a".is_empty());
27     /// ```
28     #[clippy::version = "1.53.0"]
29     pub BOOL_ASSERT_COMPARISON,
30     style,
31     "Using a boolean as comparison value in an assert_* macro when there is no need"
32 }
33
34 declare_lint_pass!(BoolAssertComparison => [BOOL_ASSERT_COMPARISON]);
35
36 fn is_bool_lit(e: &Expr<'_>) -> bool {
37     matches!(
38         e.kind,
39         ExprKind::Lit(Lit {
40             node: LitKind::Bool(_),
41             ..
42         })
43     ) && !e.span.from_expansion()
44 }
45
46 fn is_impl_not_trait_with_bool_out(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
47     let ty = cx.typeck_results().expr_ty(e);
48
49     cx.tcx
50         .lang_items()
51         .not_trait()
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(
55                 cx.tcx,
56                 Ident::from_str("Output"),
57                 ty::AssocKind::Type,
58                 trait_id,
59             )
60         })
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);
64
65             nty.is_bool()
66         })
67 }
68
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);
73         if !matches!(
74             macro_name.as_str(),
75             "assert_eq" | "debug_assert_eq" | "assert_ne" | "debug_assert_ne"
76         ) {
77             return;
78         }
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...
83             //
84             // Or there is simply no boolean and then we can leave things as is!
85             return;
86         }
87
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
92             return;
93         }
94
95         let macro_name = macro_name.as_str();
96         let non_eq_mac = &macro_name[..macro_name.len() - 3];
97         span_lint_and_sugg(
98             cx,
99             BOOL_ASSERT_COMPARISON,
100             macro_call.span,
101             &format!("used `{}!` with a literal bool", macro_name),
102             "replace it with",
103             format!("{}!(..)", non_eq_mac),
104             Applicability::MaybeIncorrect,
105         );
106     }
107 }