1 use crate::utils::{is_copy, span_lint_and_then, sugg};
2 use rustc_errors::Applicability;
4 use rustc_lint::LateContext;
5 use rustc_middle::ty::{self, Ty};
8 use super::CLONE_DOUBLE_REF;
9 use super::CLONE_ON_COPY;
11 /// Checks for the `CLONE_ON_COPY` lint.
12 pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
13 let ty = cx.typeck_results().expr_ty(expr);
14 if let ty::Ref(_, inner, _) = arg_ty.kind() {
15 if let ty::Ref(_, innermost, _) = inner.kind() {
21 "using `clone` on a double-reference; \
22 this will copy the reference of type `{}` instead of cloning the inner type",
26 if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
27 let mut ty = innermost;
29 while let ty::Ref(_, inner, _) = ty.kind() {
33 let refs: String = iter::repeat('&').take(n + 1).collect();
34 let derefs: String = iter::repeat('*').take(n).collect();
35 let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
38 "try dereferencing it",
39 format!("{}({}{}).clone()", refs, derefs, snip.deref()),
40 Applicability::MaybeIncorrect,
44 "or try being explicit if you are sure, that you want to clone a reference",
46 Applicability::MaybeIncorrect,
51 return; // don't report clone_on_copy
57 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
58 let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
59 match &cx.tcx.hir().get(parent) {
60 hir::Node::Expr(parent) => match parent.kind {
61 // &*x is a nop, &x.clone() is not
62 hir::ExprKind::AddrOf(..) => return,
63 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
64 hir::ExprKind::MethodCall(_, _, parent_args, _) if expr.hir_id == parent_args[0].hir_id => {
70 hir::Node::Stmt(stmt) => {
71 if let hir::StmtKind::Local(ref loc) = stmt.kind {
72 if let hir::PatKind::Ref(..) = loc.pat.kind {
73 // let ref y = *x borrows x, let ref y = x.clone() does not
81 // x.clone() might have dereferenced x, possibly through Deref impls
82 if cx.typeck_results().expr_ty(arg) == ty {
83 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
87 .expr_adjustments(arg)
89 .filter(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
91 let derefs: String = iter::repeat('*').take(deref_count).collect();
92 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
101 &format!("using `clone` on type `{}` which implements the `Copy` trait", ty),
103 if let Some((text, snip)) = snip {
104 diag.span_suggestion(expr.span, text, snip, Applicability::MachineApplicable);