From 186c90092016b55511a4267a31a1757aaa442c59 Mon Sep 17 00:00:00 2001 From: greg Date: Fri, 25 Dec 2015 03:22:36 -0800 Subject: [PATCH] Implement expect macro Seems like there's no way around passing in self manually --- src/parser.rs | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/src/parser.rs b/src/parser.rs index 24bf72f..e748e07 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -29,35 +29,31 @@ struct Parser<'a> { tokens: Peekable> } +macro_rules! expect { + ($tok:expr, $self_:ident) => { + match $self_.tokens.next() { + Some(next) if *next == $tok => (), + Some(next) => { + let err = format!("Expected {:?} but got {:?}", $tok, next); + return Err(ParseError { err: err }); + }, + None => { + let err = format!("Expected {:?} but got end of input", $tok); + return Err(ParseError { err: err }); + } + } + } +} + impl<'a> Parser<'a> { fn parse(&mut self) -> ParseResult { let r = self.expr(); - match self.expect(Token::Separator) { - None => (), - Some(err) => return Err(err) - } - match self.expect(Token::EOF) { - None => (), - Some(err) => return Err(err) - } + expect!(Token::Separator, self); + expect!(Token::EOF, self); r } - fn expect(&mut self, expected: Token) -> Option { - match self.tokens.next() { - Some(next) if *next == expected => None, - Some(next) => { - let err = format!("Expected {:?} but got {:?}", expected, next); - Some(ParseError { err: err }) - } - None => { - let err = format!("Expected {:?} but got end of input", expected); - Some(ParseError { err: err }) - } - } - } - fn expr(&mut self) -> ParseResult { self.tokens.next(); return Ok(AST::Number(5.0));