use crate::conversion::Convertible;
use crate::expression::forms::length::char_byte_offset;
use crate::expression::parse::{ParseResult, ParsingContext};
use crate::expression::type_::Type;
use crate::expression::value::{Value, type_of};
use crate::expression::{EvaluationContext, EvaluationError, EvaluationResult, Expr, Node, type_};
fn resolve_index(index: f64, len: usize) -> usize {
let len = len as f64;
let index = if index.is_nan() { 0.0 } else { index.trunc() };
(if index < 0.0 { (len + index).max(0.0) } else { index.min(len) }) as usize
}
#[derive(Clone, PartialEq, mln_wire::Wire)]
pub(crate) struct Slice {
input: Expr,
from_index: Expr,
to_index: Option<Expr>,
}
impl Slice {
pub(crate) fn type_(&self) -> Type {
self.input.type_()
}
fn evaluate_for_array_input(array: &[Value], from: f64, to: Option<f64>) -> Value {
let from = resolve_index(from, array.len());
let to = to.map_or(array.len(), |to| resolve_index(to, array.len()));
Value::Array(array.get(from..to).unwrap_or_default().to_vec())
}
fn evaluate_for_string_input(string: &str, from: f64, to: Option<f64>) -> Value {
let length = string.chars().count();
let from = resolve_index(from, length);
let to = to.map_or(length, |to| resolve_index(to, length));
if from >= to {
return Value::String(String::new());
}
let from_bytes = char_byte_offset(string, from);
let to_bytes = char_byte_offset(string, to);
Value::String(string[from_bytes..to_bytes].to_owned())
}
pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
debug_assert!(value.is_array());
let length = value.array_length();
if length != 3 && length != 4 {
ctx.error(format!("Expected 2 or 3 arguments, but found {} instead.", length - 1));
return None;
}
let input = ctx.parse(&value.array_member(1), 1, None, None);
let from_index = ctx.parse(&value.array_member(2), 2, Some(Type::Number), None);
let (Some(input), Some(from_index)) = (input, from_index) else {
return None;
};
let input_type = input.type_();
if !(input_type.is_array() || input_type == Type::String || input_type == Type::Value) {
ctx.error(format!(
"Expected first argument to be of type array or string, but found {} instead",
type_::to_string(&input_type)
));
return None;
}
let to_index =
if length == 4 { Some(ctx.parse(&value.array_member(3), 3, Some(Type::Number), None)?) } else { None };
Some(Expr::new(Node::Slice(Box::new(Slice { input, from_index, to_index }))))
}
pub(crate) fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
let evaluated_input = self.input.evaluate_ref(params)?;
let from = self.from_index.eval_num(params)?;
let to = self.to_index.as_ref().map(|to| to.eval_num(params)).transpose()?;
match &*evaluated_input {
Value::String(s) => Ok(Self::evaluate_for_string_input(s, from, to)),
Value::Array(v) => Ok(Self::evaluate_for_array_input(v, from, to)),
_ => Err(EvaluationError::new(format!(
"Expected first argument to be of type array or string, but found {} instead.",
type_::to_string(&type_of(&evaluated_input))
))),
}
}
pub(crate) fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
visit(&self.input);
visit(&self.from_index);
if let Some(to_index) = &self.to_index {
visit(to_index);
}
}
}