Skip to content

clippy::needless_borrow suggestion/autofix breaks code #11142

@stepancheg

Description

@stepancheg

Summary

"the borrowed expression implements the required traits" does not mean that replacing one with another is correct, because non-borrowed implementation may delegate to borrowed.

Reproducer

Repro:

trait Allocatable {
    fn allocate(self);
}

fn do_allocate(a: impl Allocatable) {
    a.allocate()
}


impl Allocatable for &'_ u32 {
    fn allocate(self) {
    }
}

impl Allocatable for u32 {
    fn allocate(self) {
        do_allocate(&self)
    }
}

fn main() {
    0u32.allocate();
}
cargo clippy --fix --allow-no-vcs
warning: the borrowed expression implements the required traits
  --> src/main.rs:14:21
   |
14 |         do_allocate(&self)
   |                     ^^^^^ help: change this to: `self`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow
   = note: `#[warn(clippy::needless_borrow)]` on by default

Replacing &self with self makes code incorrect: instead of terminating it is now stack overflow or infinite loop depending on optimization level.

Version

rustc 1.72.0-nightly (871b59520 2023-05-31)
binary: rustc
commit-hash: 871b5952023139738f72eba235063575062bc2e9
commit-date: 2023-05-31
host: aarch64-apple-darwin
release: 1.72.0-nightly
LLVM version: 16.0.4

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thing

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions