Skip to content

needless_pass_by_ref_mut should not trigger for cfg-gated mod/fn #11185

Closed
@oxalica

Description

@oxalica

Summary

In target specific modules, some functions may only mutate arguments for a specific platform. Keeping the same signature to take &mut for all of them makes higher level abstractions simpler.

If we expose this platform differences, it will propagate upwards and force every users to #[cfg] between & and &mut. This violates the abstraction goal of the library.

A solution to this issue is to treat every #[cfg] fn and #[cfg] mod { pub fn } as part of public interface, and suppress warnings that would cause signature changes on them.

Lint Name

needless_pass_by_ref_mut

Reproducer

pub struct Resource(i32);

impl Resource {
    // Real public interface.
    pub fn work(&mut self) {
        imp::work(&mut self.0);
    }
}

// Semi-public interface. Abstractions over platforms.
#[cfg(unix)]
mod imp {
    // Immutable for some platforms.
    pub fn work(data: &mut i32) { // <- needless_pass_by_ref_mut
        println!("{data}");
    }
}

#[cfg(windows)]
mod imp {
    // Mutable for some other platforms.
    pub fn work(data: &mut i32) {
        *data += 1;
        println!("{data}");
    }
}

I saw this happen:

warning: this argument is a mutable reference, but not used mutably
  --> src/lib.rs:13:23
   |
14 |     pub fn work(data: &mut i32) { // <- needless_pass_by_ref_mut
   |                       ^^^^^^^^ help: consider changing to: `&i32`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut
   = note: `#[warn(clippy::needless_pass_by_ref_mut)]` on by default

I expected to see this happen:

Version

Rust Playground, nightly.
Clippy 0.1.73 (2023-07-18 903e279)

Additional Labels

@rustbot label +I-false-positive +I-suggestion-causes-error

I think this fits I-suggestion-causes-error because the change breaks on other cfg-gated platforms.

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 haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions