From 9a84283245706c650dd23ec5f181fe98f59e6bef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emmanuel=20Beno=C3=AEt?= Date: Sun, 1 Jan 2023 11:10:48 +0100 Subject: [PATCH] Interpreter - If statement --- src/interpreter/interpretable.rs | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/interpreter/interpretable.rs b/src/interpreter/interpretable.rs index e807bc9..171f9cf 100644 --- a/src/interpreter/interpretable.rs +++ b/src/interpreter/interpretable.rs @@ -51,6 +51,11 @@ impl Interpretable for ast::StmtNode { ast::StmtNode::Print(expr) => self.on_print(environment, expr), ast::StmtNode::VarDecl(name, expr) => self.on_var_decl(environment, name, expr), ast::StmtNode::Block(statements) => self.on_block(environment, statements), + ast::StmtNode::IfStmt { + condition, + then_branch, + else_branch, + } => self.on_if_statement(environment, condition, then_branch, else_branch), } } } @@ -86,13 +91,34 @@ impl ast::StmtNode { } /// Execute the contents of a block. - fn on_block(&self, environment: &EnvironmentRef, stmts: &Vec>) -> InterpreterResult { + fn on_block( + &self, + environment: &EnvironmentRef, + stmts: &Vec>, + ) -> InterpreterResult { let child = Environment::create_child(environment); for stmt in stmts.iter() { stmt.interprete(&child)?; } Ok(Value::Nil) } + + /// Execute an if statement. + fn on_if_statement( + &self, + environment: &EnvironmentRef, + condition: &ast::ExprNode, + then_branch: &ast::StmtNode, + else_branch: &Option>, + ) -> InterpreterResult { + if condition.interprete(environment)?.is_truthy() { + then_branch.interprete(environment) + } else if let Some(else_stmt) = else_branch { + else_stmt.interprete(environment) + } else { + Ok(Value::Nil) + } + } } /* -------------------------------- * @@ -102,7 +128,7 @@ impl ast::StmtNode { impl Interpretable for ast::ExprNode { fn interprete(&self, environment: &EnvironmentRef) -> InterpreterResult { match self { - ast::ExprNode::Assignment{ name, value} => { + ast::ExprNode::Assignment { name, value } => { let value = value.interprete(environment)?; environment.borrow_mut().assign(name, value) }