feat(tazjin/rlox): Interpret if statements

Change-Id: Ic6aed29bec42098eb07e1ba9eb01dbcaae8d11e3
Reviewed-on: https://cl.tvl.fyi/c/depot/+/2322
Tested-by: BuildkiteCI
Reviewed-by: tazjin <mail@tazj.in>
This commit is contained in:
Vincent Ambo 2021-01-03 19:01:55 +03:00 committed by tazjin
parent a89777b34f
commit 93122a212e

View file

@ -127,7 +127,7 @@ impl Interpreter {
} }
Statement::Var(var) => return self.interpret_var(var), Statement::Var(var) => return self.interpret_var(var),
Statement::Block(block) => return self.interpret_block(block), Statement::Block(block) => return self.interpret_block(block),
Statement::If(_) => unimplemented!(), Statement::If(if_stmt) => return self.interpret_if(if_stmt),
} }
Ok(()) Ok(())
@ -160,6 +160,18 @@ impl Interpreter {
return result; return result;
} }
fn interpret_if<'a>(&mut self, if_stmt: &parser::If<'a>) -> Result<(), Error> {
let condition = self.eval(&if_stmt.condition)?;
if eval_truthy(&condition) {
self.interpret_stmt(&if_stmt.then_branch)
} else if let Some(else_branch) = &if_stmt.else_branch {
self.interpret_stmt(else_branch)
} else {
Ok(())
}
}
fn eval<'a>(&mut self, expr: &Expr<'a>) -> Result<Literal, Error> { fn eval<'a>(&mut self, expr: &Expr<'a>) -> Result<Literal, Error> {
match expr { match expr {
Expr::Assign(assign) => self.eval_assign(assign), Expr::Assign(assign) => self.eval_assign(assign),