use mln_conversion::Convertible;
use crate::expression::{EvaluationContext, EvaluationError, EvaluationResult, Expr, Node};
use crate::parsing_context::{ParseResult, ParsingContext};
use crate::type_;
use crate::type_::Type;
use crate::utf8_op_helpers::{get_unicode_character_offset_on_validated_utf8, unicode_length_on_validated_utf8};
use crate::value::{Value, type_of};
fn normalize_index(index: i32, length: i32) -> i32 {
if index < 0 { index.wrapping_add(length) } else { index }
}
fn static_cast_int(f: f64) -> i32 {
if f > -2_147_483_649.0 && f < 2_147_483_648.0 { f as i32 } else { i32::MIN }
}
#[derive(Clone, PartialEq, mln_wire::Wire)]
pub(crate) struct Slice {
input: Expr,
from_index: Expr,
to_index: Option<Expr>,
}
impl Slice {
pub(crate) fn get_type(&self) -> Type {
self.input.get_type()
}
fn evaluate_for_array_input(array: &[Value], from_index_value: i32, to_index_value: i32) -> Value {
let length = array.len() as i32;
let mut to_index_value = to_index_value;
if to_index_value == i32::MAX {
to_index_value = length;
}
let from_index_value = normalize_index(from_index_value, length);
to_index_value = normalize_index(to_index_value, length);
if from_index_value >= to_index_value {
return Value::Array(Vec::new());
}
to_index_value = to_index_value.min(length);
let mut result = Vec::with_capacity((to_index_value - from_index_value) as usize);
for index in from_index_value.max(0)..to_index_value {
result.push(array[index as usize].clone());
}
Value::Array(result)
}
fn evaluate_for_string_input(string: &str, from_index_value: i32, to_index_value: i32) -> Value {
let length_bytes = string.len();
let length = unicode_length_on_validated_utf8(string) as i32;
let to_index_value_bytes = if to_index_value == i32::MAX {
length_bytes
} else {
let to_index_value_chars = normalize_index(to_index_value, length);
get_unicode_character_offset_on_validated_utf8(string, to_index_value_chars as isize as usize)
};
let from_index_value_chars = normalize_index(from_index_value, length);
let from_index_value_bytes =
get_unicode_character_offset_on_validated_utf8(string, from_index_value_chars as isize as usize);
if from_index_value_bytes >= length_bytes || from_index_value_bytes >= to_index_value_bytes {
return Value::String(String::new());
}
Value::String(string[from_index_value_bytes..to_index_value_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.get_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_index_value = static_cast_int(self.from_index.eval_num(params)?);
let to_index_value = match &self.to_index {
Some(to_index) => static_cast_int(to_index.eval_num(params)?),
None => i32::MAX,
};
match &*evaluated_input {
Value::String(s) => Ok(Self::evaluate_for_string_input(s, from_index_value, to_index_value)),
Value::Array(v) => Ok(Self::evaluate_for_array_input(v, from_index_value, to_index_value)),
_ => 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);
}
}
}