rustc_mir_build::build::matches::util

Function collect_fake_borrows

Source
pub(super) fn collect_fake_borrows<'tcx>(
    cx: &mut Builder<'_, 'tcx>,
    candidates: &[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:

  1. Borrowing *x doesn’t prevent assigning to x. If x is a shared reference, the borrow isn’t even tracked. As such we have to add fake borrows of any prefixes of a place.
  2. We don’t want match x { (Some(_), _) => (), .. } to conflict with mutable borrows of x.1, so we only add fake borrows for places which are bound or tested by the match.
  3. 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 } => {}
        _ => {}
    }
  4. 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 guard x may not be Some.
    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 } => {}
        _ => {}
    }
    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.