Skip to content

Commit 3d820f7

Browse files
committed
Fix incorrect suggestion when clone_on_ref_ptr is triggered in macros
1 parent 27ae4d3 commit 3d820f7

File tree

3 files changed

+32
-7
lines changed

3 files changed

+32
-7
lines changed

clippy_lints/src/methods/mod.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2150,18 +2150,19 @@ fn lint_clone_on_ref_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::
21502150
return;
21512151
};
21522152

2153+
let snippet = if in_macro(arg.span) {
2154+
snippet_with_macro_callsite(cx, arg.span, "_")
2155+
} else {
2156+
snippet(cx, arg.span, "_")
2157+
};
2158+
21532159
span_lint_and_sugg(
21542160
cx,
21552161
CLONE_ON_REF_PTR,
21562162
expr.span,
21572163
"using `.clone()` on a ref-counted pointer",
21582164
"try this",
2159-
format!(
2160-
"{}::<{}>::clone(&{})",
2161-
caller_type,
2162-
subst.type_at(0),
2163-
snippet(cx, arg.span, "_")
2164-
),
2165+
format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet),
21652166
Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
21662167
);
21672168
}

tests/ui/unnecessary_clone.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,3 +90,21 @@ mod many_derefs {
9090
let _ = &encoded.clone();
9191
}
9292
}
93+
94+
mod issue2076 {
95+
use std::rc::Rc;
96+
97+
macro_rules! try_opt {
98+
($expr: expr) => {
99+
match $expr {
100+
Some(value) => value,
101+
None => return None,
102+
}
103+
};
104+
}
105+
106+
fn func() -> Option<Rc<u8>> {
107+
let rc = Rc::new(42);
108+
Some(try_opt!(Some(rc)).clone())
109+
}
110+
}

tests/ui/unnecessary_clone.stderr

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,5 +96,11 @@ help: or try being explicit if you are sure, that you want to clone a reference
9696
LL | let _ = &<&[u8]>::clone(encoded);
9797
| ^^^^^^^^^^^^^^^^^^^^^^^
9898

99-
error: aborting due to 11 previous errors
99+
error: using `.clone()` on a ref-counted pointer
100+
--> $DIR/unnecessary_clone.rs:108:14
101+
|
102+
LL | Some(try_opt!(Some(rc)).clone())
103+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `Rc::<u8>::clone(&try_opt!(Some(rc)))`
104+
105+
error: aborting due to 12 previous errors
100106

0 commit comments

Comments
 (0)