]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/map_clone.rs
Auto merge of #3970 - rust-lang:map_copied, r=flip1995
[rust.git] / clippy_lints / src / map_clone.rs
1 use crate::utils::paths;
2 use crate::utils::{
3     in_macro, is_copy, match_trait_method, match_type, remove_blocks, snippet_with_applicability, span_lint_and_sugg,
4 };
5 use if_chain::if_chain;
6 use rustc::hir;
7 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
8 use rustc::ty;
9 use rustc::{declare_tool_lint, lint_array};
10 use rustc_errors::Applicability;
11 use syntax::ast::Ident;
12 use syntax::source_map::Span;
13
14 #[derive(Clone)]
15 pub struct Pass;
16
17 declare_clippy_lint! {
18     /// **What it does:** Checks for usage of `iterator.map(|x| x.clone())` and suggests
19     /// `iterator.cloned()` instead
20     ///
21     /// **Why is this bad?** Readability, this can be written more concisely
22     ///
23     /// **Known problems:** None
24     ///
25     /// **Example:**
26     ///
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     pub MAP_CLONE,
41     style,
42     "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
43 }
44
45 impl LintPass for Pass {
46     fn get_lints(&self) -> LintArray {
47         lint_array!(MAP_CLONE)
48     }
49
50     fn name(&self) -> &'static str {
51         "MapClone"
52     }
53 }
54
55 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
56     fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
57         if in_macro(e.span) {
58             return;
59         }
60
61         if_chain! {
62             if let hir::ExprKind::MethodCall(ref method, _, ref args) = e.node;
63             if args.len() == 2;
64             if method.ident.as_str() == "map";
65             let ty = cx.tables.expr_ty(&args[0]);
66             let is_option = match_type(cx, ty, &paths::OPTION);
67             if is_option || match_trait_method(cx, e, &paths::ITERATOR);
68             if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].node;
69             let closure_body = cx.tcx.hir().body(body_id);
70             let closure_expr = remove_blocks(&closure_body.value);
71             then {
72                 match closure_body.arguments[0].pat.node {
73                     hir::PatKind::Ref(ref inner, _) => if let hir::PatKind::Binding(
74                         hir::BindingAnnotation::Unannotated, .., name, None
75                     ) = inner.node {
76                         if ident_eq(name, closure_expr) {
77                             // FIXME When Iterator::copied() stabilizes we can remove is_option
78                             // from here and the other lint() calls
79                             lint(cx, e.span, args[0].span, is_option);
80                         }
81                     },
82                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, .., name, None) => {
83                         match closure_expr.node {
84                             hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner) => {
85                                 if ident_eq(name, inner) && !cx.tables.expr_ty(inner).is_box() {
86                                     lint(cx, e.span, args[0].span, is_option);
87                                 }
88                             },
89                             hir::ExprKind::MethodCall(ref method, _, ref obj) => {
90                                 if ident_eq(name, &obj[0]) && method.ident.as_str() == "clone"
91                                     && match_trait_method(cx, closure_expr, &paths::CLONE_TRAIT) {
92
93                                     let obj_ty = cx.tables.expr_ty(&obj[0]);
94                                     if let ty::Ref(_, ty, _) = obj_ty.sty {
95                                         let copy = is_copy(cx, ty);
96                                         lint(cx, e.span, args[0].span, is_option && copy);
97                                     } else {
98                                         lint_needless_cloning(cx, e.span, args[0].span);
99                                     }
100                                 }
101                             },
102                             _ => {},
103                         }
104                     },
105                     _ => {},
106                 }
107             }
108         }
109     }
110 }
111
112 fn ident_eq(name: Ident, path: &hir::Expr) -> bool {
113     if let hir::ExprKind::Path(hir::QPath::Resolved(None, ref path)) = path.node {
114         path.segments.len() == 1 && path.segments[0].ident == name
115     } else {
116         false
117     }
118 }
119
120 fn lint_needless_cloning(cx: &LateContext<'_, '_>, root: Span, receiver: Span) {
121     span_lint_and_sugg(
122         cx,
123         MAP_CLONE,
124         root.trim_start(receiver).unwrap(),
125         "You are needlessly cloning iterator elements",
126         "Remove the map call",
127         String::new(),
128         Applicability::MachineApplicable,
129     )
130 }
131
132 fn lint(cx: &LateContext<'_, '_>, replace: Span, root: Span, copied: bool) {
133     let mut applicability = Applicability::MachineApplicable;
134     if copied {
135         span_lint_and_sugg(
136             cx,
137             MAP_CLONE,
138             replace,
139             "You are using an explicit closure for copying elements",
140             "Consider calling the dedicated `copied` method",
141             format!(
142                 "{}.copied()",
143                 snippet_with_applicability(cx, root, "..", &mut applicability)
144             ),
145             applicability,
146         )
147     } else {
148         span_lint_and_sugg(
149             cx,
150             MAP_CLONE,
151             replace,
152             "You are using an explicit closure for cloning elements",
153             "Consider calling the dedicated `cloned` method",
154             format!(
155                 "{}.cloned()",
156                 snippet_with_applicability(cx, root, "..", &mut applicability)
157             ),
158             applicability,
159         )
160     }
161 }