Add unary expressions

Adds parsing of unary plus to the parser.
This commit is contained in:
Aodhnait Étaín 2021-05-27 15:55:35 +00:00
parent 155325e78c
commit 56fffd6911
Signed by: aodhneine
GPG key ID: ECE91C73AD45F245

View file

@ -121,6 +121,7 @@ struct Parser<'a> {
enum Expr<'a> {
Literal(&'a str),
// Paren(Box<Expr<'a>>),
Unary(Token<'a>, Box<Expr<'a>>),
Binary(Token<'a>, Box<Expr<'a>>, Box<Expr<'a>>),
}
@ -177,8 +178,19 @@ impl<'a> Parser<'a> {
};
}
fn parse_unary_expr(&mut self) -> Option<Expr<'a>> {
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<Expr<'a>> {
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));