Skip to content

Commit

Permalink
✨ evaluate let statements
Browse files Browse the repository at this point in the history
  • Loading branch information
KPMGE committed Mar 15, 2024
1 parent 3928cec commit 60ac5cb
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
29 changes: 23 additions & 6 deletions src/evaluator.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
use crate::ast::{AstNode, Expression, Statement};
use std::collections::HashMap;
use crate::token::Token;

#[derive(Default)]
pub struct Evaluator {}
pub struct Evaluator {
context: HashMap<String, Object>
}

#[derive(Debug, Clone, PartialEq)]
pub enum Object {
Expand All @@ -14,18 +17,29 @@ pub enum Object {

impl Evaluator {
pub fn new() -> Self {
Evaluator::default()
Evaluator {
context: HashMap::new()
}
}

pub fn eval(&self, node: AstNode) -> Object {
pub fn eval(&mut self, node: AstNode) -> Object {
match node {
AstNode::Program { statements } => self.eval_program(statements),
AstNode::Statement(statement) => match statement {
Statement::ReturnStatement { value, .. } => {
let result_object = self.eval(AstNode::Expression(value));
Object::Return(Box::new(result_object))
}
Statement::LetStatement { .. } => todo!(),
Statement::LetStatement { name, value, .. } => {
let let_name = match name {
Expression::Identifier { token: Token::Identifier(str) } => str,
_ => panic!()
};

let result_object = self.eval(AstNode::Expression(value));
self.context.insert(let_name.clone(), result_object.clone());
result_object
},
},
AstNode::Expression(expression) => match expression {
Expression::Int {
Expand Down Expand Up @@ -62,13 +76,16 @@ impl Evaluator {
}

Object::Null
},
Expression::Identifier { token: Token::Identifier(let_name) } => {
self.context.get(&let_name).expect("ERROR: Could not find identifer").clone()
}
_ => todo!(),
},
}
}

fn eval_program(&self, statements: Vec<AstNode>) -> Object {
fn eval_program(&mut self, statements: Vec<AstNode>) -> Object {
let mut result = Object::Null;

for statement in statements {
Expand All @@ -81,7 +98,7 @@ impl Evaluator {
result
}

fn eval_block_statement(&self, statements: Vec<AstNode>) -> Object {
fn eval_block_statement(&mut self, statements: Vec<AstNode>) -> Object {
let mut result = Object::Null;

for statement in statements {
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use kl_rs::{evaluator::Evaluator, lexer::Lexer, parser::Parser, token::Token};
fn main() {
let stdin = std::io::stdin();
let mut handle = stdin.lock();
let mut evaluator = Evaluator::new();

loop {
let mut input = String::new();
Expand Down Expand Up @@ -58,7 +59,6 @@ fn main() {
println!();

println!("EVALUATED: ");
let evaluator = Evaluator::new();
let object = evaluator.eval(program);
println!("{}", object.inspect());
}
Expand Down

0 comments on commit 60ac5cb

Please sign in to comment.