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