]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs
Auto merge of #99422 - Dylan-DPC:rollup-htjofm6, r=Dylan-DPC
[rust.git] / src / tools / clippy / clippy_lints / src / methods / clone_on_copy.rs
1 use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
2 use clippy_utils::get_parent_node;
3 use clippy_utils::source::snippet_with_context;
4 use clippy_utils::sugg;
5 use clippy_utils::ty::is_copy;
6 use rustc_errors::Applicability;
7 use rustc_hir::{BindingAnnotation, Expr, ExprKind, MatchSource, Node, PatKind};
8 use rustc_lint::LateContext;
9 use rustc_middle::ty::{self, adjustment::Adjust};
10 use rustc_span::symbol::{sym, Symbol};
11
12 use super::CLONE_DOUBLE_REF;
13 use super::CLONE_ON_COPY;
14
15 /// Checks for the `CLONE_ON_COPY` lint.
16 #[allow(clippy::too_many_lines)]
17 pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, method_name: Symbol, args: &[Expr<'_>]) {
18     let arg = match args {
19         [arg] if method_name == sym::clone => arg,
20         _ => return,
21     };
22     if cx
23         .typeck_results()
24         .type_dependent_def_id(expr.hir_id)
25         .and_then(|id| cx.tcx.trait_of_item(id))
26         .zip(cx.tcx.lang_items().clone_trait())
27         .map_or(true, |(x, y)| x != y)
28     {
29         return;
30     }
31     let arg_adjustments = cx.typeck_results().expr_adjustments(arg);
32     let arg_ty = arg_adjustments
33         .last()
34         .map_or_else(|| cx.typeck_results().expr_ty(arg), |a| a.target);
35
36     let ty = cx.typeck_results().expr_ty(expr);
37     if let ty::Ref(_, inner, _) = arg_ty.kind() {
38         if let ty::Ref(_, innermost, _) = inner.kind() {
39             span_lint_and_then(
40                 cx,
41                 CLONE_DOUBLE_REF,
42                 expr.span,
43                 &format!(
44                     "using `clone` on a double-reference; \
45                     this will copy the reference of type `{}` instead of cloning the inner type",
46                     ty
47                 ),
48                 |diag| {
49                     if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
50                         let mut ty = innermost;
51                         let mut n = 0;
52                         while let ty::Ref(_, inner, _) = ty.kind() {
53                             ty = inner;
54                             n += 1;
55                         }
56                         let refs = "&".repeat(n + 1);
57                         let derefs = "*".repeat(n);
58                         let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
59                         diag.span_suggestion(
60                             expr.span,
61                             "try dereferencing it",
62                             format!("{}({}{}).clone()", refs, derefs, snip.deref()),
63                             Applicability::MaybeIncorrect,
64                         );
65                         diag.span_suggestion(
66                             expr.span,
67                             "or try being explicit if you are sure, that you want to clone a reference",
68                             explicit,
69                             Applicability::MaybeIncorrect,
70                         );
71                     }
72                 },
73             );
74             return; // don't report clone_on_copy
75         }
76     }
77
78     if is_copy(cx, ty) {
79         let parent_is_suffix_expr = match get_parent_node(cx.tcx, expr.hir_id) {
80             Some(Node::Expr(parent)) => match parent.kind {
81                 // &*x is a nop, &x.clone() is not
82                 ExprKind::AddrOf(..) => return,
83                 // (*x).func() is useless, x.clone().func() can work in case func borrows self
84                 ExprKind::MethodCall(_, [self_arg, ..], _)
85                     if expr.hir_id == self_arg.hir_id && ty != cx.typeck_results().expr_ty_adjusted(expr) =>
86                 {
87                     return;
88                 },
89                 ExprKind::MethodCall(_, [self_arg, ..], _) if expr.hir_id == self_arg.hir_id => true,
90                 ExprKind::Match(_, _, MatchSource::TryDesugar | MatchSource::AwaitDesugar)
91                 | ExprKind::Field(..)
92                 | ExprKind::Index(..) => true,
93                 _ => false,
94             },
95             // local binding capturing a reference
96             Some(Node::Local(l))
97                 if matches!(
98                     l.pat.kind,
99                     PatKind::Binding(BindingAnnotation::Ref | BindingAnnotation::RefMut, ..)
100                 ) =>
101             {
102                 return;
103             },
104             _ => false,
105         };
106
107         let mut app = Applicability::MachineApplicable;
108         let snip = snippet_with_context(cx, arg.span, expr.span.ctxt(), "_", &mut app).0;
109
110         let deref_count = arg_adjustments
111             .iter()
112             .take_while(|adj| matches!(adj.kind, Adjust::Deref(_)))
113             .count();
114         let (help, sugg) = if deref_count == 0 {
115             ("try removing the `clone` call", snip.into())
116         } else if parent_is_suffix_expr {
117             ("try dereferencing it", format!("({}{})", "*".repeat(deref_count), snip))
118         } else {
119             ("try dereferencing it", format!("{}{}", "*".repeat(deref_count), snip))
120         };
121
122         span_lint_and_sugg(
123             cx,
124             CLONE_ON_COPY,
125             expr.span,
126             &format!("using `clone` on type `{}` which implements the `Copy` trait", ty),
127             help,
128             sugg,
129             app,
130         );
131     }
132 }