]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/map_clone.rs
Rollup merge of #105615 - WaffleLapkin:remove_opt_scope_span_mention, r=compiler...
[rust.git] / src / tools / clippy / clippy_lints / src / methods / map_clone.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::msrvs::{self, Msrv};
3 use clippy_utils::source::snippet_with_applicability;
4 use clippy_utils::ty::{is_copy, is_type_diagnostic_item};
5 use clippy_utils::{is_diag_trait_item, peel_blocks};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir as hir;
9 use rustc_lint::LateContext;
10 use rustc_middle::mir::Mutability;
11 use rustc_middle::ty;
12 use rustc_middle::ty::adjustment::Adjust;
13 use rustc_span::symbol::Ident;
14 use rustc_span::{sym, Span};
15
16 use super::MAP_CLONE;
17
18 pub(super) fn check(cx: &LateContext<'_>, e: &hir::Expr<'_>, recv: &hir::Expr<'_>, arg: &hir::Expr<'_>, msrv: &Msrv) {
19     if_chain! {
20         if let Some(method_id) = cx.typeck_results().type_dependent_def_id(e.hir_id);
21         if cx.tcx.impl_of_method(method_id)
22             .map_or(false, |id| is_type_diagnostic_item(cx, cx.tcx.type_of(id), sym::Option))
23             || is_diag_trait_item(cx, method_id, sym::Iterator);
24         if let hir::ExprKind::Closure(&hir::Closure{ body, .. }) = arg.kind;
25         then {
26             let closure_body = cx.tcx.hir().body(body);
27             let closure_expr = peel_blocks(closure_body.value);
28             match closure_body.params[0].pat.kind {
29                 hir::PatKind::Ref(inner, hir::Mutability::Not) => if let hir::PatKind::Binding(
30                     hir::BindingAnnotation::NONE, .., name, None
31                 ) = inner.kind {
32                     if ident_eq(name, closure_expr) {
33                         lint_explicit_closure(cx, e.span, recv.span, true, msrv);
34                     }
35                 },
36                 hir::PatKind::Binding(hir::BindingAnnotation::NONE, .., name, None) => {
37                     match closure_expr.kind {
38                         hir::ExprKind::Unary(hir::UnOp::Deref, inner) => {
39                             if ident_eq(name, inner) {
40                                 if let ty::Ref(.., Mutability::Not) = cx.typeck_results().expr_ty(inner).kind() {
41                                     lint_explicit_closure(cx, e.span, recv.span, true, msrv);
42                                 }
43                             }
44                         },
45                         hir::ExprKind::MethodCall(method, obj, [], _) => if_chain! {
46                             if ident_eq(name, obj) && method.ident.name == sym::clone;
47                             if let Some(fn_id) = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id);
48                             if let Some(trait_id) = cx.tcx.trait_of_item(fn_id);
49                             if cx.tcx.lang_items().clone_trait().map_or(false, |id| id == trait_id);
50                             // no autoderefs
51                             if !cx.typeck_results().expr_adjustments(obj).iter()
52                                 .any(|a| matches!(a.kind, Adjust::Deref(Some(..))));
53                             then {
54                                 let obj_ty = cx.typeck_results().expr_ty(obj);
55                                 if let ty::Ref(_, ty, mutability) = obj_ty.kind() {
56                                     if matches!(mutability, Mutability::Not) {
57                                         let copy = is_copy(cx, *ty);
58                                         lint_explicit_closure(cx, e.span, recv.span, copy, msrv);
59                                     }
60                                 } else {
61                                     lint_needless_cloning(cx, e.span, recv.span);
62                                 }
63                             }
64                         },
65                         _ => {},
66                     }
67                 },
68                 _ => {},
69             }
70         }
71     }
72 }
73
74 fn ident_eq(name: Ident, path: &hir::Expr<'_>) -> bool {
75     if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = path.kind {
76         path.segments.len() == 1 && path.segments[0].ident == name
77     } else {
78         false
79     }
80 }
81
82 fn lint_needless_cloning(cx: &LateContext<'_>, root: Span, receiver: Span) {
83     span_lint_and_sugg(
84         cx,
85         MAP_CLONE,
86         root.trim_start(receiver).unwrap(),
87         "you are needlessly cloning iterator elements",
88         "remove the `map` call",
89         String::new(),
90         Applicability::MachineApplicable,
91     );
92 }
93
94 fn lint_explicit_closure(cx: &LateContext<'_>, replace: Span, root: Span, is_copy: bool, msrv: &Msrv) {
95     let mut applicability = Applicability::MachineApplicable;
96
97     let (message, sugg_method) = if is_copy && msrv.meets(msrvs::ITERATOR_COPIED) {
98         ("you are using an explicit closure for copying elements", "copied")
99     } else {
100         ("you are using an explicit closure for cloning elements", "cloned")
101     };
102
103     span_lint_and_sugg(
104         cx,
105         MAP_CLONE,
106         replace,
107         message,
108         &format!("consider calling the dedicated `{sugg_method}` method"),
109         format!(
110             "{}.{sugg_method}()",
111             snippet_with_applicability(cx, root, "..", &mut applicability),
112         ),
113         applicability,
114     );
115 }