Borrow checker disallow safe code when is used specific combination of pattern matching and mutable references

Borrow checker (stable 1.100.0 and nightly (Polonius Alpha) 2026-11-22 137d1d49458b73b7b85d) does not allow following code:

let mut stack: Vec<&'a mut Tree<V>> = vec![root]
let mut values: Vec<&'a mut V> = Vec::new();

while let Some(node) = stack.pop() {
    match node {
        Tree::Value(value) => values.push(value),
        Tree::Tree(children) if children.len() % 2 == 0 => {
            stack.extend(children.values_mut());
        }
        Tree::Tree(children) => {
            stack.extend(children.values_mut().rev());
        }
    }
}

It considers first and second borrow of children as not exclusive:

 15 |             Tree::Tree(children) if children.len() % 2 == 0 => {
    |                        -------- first mutable borrow occurs here
...
 18 |             Tree::Tree(children) => {
    |                        ^^^^^^^^ second mutable borrow occurs here

Of course code is accepted by compiler if there is only one pattern for each enum variant.

minimal example in Rust's playground

I created this topic once I was not able to find either note in documentation or reported bug to this behavior and because it affects both borrow checkers.

It looks like the match guard is extending the lifetime of the children match. Consider this similar code (where I added an extra bool to the Tree variant):

        match node {
            Tree::Value(value) => values.push(value),
            Tree::Tree(children, false) if true => {
                stack.extend(children.values_mut());
            }
            Tree::Tree(children, true) => {
                stack.extend(children.values_mut().rev());
            }
            _ => { unreachable!() }
        }

This has a borrow-check error, but if you remove the if true, it compiles.

As such, I suspect that the match guard is extending the lifetime of children to the end of the match block, and also suspect that changing this behavior would be likely to break something. Intuitively it seems like the lifetime of things matched by the pattern should end at the end of the match guard if the match guard is false, but it wouldn't surprise me if that were impossible to implement or contradicted other parts of the language.

An example for the sort of thing I have in mind (this works in current Rust, but might not be quite impossible to reconcile with allowing the original program to borrow-check):

use core::hint::black_box;

#[derive(Debug)]
struct Holder<T>(T);

pub fn main() {
    let a = black_box(Holder(Holder(true)));
    let t = loop {
        match &a {
            Holder(a0) if break a0 => { unreachable!() }
            Holder(_) => { unreachable!() }
        }
    };
    
    dbg!(t);
}

In this case, a0 outlives the match (and indeed the loop), although it is possible to make this work by considering t to be a clone (technically copy) of a0 that has a longer lifetime than a0 does.

1 Like

I am not sure what the root cause is, but the following equivalent pattern seems to compile fine.

use std::collections::BTreeMap;

enum Tree<V> {
    Value(V),
    Tree(BTreeMap<&'static str, Self>),
}

fn collect_values_mut<'a, V>(root: &'a mut Tree<V>) -> Vec<&'a mut V> {
    let mut stack: Vec<&'a mut Tree<V>> = vec![root];
    let mut values: Vec<&'a mut V> = Vec::new();

    while let Some(node) = stack.pop() {
        match node {
            Tree::Value(value) => values.push(value),
            Tree::Tree(children) => if children.len() % 2 == 0 {
                stack.extend(children.values_mut());
            } else {
                stack.extend(children.values_mut().rev())
            },
        }
    }

    values
}

fn main() {}
2 Likes

Interesting points!

Regarding first, if you change order of arms to following:

while let Some(node) = stack.pop() {
            match node {
        Tree::Value(value) => values.push(value),
        Tree::Tree(children, false) if true => {
            stack.extend(children.values_mut());
        }
        _ => { unreachable!() }
        Tree::Tree(children, true) => {
            stack.extend(children.values_mut().rev());
        }
    }
}

another error occurs before E0499

error[E0503]: cannot use `*node` because it was mutably borrowed
   --> src/main.rs:13:22
    |
  8 | fn collect_values_mut<'a, V>(root: &'a mut Tree<V>) -> Vec<&'a mut V> {
    |                       -- lifetime `'a` defined here
  9 |     let mut stack: Vec<&'a mut Tree<V>> = vec![root];
    |                    -------------------- type annotation requires that `node.0` is borrowed for `'a`
...
 13 |                match node {
    |                      ^^^^ use of borrowed `node.0`
 14 |             Tree::Value(value) => values.push(value),
 15 |             Tree::Tree(children, false) if true => {
    |                        -------- `node.0` is borrowed here
    |
note: requirement that the value outlives `'a` introduced here
   --> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/collect.rs:416:31
    |
416 |     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I);
    |                               ^^^^^^^^

Regarding second example: please keep in mind that those weird errors occur only when pattern matching is done on mutable reference.

I might be misunderstanding what you tested, but your minimal example does appear to work under polonius, no?

Similarly, this same workaround as applicable in many other supported-only-with-polonius kind of cases appears to work here, too, e.g.:

fn collect_values_mut<'a, V>(root: &'a mut Tree<V>) -> Vec<&'a mut V> {
    let mut stack: Vec<&'a mut Tree<V>> = vec![root];
    let mut values: Vec<&'a mut V> = Vec::new();

    while let Some(node) = stack.pop() {
        match node {
            Tree::Value(value) => values.push(value),
            Tree::Tree(children) if children.len() % 2 == 0 => {
                // re-do the destructuring once
                // the branch taken is known
                let Tree::Tree(children) = node else { unreachable!() };

                stack.extend(children.values_mut());
            }
            Tree::Tree(children) => {
                stack.extend(children.values_mut().rev());
            }
        }
    }

    values
}

