I'm trying to make a simple LISP parser, but I'm stuck on the step where I convert the vector of tokens into a tree of AST nodes.
I create the root of the tree, and then maintain a stack of references into the tree where I currently want to add the next node. The problem is that no matter what I try, it seems that the borrow checker thinks I'm referencing something that doesn't live long enough.
This is the code:
pub fn parse(tokens: &Vec<Token>) -> Node {
let mut root: Vec<Node> = vec![];
{
tokens.into_iter().fold(vec![&mut root], handle_token);
}
Node::List(root)
}
fn handle_token<'a>(mut stack: Vec<&'a mut Vec<Node>>, token: &Token) -> Vec<&'a mut Vec<Node>> {
if *token == Token::LParen {
let new_node = Node::List(vec![]); // Create the new node
stack[0].push(new_node); // Add it to the tree
match stack[0][0] {
Node::List(ref mut the_vec) => stack.push(the_vec), // Finally, add a mutable reference to the new vector so that subsequent nodes will become children of this Node
_ => panic!(),
};
} else if *token == Token::RParen {
stack.pop();
} else {
match *token {
Token::Identifier(ref identifier) => {
stack[0].push(Node::Identifier(identifier.to_owned()))
}
Token::Number(number) => stack[0].push(Node::Number(number)),
Token::Str(ref s) => stack[0].push(Node::Str(s.to_owned())),
Token::EOF => {}
_ => panic!(),
}
}
stack
}
This is the compiler output:
error: `stack` does not live long enough
--> src/parser.rs:30:15
|
30 | match stack[0][0] {
| ^^^^^ does not live long enough
...
47 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the block at 26:96...
--> src/parser.rs:26:97
|
26 | fn handle_token<'a>(mut stack: Vec<&'a mut Vec<Node>>, token: &Token) -> Vec<&'a mut Vec<Node>> {
| ^
After researching this a bit, it seems like I'm trying to do something completely non-idiomatic to Rust, but I'm not sure. Is there a simple way to make this work, or do I need to rethink this?
I tried to reduce the problem to a minimal example:
enum Token {
Start,
End,
Value(i32),
}
enum Node {
List(Vec<Node>),
Value(i32),
}
fn main() {
let v = vec![Token::Start, Token::Value(1), Token::End];
parse(&v);
}
fn parse(tokens: &Vec<Token>) -> Node {
let mut root: Vec<Node> = vec![];
{
tokens.into_iter().fold(vec![&mut root], handle_token);
}
Node::List(root)
}
fn handle_token<'a>(mut stack: Vec<&'a mut Vec<Node>>, token: &Token) -> Vec<&'a mut Vec<Node>> {
match *token {
Token::Start => {
stack[0].push(Node::List(vec![])); // Add the new node to the tree
match stack[0][0] {
Node::List(ref mut the_vec) => stack.push(the_vec), // Add a mutable reference to the new vector so that subsequent nodes will become children of this Node
_ => panic!(),
};
},
Token::End => { stack.pop(); },
Token::Value(v) => stack[0].push(Node::Value(v)),
}
stack
}