rust-lang / rust-lang/rust-clippy

`ref_as_ptr` suggests using `ptr::from_ref(r)` where it should instead suggest `ptr::from_mut(r)` for `r: &mut T`.

Open
#12,882 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-suggestion-causes-bug
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

ptr::from_ref creates a pointer that isn't safe to cast to *mut T but ptr::from_mut(x).cast_const() creates a pointer that is safe to cast to *mut T. Unless Clippy is sure that the resultant pointer is never going to be cast to *mut T, it should recommend from_mut when it sees an expression r as *const T where r: &mut T. See https://github.com/rust-lang/rust/issues/56604#issuecomment-2143193486, https://github.com/rust-lang/rust-clippy/issues/12791, https://github.com/rust-lang/rust/pull/125897.

Reproducer

I tried this code:

#![deny(clippy::ref_as_ptr)]

fn bar<T>(_x: *const T) {}

fn foo<T>(x: &mut T) {
   bar(x as *const T);
}

I expected to see this happen:

Clippy should recommended ptr::from_mut(x) or ptr::from_mut(x).cast_const().

Instead, this happened:

Clippy recommended ptr::from_ref(x).

Version
Nightly channel
Build using the Nightly version: 1.80.0-nightly
(2024-06-02 032af18af578f4283a29)
Additional Labels

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the ref_as_ptr lint entry point and reproduce the issue with the Rust snippet in this report. Check the lint's existing tests and diagnostic output; done means the &mut T case recommends ptr::from_mut(x) or ptr::from_mut(x).cast_const() without changing other cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
50/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.