add evaluator

This commit is contained in:
Raptorox 2026-05-21 17:12:06 +02:00
parent c70c5fab4d
commit 99be8a16c7
No known key found for this signature in database
GPG key ID: 8B3556FC3ED1F6D8
3 changed files with 48 additions and 4 deletions

38
src/eval.rs Normal file
View file

@ -0,0 +1,38 @@
use crate::parser::{BinaryOp, Expr, UnaryOp};
pub struct Evaluator {
ast: Expr
}
impl Evaluator {
pub fn new(ast: Expr) -> Self {
Self {
ast
}
}
fn eval_expr(&self, expr: Expr) -> i64 {
match expr {
Expr::Number(n) => n,
Expr::Unary { op, right } => {
match op {
UnaryOp::Neg => -self.eval_expr(*right)
}
},
Expr::Binary { op, left, right } => {
match op {
BinaryOp::Add => self.eval_expr(*left) + self.eval_expr(*right),
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)
}
},
expr => panic!("can't eval expression: {expr:?}")
}
}
pub fn eval(&self) -> i64 {
self.eval_expr(self.ast.clone())
}
}