use std::fmt::{self, Display, Formatter};
use serde::{Deserialize, Serialize};
use crate::{
context::Context,
error::{RuntimeError, ValidationError},
value::ValueInner,
};
use super::{AbstractNode, Evaluation, Expression, Type, ValueNode, WithPosition};
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct MapIndex {
collection: Expression,
index: Expression,
}
impl MapIndex {
pub fn new(left: Expression, right: Expression) -> Self {
Self {
collection: left,
index: right,
}
}
}
impl AbstractNode for MapIndex {
fn define_types(&self, _context: &Context) -> Result<(), ValidationError> {
self.collection.define_types(_context)?;
self.index.define_types(_context)
}
fn validate(&self, context: &Context, _manage_memory: bool) -> Result<(), ValidationError> {
self.collection.validate(context, _manage_memory)?;
let collection_type = if let Some(r#type) = self.collection.expected_type(context)? {
r#type
} else {
return Err(ValidationError::ExpectedExpression(
self.collection.position(),
));
};
if let (Type::Map(fields), Expression::Identifier(identifier)) =
(collection_type, &self.index)
{
if !fields.contains_key(&identifier.node) {
return Err(ValidationError::FieldNotFound {
identifier: identifier.node.clone(),
position: identifier.position,
});
}
}
if let Expression::Identifier(_) = &self.index {
Ok(())
} else {
self.index.validate(context, _manage_memory)
}
}
fn evaluate(
self,
context: &Context,
_manage_memory: bool,
) -> Result