]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/map_clone.rs
Add Applicability::Unspecified to span_lint_and_sugg functions
[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
11 use crate::rustc::hir;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::rustc_errors::Applicability;
15 use crate::syntax::ast::Ident;
16 use crate::syntax::source_map::Span;
17 use crate::utils::paths;
18 use crate::utils::{in_macro, match_trait_method, match_type, remove_blocks, snippet, span_lint_and_sugg};
19 use if_chain::if_chain;
20
21 #[derive(Clone)]
22 pub struct Pass;
23
24 /// **What it does:** Checks for usage of `iterator.map(|x| x.clone())` and suggests
25 /// `iterator.cloned()` instead
26 ///
27 /// **Why is this bad?** Readability, this can be written more concisely
28 ///
29 /// **Known problems:** None.
30 ///
31 /// **Example:**
32 ///
33 /// ```rust
34 /// let x = vec![42, 43];
35 /// let y = x.iter();
36 /// let z = y.map(|i| *i);
37 /// ```
38 ///
39 /// The correct use would be:
40 ///
41 /// ```rust
42 /// let x = vec![42, 43];
43 /// let y = x.iter();
44 /// let z = y.cloned();
45 /// ```
46 declare_clippy_lint! {
47     pub MAP_CLONE,
48     style,
49     "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
50 }
51
52 impl LintPass for Pass {
53     fn get_lints(&self) -> LintArray {
54         lint_array!(MAP_CLONE)
55     }
56 }
57
58 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
59     fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
60         if in_macro(e.span) {
61             return;
62         }
63
64         if_chain! {
65             if let hir::ExprKind::MethodCall(ref method, _, ref args) = e.node;
66             if args.len() == 2;
67             if method.ident.as_str() == "map";
68             let ty = cx.tables.expr_ty(&args[0]);
69             if match_type(cx, ty, &paths::OPTION) || match_trait_method(cx, e, &paths::ITERATOR);
70             if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].node;
71             let closure_body = cx.tcx.hir.body(body_id);
72             let closure_expr = remove_blocks(&closure_body.value);
73             then {
74                 match closure_body.arguments[0].pat.node {
75                     hir::PatKind::Ref(ref inner, _) => if let hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) = inner.node {
76                         lint(cx, e.span, args[0].span, name, closure_expr);
77                     },
78                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => match closure_expr.node {
79                         hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner) if !cx.tables.expr_ty(inner).is_box() => lint(cx, e.span, args[0].span, name, inner),
80                         hir::ExprKind::MethodCall(ref method, _, ref obj) => if method.ident.as_str() == "clone" && match_trait_method(cx, closure_expr, &paths::CLONE_TRAIT) {
81                             lint(cx, e.span, args[0].span, name, &obj[0]);
82                         }
83                         _ => {},
84                     },
85                     _ => {},
86                 }
87             }
88         }
89     }
90 }
91
92 fn lint(cx: &LateContext<'_, '_>, replace: Span, root: Span, name: Ident, path: &hir::Expr) {
93     if let hir::ExprKind::Path(hir::QPath::Resolved(None, ref path)) = path.node {
94         if path.segments.len() == 1 && path.segments[0].ident == name {
95             span_lint_and_sugg(
96                 cx,
97                 MAP_CLONE,
98                 replace,
99                 "You are using an explicit closure for cloning elements",
100                 "Consider calling the dedicated `cloned` method",
101                 format!("{}.cloned()", snippet(cx, root, "..")),
102                 Applicability::Unspecified,
103             )
104         }
105     }
106 }