]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/ok_expect.rs
Auto merge of #89219 - nickkuk:str_split_once_get_unchecked, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / clippy_lints / src / methods / ok_expect.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
3 use if_chain::if_chain;
4 use rustc_hir as hir;
5 use rustc_lint::LateContext;
6 use rustc_middle::ty::{self, Ty};
7 use rustc_span::sym;
8
9 use super::OK_EXPECT;
10
11 /// lint use of `ok().expect()` for `Result`s
12 pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr<'_>) {
13     if_chain! {
14         // lint if the caller of `ok()` is a `Result`
15         if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::Result);
16         let result_type = cx.typeck_results().expr_ty(recv);
17         if let Some(error_type) = get_error_type(cx, result_type);
18         if has_debug_impl(error_type, cx);
19
20         then {
21             span_lint_and_help(
22                 cx,
23                 OK_EXPECT,
24                 expr.span,
25                 "called `ok().expect()` on a `Result` value",
26                 None,
27                 "you can call `expect()` directly on the `Result`",
28             );
29         }
30     }
31 }
32
33 /// Given a `Result<T, E>` type, return its error type (`E`).
34 fn get_error_type<'a>(cx: &LateContext<'_>, ty: Ty<'a>) -> Option<Ty<'a>> {
35     match ty.kind() {
36         ty::Adt(_, substs) if is_type_diagnostic_item(cx, ty, sym::Result) => substs.types().nth(1),
37         _ => None,
38     }
39 }
40
41 /// This checks whether a given type is known to implement Debug.
42 fn has_debug_impl<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool {
43     cx.tcx
44         .get_diagnostic_item(sym::Debug)
45         .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
46 }