2024-03-07 17:29:07 +00:00
|
|
|
use crate::{
|
|
|
|
context::Context,
|
|
|
|
error::{RuntimeError, ValidationError},
|
|
|
|
Value,
|
|
|
|
};
|
|
|
|
|
2024-03-08 17:24:11 +00:00
|
|
|
use super::{AbstractTree, Action, Expression, Type, ValueNode};
|
2024-03-07 17:29:07 +00:00
|
|
|
|
|
|
|
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
|
2024-03-08 21:14:47 +00:00
|
|
|
pub struct Index {
|
|
|
|
left: Expression,
|
|
|
|
right: Expression,
|
2024-03-07 17:29:07 +00:00
|
|
|
}
|
|
|
|
|
2024-03-08 21:14:47 +00:00
|
|
|
impl Index {
|
|
|
|
pub fn new(left: Expression, right: Expression) -> Self {
|
2024-03-07 17:29:07 +00:00
|
|
|
Self { left, right }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-08 21:14:47 +00:00
|
|
|
impl AbstractTree for Index {
|
2024-03-07 21:13:15 +00:00
|
|
|
fn expected_type(&self, _context: &Context) -> Result<Type, ValidationError> {
|
|
|
|
let left_type = self.left.expected_type(_context)?;
|
2024-03-07 17:29:07 +00:00
|
|
|
|
|
|
|
if let (
|
|
|
|
Expression::Value(ValueNode::List(expression_list)),
|
|
|
|
Expression::Value(ValueNode::Integer(index)),
|
|
|
|
) = (&self.left, &self.right)
|
|
|
|
{
|
|
|
|
let expression = if let Some(expression) = expression_list.get(*index as usize) {
|
|
|
|
expression
|
|
|
|
} else {
|
|
|
|
return Ok(Type::None);
|
|
|
|
};
|
|
|
|
|
2024-03-07 21:13:15 +00:00
|
|
|
expression.expected_type(_context)
|
2024-03-07 17:29:07 +00:00
|
|
|
} else {
|
|
|
|
Err(ValidationError::CannotIndex(left_type))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn validate(&self, context: &Context) -> Result<(), ValidationError> {
|
|
|
|
let left_type = self.left.expected_type(context)?;
|
|
|
|
|
|
|
|
match left_type {
|
|
|
|
Type::List => todo!(),
|
|
|
|
Type::ListOf(_) => todo!(),
|
|
|
|
Type::ListExact(_) => {
|
|
|
|
let right_type = self.right.expected_type(context)?;
|
|
|
|
|
|
|
|
if let Type::Integer = right_type {
|
|
|
|
Ok(())
|
|
|
|
} else {
|
|
|
|
Err(ValidationError::CannotIndexWith(left_type, right_type))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => Err(ValidationError::CannotIndex(left_type)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-08 17:24:11 +00:00
|
|
|
fn run(self, _context: &Context) -> Result<Action, RuntimeError> {
|
|
|
|
let left_value = self.left.run(_context)?.as_return_value()?;
|
|
|
|
let right_value = self.right.run(_context)?.as_return_value()?;
|
2024-03-07 17:29:07 +00:00
|
|
|
|
|
|
|
if let (Some(list), Some(index)) = (left_value.as_list(), right_value.as_integer()) {
|
2024-03-08 17:24:11 +00:00
|
|
|
Ok(Action::Return(
|
|
|
|
list.get(index as usize)
|
|
|
|
.cloned()
|
|
|
|
.unwrap_or_else(Value::none),
|
|
|
|
))
|
2024-03-07 17:29:07 +00:00
|
|
|
} else {
|
|
|
|
Err(RuntimeError::ValidationFailure(
|
|
|
|
ValidationError::CannotIndexWith(left_value.r#type(), right_value.r#type()),
|
|
|
|
))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|