2021-03-25 13:29:11 -05:00
|
|
|
use clippy_utils::diagnostics::span_lint_and_sugg;
|
|
|
|
use clippy_utils::paths;
|
|
|
|
use clippy_utils::source::snippet_with_macro_callsite;
|
|
|
|
use clippy_utils::ty::{is_type_diagnostic_item, match_type};
|
2021-03-12 08:30:50 -06:00
|
|
|
use rustc_errors::Applicability;
|
|
|
|
use rustc_hir as hir;
|
|
|
|
use rustc_lint::LateContext;
|
|
|
|
use rustc_middle::ty;
|
2021-03-25 13:29:11 -05:00
|
|
|
use rustc_span::symbol::{sym, Symbol};
|
2021-03-12 08:30:50 -06:00
|
|
|
|
|
|
|
use super::CLONE_ON_REF_PTR;
|
|
|
|
|
2022-09-01 04:43:35 -05:00
|
|
|
pub(super) fn check(
|
|
|
|
cx: &LateContext<'_>,
|
|
|
|
expr: &hir::Expr<'_>,
|
|
|
|
method_name: Symbol,
|
|
|
|
receiver: &hir::Expr<'_>,
|
|
|
|
args: &[hir::Expr<'_>],
|
|
|
|
) {
|
|
|
|
if !(args.is_empty() && method_name == sym::clone) {
|
2021-03-25 13:29:11 -05:00
|
|
|
return;
|
|
|
|
}
|
2022-09-02 08:48:14 -05:00
|
|
|
let obj_ty = cx.typeck_results().expr_ty(receiver).peel_refs();
|
2021-03-12 08:30:50 -06:00
|
|
|
|
|
|
|
if let ty::Adt(_, subst) = obj_ty.kind() {
|
|
|
|
let caller_type = if is_type_diagnostic_item(cx, obj_ty, sym::Rc) {
|
|
|
|
"Rc"
|
|
|
|
} else if is_type_diagnostic_item(cx, obj_ty, sym::Arc) {
|
|
|
|
"Arc"
|
|
|
|
} else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
|
|
|
|
"Weak"
|
|
|
|
} else {
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
|
2022-09-02 08:48:14 -05:00
|
|
|
let snippet = snippet_with_macro_callsite(cx, receiver.span, "..");
|
2021-03-12 08:30:50 -06:00
|
|
|
|
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
CLONE_ON_REF_PTR,
|
|
|
|
expr.span,
|
|
|
|
"using `.clone()` on a ref-counted pointer",
|
|
|
|
"try this",
|
2022-09-23 12:42:59 -05:00
|
|
|
format!("{caller_type}::<{}>::clone(&{snippet})", subst.type_at(0)),
|
2021-03-12 08:30:50 -06:00
|
|
|
Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|