From 56fffd69111ec5512ccad8f79d13d9bc922d289a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aodhnait=20=C3=89ta=C3=ADn?= Date: Thu, 27 May 2021 15:55:35 +0000 Subject: [PATCH] Add unary expressions Adds parsing of unary plus to the parser. --- src/main.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index ad8c9e1..a70c061 100644 --- a/src/main.rs +++ b/src/main.rs @@ -121,6 +121,7 @@ struct Parser<'a> { enum Expr<'a> { Literal(&'a str), // Paren(Box>), + Unary(Token<'a>, Box>), Binary(Token<'a>, Box>, Box>), } @@ -177,8 +178,19 @@ impl<'a> Parser<'a> { }; } + fn parse_unary_expr(&mut self) -> Option> { + return match self.peek()? { + token @ Token::Plus => { + self.bump(); + let expr = self.parse_unary_expr()?; + Some(Expr::Unary(token, box expr)) + }, + _ => self.parse_primary_expr(), + }; + } + pub fn parse_expr(&mut self, min_precedence: usize) -> Option> { - let mut lhs = self.parse_primary_expr()?; + let mut lhs = self.parse_unary_expr()?; loop { let token = self.peek()?; @@ -199,9 +211,10 @@ impl<'a> Parser<'a> { } fn main() { + let inline_source = "3 + +5 * +7;"; // let inline_source = "3 + 5 * 7;"; // let inline_source = "(3 + 5) + 7;"; - let inline_source = "3 + (5 + (7 + 11));"; + // let inline_source = "3 + (5 + (7 + 11));"; let mut source = Source::new(inline_source); let mut parser = Parser::new(&mut source); eprintln!("{:?}", parser.parse_expr(0));