I am writing a parser in Rust. It is a structure owning a vector of tokens (with a lifetime 'a
) with methods mutating its start-end indices and state.
A common pattern among the parsing methods is the following:
fn eat_item(&mut self) -> ParseResult {
let elim = self.eat_item_eliminator()?;
self.eat_token(TT::Colon)?;
// ...
Ok(/*AST Node*/)
}
fn eat_item_eliminator(&mut self) -> ParseResult { ... }
fn eat_token(&mut self, tt: TT) -> Result<(), ParseError> { ... }
Token
borrows a slice of source string, and thus requires a lifetime and cannot be Copy
ed.
I've reduced my code to:
struct A {}
impl A {
pub fn mut1(&mut self) -> Result<usize, &str> {
let foo = self.mut2()?;
self.mut3()?;
Ok(foo)
}
fn mut2(&mut self) -> Result<usize, &str> {
Ok(1)
}
fn mut3(&mut self) -> Result<(), &str> {
Ok(())
}
}
fn main() {
let mut a = A {};
let _ = a.mut1();
}
The error is:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:7:9
|
4 | pub fn mut1(&mut self) -> Result<usize, &str> {
| - let's call the lifetime of this reference `'1`
5 | let foo = self.mut2()?;
| ---- - returning this value requires that `*self` is borrowed for `'1`
| |
| first mutable borrow occurs here
6 |
7 | self.mut3()?;
| ^^^^ second mutable borrow occurs here
Is there a clean way of changing the structure of my parser so that no such conflicts arise?