From be40cd61c403160f402d446d7af4dcaebcf47274 Mon Sep 17 00:00:00 2001 From: Ryan Chandler Date: Mon, 25 Jul 2022 20:16:18 +0100 Subject: [PATCH] parser: support basic math ops --- trunk_lexer/src/lexer.rs | 11 +++++++++++ trunk_parser/src/ast.rs | 4 ++++ trunk_parser/src/parser/mod.rs | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+) diff --git a/trunk_lexer/src/lexer.rs b/trunk_lexer/src/lexer.rs index 7778035..25a9012 100644 --- a/trunk_lexer/src/lexer.rs +++ b/trunk_lexer/src/lexer.rs @@ -496,6 +496,17 @@ impl Lexer { TokenKind::Comment(buffer) } }, + '*' => { + self.col += 1; + + if let Some('*') = it.peek() { + self.col += 1; + it.next(); + TokenKind::Pow + } else { + TokenKind::Asterisk + } + }, '|' => { self.col += 1; // TODO: Handle boolean or || tokens. diff --git a/trunk_parser/src/ast.rs b/trunk_parser/src/ast.rs index 3f82321..3f65e05 100644 --- a/trunk_parser/src/ast.rs +++ b/trunk_parser/src/ast.rs @@ -243,6 +243,8 @@ pub struct ArrayItem { pub enum InfixOp { Add, Sub, + Div, + Mul, LessThan, } @@ -251,6 +253,8 @@ impl From for InfixOp { match k { TokenKind::Plus => Self::Add, TokenKind::Minus => Self::Sub, + TokenKind::Asterisk => Self::Mul, + TokenKind::Slash => Self::Div, TokenKind::LessThan => Self::LessThan, _ => unreachable!() } diff --git a/trunk_parser/src/parser/mod.rs b/trunk_parser/src/parser/mod.rs index 5c1b80d..7395c51 100644 --- a/trunk_parser/src/parser/mod.rs +++ b/trunk_parser/src/parser/mod.rs @@ -911,6 +911,7 @@ fn infix(lhs: Expression, op: TokenKind, rhs: Expression) -> Expression { fn infix_binding_power(t: &TokenKind) -> Option<(u8, u8)> { Some(match t { + TokenKind::Asterisk | TokenKind::Slash => (13, 14), TokenKind::Plus | TokenKind::Minus => (11, 12), TokenKind::LessThan => (9, 10), TokenKind::Equals => (2, 1), @@ -1011,6 +1012,14 @@ mod tests { }; } + macro_rules! expr { + ($expr:expr) => { + Statement::Expression { + expr: $expr, + } + }; + } + #[test] fn paren_expression() { assert_ast("