rust icon indicating copy to clipboard operation
rust copied to clipboard

"Cannot root managed value long enough" with recursion and returning borrowed pointers

Open ttaubert opened this issue 13 years ago • 4 comments

I wonder if this shouldn't work?

struct Node<T> {
  val: T,
  next: Option<@Node<T>>
}

impl<T> Node<T> {
  pure fn get(&self) -> &self/T {
    match self.next {
      Some(next) => next.get(),
      None => &self.val
    }
  }
}

fn main() {}

The failure is:

19:20: 19:24 error: illegal borrow: cannot root managed value long enough
19       Some(next) => next.get(),
                       ^~~~
17:32: 22:3 note: managed value would have to be rooted for the lifetime &self as defined on the block at 17:32...
17   pure fn get(&self) -> &self/T {
18     match self.next {
19       Some(next) => next.get(),
20       None => &self.val
21     }
22   }
17:32: 22:3 note: ...but can only be rooted for the block at 17:32
17   pure fn get(&self) -> &self/T {
18     match self.next {
19       Some(next) => next.get(),
20       None => &self.val
21     }
22   }

https://github.com/mozilla/rust/blob/incoming/src/librustc/middle/borrowck/preserve.rs#L333

attempt_root() expects a ty::re_scope but self.scope_region is a ty::re_free. self.scope_region's id is the same as self.root_ub (root_region's id).

CC'ing @nikomatsakis because he's the borrowed pointer specialist.

ttaubert avatar Jan 01 '13 18:01 ttaubert

I think this never should have worked, since the Node struct is declared to contain a managed box. The error message isn't the clearest, but is saying the compiler doesn't know that the lifetime of the contents of a node's next field is the same as the lifetime of the contents of the node itself.

I'll check in a modified run-pass test case (where the next field contains a pointer with a lifetime annotation).

catamorphism avatar Mar 29 '13 02:03 catamorphism

Pending #5620

catamorphism avatar Mar 29 '13 02:03 catamorphism

Doesn't look critical for 0.6

brson avatar Mar 31 '13 05:03 brson

Yeah, this is working-as-intended. The associated test (which landed) shows how this needs to be written if you want to use borrowed pointers here. Closing.

graydon avatar May 15 '13 17:05 graydon