Enum flowistry_pdg::rustc::mir::MutBorrowKind
source · pub enum MutBorrowKind {
Default,
TwoPhaseBorrow,
ClosureCapture,
}
Variants§
Default
TwoPhaseBorrow
This borrow arose from method-call auto-ref. (i.e., adjustment::Adjust::Borrow
)
ClosureCapture
Data must be immutable but not aliasable. This kind of borrow cannot currently be expressed by the user and is used only in implicit closure bindings. It is needed when the closure is borrowing or mutating a mutable referent, e.g.:
let mut z = 3;
let x: &mut isize = &mut z;
let y = || *x += 5;
If we were to try to translate this closure into a more explicit form, we’d encounter an error with the code as written:
struct Env<'a> { x: &'a &'a mut isize }
let mut z = 3;
let x: &mut isize = &mut z;
let y = (&mut Env { x: &x }, fn_ptr); // Closure is pair of env and fn
fn fn_ptr(env: &mut Env) { **env.x += 5; }
This is then illegal because you cannot mutate an &mut
found
in an aliasable location. To solve, you’d have to translate with
an &mut
borrow:
struct Env<'a> { x: &'a mut &'a mut isize }
let mut z = 3;
let x: &mut isize = &mut z;
let y = (&mut Env { x: &mut x }, fn_ptr); // changed from &x to &mut x
fn fn_ptr(env: &mut Env) { **env.x += 5; }
Now the assignment to **env.x
is legal, but creating a
mutable pointer to x
is not because x
is not mutable. We
could fix this by declaring x
as let mut x
. This is ok in
user code, if awkward, but extra weird for closures, since the
borrow is hidden.
So we introduce a ClosureCapture
borrow – user will not have to mark the variable
containing the mutable reference as mut
, as they didn’t ever
intend to mutate the mutable reference itself. We still mutable capture it in order to
mutate the pointed value through it (but not mutating the reference itself).
This solves the problem. For simplicity, we don’t give users the way to express this borrow, it’s just used when translating closures.