Skip to content

needless_pass_by_ref_mut suggests (potentially unsound) code that triggers mut_from_ref #11180

Description

@taiki-e

Summary

needless_pass_by_ref_mut (warn by default) suggests code that triggers mut_from_ref (error by default).

The suggested code itself is also suspicious from a soundness point of view.

Mentioning @GuillaumeGomez, who implement this lint in #10900.

Reproducer

I tried this code:

#![allow(dead_code)]

use std::ptr::NonNull;

struct Data<T: ?Sized> {
    value: T,
}

unsafe fn get_mut_unchecked<T>(ptr: &mut NonNull<Data<T>>) -> &mut T {
    unsafe { &mut (*ptr.as_ptr()).value }
}

This happened:

warning: this argument is a mutable reference, but not used mutably
 --> src/lib.rs:7:37
  |
7 | unsafe fn get_mut_unchecked<T>(ptr: &mut NonNull<Data<T>>) -> &mut T {
  |                                     ^^^^^^^^^^^^^^^^^^^^^ help: consider changing to: `&NonNull<Data<T>>`
  |
  = 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

And when I applied the suggestion:

#![allow(dead_code)]

use std::ptr::NonNull;

struct Data<T: ?Sized> {
    value: T,
}

unsafe fn get_mut_unchecked<T>(ptr: &NonNull<Data<T>>) -> &mut T {
    unsafe { &mut (*ptr.as_ptr()).value }
}

Then, this happened:

error: mutable borrow from immutable input(s)
 --> src/lib.rs:9:59
  |
9 | unsafe fn get_mut_unchecked<T>(ptr: &NonNull<Data<T>>) -> &mut T {
  |                                                           ^^^^^^
  |
note: immutable borrow here
 --> src/lib.rs:9:37
  |
9 | unsafe fn get_mut_unchecked<T>(ptr: &NonNull<Data<T>>) -> &mut T {
  |                                     ^^^^^^^^^^^^^^^^^
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#mut_from_ref
  = note: `#[deny(clippy::mut_from_ref)]` on by default

Version

rustc 1.73.0-nightly (da6b55cc5 2023-07-17)
binary: rustc
commit-hash: da6b55cc5eaf76ed6acb7dc2f7d611e32af7c9a7
commit-date: 2023-07-17
host: aarch64-apple-darwin
release: 1.73.0-nightly
LLVM version: 16.0.5

Additional Labels

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

No activity

Activity on this issue will appear here.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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