Function rustc_mir_build::build::matches::util::collect_fake_borrows
source · pub(super) fn collect_fake_borrows<'tcx>(
cx: &mut Builder<'_, 'tcx>,
candidates: &[&mut Candidate<'_, 'tcx>],
temp_span: Span,
scrutinee_base: PlaceBase,
) -> Vec<(Place<'tcx>, Local, FakeBorrowKind)>
Expand description
Determine the set of places that have to be stable across match guards.
Returns a list of places that need a fake borrow along with a local to store it.
Match exhaustiveness checking is not able to handle the case where the place being matched on is mutated in the guards. We add “fake borrows” to the guards that prevent any mutation of the place being matched. There are a some subtleties:
- Borrowing
*x
doesn’t prevent assigning tox
. Ifx
is a shared reference, the borrow isn’t even tracked. As such we have to add fake borrows of any prefixes of a place. - We don’t want
match x { (Some(_), _) => (), .. }
to conflict with mutable borrows ofx.1
, so we only add fake borrows for places which are bound or tested by the match. - We don’t want
match x { Some(_) => (), .. }
to conflict with mutable borrows of(x as Some).0
, so the borrows are a special shallow borrow that only affects the place and not its projections.let mut x = (Some(0), true); match x { (Some(_), false) => {} _ if { if let Some(ref mut y) = x.0 { *y += 1 }; true } => {} _ => {} }
- The fake borrows may be of places in inactive variants, e.g. here we need to fake borrow
x
and(x as Some).0
, but when we reach the guardx
may not beSome
.So it would be UB to generate code for the fake borrows. They therefore have to be removed by a MIR pass run after borrow checking.let mut x = (Some(Some(0)), true); match x { (Some(Some(_)), false) => {} _ if { if let Some(Some(ref mut y)) = x.0 { *y += 1 }; true } => {} _ => {} }