]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/map_clone.rs
Auto merge of #3596 - xfix:remove-crate-from-paths, r=flip1995
[rust.git] / clippy_lints / src / map_clone.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::utils::paths;
11 use crate::utils::{
12     in_macro, match_trait_method, match_type, remove_blocks, snippet_with_applicability, span_lint_and_sugg,
13 };
14 use if_chain::if_chain;
15 use rustc::hir;
16 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
17 use rustc::{declare_tool_lint, lint_array};
18 use rustc_errors::Applicability;
19 use syntax::ast::Ident;
20 use syntax::source_map::Span;
21
22 #[derive(Clone)]
23 pub struct Pass;
24
25 /// **What it does:** Checks for usage of `iterator.map(|x| x.clone())` and suggests
26 /// `iterator.cloned()` instead
27 ///
28 /// **Why is this bad?** Readability, this can be written more concisely
29 ///
30 /// **Known problems:** Sometimes `.cloned()` requires stricter trait
31 /// bound than `.map(|e| e.clone())` (which works because of the coercion).
32 /// See [#498](https://github.com/rust-lang-nursery/rust-clippy/issues/498).
33 ///
34 /// **Example:**
35 ///
36 /// ```rust
37 /// let x = vec![42, 43];
38 /// let y = x.iter();
39 /// let z = y.map(|i| *i);
40 /// ```
41 ///
42 /// The correct use would be:
43 ///
44 /// ```rust
45 /// let x = vec![42, 43];
46 /// let y = x.iter();
47 /// let z = y.cloned();
48 /// ```
49 declare_clippy_lint! {
50     pub MAP_CLONE,
51     style,
52     "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
53 }
54
55 impl LintPass for Pass {
56     fn get_lints(&self) -> LintArray {
57         lint_array!(MAP_CLONE)
58     }
59 }
60
61 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
62     fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
63         if in_macro(e.span) {
64             return;
65         }
66
67         if_chain! {
68             if let hir::ExprKind::MethodCall(ref method, _, ref args) = e.node;
69             if args.len() == 2;
70             if method.ident.as_str() == "map";
71             let ty = cx.tables.expr_ty(&args[0]);
72             if match_type(cx, ty, &paths::OPTION) || match_trait_method(cx, e, &paths::ITERATOR);
73             if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].node;
74             let closure_body = cx.tcx.hir().body(body_id);
75             let closure_expr = remove_blocks(&closure_body.value);
76             then {
77                 match closure_body.arguments[0].pat.node {
78                     hir::PatKind::Ref(ref inner, _) => if let hir::PatKind::Binding(
79                         hir::BindingAnnotation::Unannotated, _, name, None
80                     ) = inner.node {
81                         lint(cx, e.span, args[0].span, name, closure_expr);
82                     },
83                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
84                         match closure_expr.node {
85                             hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner) => {
86                                 if !cx.tables.expr_ty(inner).is_box() {
87                                     lint(cx, e.span, args[0].span, name, inner);
88                                 }
89                             },
90                             hir::ExprKind::MethodCall(ref method, _, ref obj) => {
91                                 if method.ident.as_str() == "clone"
92                                     && match_trait_method(cx, closure_expr, &paths::CLONE_TRAIT) {
93                                     lint(cx, e.span, args[0].span, name, &obj[0]);
94                                 }
95                             },
96                             _ => {},
97                         }
98                     },
99                     _ => {},
100                 }
101             }
102         }
103     }
104 }
105
106 fn lint(cx: &LateContext<'_, '_>, replace: Span, root: Span, name: Ident, path: &hir::Expr) {
107     if let hir::ExprKind::Path(hir::QPath::Resolved(None, ref path)) = path.node {
108         if path.segments.len() == 1 && path.segments[0].ident == name {
109             let mut applicability = Applicability::MachineApplicable;
110             span_lint_and_sugg(
111                 cx,
112                 MAP_CLONE,
113                 replace,
114                 "You are using an explicit closure for cloning elements",
115                 "Consider calling the dedicated `cloned` method",
116                 format!(
117                     "{}.cloned()",
118                     snippet_with_applicability(cx, root, "..", &mut applicability)
119                 ),
120                 applicability,
121             )
122         }
123     }
124 }