]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/assertions_on_result_states.rs
Rollup merge of #101266 - LuisCardosoOliveira:translation-rustcsession-pt3, r=davidtwco
[rust.git] / src / tools / clippy / 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     /// ### Known problems
23     /// The suggested replacement decreases the readability of code and log output.
24     ///
25     /// ### Example
26     /// ```rust,ignore
27     /// # let r = Ok::<_, ()>(());
28     /// assert!(r.is_ok());
29     /// # let r = Err::<_, ()>(());
30     /// assert!(r.is_err());
31     /// ```
32     #[clippy::version = "1.64.0"]
33     pub ASSERTIONS_ON_RESULT_STATES,
34     restriction,
35     "`assert!(r.is_ok())`/`assert!(r.is_err())` gives worse error message than directly calling `r.unwrap()`/`r.unwrap_err()`"
36 }
37
38 declare_lint_pass!(AssertionsOnResultStates => [ASSERTIONS_ON_RESULT_STATES]);
39
40 impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates {
41     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
42         if let Some(macro_call) = root_macro_call_first_node(cx, e)
43             && matches!(cx.tcx.get_diagnostic_name(macro_call.def_id), Some(sym::assert_macro))
44             && let Some((condition, panic_expn)) = find_assert_args(cx, e, macro_call.expn)
45             && matches!(panic_expn, PanicExpn::Empty)
46             && let ExprKind::MethodCall(method_segment, recv, [], _) = condition.kind
47             && let result_type_with_refs = cx.typeck_results().expr_ty(recv)
48             && let result_type = result_type_with_refs.peel_refs()
49             && is_type_diagnostic_item(cx, result_type, sym::Result)
50             && let ty::Adt(_, substs) = result_type.kind()
51         {
52             if !is_copy(cx, result_type) {
53                 if result_type_with_refs != result_type {
54                     return;
55                 } else if let Res::Local(binding_id) = path_res(cx, recv)
56                     && local_used_after_expr(cx, binding_id, recv)
57                 {
58                     return;
59                 }
60             }
61             let mut app = Applicability::MachineApplicable;
62             match method_segment.ident.as_str() {
63                 "is_ok" if type_suitable_to_unwrap(cx, substs.type_at(1)) => {
64                     span_lint_and_sugg(
65                         cx,
66                         ASSERTIONS_ON_RESULT_STATES,
67                         macro_call.span,
68                         "called `assert!` with `Result::is_ok`",
69                         "replace with",
70                         format!(
71                             "{}.unwrap()",
72                             snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0
73                         ),
74                         app,
75                     );
76                 }
77                 "is_err" if type_suitable_to_unwrap(cx, substs.type_at(0)) => {
78                     span_lint_and_sugg(
79                         cx,
80                         ASSERTIONS_ON_RESULT_STATES,
81                         macro_call.span,
82                         "called `assert!` with `Result::is_err`",
83                         "replace with",
84                         format!(
85                             "{}.unwrap_err()",
86                             snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0
87                         ),
88                         app,
89                     );
90                 }
91                 _ => (),
92             };
93         }
94     }
95 }
96
97 /// This checks whether a given type is known to implement Debug.
98 fn has_debug_impl<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
99     cx.tcx
100         .get_diagnostic_item(sym::Debug)
101         .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
102 }
103
104 fn type_suitable_to_unwrap<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
105     has_debug_impl(cx, ty) && !ty.is_unit() && !ty.is_never()
106 }