]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/map_clone.rs
Auto merge of #3662 - mikerite:fix-498, r=oli-obk
[rust.git] / clippy_lints / src / map_clone.rs
1 use crate::utils::paths;
2 use crate::utils::{
3     in_macro, 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 /// **What it does:** Checks for usage of `iterator.map(|x| x.clone())` and suggests
18 /// `iterator.cloned()` 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 declare_clippy_lint! {
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
51 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
52     fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
53         if in_macro(e.span) {
54             return;
55         }
56
57         if_chain! {
58             if let hir::ExprKind::MethodCall(ref method, _, ref args) = e.node;
59             if args.len() == 2;
60             if method.ident.as_str() == "map";
61             let ty = cx.tables.expr_ty(&args[0]);
62             if match_type(cx, ty, &paths::OPTION) || match_trait_method(cx, e, &paths::ITERATOR);
63             if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].node;
64             let closure_body = cx.tcx.hir().body(body_id);
65             let closure_expr = remove_blocks(&closure_body.value);
66             then {
67                 match closure_body.arguments[0].pat.node {
68                     hir::PatKind::Ref(ref inner, _) => if let hir::PatKind::Binding(
69                         hir::BindingAnnotation::Unannotated, _, name, None
70                     ) = inner.node {
71                         if ident_eq(name, closure_expr) {
72                             lint(cx, e.span, args[0].span);
73                         }
74                     },
75                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
76                         match closure_expr.node {
77                             hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner) => {
78                                 if ident_eq(name, inner) && !cx.tables.expr_ty(inner).is_box() {
79                                     lint(cx, e.span, args[0].span);
80                                 }
81                             },
82                             hir::ExprKind::MethodCall(ref method, _, ref obj) => {
83                                 if ident_eq(name, &obj[0]) && method.ident.as_str() == "clone"
84                                     && match_trait_method(cx, closure_expr, &paths::CLONE_TRAIT) {
85
86                                     let obj_ty = cx.tables.expr_ty(&obj[0]);
87                                     if let ty::Ref(..) = obj_ty.sty {
88                                         lint(cx, e.span, args[0].span);
89                                     } else {
90                                         lint_needless_cloning(cx, e.span, args[0].span);
91                                     }
92                                 }
93                             },
94                             _ => {},
95                         }
96                     },
97                     _ => {},
98                 }
99             }
100         }
101     }
102 }
103
104 fn ident_eq(name: Ident, path: &hir::Expr) -> bool {
105     if let hir::ExprKind::Path(hir::QPath::Resolved(None, ref path)) = path.node {
106         path.segments.len() == 1 && path.segments[0].ident == name
107     } else {
108         false
109     }
110 }
111
112 fn lint_needless_cloning(cx: &LateContext<'_, '_>, root: Span, receiver: Span) {
113     span_lint_and_sugg(
114         cx,
115         MAP_CLONE,
116         root.trim_start(receiver).unwrap(),
117         "You are needlessly cloning iterator elements",
118         "Remove the map call",
119         String::new(),
120         Applicability::MachineApplicable,
121     )
122 }
123
124 fn lint(cx: &LateContext<'_, '_>, replace: Span, root: Span) {
125     let mut applicability = Applicability::MachineApplicable;
126     span_lint_and_sugg(
127         cx,
128         MAP_CLONE,
129         replace,
130         "You are using an explicit closure for cloning elements",
131         "Consider calling the dedicated `cloned` method",
132         format!(
133             "{}.cloned()",
134             snippet_with_applicability(cx, root, "..", &mut applicability)
135         ),
136         applicability,
137     )
138 }