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;
5 use rustc_lint::LateContext;
6 use rustc_middle::ty::{self, Ty};
11 /// lint use of `ok().expect()` for `Result`s
12 pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr<'_>) {
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_type);
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);
25 "called `ok().expect()` on a `Result` value",
27 "you can call `expect()` directly on the `Result`",
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>> {
36 ty::Adt(_, substs) if is_type_diagnostic_item(cx, ty, sym::result_type) => substs.types().nth(1),
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 {
44 .get_diagnostic_item(sym::debug_trait)
45 .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))