Add unary expressions
Adds parsing of unary plus to the parser.
This commit is contained in:
parent
155325e78c
commit
56fffd6911
17
src/main.rs
17
src/main.rs
|
@ -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));
|
||||
|
|
Loading…
Reference in a new issue