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