(playground)


Edit: Oh, I see you're talking about the polonius alpha that's automatically enabled on nightly. Sorry I kinda didn't have that on my radar at the moment. Apparently there are still differences between that and full -Zpolonius then? :thinking:

I was trying to make a more typical polonius example for comparison with

use either::Either::{self, Left, Right};
use std::collections::BTreeMap;

enum Tree<V> {
    Value(V),
    Tree(BTreeMap<&'static str, Self>),
}

fn handle_value<V>(node: &mut Tree<V>) -> Either<&mut V, Vec<&mut Tree<V>>> {
    match node {
        Tree::Value(value) => return Left(value),
        Tree::Tree(children) if children.len() % 2 == 0 => return Right(children.values_mut().collect()),
        Tree::Tree(children) => return Right(children.values_mut().rev().collect()),
    }
}

but that one does work on nightly without unstable flags.

That does not surprise me, as it avoids the polonius-needing pattern altogether. (I.e. it works on stable, too; as does the same change applied to the handle_value example.)

Yes, indeed, to be honest, I am surprised that on nightly there are three different behaviors of borrow checker:

  1. without polonius argument
  2. -Zpolonius
  3. -Zpolonius=off

In case of issue related to this topic, there is difference between no polonius argument and -Zpolonius: only explicitly enabled polonius -Zpolonius fixes this issue. It is behavior totally opposite to my previous issue with borrow checker, that on nightly, fails only with -Zpolonius=off and compiles without polonius argument or with -Zpolonius.

Asking rustc about it confirms it’s 3 possibilities indeed:

$ rustc +nightly -Zpolonius=
error: incorrect value `` for unstable option `polonius` - either no value or one of `legacy` (the default), `off`, or `next` was expected

Based on testing what works and what doesn't, it looks like currently
-Zpolonius is short for -Zpolonius=legacy, and
on nightly, the implicitly enabled default is actually -Zpolonius=next.

Looking at

seems to confirm that it's meant to be a subset

In 2023, a new formulation of a Polonius-style borrow checker was imagined that required minimal rearchitecture of the existing NLL implementation and could be extended to allow more code to compile. […]

We're nearly there now! At this point, there are no known remaining issues with the subset coined Polonius Alpha that we intend to stabilize.

1 Like

Thank you very much for explanation. It works as you described and it makes sense that subset which requires less architecture changes has behavior more closer to NLL.

I "minimized"[1] (though maybe it's not actually that closely related even more, IDK[2].. transformed) this case to something like

fn f1<'a>(x: &'a mut u8, cond: bool, out: &mut &'a mut u8) {
    let y: &mut u8 = x;
    *out = if cond { y } else { x };
}

some exploration (the "fails on polonius=next" cases do work in polonius=legacy)

// doesn't work like this
// | fails on polonius=next (default on current nightlies)
// fn f1<'a>(x: &'a mut u8, cond: bool, out: &mut &'a mut u8) {
//     let y: &mut u8 = x;
//     *out = if cond { y } else { x };
// }

// but it does in two steps
fn f2a<'a>(x: &'a mut u8, cond: bool) -> &'a mut u8 {
    let y: &mut u8 = x;
    if cond { y } else { x }
}
fn f2b<'a>(x: &'a mut u8, cond: bool, out: &mut &'a mut u8) {
    *out = f2a(x, cond);
}

// double checking it wasn't about the implicit block either
// | fails on polonius=next (default on current nightlies)
// fn f3<'a>(x: &'a mut u8, cond: bool, out: &mut &'a mut u8) {
//     *out = {
//         let y: &mut u8 = x;
//         if cond { y } else { x }
//     };
// }

// using immediately invoked closure for comparison
fn f4<'a>(x: &'a mut u8, cond: bool, out: &mut &'a mut u8) {
    *out = (|| {
        let y: &mut u8 = x;
        if cond { y } else { x }
    })();
}

// using async for comparison
async fn f5<'a>(x: &'a mut u8, cond: bool, out: &mut &'a mut u8) {
    *out = async {
        let y: &mut u8 = x;
        if cond { y } else { x }
    }.await;
}

// passing instead of capturing
fn f6<'a>(x: &'a mut u8, cond: bool, out: &mut &'a mut u8) {
    *out = (|x: &'a mut _, cond| {
        let y: &mut u8 = x;
        if cond { y } else { x }
    })(x, cond);
}

This is all rather curious; not sure what to think of it yet.


  1. For full disclosure I only manually did this up to this minimization:

    fn one_step<'a, V>(stack: &mut Vec<&'a mut Option<Vec<V>>>, values: &mut Vec<&'a mut V>) {
        if let Some(node) = stack.pop() {
            match node {
                None => (),
                Some(children) if children.len() % 2 == 0 => {
                    values.extend(children.iter_mut());
                }
                Some(children) => {
                    values.extend(children.iter_mut().rev());
                }
            }
        }
    }
    

    then used an LLM to do more minimization work resulting in something similar to f1. Finally, I hand adjusted argument names and order, changed the syntax to achieve the reborrow. Afterwards, all the exploration into f2, f3 etc.. was manual again. ↩︎

  2. certainly the workarounds aren't easily transferable anymore ↩︎

1 Like