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