|
| 1 | +use crate::lints::{CloneDoubleRefExplicit, CloneDoubleRefTryDeref}; |
| 2 | +use crate::{lints, LateLintPass, LintContext}; |
| 3 | + |
| 4 | +use rustc_hir as hir; |
| 5 | +use rustc_hir::ExprKind; |
| 6 | +use rustc_middle::ty; |
| 7 | +use rustc_middle::ty::adjustment::Adjust; |
| 8 | +use rustc_span::sym; |
| 9 | + |
| 10 | +declare_lint! { |
| 11 | + /// The `clone_double_ref` lint checks for usage of `.clone()` on an `&&T`, |
| 12 | + /// which copies the inner `&T`, instead of cloning the underlying `T` and |
| 13 | + /// can be confusing. |
| 14 | + pub CLONE_DOUBLE_REF, |
| 15 | + Warn, |
| 16 | + "using `clone` on `&&T`" |
| 17 | +} |
| 18 | + |
| 19 | +declare_lint_pass!(CloneDoubleRef => [CLONE_DOUBLE_REF]); |
| 20 | + |
| 21 | +impl<'tcx> LateLintPass<'tcx> for CloneDoubleRef { |
| 22 | + fn check_expr(&mut self, cx: &crate::LateContext<'tcx>, e: &'tcx hir::Expr<'tcx>) { |
| 23 | + let ExprKind::MethodCall(path, receiver, args, _) = &e.kind else { return; }; |
| 24 | + |
| 25 | + if path.ident.name != sym::clone || !args.is_empty() { |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + let typeck_results = cx.typeck_results(); |
| 30 | + |
| 31 | + if typeck_results |
| 32 | + .type_dependent_def_id(e.hir_id) |
| 33 | + .and_then(|id| cx.tcx.trait_of_item(id)) |
| 34 | + .zip(cx.tcx.lang_items().clone_trait()) |
| 35 | + .map_or(true, |(x, y)| x != y) |
| 36 | + { |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + let arg_adjustments = cx.typeck_results().expr_adjustments(receiver); |
| 41 | + |
| 42 | + // https://github.com/rust-lang/rust-clippy/issues/9272 |
| 43 | + if arg_adjustments.iter().any(|adj| matches!(adj.kind, Adjust::Deref(Some(_)))) { |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + if !receiver.span.eq_ctxt(e.span) { |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + let arg_ty = arg_adjustments |
| 52 | + .last() |
| 53 | + .map_or_else(|| cx.typeck_results().expr_ty(receiver), |a| a.target); |
| 54 | + |
| 55 | + let ty = cx.typeck_results().expr_ty(e); |
| 56 | + |
| 57 | + if let ty::Ref(_, inner, _) = arg_ty.kind() |
| 58 | + && let ty::Ref(_, innermost, _) = inner.kind() { |
| 59 | + let mut inner_ty = innermost; |
| 60 | + let mut n = 1; |
| 61 | + while let ty::Ref(_, inner, _) = inner_ty.kind() { |
| 62 | + inner_ty = inner; |
| 63 | + n += 1; |
| 64 | + } |
| 65 | + let refs = "&".repeat(n); |
| 66 | + let derefs = "*".repeat(n); |
| 67 | + let start = e.span.with_hi(receiver.span.lo()); |
| 68 | + let end = e.span.with_lo(receiver.span.hi()); |
| 69 | + cx.emit_spanned_lint(CLONE_DOUBLE_REF, e.span, lints::CloneDoubleRef { |
| 70 | + ty, |
| 71 | + try_deref: CloneDoubleRefTryDeref { |
| 72 | + start, |
| 73 | + end, |
| 74 | + refs: refs.clone(), |
| 75 | + derefs, |
| 76 | + }, |
| 77 | + explicit: CloneDoubleRefExplicit { |
| 78 | + start, |
| 79 | + end, |
| 80 | + refs, |
| 81 | + ty: *inner_ty, |
| 82 | + } |
| 83 | + }); |
| 84 | + } |
| 85 | + } |
| 86 | +} |
0 commit comments