1 use crate::utils::paths;
3 in_macro, match_trait_method, match_type, remove_blocks, snippet_with_applicability, span_lint_and_sugg,
5 use if_chain::if_chain;
7 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
8 use rustc::{declare_tool_lint, lint_array};
9 use rustc_errors::Applicability;
10 use syntax::ast::Ident;
11 use syntax::source_map::Span;
16 /// **What it does:** Checks for usage of `iterator.map(|x| x.clone())` and suggests
17 /// `iterator.cloned()` instead
19 /// **Why is this bad?** Readability, this can be written more concisely
21 /// **Known problems:** Sometimes `.cloned()` requires stricter trait
22 /// bound than `.map(|e| e.clone())` (which works because of the coercion).
23 /// See [#498](https://github.com/rust-lang-nursery/rust-clippy/issues/498).
28 /// let x = vec![42, 43];
30 /// let z = y.map(|i| *i);
33 /// The correct use would be:
36 /// let x = vec![42, 43];
38 /// let z = y.cloned();
40 declare_clippy_lint! {
43 "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
46 impl LintPass for Pass {
47 fn get_lints(&self) -> LintArray {
48 lint_array!(MAP_CLONE)
52 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
53 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
59 if let hir::ExprKind::MethodCall(ref method, _, ref args) = e.node;
61 if method.ident.as_str() == "map";
62 let ty = cx.tables.expr_ty(&args[0]);
63 if match_type(cx, ty, &paths::OPTION) || match_trait_method(cx, e, &paths::ITERATOR);
64 if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].node;
65 let closure_body = cx.tcx.hir().body(body_id);
66 let closure_expr = remove_blocks(&closure_body.value);
68 match closure_body.arguments[0].pat.node {
69 hir::PatKind::Ref(ref inner, _) => if let hir::PatKind::Binding(
70 hir::BindingAnnotation::Unannotated, _, name, None
72 lint(cx, e.span, args[0].span, name, closure_expr);
74 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
75 match closure_expr.node {
76 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner) => {
77 if !cx.tables.expr_ty(inner).is_box() {
78 lint(cx, e.span, args[0].span, name, inner);
81 hir::ExprKind::MethodCall(ref method, _, ref obj) => {
82 if method.ident.as_str() == "clone"
83 && match_trait_method(cx, closure_expr, &paths::CLONE_TRAIT) {
84 lint(cx, e.span, args[0].span, name, &obj[0]);
97 fn lint(cx: &LateContext<'_, '_>, replace: Span, root: Span, name: Ident, path: &hir::Expr) {
98 if let hir::ExprKind::Path(hir::QPath::Resolved(None, ref path)) = path.node {
99 if path.segments.len() == 1 && path.segments[0].ident == name {
100 let mut applicability = Applicability::MachineApplicable;
105 "You are using an explicit closure for cloning elements",
106 "Consider calling the dedicated `cloned` method",
109 snippet_with_applicability(cx, root, "..", &mut applicability)