error: cannot infer an appropriate lifetime for autoref due to conflicting requirements [E0495]

≯℡__Kan透↙ 提交于 2019-12-02 06:50:42
robbepop

I found a solution to my problems and now everything compiles fine.

The problem was in fact a lifetime problem but not only within the TokenStream trait. I had lifetime issues in several places across the entire code.

Some notable places from the long code in the initial post:

lexer.rs: line 46 - 58

fn scan_line_comment<'b>(&self) -> Token<'b> { Token::EndOfFile }
fn scan_multi_line_comment<'b>(&self) -> Token<'b> { Token::EndOfFile }


fn scan_identifier<'b>(&self) -> Token<'b> { Token::EndOfFile }
fn scan_char_literal<'b>(&self) -> Token<'b> { Token::EndOfFile }
fn scan_string_literal<'b>(&self) -> Token<'b> { Token::EndOfFile }
fn scan_number_literal<'b>(&self) -> Token<'b> { Token::EndOfFile }

fn consume_and_return<'b>(&mut self, token: Token<'b>) -> Token<'b> {
    self.consume_next();
    token
}

I had to insert the lifetime 'b to specify that the Token may outlive the Lexer instance.

The TokenStream required a new lifetime parameter so that it can specify that extended lifetime as well:

pub trait TokenStream<'a> {
    fn next_token(&mut self) -> Token<'a>;
}

The TokenStream implementation for Lexer had to be adjusted for this change:

impl<'a, 'b> TokenStream<'b> for Lexer<'a> {
    fn next_token(&mut self) -> Token<'b> {
        ...
    }
    ...
}

As well as the Iterator implementation for Lexer

impl<'a> Iterator for Lexer<'a> {
    type Item = Token<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let token = self.next_token();
        match token {
            Token::EndOfFile => None,
            _                => Some(token)
        }
    }
}

That's it!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!