From 8c507cb1dab189594614ed0960399e8eee86363c Mon Sep 17 00:00:00 2001 From: Raptorox <70806316+Raptorox@users.noreply.github.com> Date: Thu, 21 May 2026 17:39:43 +0200 Subject: [PATCH] add exponentiation --- src/eval.rs | 3 ++- src/expr.rs | 8 +++++--- src/lexer.rs | 1 + src/parser.rs | 1 + src/token.rs | 1 + 5 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/eval.rs b/src/eval.rs index df5b4f3..3d486e8 100644 --- a/src/eval.rs +++ b/src/eval.rs @@ -25,7 +25,8 @@ impl Evaluator { BinaryOp::Sub => self.eval_expr(*left) - self.eval_expr(*right), BinaryOp::Mul => self.eval_expr(*left) * self.eval_expr(*right), BinaryOp::Div => self.eval_expr(*left) / self.eval_expr(*right), - BinaryOp::Mod => self.eval_expr(*left) % self.eval_expr(*right) + BinaryOp::Mod => self.eval_expr(*left) % self.eval_expr(*right), + BinaryOp::Exp => self.eval_expr(*left).pow(self.eval_expr(*right) as u32) // probably shouldn't cast like that } }, expr => panic!("can't eval expression: {expr:?}") diff --git a/src/expr.rs b/src/expr.rs index 7a32386..06da22a 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -4,7 +4,8 @@ pub enum BinaryOp { Sub, Mul, Div, - Mod + Mod, + Exp } #[derive(Debug, Clone)] @@ -14,14 +15,15 @@ pub enum UnaryOp { pub fn prefix_bp(op: &UnaryOp) -> u8 { match op { - UnaryOp::Neg => 5 + UnaryOp::Neg => 7 } } pub fn infix_bp(op: &BinaryOp) -> (u8, u8) { match op { BinaryOp::Add | BinaryOp::Sub => (1, 2), - BinaryOp::Mul | BinaryOp::Div | BinaryOp::Mod => (3, 4) + BinaryOp::Mul | BinaryOp::Div | BinaryOp::Mod => (3, 4), + BinaryOp::Exp => (5, 6) } } diff --git a/src/lexer.rs b/src/lexer.rs index a4045c3..32d806a 100644 --- a/src/lexer.rs +++ b/src/lexer.rs @@ -59,6 +59,7 @@ impl Lexer { Some(b'*') => {self.advance(); Some(Token::Asterisk)}, Some(b'/') => {self.advance(); Some(Token::Slash)}, Some(b'%') => {self.advance(); Some(Token::Percent)}, + Some(b'^') => {self.advance(); Some(Token::Caret)}, Some(b'(') => {self.advance(); Some(Token::LParen)}, Some(b')') => {self.advance(); Some(Token::RParen)}, diff --git a/src/parser.rs b/src/parser.rs index eb8937a..3afc6e0 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -69,6 +69,7 @@ impl Parser { Some(Token::Asterisk) => BinaryOp::Mul, Some(Token::Slash) => BinaryOp::Div, Some(Token::Percent) => BinaryOp::Mod, + Some(Token::Caret) => BinaryOp::Exp, _ => break }; diff --git a/src/token.rs b/src/token.rs index e5759e8..c193fbe 100644 --- a/src/token.rs +++ b/src/token.rs @@ -9,6 +9,7 @@ pub enum Token { Asterisk, Slash, Percent, + Caret, // Parentheses LParen,