]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/assertions_on_result_states.rs
Merge commit '7248d06384c6a90de58c04c1f46be88821278d8b' into sync-from-clippy
[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::source::snippet_with_context;
4 use clippy_utils::ty::{has_debug_impl, is_copy, is_type_diagnostic_item};
5 use clippy_utils::usage::local_used_after_expr;
6 use clippy_utils::{is_expr_final_block_expr, path_res};
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 semicolon = if is_expr_final_block_expr(cx.tcx, e) {";"} else {""};
62             let mut app = Applicability::MachineApplicable;
63             match method_segment.ident.as_str() {
64                 "is_ok" if type_suitable_to_unwrap(cx, substs.type_at(1)) => {
65                     span_lint_and_sugg(
66                         cx,
67                         ASSERTIONS_ON_RESULT_STATES,
68                         macro_call.span,
69                         "called `assert!` with `Result::is_ok`",
70                         "replace with",
71                         format!(
72                             "{}.unwrap(){}",
73                             snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0,
74                             semicolon
75                         ),
76                         app,
77                     );
78                 }
79                 "is_err" if type_suitable_to_unwrap(cx, substs.type_at(0)) => {
80                     span_lint_and_sugg(
81                         cx,
82                         ASSERTIONS_ON_RESULT_STATES,
83                         macro_call.span,
84                         "called `assert!` with `Result::is_err`",
85                         "replace with",
86                         format!(
87                             "{}.unwrap_err(){}",
88                             snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0,
89                             semicolon
90                         ),
91                         app,
92                     );
93                 }
94                 _ => (),
95             };
96         }
97     }
98 }
99
100 fn type_suitable_to_unwrap<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
101     has_debug_impl(cx, ty) && !ty.is_unit() && !ty.is_never()
102 }