1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::ty::{is_copy, is_type_diagnostic_item};
4 use clippy_utils::{is_trait_method, meets_msrv, msrvs, peel_blocks};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
8 use rustc_lint::{LateContext, LateLintPass, LintContext};
9 use rustc_middle::mir::Mutability;
11 use rustc_middle::ty::adjustment::Adjust;
12 use rustc_semver::RustcVersion;
13 use rustc_session::{declare_tool_lint, impl_lint_pass};
14 use rustc_span::symbol::Ident;
15 use rustc_span::{sym, Span};
17 declare_clippy_lint! {
19 /// Checks for usage of `map(|x| x.clone())` or
20 /// dereferencing closures for `Copy` types, on `Iterator` or `Option`,
21 /// and suggests `cloned()` or `copied()` instead
23 /// ### Why is this bad?
24 /// Readability, this can be written more concisely
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 #[clippy::version = "pre 1.29.0"]
43 "using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
47 msrv: Option<RustcVersion>,
50 impl_lint_pass!(MapClone => [MAP_CLONE]);
53 pub fn new(msrv: Option<RustcVersion>) -> Self {
58 impl<'tcx> LateLintPass<'tcx> for MapClone {
59 fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
60 if e.span.from_expansion() {
65 if let hir::ExprKind::MethodCall(method, _, args, _) = e.kind;
67 if method.ident.name == sym::map;
68 let ty = cx.typeck_results().expr_ty(&args[0]);
69 if is_type_diagnostic_item(cx, ty, sym::Option) || is_trait_method(cx, e, sym::Iterator);
70 if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].kind;
72 let closure_body = cx.tcx.hir().body(body_id);
73 let closure_expr = peel_blocks(&closure_body.value);
74 match closure_body.params[0].pat.kind {
75 hir::PatKind::Ref(inner, hir::Mutability::Not) => if let hir::PatKind::Binding(
76 hir::BindingAnnotation::Unannotated, .., name, None
78 if ident_eq(name, closure_expr) {
79 self.lint_explicit_closure(cx, e.span, args[0].span, true);
82 hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, .., name, None) => {
83 match closure_expr.kind {
84 hir::ExprKind::Unary(hir::UnOp::Deref, inner) => {
85 if ident_eq(name, inner) {
86 if let ty::Ref(.., Mutability::Not) = cx.typeck_results().expr_ty(inner).kind() {
87 self.lint_explicit_closure(cx, e.span, args[0].span, true);
91 hir::ExprKind::MethodCall(method, _, [obj], _) => if_chain! {
92 if ident_eq(name, obj) && method.ident.name == sym::clone;
93 if let Some(fn_id) = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id);
94 if let Some(trait_id) = cx.tcx.trait_of_item(fn_id);
95 if cx.tcx.lang_items().clone_trait().map_or(false, |id| id == trait_id);
97 if !cx.typeck_results().expr_adjustments(obj).iter()
98 .any(|a| matches!(a.kind, Adjust::Deref(Some(..))));
100 let obj_ty = cx.typeck_results().expr_ty(obj);
101 if let ty::Ref(_, ty, mutability) = obj_ty.kind() {
102 if matches!(mutability, Mutability::Not) {
103 let copy = is_copy(cx, ty);
104 self.lint_explicit_closure(cx, e.span, args[0].span, copy);
107 lint_needless_cloning(cx, e.span, args[0].span);
120 extract_msrv_attr!(LateContext);
123 fn ident_eq(name: Ident, path: &hir::Expr<'_>) -> bool {
124 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = path.kind {
125 path.segments.len() == 1 && path.segments[0].ident == name
131 fn lint_needless_cloning(cx: &LateContext<'_>, root: Span, receiver: Span) {
135 root.trim_start(receiver).unwrap(),
136 "you are needlessly cloning iterator elements",
137 "remove the `map` call",
139 Applicability::MachineApplicable,
144 fn lint_explicit_closure(&self, cx: &LateContext<'_>, replace: Span, root: Span, is_copy: bool) {
145 let mut applicability = Applicability::MachineApplicable;
146 let message = if is_copy {
147 "you are using an explicit closure for copying elements"
149 "you are using an explicit closure for cloning elements"
151 let sugg_method = if is_copy && meets_msrv(self.msrv.as_ref(), &msrvs::ITERATOR_COPIED) {
162 &format!("consider calling the dedicated `{}` method", sugg_method),
165 snippet_with_applicability(cx, root, "..", &mut applicability),