From 99be8a16c753575148bd0b93a6fb19748825a6c4 Mon Sep 17 00:00:00 2001 From: Raptorox <70806316+Raptorox@users.noreply.github.com> Date: Thu, 21 May 2026 17:12:06 +0200 Subject: [PATCH] add evaluator --- src/eval.rs | 38 ++++++++++++++++++++++++++++++++++++++ src/main.rs | 8 +++++++- src/parser.rs | 6 +++--- 3 files changed, 48 insertions(+), 4 deletions(-) create mode 100644 src/eval.rs diff --git a/src/eval.rs b/src/eval.rs new file mode 100644 index 0000000..7707b86 --- /dev/null +++ b/src/eval.rs @@ -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()) + } +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 79fb1d3..4d61fc5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,8 @@ mod lexer; use lexer::Lexer; mod parser; use parser::Parser; +mod eval; +use eval::Evaluator; fn main() -> std::io::Result<()> { let args = std::env::args().collect::>(); @@ -29,7 +31,11 @@ fn main() -> std::io::Result<()> { let parsed = parser.parse(); match parsed { parser::Expr::EOL => break, - _ => println!("{:?}", parsed) + _ => { + println!("AST: {:?}", parsed); + let eval = Evaluator::new(parsed); + println!("Eval: {:?}", eval.eval()); + } } } diff --git a/src/parser.rs b/src/parser.rs index 357d42b..9e26822 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1,6 +1,6 @@ use crate::token::Token; -#[derive(Debug)] +#[derive(Debug, Clone)] pub enum BinaryOp { Add, Sub, @@ -9,7 +9,7 @@ pub enum BinaryOp { Mod } -#[derive(Debug)] +#[derive(Debug, Clone)] pub enum UnaryOp { Neg } @@ -27,7 +27,7 @@ fn infix_bp(op: &BinaryOp) -> (u8, u8) { } } -#[derive(Debug)] +#[derive(Debug, Clone)] pub enum Expr { Number(i64), Ident(String),