From 1af1589550cd50d7477abe310bfe9fdeb56a3abe Mon Sep 17 00:00:00 2001 From: greg Date: Mon, 28 Dec 2015 22:27:26 -0800 Subject: [PATCH] Make Parser class internally use IntoIterator And wrap the next() and peek() methods --- src/parser.rs | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/parser.rs b/src/parser.rs index e45f5d5..aacbca1 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1,5 +1,6 @@ use std::iter::Peekable; use std::slice::Iter; +use std::vec::IntoIter; use tokenizer::Token; @@ -25,15 +26,25 @@ pub type ParseResult = Result; */ -struct Parser<'a> { - tokens: Peekable> +struct Parser { + tokens: Peekable> } -impl<'a> Parser<'a> { +impl Parser { + fn next(&mut self) -> Option { + self.tokens.next() + } + + fn lookahead(&mut self) -> Option<&Token> { + self.tokens.peek() + } +} + +impl Parser { fn expect(&mut self, expected: Token) -> ParseResult<()> { - match self.tokens.next() { - Some(next) if *next == expected => Ok(()), + match self.next() { + Some(ref next) if *next == expected => Ok(()), Some(next) => { let err = format!("Expected {:?} but got {:?}", expected, next); return Err(ParseError { err: err }); @@ -53,13 +64,13 @@ impl<'a> Parser<'a> { } fn expr(&mut self) -> ParseResult { - self.tokens.next(); + self.next(); return Ok(AST::Number(5.0)); } } pub fn parse(input: Vec) -> ParseResult { - let mut iter = input.iter().peekable(); + let mut iter = input.into_iter().peekable(); let mut parser = Parser { tokens: iter }; return parser.parse(); }