]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/option_as_ref_deref.rs
Auto merge of #101232 - nikic:issue-98294, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / clippy_lints / src / methods / option_as_ref_deref.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet;
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use clippy_utils::{match_def_path, meets_msrv, msrvs, path_to_local_id, paths, peel_blocks};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir as hir;
8 use rustc_lint::LateContext;
9 use rustc_middle::ty;
10 use rustc_semver::RustcVersion;
11 use rustc_span::sym;
12
13 use super::OPTION_AS_REF_DEREF;
14
15 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
16 pub(super) fn check<'tcx>(
17     cx: &LateContext<'tcx>,
18     expr: &hir::Expr<'_>,
19     as_ref_recv: &hir::Expr<'_>,
20     map_arg: &hir::Expr<'_>,
21     is_mut: bool,
22     msrv: Option<RustcVersion>,
23 ) {
24     if !meets_msrv(msrv, msrvs::OPTION_AS_DEREF) {
25         return;
26     }
27
28     let same_mutability = |m| (is_mut && m == &hir::Mutability::Mut) || (!is_mut && m == &hir::Mutability::Not);
29
30     let option_ty = cx.typeck_results().expr_ty(as_ref_recv);
31     if !is_type_diagnostic_item(cx, option_ty, sym::Option) {
32         return;
33     }
34
35     let deref_aliases: [&[&str]; 9] = [
36         &paths::DEREF_TRAIT_METHOD,
37         &paths::DEREF_MUT_TRAIT_METHOD,
38         &paths::CSTRING_AS_C_STR,
39         &paths::OS_STRING_AS_OS_STR,
40         &paths::PATH_BUF_AS_PATH,
41         &paths::STRING_AS_STR,
42         &paths::STRING_AS_MUT_STR,
43         &paths::VEC_AS_SLICE,
44         &paths::VEC_AS_MUT_SLICE,
45     ];
46
47     let is_deref = match map_arg.kind {
48         hir::ExprKind::Path(ref expr_qpath) => cx
49             .qpath_res(expr_qpath, map_arg.hir_id)
50             .opt_def_id()
51             .map_or(false, |fun_def_id| {
52                 deref_aliases.iter().any(|path| match_def_path(cx, fun_def_id, path))
53             }),
54         hir::ExprKind::Closure(&hir::Closure { body, .. }) => {
55             let closure_body = cx.tcx.hir().body(body);
56             let closure_expr = peel_blocks(&closure_body.value);
57
58             match &closure_expr.kind {
59                 hir::ExprKind::MethodCall(_, receiver, [], _) => {
60                     if_chain! {
61                         if path_to_local_id(receiver, closure_body.params[0].pat.hir_id);
62                         let adj = cx
63                             .typeck_results()
64                             .expr_adjustments(receiver)
65                             .iter()
66                             .map(|x| &x.kind)
67                             .collect::<Box<[_]>>();
68                         if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
69                         then {
70                             let method_did = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id).unwrap();
71                             deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
72                         } else {
73                             false
74                         }
75                     }
76                 },
77                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, inner) if same_mutability(m) => {
78                     if_chain! {
79                         if let hir::ExprKind::Unary(hir::UnOp::Deref, inner1) = inner.kind;
80                         if let hir::ExprKind::Unary(hir::UnOp::Deref, inner2) = inner1.kind;
81                         then {
82                             path_to_local_id(inner2, closure_body.params[0].pat.hir_id)
83                         } else {
84                             false
85                         }
86                     }
87                 },
88                 _ => false,
89             }
90         },
91         _ => false,
92     };
93
94     if is_deref {
95         let current_method = if is_mut {
96             format!(".as_mut().map({})", snippet(cx, map_arg.span, ".."))
97         } else {
98             format!(".as_ref().map({})", snippet(cx, map_arg.span, ".."))
99         };
100         let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
101         let hint = format!("{}.{}()", snippet(cx, as_ref_recv.span, ".."), method_hint);
102         let suggestion = format!("try using {} instead", method_hint);
103
104         let msg = format!(
105             "called `{0}` on an Option value. This can be done more directly \
106             by calling `{1}` instead",
107             current_method, hint
108         );
109         span_lint_and_sugg(
110             cx,
111             OPTION_AS_REF_DEREF,
112             expr.span,
113             &msg,
114             &suggestion,
115             hint,
116             Applicability::MachineApplicable,
117         );
118     }
119 }