]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/map_clone.rs
Merge pull request #3465 from flip1995/rustfmt
[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::rustc::hir;
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use crate::rustc_errors::Applicability;
14 use crate::syntax::ast::Ident;
15 use crate::syntax::source_map::Span;
16 use crate::utils::paths;
17 use crate::utils::{
18     in_macro, match_trait_method, match_type, remove_blocks, snippet_with_applicability, span_lint_and_sugg,
19 };
20 use if_chain::if_chain;
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:** None.
31 ///
32 /// **Example:**
33 ///
34 /// ```rust
35 /// let x = vec![42, 43];
36 /// let y = x.iter();
37 /// let z = y.map(|i| *i);
38 /// ```
39 ///
40 /// The correct use would be:
41 ///
42 /// ```rust
43 /// let x = vec![42, 43];
44 /// let y = x.iter();
45 /// let z = y.cloned();
46 /// ```
47 declare_clippy_lint! {
48     pub MAP_CLONE,
49     style,
50     "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
51 }
52
53 impl LintPass for Pass {
54     fn get_lints(&self) -> LintArray {
55         lint_array!(MAP_CLONE)
56     }
57 }
58
59 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
60     fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
61         if in_macro(e.span) {
62             return;
63         }
64
65         if_chain! {
66             if let hir::ExprKind::MethodCall(ref method, _, ref args) = e.node;
67             if args.len() == 2;
68             if method.ident.as_str() == "map";
69             let ty = cx.tables.expr_ty(&args[0]);
70             if match_type(cx, ty, &paths::OPTION) || match_trait_method(cx, e, &paths::ITERATOR);
71             if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].node;
72             let closure_body = cx.tcx.hir.body(body_id);
73             let closure_expr = remove_blocks(&closure_body.value);
74             then {
75                 match closure_body.arguments[0].pat.node {
76                     hir::PatKind::Ref(ref inner, _) => if let hir::PatKind::Binding(
77                         hir::BindingAnnotation::Unannotated, _, name, None
78                     ) = inner.node {
79                         lint(cx, e.span, args[0].span, name, closure_expr);
80                     },
81                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
82                         match closure_expr.node {
83                             hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner) => {
84                                 if !cx.tables.expr_ty(inner).is_box() {
85                                     lint(cx, e.span, args[0].span, name, inner);
86                                 }
87                             },
88                             hir::ExprKind::MethodCall(ref method, _, ref obj) => {
89                                 if method.ident.as_str() == "clone"
90                                     && match_trait_method(cx, closure_expr, &paths::CLONE_TRAIT) {
91                                     lint(cx, e.span, args[0].span, name, &obj[0]);
92                                 }
93                             },
94                             _ => {},
95                         }
96                     },
97                     _ => {},
98                 }
99             }
100         }
101     }
102 }
103
104 fn lint(cx: &LateContext<'_, '_>, replace: Span, root: Span, name: Ident, path: &hir::Expr) {
105     if let hir::ExprKind::Path(hir::QPath::Resolved(None, ref path)) = path.node {
106         if path.segments.len() == 1 && path.segments[0].ident == name {
107             let mut applicability = Applicability::MachineApplicable;
108             span_lint_and_sugg(
109                 cx,
110                 MAP_CLONE,
111                 replace,
112                 "You are using an explicit closure for cloning elements",
113                 "Consider calling the dedicated `cloned` method",
114                 format!(
115                     "{}.cloned()",
116                     snippet_with_applicability(cx, root, "..", &mut applicability)
117                 ),
118                 applicability,
119             )
120         }
121     }
122 }