52 lines
1.7 KiB
Rust
52 lines
1.7 KiB
Rust
use super::Interpret;
|
|
use super::{types::Value, RuntimeError};
|
|
use crate::ast::expression::expression_node;
|
|
|
|
impl Interpret for expression_node::ExpressionNode {
|
|
fn interpret(&self) -> Result<Value, RuntimeError> {
|
|
expression_node::all_variants!(self, n => n.interpret())
|
|
}
|
|
}
|
|
|
|
impl Interpret for expression_node::Literal {
|
|
fn interpret(&self) -> Result<Value, RuntimeError> {
|
|
Ok(self.clone().into())
|
|
}
|
|
}
|
|
|
|
impl Interpret for expression_node::BinaryExpr {
|
|
fn interpret(&self) -> Result<Value, RuntimeError> {
|
|
let left_val = self.left.interpret().expect("expected lval");
|
|
let right_val = self.right.interpret().expect("expected rval");
|
|
match self.operator {
|
|
expression_node::Operator::BangEqual => Ok((left_val != right_val).into()),
|
|
expression_node::Operator::Less => Ok((left_val < right_val).into()),
|
|
expression_node::Operator::LessEqual => Ok((left_val <= right_val).into()),
|
|
expression_node::Operator::Greater => Ok((left_val > right_val).into()),
|
|
expression_node::Operator::GreaterEqual => Ok((left_val >= right_val).into()),
|
|
expression_node::Operator::EqualEqual => Ok((left_val == right_val).into()),
|
|
expression_node::Operator::Equal => todo!(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Interpret for expression_node::UnaryExpr {
|
|
fn interpret(&self) -> Result<Value, RuntimeError> {
|
|
let val = self.right.interpret()?;
|
|
match self.operator {
|
|
expression_node::UnaryOperator::Bang => Ok(Value::Bool(!val.truthy())),
|
|
expression_node::UnaryOperator::Minus => match val {
|
|
Value::Int(i) => Ok(Value::Int(-i)),
|
|
Value::Float(f) => Ok(Value::Float(-f)),
|
|
_ => Err(RuntimeError),
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Interpret for expression_node::GroupingExpr {
|
|
fn interpret(&self) -> Result<Value, RuntimeError> {
|
|
self.0.interpret()
|
|
}
|
|
}
|