Skip to content

Commit

Permalink
Auto merge of rust-lang#9096 - Jarcho:needless_borrow_subs, r=Manishe…
Browse files Browse the repository at this point in the history
…arth

Fix `needless_borrow` 9095

fixes rust-lang#9095
changelog: Don't lint `needless_borrow` on method receivers when it would change which trait impl is called
  • Loading branch information
bors committed Jul 6, 2022
2 parents f93d418 + 988b813 commit afb34eb
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
11 changes: 8 additions & 3 deletions clippy_lints/src/dereference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -772,9 +772,14 @@ fn walk_parents<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> (Position, &
} else if let Some(trait_id) = cx.tcx.trait_of_item(id)
&& let arg_ty = cx.tcx.erase_regions(cx.typeck_results().expr_ty_adjusted(e))
&& let ty::Ref(_, sub_ty, _) = *arg_ty.kind()
&& let subs = cx.typeck_results().node_substs_opt(child_id).unwrap_or_else(
|| cx.tcx.mk_substs([].iter())
) && let impl_ty = if cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref() {
&& let subs = match cx
.typeck_results()
.node_substs_opt(parent.hir_id)
.and_then(|subs| subs.get(1..))
{
Some(subs) => cx.tcx.mk_substs(subs.iter().copied()),
None => cx.tcx.mk_substs([].iter()),
} && let impl_ty = if cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref() {
// Trait methods taking `&self`
sub_ty
} else {
Expand Down
12 changes: 12 additions & 0 deletions tests/ui/needless_borrow.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,18 @@ fn main() {
fn foo_ref(&self) {}
}
(&&()).foo_ref(); // Don't lint. `&()` will call `<() as FooRef>::foo_ref`

struct S;
impl From<S> for u32 {
fn from(s: S) -> Self {
(&s).into()
}
}
impl From<&S> for u32 {
fn from(s: &S) -> Self {
0
}
}
}

#[allow(clippy::needless_borrowed_reference)]
Expand Down
12 changes: 12 additions & 0 deletions tests/ui/needless_borrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,18 @@ fn main() {
fn foo_ref(&self) {}
}
(&&()).foo_ref(); // Don't lint. `&()` will call `<() as FooRef>::foo_ref`

struct S;
impl From<S> for u32 {
fn from(s: S) -> Self {
(&s).into()
}
}
impl From<&S> for u32 {
fn from(s: &S) -> Self {
0
}
}
}

#[allow(clippy::needless_borrowed_reference)]
Expand Down

0 comments on commit afb34eb

Please sign in to comment.