Skip to content

op_ref false positive #12463

@karolzwolak

Description

@karolzwolak

Summary

playground

#[derive(Clone, Copy)]
struct Matrix {}

trait Trait {}

impl<T> std::ops::Mul<T> for &Matrix
where
    T: Trait,
{
    type Output = T;
    fn mul(self, _: T) -> Self::Output {
        todo!()
    }
}

impl<T> std::ops::Mul<T> for Matrix
where
    T: Trait,
{
    type Output = T;
    fn mul(self, rhs: T) -> Self::Output {
        &self * rhs
    }
}

Gives this warning:

warning: needlessly taken reference of left operand
  --> src/lib.rs:22:9
   |
22 |         &self * rhs
   |         -----^^^^^^
   |         |
   |         help: use the left value directly: `self`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#op_ref
   = note: `#[warn(clippy::op_ref)]` on by default

Clippy incorrectly complains about adding reference here. It suggests removing '&', but that obviously leads to infinitely recursive multiplication implementation. The reference is needed because the actual multiplication is implemented for borrowed type.

Removing Copy from Matrix solves it: playground
Implementing Mul trait on a type directly fixes issue: playground

Lint Name

op_ref

Reproducer

I tried this code:

#[derive(Clone, Copy)]
struct Matrix {}

trait Trait {}

impl<T> std::ops::Mul<T> for &Matrix
where
    T: Trait,
{
    type Output = T;
    fn mul(self, _: T) -> Self::Output {
        todo!()
    }
}

impl<T> std::ops::Mul<T> for Matrix
where
    T: Trait,
{
    type Output = T;
    fn mul(self, rhs: T) -> Self::Output {
        &self * rhs
    }
}

I saw this happen:

warning: needlessly taken reference of left operand
  --> src/lib.rs:22:9
   |
22 |         &self * rhs
   |         -----^^^^^^
   |         |
   |         help: use the left value directly: `self`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#op_ref
   = note: `#[warn(clippy::op_ref)]` on by default

I expected to see this happen:

Version

rustc 1.76.0 (07dca489a 2024-02-04)
binary: rustc
commit-hash: 07dca489ac2d933c78d3c5158e3f43beefeb02ce
commit-date: 2024-02-04
host: x86_64-unknown-linux-gnu
release: 1.76.0
LLVM version: 17.0.6

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions