|
| 1 | +// check-pass |
| 2 | +// |
| 3 | +// rust-lang/rust#73592: borrow_mut through Deref should work. |
| 4 | +// |
| 5 | +// Before #72280, when we see something like `&mut *rcvr.method()`, we |
| 6 | +// incorrectly requires `rcvr` to be type-checked as a mut place. While this |
| 7 | +// requirement is usually correct for smart pointers, it is overly restrictive |
| 8 | +// for types like `Mutex` or `RefCell` which can produce a guard that |
| 9 | +// implements `DerefMut` from `&self`. |
| 10 | +// |
| 11 | +// Making it more confusing, because we use Deref as the fallback when DerefMut |
| 12 | +// is implemented, we won't see an issue when the smart pointer does not |
| 13 | +// implement `DerefMut`. It only causes an issue when `rcvr` is obtained via a |
| 14 | +// type that implements both `Deref` or `DerefMut`. |
| 15 | +// |
| 16 | +// This bug is only discovered in #73592 after it is already fixed as a side-effect |
| 17 | +// of a refactoring made in #72280. |
| 18 | + |
| 19 | +#![warn(unused_mut)] |
| 20 | + |
| 21 | +use std::pin::Pin; |
| 22 | +use std::cell::RefCell; |
| 23 | + |
| 24 | +struct S(RefCell<()>); |
| 25 | + |
| 26 | +fn test_pin(s: Pin<&S>) { |
| 27 | + // This works before #72280. |
| 28 | + let _ = &mut *s.0.borrow_mut(); |
| 29 | +} |
| 30 | + |
| 31 | +fn test_pin_mut(s: Pin<&mut S>) { |
| 32 | + // This should compile but didn't before #72280. |
| 33 | + let _ = &mut *s.0.borrow_mut(); |
| 34 | +} |
| 35 | + |
| 36 | +fn test_vec(s: &Vec<RefCell<()>>) { |
| 37 | + // This should compile but didn't before #72280. |
| 38 | + let _ = &mut *s[0].borrow_mut(); |
| 39 | +} |
| 40 | + |
| 41 | +fn test_mut_pin(mut s: Pin<&S>) { |
| 42 | + //~^ WARN variable does not need to be mutable |
| 43 | + let _ = &mut *s.0.borrow_mut(); |
| 44 | +} |
| 45 | + |
| 46 | +fn test_mut_pin_mut(mut s: Pin<&mut S>) { |
| 47 | + //~^ WARN variable does not need to be mutable |
| 48 | + let _ = &mut *s.0.borrow_mut(); |
| 49 | +} |
| 50 | + |
| 51 | +fn main() { |
| 52 | + let mut s = S(RefCell::new(())); |
| 53 | + test_pin(Pin::new(&s)); |
| 54 | + test_pin_mut(Pin::new(&mut s)); |
| 55 | + test_mut_pin(Pin::new(&s)); |
| 56 | + test_mut_pin_mut(Pin::new(&mut s)); |
| 57 | + test_vec(&vec![s.0]); |
| 58 | +} |
0 commit comments