]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/assertions_on_result_states.rs
Add `[assertions_on_result_states]` lint
[rust.git] / clippy_lints / src / assertions_on_result_states.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::macros::{find_assert_args, root_macro_call_first_node, PanicExpn};
3 use clippy_utils::path_res;
4 use clippy_utils::source::snippet_with_context;
5 use clippy_utils::ty::{implements_trait, is_copy, is_type_diagnostic_item};
6 use clippy_utils::usage::local_used_after_expr;
7 use rustc_errors::Applicability;
8 use rustc_hir::def::Res;
9 use rustc_hir::{Expr, ExprKind};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::ty::{self, Ty};
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::sym;
14
15 declare_clippy_lint! {
16     /// ### What it does
17     /// Checks for `assert!(r.is_ok())` or `assert!(r.is_err())` calls.
18     ///
19     /// ### Why is this bad?
20     /// An assertion failure cannot output an useful message of the error.
21     ///
22     /// ### Example
23     /// ```rust,ignore
24     /// # let r = Ok::<_, ()>(());
25     /// assert!(r.is_ok());
26     /// # let r = Err::<_, ()>(());
27     /// assert!(r.is_err());
28     /// ```
29     #[clippy::version = "1.64.0"]
30     pub ASSERTIONS_ON_RESULT_STATES,
31     style,
32     "`assert!(r.is_ok())`/`assert!(r.is_err())` gives worse error message than directly calling `r.unwrap()`/`r.unwrap_err()`"
33 }
34
35 declare_lint_pass!(AssertionsOnResultStates => [ASSERTIONS_ON_RESULT_STATES]);
36
37 impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates {
38     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
39         if let Some(macro_call) = root_macro_call_first_node(cx, e)
40             && matches!(cx.tcx.get_diagnostic_name(macro_call.def_id), Some(sym::assert_macro))
41             && let Some((condition, panic_expn)) = find_assert_args(cx, e, macro_call.expn)
42             && matches!(panic_expn, PanicExpn::Empty)
43             && let ExprKind::MethodCall(method_segment, [recv], _) = condition.kind
44             && let result_type_with_refs = cx.typeck_results().expr_ty(recv)
45             && let result_type = result_type_with_refs.peel_refs()
46             && is_type_diagnostic_item(cx, result_type, sym::Result)
47             && let ty::Adt(_, substs) = result_type.kind()
48         {
49             if !is_copy(cx, result_type) {
50                 if result_type_with_refs != result_type {
51                     return;
52                 } else if let Res::Local(binding_id) = path_res(cx, recv)
53                     && local_used_after_expr(cx, binding_id, recv) {
54                     return;
55                 }
56             }
57             let mut app = Applicability::MachineApplicable;
58             match method_segment.ident.as_str() {
59                 "is_ok" if has_debug_impl(cx, substs.type_at(1)) => {
60                     span_lint_and_sugg(
61                         cx,
62                         ASSERTIONS_ON_RESULT_STATES,
63                         macro_call.span,
64                         "called `assert!` with `Result::is_ok`",
65                         "replace with",
66                         format!(
67                             "{}.unwrap()",
68                             snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0
69                         ),
70                         app,
71                     );
72                 }
73                 "is_err" if has_debug_impl(cx, substs.type_at(0)) => {
74                     span_lint_and_sugg(
75                         cx,
76                         ASSERTIONS_ON_RESULT_STATES,
77                         macro_call.span,
78                         "called `assert!` with `Result::is_err`",
79                         "replace with",
80                         format!(
81                             "{}.unwrap_err()",
82                             snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0
83                         ),
84                         app,
85                     );
86                 }
87                 _ => (),
88             };
89         }
90     }
91 }
92
93 /// This checks whether a given type is known to implement Debug.
94 fn has_debug_impl<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
95     cx.tcx
96         .get_diagnostic_item(sym::Debug)
97         .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
98 }