Implement parentheses grouping

This commit is contained in:
Daniel M 2022-01-28 14:11:39 +01:00
parent 807482583a
commit 74dbf724a5
2 changed files with 22 additions and 1 deletions

View File

@ -7,6 +7,12 @@ pub enum Token {
/// Integer literal (64-bit) /// Integer literal (64-bit)
I64(i64), I64(i64),
/// Left parenthesis ('(')
LParen,
/// Right parentheses (')')
RParen,
/// Plus (+) /// Plus (+)
Add, Add,
@ -99,6 +105,8 @@ impl<'a> Lexer<'a> {
'|' => tokens.push(Token::BOr), '|' => tokens.push(Token::BOr),
'&' => tokens.push(Token::BAnd), '&' => tokens.push(Token::BAnd),
'^' => tokens.push(Token::BXor), '^' => tokens.push(Token::BXor),
'(' => tokens.push(Token::LParen),
')' => tokens.push(Token::RParen),
//TODO: Don't panic, keep calm //TODO: Don't panic, keep calm
_ => panic!("Lexer encountered unexpected char: '{}'", ch), _ => panic!("Lexer encountered unexpected char: '{}'", ch),

View File

@ -47,7 +47,7 @@ pub enum Ast {
/* /*
## Grammar ## Grammar
### Expressions ### Expressions
expr_primary = LITERAL expr_primary = LITERAL | "(" expr ")"
expr_mul = expr_primary (("*" | "/" | "%") expr_primary)* expr_mul = expr_primary (("*" | "/" | "%") expr_primary)*
expr_add = expr_mul (("+" | "-") expr_mul)* expr_add = expr_mul (("+" | "-") expr_mul)*
expr_shift = expr_add ((">>" | "<<") expr_add)* expr_shift = expr_add ((">>" | "<<") expr_add)*
@ -110,6 +110,19 @@ impl<T: Iterator<Item = Token>> Parser<T> {
match self.next() { match self.next() {
Token::I64(val) => Ast::I64(val), Token::I64(val) => Ast::I64(val),
Token::LParen => {
// The tokens was an opening parenthesis, so parse a full expression again as the
// expression inside the parentheses `"(" expr ")"`
let inner = self.parse_expr();
// If there is no closing parenthesis after the expression, it is a syntax error
if !matches!(self.next(), Token::RParen) {
panic!("Error parsing primary expr: Missing closing parenthesis ')'");
}
inner
}
tok => panic!("Error parsing primary expr: Unexpected Token '{:?}'", tok), tok => panic!("Error parsing primary expr: Unexpected Token '{:?}'", tok),
} }
} }