1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::msrvs::{self, Msrv};
3 use clippy_utils::source::snippet;
4 use clippy_utils::ty::is_type_diagnostic_item;
5 use clippy_utils::{match_def_path, path_to_local_id, paths, peel_blocks};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
9 use rustc_lint::LateContext;
13 use super::OPTION_AS_REF_DEREF;
15 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
19 as_ref_recv: &hir::Expr<'_>,
20 map_arg: &hir::Expr<'_>,
24 if !msrv.meets(msrvs::OPTION_AS_DEREF) {
28 let same_mutability = |m| (is_mut && m == &hir::Mutability::Mut) || (!is_mut && m == &hir::Mutability::Not);
30 let option_ty = cx.typeck_results().expr_ty(as_ref_recv);
31 if !is_type_diagnostic_item(cx, option_ty, sym::Option) {
35 let deref_aliases: [&[&str]; 8] = [
36 &paths::DEREF_MUT_TRAIT_METHOD,
37 &paths::CSTRING_AS_C_STR,
38 &paths::OS_STRING_AS_OS_STR,
39 &paths::PATH_BUF_AS_PATH,
40 &paths::STRING_AS_STR,
41 &paths::STRING_AS_MUT_STR,
43 &paths::VEC_AS_MUT_SLICE,
46 let is_deref = match map_arg.kind {
47 hir::ExprKind::Path(ref expr_qpath) => {
48 cx.qpath_res(expr_qpath, map_arg.hir_id)
50 .map_or(false, |fun_def_id| {
51 cx.tcx.is_diagnostic_item(sym::deref_method, fun_def_id)
52 || deref_aliases.iter().any(|path| match_def_path(cx, fun_def_id, path))
55 hir::ExprKind::Closure(&hir::Closure { body, .. }) => {
56 let closure_body = cx.tcx.hir().body(body);
57 let closure_expr = peel_blocks(closure_body.value);
59 match &closure_expr.kind {
60 hir::ExprKind::MethodCall(_, receiver, [], _) => {
62 if path_to_local_id(receiver, closure_body.params[0].pat.hir_id);
65 .expr_adjustments(receiver)
68 .collect::<Box<[_]>>();
69 if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
71 let method_did = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id).unwrap();
72 cx.tcx.is_diagnostic_item(sym::deref_method, method_did)
73 || deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
79 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, inner) if same_mutability(m) => {
81 if let hir::ExprKind::Unary(hir::UnOp::Deref, inner1) = inner.kind;
82 if let hir::ExprKind::Unary(hir::UnOp::Deref, inner2) = inner1.kind;
84 path_to_local_id(inner2, closure_body.params[0].pat.hir_id)
97 let current_method = if is_mut {
98 format!(".as_mut().map({})", snippet(cx, map_arg.span, ".."))
100 format!(".as_ref().map({})", snippet(cx, map_arg.span, ".."))
102 let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
103 let hint = format!("{}.{method_hint}()", snippet(cx, as_ref_recv.span, ".."));
104 let suggestion = format!("try using {method_hint} instead");
107 "called `{current_method}` on an Option value. This can be done more directly \
108 by calling `{hint}` instead"
117 Applicability::MachineApplicable,