Implement parentheses grouping
This commit is contained in:
parent
807482583a
commit
74dbf724a5
@ -7,6 +7,12 @@ pub enum Token {
|
||||
/// Integer literal (64-bit)
|
||||
I64(i64),
|
||||
|
||||
/// Left parenthesis ('(')
|
||||
LParen,
|
||||
|
||||
/// Right parentheses (')')
|
||||
RParen,
|
||||
|
||||
/// Plus (+)
|
||||
Add,
|
||||
|
||||
@ -99,6 +105,8 @@ impl<'a> Lexer<'a> {
|
||||
'|' => tokens.push(Token::BOr),
|
||||
'&' => tokens.push(Token::BAnd),
|
||||
'^' => tokens.push(Token::BXor),
|
||||
'(' => tokens.push(Token::LParen),
|
||||
')' => tokens.push(Token::RParen),
|
||||
|
||||
//TODO: Don't panic, keep calm
|
||||
_ => panic!("Lexer encountered unexpected char: '{}'", ch),
|
||||
|
||||
@ -47,7 +47,7 @@ pub enum Ast {
|
||||
/*
|
||||
## Grammar
|
||||
### Expressions
|
||||
expr_primary = LITERAL
|
||||
expr_primary = LITERAL | "(" expr ")"
|
||||
expr_mul = expr_primary (("*" | "/" | "%") expr_primary)*
|
||||
expr_add = expr_mul (("+" | "-") expr_mul)*
|
||||
expr_shift = expr_add ((">>" | "<<") expr_add)*
|
||||
@ -110,6 +110,19 @@ impl<T: Iterator<Item = Token>> Parser<T> {
|
||||
match self.next() {
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user