1
Fork 0

Rollup merge of #116421 - Urgau:inter-mut-invalid_ref_casting, r=oli-obk

Clarify `invalid_reference_casting` lint around interior mutable types

This is PR intends to clarify the `invalid_reference_casting` lint around interior mutable types by adding a note for them saying that they should go through `UnsafeCell::get`.

So for this code:
```rust
let cell = &std::cell::UnsafeCell::new(0);
let _num = &mut *(cell as *const _ as *mut i32);
```

the following note will be added to the lint output:

```diff
 error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused,  consider instead using an `UnsafeCell`
   --> $DIR/reference_casting.rs:68:16
    |
 LL |     let _num = &mut *(cell as *const _ as *mut i32);
    |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = 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`
```

Suggestion are welcome around the note contents.

Fixes https://github.com/rust-lang/rust/issues/116410
cc `@RalfJung`
This commit is contained in:
Matthias Krüger 2023-10-06 06:23:48 +02:00 committed by GitHub
commit 7d7004d3e6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 68 additions and 32 deletions

View file

@ -323,6 +323,8 @@ lint_invalid_reference_casting_borrow_as_mut = casting `&T` to `&mut T` is undef
lint_invalid_reference_casting_note_book = for more information, visit <https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>
lint_invalid_reference_casting_note_ty_has_interior_mutability = even for types with interior mutability, the only legal way to obtain a mutable pointer from a shared reference is through `UnsafeCell::get`
lint_lintpass_by_hand = implementing `LintPass` by hand
.help = try using `declare_lint_pass!` or `impl_lint_pass!` instead