]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/map_clone.rs
Merge commit 'a5d597637dcb78dc73f93561ce474f23d4177c35' into clippyup
[rust.git] / src / tools / clippy / clippy_lints / src / map_clone.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::is_trait_method;
3 use clippy_utils::remove_blocks;
4 use clippy_utils::source::snippet_with_applicability;
5 use clippy_utils::ty::{is_copy, is_type_diagnostic_item};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir as hir;
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::mir::Mutability;
11 use rustc_middle::ty;
12 use rustc_middle::ty::adjustment::Adjust;
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
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 declare_lint_pass!(MapClone => [MAP_CLONE]);
47
48 impl<'tcx> LateLintPass<'tcx> for MapClone {
49     fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
50         if e.span.from_expansion() {
51             return;
52         }
53
54         if_chain! {
55             if let hir::ExprKind::MethodCall(method, _, args, _) = e.kind;
56             if args.len() == 2;
57             if method.ident.name == sym::map;
58             let ty = cx.typeck_results().expr_ty(&args[0]);
59             if is_type_diagnostic_item(cx, ty, sym::Option) || is_trait_method(cx, e, sym::Iterator);
60             if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].kind;
61             then {
62                 let closure_body = cx.tcx.hir().body(body_id);
63                 let closure_expr = remove_blocks(&closure_body.value);
64                 match closure_body.params[0].pat.kind {
65                     hir::PatKind::Ref(inner, hir::Mutability::Not) => if let hir::PatKind::Binding(
66                         hir::BindingAnnotation::Unannotated, .., name, None
67                     ) = inner.kind {
68                         if ident_eq(name, closure_expr) {
69                             lint(cx, e.span, args[0].span, true);
70                         }
71                     },
72                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, .., name, None) => {
73                         match closure_expr.kind {
74                             hir::ExprKind::Unary(hir::UnOp::Deref, inner) => {
75                                 if ident_eq(name, inner) {
76                                     if let ty::Ref(.., Mutability::Not) = cx.typeck_results().expr_ty(inner).kind() {
77                                         lint(cx, e.span, args[0].span, true);
78                                     }
79                                 }
80                             },
81                             hir::ExprKind::MethodCall(method, _, [obj], _) => if_chain! {
82                                 if ident_eq(name, obj) && method.ident.name == sym::clone;
83                                 if let Some(fn_id) = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id);
84                                 if let Some(trait_id) = cx.tcx.trait_of_item(fn_id);
85                                 if cx.tcx.lang_items().clone_trait().map_or(false, |id| id == trait_id);
86                                 // no autoderefs
87                                 if !cx.typeck_results().expr_adjustments(obj).iter()
88                                     .any(|a| matches!(a.kind, Adjust::Deref(Some(..))));
89                                 then {
90                                     let obj_ty = cx.typeck_results().expr_ty(obj);
91                                     if let ty::Ref(_, ty, mutability) = obj_ty.kind() {
92                                         if matches!(mutability, Mutability::Not) {
93                                             let copy = is_copy(cx, ty);
94                                             lint(cx, e.span, args[0].span, copy);
95                                         }
96                                     } else {
97                                         lint_needless_cloning(cx, e.span, args[0].span);
98                                     }
99                                 }
100                             },
101                             _ => {},
102                         }
103                     },
104                     _ => {},
105                 }
106             }
107         }
108     }
109 }
110
111 fn ident_eq(name: Ident, path: &hir::Expr<'_>) -> bool {
112     if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = path.kind {
113         path.segments.len() == 1 && path.segments[0].ident == name
114     } else {
115         false
116     }
117 }
118
119 fn lint_needless_cloning(cx: &LateContext<'_>, root: Span, receiver: Span) {
120     span_lint_and_sugg(
121         cx,
122         MAP_CLONE,
123         root.trim_start(receiver).unwrap(),
124         "you are needlessly cloning iterator elements",
125         "remove the `map` call",
126         String::new(),
127         Applicability::MachineApplicable,
128     );
129 }
130
131 fn lint(cx: &LateContext<'_>, replace: Span, root: Span, copied: bool) {
132     let mut applicability = Applicability::MachineApplicable;
133     if copied {
134         span_lint_and_sugg(
135             cx,
136             MAP_CLONE,
137             replace,
138             "you are using an explicit closure for copying elements",
139             "consider calling the dedicated `copied` method",
140             format!(
141                 "{}.copied()",
142                 snippet_with_applicability(cx, root, "..", &mut applicability)
143             ),
144             applicability,
145         );
146     } else {
147         span_lint_and_sugg(
148             cx,
149             MAP_CLONE,
150             replace,
151             "you are using an explicit closure for cloning elements",
152             "consider calling the dedicated `cloned` method",
153             format!(
154                 "{}.cloned()",
155                 snippet_with_applicability(cx, root, "..", &mut applicability)
156             ),
157             applicability,
158         );
159     }
160 }