]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/map_clone.rs
Allow UUID style formatting for `inconsistent_digit_grouping` lint
[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_ast::ast::Ident;
7 use rustc_errors::Applicability;
8 use rustc_hir as hir;
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::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.kind;
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].kind;
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.kind {
61                     hir::PatKind::Ref(ref inner, _) => if let hir::PatKind::Binding(
62                         hir::BindingAnnotation::Unannotated, .., name, None
63                     ) = inner.kind {
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.kind {
70                             hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner) => {
71                                 if ident_eq(name, inner) {
72                                     if let ty::Ref(..) = cx.tables.expr_ty(inner).kind {
73                                         lint(cx, e.span, args[0].span, true);
74                                     }
75                                 }
76                             },
77                             hir::ExprKind::MethodCall(ref method, _, ref obj) => {
78                                 if ident_eq(name, &obj[0]) && method.ident.as_str() == "clone"
79                                     && match_trait_method(cx, closure_expr, &paths::CLONE_TRAIT) {
80
81                                     let obj_ty = cx.tables.expr_ty(&obj[0]);
82                                     if let ty::Ref(_, ty, _) = obj_ty.kind {
83                                         let copy = is_copy(cx, ty);
84                                         lint(cx, e.span, args[0].span, copy);
85                                     } else {
86                                         lint_needless_cloning(cx, e.span, args[0].span);
87                                     }
88                                 }
89                             },
90                             _ => {},
91                         }
92                     },
93                     _ => {},
94                 }
95             }
96         }
97     }
98 }
99
100 fn ident_eq(name: Ident, path: &hir::Expr<'_>) -> bool {
101     if let hir::ExprKind::Path(hir::QPath::Resolved(None, ref path)) = path.kind {
102         path.segments.len() == 1 && path.segments[0].ident == name
103     } else {
104         false
105     }
106 }
107
108 fn lint_needless_cloning(cx: &LateContext<'_, '_>, root: Span, receiver: Span) {
109     span_lint_and_sugg(
110         cx,
111         MAP_CLONE,
112         root.trim_start(receiver).unwrap(),
113         "You are needlessly cloning iterator elements",
114         "Remove the `map` call",
115         String::new(),
116         Applicability::MachineApplicable,
117     )
118 }
119
120 fn lint(cx: &LateContext<'_, '_>, replace: Span, root: Span, copied: bool) {
121     let mut applicability = Applicability::MachineApplicable;
122     if copied {
123         span_lint_and_sugg(
124             cx,
125             MAP_CLONE,
126             replace,
127             "You are using an explicit closure for copying elements",
128             "Consider calling the dedicated `copied` method",
129             format!(
130                 "{}.copied()",
131                 snippet_with_applicability(cx, root, "..", &mut applicability)
132             ),
133             applicability,
134         )
135     } else {
136         span_lint_and_sugg(
137             cx,
138             MAP_CLONE,
139             replace,
140             "You are using an explicit closure for cloning elements",
141             "Consider calling the dedicated `cloned` method",
142             format!(
143                 "{}.cloned()",
144                 snippet_with_applicability(cx, root, "..", &mut applicability)
145             ),
146             applicability,
147         )
148     }
149 }