From 32a90b8103f62a039ba5cb247394a66bc919121c Mon Sep 17 00:00:00 2001 From: greg Date: Sat, 26 Dec 2015 00:50:14 -0800 Subject: [PATCH] write expect and also make the ParseResult type more general so it can be used for more things. --- src/parser.rs | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/src/parser.rs b/src/parser.rs index e748e07..e45f5d5 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -4,7 +4,7 @@ use std::slice::Iter; use tokenizer::Token; #[derive(Debug)] -enum AST { +pub enum AST { BinOp(Box, Box, Box), Number(f64), Name(String), @@ -15,7 +15,7 @@ pub struct ParseError { err: String } -pub type ParseResult = Result; +pub type ParseResult = Result; /* grammar @@ -29,38 +29,36 @@ struct Parser<'a> { tokens: Peekable> } -macro_rules! expect { - ($tok:expr, $self_:ident) => { - match $self_.tokens.next() { - Some(next) if *next == $tok => (), +impl<'a> Parser<'a> { + + fn expect(&mut self, expected: Token) -> ParseResult<()> { + match self.tokens.next() { + Some(next) if *next == expected => Ok(()), Some(next) => { - let err = format!("Expected {:?} but got {:?}", $tok, next); + let err = format!("Expected {:?} but got {:?}", expected, next); return Err(ParseError { err: err }); }, None => { - let err = format!("Expected {:?} but got end of input", $tok); + let err = format!("Expected {:?} but got end of input", expected); return Err(ParseError { err: err }); } } } -} -impl<'a> Parser<'a> { - - fn parse(&mut self) -> ParseResult { + fn parse(&mut self) -> ParseResult { let r = self.expr(); - expect!(Token::Separator, self); - expect!(Token::EOF, self); + try!(self.expect(Token::Separator)); + try!(self.expect(Token::EOF)); r } - fn expr(&mut self) -> ParseResult { + fn expr(&mut self) -> ParseResult { self.tokens.next(); return Ok(AST::Number(5.0)); } } -pub fn parse(input: Vec) -> ParseResult { +pub fn parse(input: Vec) -> ParseResult { let mut iter = input.iter().peekable(); let mut parser = Parser { tokens: iter }; return parser.parse();