Skip to content

Commit ad7a03c

Browse files
committed
Auto merge of #5951 - ThibsG:FixMacroCloneOnRefPtr2076, r=ebroto
Fix incorrect suggestion when `clone_on_ref_ptr` is triggered in macros In the lint `clone_on_ref_ptr`, if the `span` is in a macro, don't expand it for suggestion. Fixes: #2076 changelog: none r? @ebroto
2 parents e191151 + 370fc45 commit ad7a03c

File tree

3 files changed

+28
-7
lines changed

3 files changed

+28
-7
lines changed

clippy_lints/src/methods/mod.rs

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

2153+
let snippet = snippet_with_macro_callsite(cx, arg.span, "_");
2154+
21532155
span_lint_and_sugg(
21542156
cx,
21552157
CLONE_ON_REF_PTR,
21562158
expr.span,
21572159
"using `.clone()` on a ref-counted pointer",
21582160
"try this",
2159-
format!(
2160-
"{}::<{}>::clone(&{})",
2161-
caller_type,
2162-
subst.type_at(0),
2163-
snippet(cx, arg.span, "_")
2164-
),
2161+
format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet),
21652162
Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
21662163
);
21672164
}

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)