]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/map_clone.rs
Rollup merge of #94030 - ChayimFriedman2:issue-94010, r=petrochenkov
[rust.git] / src / tools / clippy / clippy_lints / src / map_clone.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::ty::{is_copy, is_type_diagnostic_item};
4 use clippy_utils::{is_trait_method, meets_msrv, msrvs, peel_blocks};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir as hir;
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::mir::Mutability;
10 use rustc_middle::ty;
11 use rustc_middle::ty::adjustment::Adjust;
12 use rustc_semver::RustcVersion;
13 use rustc_session::{declare_tool_lint, impl_lint_pass};
14 use rustc_span::symbol::Ident;
15 use rustc_span::{sym, Span};
16
17 declare_clippy_lint! {
18     /// ### What it does
19     /// Checks for usage of `map(|x| x.clone())` or
20     /// dereferencing closures for `Copy` types, on `Iterator` or `Option`,
21     /// and suggests `cloned()` or `copied()` instead
22     ///
23     /// ### Why is this bad?
24     /// Readability, this can be written more concisely
25     ///
26     /// ### Example
27     /// ```rust
28     /// let x = vec![42, 43];
29     /// let y = x.iter();
30     /// let z = y.map(|i| *i);
31     /// ```
32     ///
33     /// The correct use would be:
34     ///
35     /// ```rust
36     /// let x = vec![42, 43];
37     /// let y = x.iter();
38     /// let z = y.cloned();
39     /// ```
40     #[clippy::version = "pre 1.29.0"]
41     pub MAP_CLONE,
42     style,
43     "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
44 }
45
46 pub struct MapClone {
47     msrv: Option<RustcVersion>,
48 }
49
50 impl_lint_pass!(MapClone => [MAP_CLONE]);
51
52 impl MapClone {
53     pub fn new(msrv: Option<RustcVersion>) -> Self {
54         Self { msrv }
55     }
56 }
57
58 impl<'tcx> LateLintPass<'tcx> for MapClone {
59     fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
60         if e.span.from_expansion() {
61             return;
62         }
63
64         if_chain! {
65             if let hir::ExprKind::MethodCall(method, args, _) = e.kind;
66             if args.len() == 2;
67             if method.ident.name == sym::map;
68             let ty = cx.typeck_results().expr_ty(&args[0]);
69             if is_type_diagnostic_item(cx, ty, sym::Option) || is_trait_method(cx, e, sym::Iterator);
70             if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].kind;
71             then {
72                 let closure_body = cx.tcx.hir().body(body_id);
73                 let closure_expr = peel_blocks(&closure_body.value);
74                 match closure_body.params[0].pat.kind {
75                     hir::PatKind::Ref(inner, hir::Mutability::Not) => if let hir::PatKind::Binding(
76                         hir::BindingAnnotation::Unannotated, .., name, None
77                     ) = inner.kind {
78                         if ident_eq(name, closure_expr) {
79                             self.lint_explicit_closure(cx, e.span, args[0].span, true);
80                         }
81                     },
82                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, .., name, None) => {
83                         match closure_expr.kind {
84                             hir::ExprKind::Unary(hir::UnOp::Deref, inner) => {
85                                 if ident_eq(name, inner) {
86                                     if let ty::Ref(.., Mutability::Not) = cx.typeck_results().expr_ty(inner).kind() {
87                                         self.lint_explicit_closure(cx, e.span, args[0].span, true);
88                                     }
89                                 }
90                             },
91                             hir::ExprKind::MethodCall(method, [obj], _) => if_chain! {
92                                 if ident_eq(name, obj) && method.ident.name == sym::clone;
93                                 if let Some(fn_id) = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id);
94                                 if let Some(trait_id) = cx.tcx.trait_of_item(fn_id);
95                                 if cx.tcx.lang_items().clone_trait().map_or(false, |id| id == trait_id);
96                                 // no autoderefs
97                                 if !cx.typeck_results().expr_adjustments(obj).iter()
98                                     .any(|a| matches!(a.kind, Adjust::Deref(Some(..))));
99                                 then {
100                                     let obj_ty = cx.typeck_results().expr_ty(obj);
101                                     if let ty::Ref(_, ty, mutability) = obj_ty.kind() {
102                                         if matches!(mutability, Mutability::Not) {
103                                             let copy = is_copy(cx, *ty);
104                                             self.lint_explicit_closure(cx, e.span, args[0].span, copy);
105                                         }
106                                     } else {
107                                         lint_needless_cloning(cx, e.span, args[0].span);
108                                     }
109                                 }
110                             },
111                             _ => {},
112                         }
113                     },
114                     _ => {},
115                 }
116             }
117         }
118     }
119
120     extract_msrv_attr!(LateContext);
121 }
122
123 fn ident_eq(name: Ident, path: &hir::Expr<'_>) -> bool {
124     if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = path.kind {
125         path.segments.len() == 1 && path.segments[0].ident == name
126     } else {
127         false
128     }
129 }
130
131 fn lint_needless_cloning(cx: &LateContext<'_>, root: Span, receiver: Span) {
132     span_lint_and_sugg(
133         cx,
134         MAP_CLONE,
135         root.trim_start(receiver).unwrap(),
136         "you are needlessly cloning iterator elements",
137         "remove the `map` call",
138         String::new(),
139         Applicability::MachineApplicable,
140     );
141 }
142
143 impl MapClone {
144     fn lint_explicit_closure(&self, cx: &LateContext<'_>, replace: Span, root: Span, is_copy: bool) {
145         let mut applicability = Applicability::MachineApplicable;
146         let message = if is_copy {
147             "you are using an explicit closure for copying elements"
148         } else {
149             "you are using an explicit closure for cloning elements"
150         };
151         let sugg_method = if is_copy && meets_msrv(self.msrv.as_ref(), &msrvs::ITERATOR_COPIED) {
152             "copied"
153         } else {
154             "cloned"
155         };
156
157         span_lint_and_sugg(
158             cx,
159             MAP_CLONE,
160             replace,
161             message,
162             &format!("consider calling the dedicated `{}` method", sugg_method),
163             format!(
164                 "{}.{}()",
165                 snippet_with_applicability(cx, root, "..", &mut applicability),
166                 sugg_method,
167             ),
168             applicability,
169         );
170     }
171 }