Skip to content

Implementation of trait method using method with same name in foreign module triggers only_used_in_recursion false positive #8560

Closed
@bhgomes

Description

@bhgomes

Summary

Clippy seems to get confused about recursion when checking against methods with the same name but which are resolved differently. If we define a trait and a struct with methods named identically and implement the trait on that struct clippy will sometimes believe that the implementation will perform recursion. In the case when the struct is defined in a different module than the trait, clippy will report a false-positive, and if they are defined in the same module, it will not report a warning (the correct behavior).

Lint Name

only_used_in_recursion

Reproducer

I tried this code:

//! Nightly Clippy False-Positive

/// Base Trait
trait Trait {
    /// Target Method
    fn method(&mut self, arg: usize);
}

/// Foreign Module
mod module {
    /// Foreign Structure
    pub struct Struct(pub usize);
    
    impl Struct {
        /// Implementation of Target Method
        pub fn method(&mut self, arg: usize) {
            self.0 += arg;
        }
    }
}

impl Trait for module::Struct {
    /// Implementation of Trait Method using Target Method.
    fn method(&mut self, arg: usize) {
        self.method(arg);
    }
}

fn main() {
    let mut value = module::Struct(4);
    Trait::method(&mut value, 3);
    assert_eq!(value.0, 7);
}

I saw this happen:

warning: parameter is only used in recursion
  --> src/main.rs:24:26
   |
24 |     fn method(&mut self, arg: usize) {
   |                          ^^^ help: if this is intentional, prefix with an underscore: `_arg`
   |
   = note: `#[warn(clippy::only_used_in_recursion)]` on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#only_used_in_recursion

I expected no warning since method resolution will find the struct method first. However, this false-positive only occurs when Struct comes from a module different from the module where Trait is defined.

With false-positive: https://play.rust-lang.org/?version=nightly&mode=release&edition=2021&gist=5091defb5bbd631f501cf0ee4b9ca634
Without false-positive: https://play.rust-lang.org/?version=nightly&mode=release&edition=2021&gist=681c30742b8253d9cc94a0c11faca36a

Version

rustc 1.61.0-nightly (461e80780 2022-03-16)
binary: rustc
commit-hash: 461e8078010433ff7de2db2aaae8a3cfb0847215
commit-date: 2022-03-16
host: x86_64-apple-darwin
release: 1.61.0-nightly
LLVM version: 14.0.0

Additional Labels

N/A

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