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