Skip to content

Commit afb34eb

Browse files
committed
Auto merge of #9096 - Jarcho:needless_borrow_subs, r=Manishearth
Fix `needless_borrow` 9095 fixes #9095 changelog: Don't lint `needless_borrow` on method receivers when it would change which trait impl is called
2 parents f93d418 + 988b813 commit afb34eb

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

clippy_lints/src/dereference.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -772,9 +772,14 @@ fn walk_parents<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> (Position, &
772772
} else if let Some(trait_id) = cx.tcx.trait_of_item(id)
773773
&& let arg_ty = cx.tcx.erase_regions(cx.typeck_results().expr_ty_adjusted(e))
774774
&& let ty::Ref(_, sub_ty, _) = *arg_ty.kind()
775-
&& let subs = cx.typeck_results().node_substs_opt(child_id).unwrap_or_else(
776-
|| cx.tcx.mk_substs([].iter())
777-
) && let impl_ty = if cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref() {
775+
&& let subs = match cx
776+
.typeck_results()
777+
.node_substs_opt(parent.hir_id)
778+
.and_then(|subs| subs.get(1..))
779+
{
780+
Some(subs) => cx.tcx.mk_substs(subs.iter().copied()),
781+
None => cx.tcx.mk_substs([].iter()),
782+
} && let impl_ty = if cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref() {
778783
// Trait methods taking `&self`
779784
sub_ty
780785
} else {

tests/ui/needless_borrow.fixed

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,18 @@ fn main() {
115115
fn foo_ref(&self) {}
116116
}
117117
(&&()).foo_ref(); // Don't lint. `&()` will call `<() as FooRef>::foo_ref`
118+
119+
struct S;
120+
impl From<S> for u32 {
121+
fn from(s: S) -> Self {
122+
(&s).into()
123+
}
124+
}
125+
impl From<&S> for u32 {
126+
fn from(s: &S) -> Self {
127+
0
128+
}
129+
}
118130
}
119131

120132
#[allow(clippy::needless_borrowed_reference)]

tests/ui/needless_borrow.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,18 @@ fn main() {
115115
fn foo_ref(&self) {}
116116
}
117117
(&&()).foo_ref(); // Don't lint. `&()` will call `<() as FooRef>::foo_ref`
118+
119+
struct S;
120+
impl From<S> for u32 {
121+
fn from(s: S) -> Self {
122+
(&s).into()
123+
}
124+
}
125+
impl From<&S> for u32 {
126+
fn from(s: &S) -> Self {
127+
0
128+
}
129+
}
118130
}
119131

120132
#[allow(clippy::needless_borrowed_reference)]

0 commit comments

Comments
 (0)