Skip to content

[nll] help user trace lifetimes through error messages #53220

Closed
@nikomatsakis

Description

@nikomatsakis

I am archiving this error (playground) which arose while porting rustc to use NLL. It is a non-trivial case of tracing lifetimes. I believe the error is legit, but it'd be nice if we could help the user see how the lifetime winds up over-extended:

#![feature(nll)]

struct RawArchive;
struct RawArchiveIterator<'a> { x: &'a RawArchive }
struct RawArchiveChild<'a> { x: &'a RawArchive }

struct ArchiveRO {
    raw: &'static mut RawArchive
}

struct Iter<'a> {
    raw: &'a mut RawArchiveIterator<'a>,
}

struct Child<'a> {
    raw: &'a mut RawArchiveChild<'a>,
}

impl ArchiveRO {
    pub fn iter(&self) -> Iter<'_> {
        panic!()
    }
}

impl Drop for ArchiveRO {
    fn drop(&mut self) { }
}

impl<'a> Iterator for Iter<'a> {
    type Item = Result<Child<'a>, String>;

    fn next(&mut self) -> Option<Result<Child<'a>, String>> {
        panic!()
    }
}

impl<'a> Drop for Iter<'a> {
    fn drop(&mut self) { }
}

impl<'a> Drop for Child<'a> {
    fn drop(&mut self) { }
}

fn error(archive: &ArchiveRO) {
    let mut members: Vec<&mut RawArchiveChild<'_>> = vec![];
    for child in archive.iter() {
        match child {
            Ok(child) => members.push(child.raw),
            Err(_) => ()
        }
    }
    members.len();
}
  
fn main() { }

Currently gives:

error[E0597]: `*child.raw` does not live long enough
  --> src/main.rs:49:39
   |
49 |             Ok(child) => members.push(child.raw),
   |                                       ^^^^^^^^^ borrowed value does not live long enough
50 |             Err(_) => ()
51 |         }
   |         - `*child.raw` dropped here while still borrowed
52 |     }
53 |     members.len();
   |     ------- borrow used here in later iteration of loop

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-NLLArea: Non-lexical lifetimes (NLL)NLL-diagnosticsWorking towards the "diagnostic parity" goalT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions