Double mutable borrow error in a loop happens even with NLL on

This is a limitation of the current implementation of non-lexical lifetimes This can be shown with this reduced case:

fn next<'buf>(buffer: &'buf mut String) -> &'buf str {
    loop {
        let event = parse(buffer);

        if true {
            return event;
        }
    }
}

fn parse<'buf>(_buffer: &'buf mut String) -> &'buf str {
    unimplemented!()
}

fn main() {}

This limitation prevents NLL case #3: conditional control flow across functions

In compiler developer terms, the current implementation of non-lexical lifetimes is “location insensitive”. Location sensitivity was originally available but it was disabled in the name of performance.

I asked Niko Matsakis about this code:

In the context of your example: the value event only has to have the lifetime 'buf conditionally — at the return point which may or may not execute. But when we are “location insensitive”, we just track the lifetime that event must have anywhere, without considering where that lifetime must hold. In this case, that means we make it hold everywhere, which is why you get a compilation failure.

One subtle thing is that the current analysis is location sensitive in one respect — where the borrow takes place. The length of the borrow is not.

The good news is that adding this concept of location sensitivity back is seen as an enhancement to the implementation of non-lexical lifetimes. The bad news:

That may or may not be before the [Rust 2018] edition.

(Note: it did not make it into the initial release of Rust 2018)

This hinges on a (even newer!) underlying implementation of non-lexical lifetimes that improves the performance. You can opt-in to this half-implemented version using -Z polonius:

rustc +nightly -Zpolonius --edition=2018 example.rs
RUSTFLAGS="-Zpolonius" cargo +nightly build

Because this is across functions, you can sometimes work around this by inlining the function.

Leave a Comment