Skip to content

Commit 1615813

Browse files
committed
Moves clone_on_ref_ptr to be a restriction lint
Also updates the suggestion to include the full type (e.g. `Arc<Foo>::clone(&rc)`) and adds a case using trait objects to the UI tests.
1 parent 41a710e commit 1615813

File tree

2 files changed

+27
-20
lines changed

2 files changed

+27
-20
lines changed

clippy_lints/src/methods.rs

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -361,9 +361,8 @@ declare_lint! {
361361
/// ```rust
362362
/// x.clone()
363363
/// ```
364-
declare_lint! {
364+
declare_restriction_lint! {
365365
pub CLONE_ON_REF_PTR,
366-
Warn,
367366
"using 'clone' on a ref-counted pointer"
368367
}
369368

@@ -1013,24 +1012,26 @@ fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_t
10131012
fn lint_clone_on_ref_ptr(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
10141013
let (obj_ty, _) = walk_ptrs_ty_depth(cx.tables.expr_ty(arg));
10151014

1016-
let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1017-
"Rc"
1018-
} else if match_type(cx, obj_ty, &paths::ARC) {
1019-
"Arc"
1020-
} else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1021-
"Weak"
1022-
} else {
1023-
return;
1024-
};
1015+
if let ty::TyAdt(_, subst) = obj_ty.sty {
1016+
let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1017+
"Rc"
1018+
} else if match_type(cx, obj_ty, &paths::ARC) {
1019+
"Arc"
1020+
} else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1021+
"Weak"
1022+
} else {
1023+
return;
1024+
};
10251025

1026-
span_lint_and_sugg(
1027-
cx,
1028-
CLONE_ON_REF_PTR,
1029-
expr.span,
1030-
"using '.clone()' on a ref-counted pointer",
1031-
"try this",
1032-
format!("{}::clone(&{})", caller_type, snippet(cx, arg.span, "_")),
1033-
);
1026+
span_lint_and_sugg(
1027+
cx,
1028+
CLONE_ON_REF_PTR,
1029+
expr.span,
1030+
"using '.clone()' on a ref-counted pointer",
1031+
"try this",
1032+
format!("{}<{}>::clone(&{})", caller_type, subst.type_at(0), snippet(cx, arg.span, "_")),
1033+
);
1034+
}
10341035
}
10351036

10361037

tests/ui/unnecessary_clone.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
1+
#![warn(clone_on_ref_ptr)]
12
#![allow(unused)]
23

34
use std::collections::HashSet;
45
use std::collections::VecDeque;
56
use std::rc::{self, Rc};
67
use std::sync::{self, Arc};
78

9+
trait SomeTrait {}
10+
struct SomeImpl;
11+
impl SomeTrait for SomeImpl {}
12+
813
fn main() {}
914

1015
fn clone_on_copy() {
@@ -34,7 +39,8 @@ fn clone_on_ref_ptr() {
3439
arc_weak.clone();
3540
sync::Weak::clone(&arc_weak);
3641

37-
42+
let x = Arc::new(SomeImpl);
43+
let _: Arc<SomeTrait> = x.clone();
3844
}
3945

4046
fn clone_on_copy_generic<T: Copy>(t: T) {

0 commit comments

Comments
 (0)