Skip to content

invalid_reference_casting fires for correct usage of UnsafeCell #159915

Description

@RalfJung

Code

use std::cell::UnsafeCell;

unsafe fn get_mut_unchecked<T>(ptr: &UnsafeCell<T>) -> &mut T {
    let t = ptr as *const UnsafeCell<T> as *mut T;
    unsafe { &mut *t }
}

Current output

--> src/lib.rs:5:14
  |
4 |     let t = ptr as *const UnsafeCell<T> as *mut T;
  |             ------------------------------------- casting happened here
5 |     unsafe { &mut *t }
  |              ^^^^^^^
  |
  = note: for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>
  = note: even for types with interior mutability, the only legal way to obtain a mutable pointer from a shared reference is through `UnsafeCell::get`
  = note: `#[deny(invalid_reference_casting)]` on by default

Desired output

(none)

Rationale and extra context

#159730 relaxed the rules for UnsafeCell. Under the new rules, the given code is equivalent to

unsafe fn get_mut_unchecked<T>(ptr: &UnsafeCell<T>) -> &mut T {
    let t = ptr.get();
    unsafe { &mut *t }
}

This does not raise a diagnostic either, so there's no longer a reason to raise a diagnostic for the original code.

Cc @Urgau

Other cases

Rust Version

nightly

Anything else?

No response

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

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions