1use mln_conversion::Convertible;
2
3use crate::expression::{EvaluationContext, EvaluationError, EvaluationResult, Expr, Node};
4use crate::parsing_context::{ParseResult, ParsingContext};
5use crate::type_;
6use crate::type_::Type;
7use crate::utf8_op_helpers::{get_unicode_character_offset_on_validated_utf8, unicode_length_on_validated_utf8};
8use crate::value::{Value, type_of};
9
10fn normalize_index(index: i32, length: i32) -> i32 {
11 if index < 0 { index.wrapping_add(length) } else { index }
12}
13
14fn static_cast_int(f: f64) -> i32 {
17 if f > -2_147_483_649.0 && f < 2_147_483_648.0 { f as i32 } else { i32::MIN }
18}
19
20#[derive(Clone, PartialEq, mln_wire::Wire)]
22pub(crate) struct Slice {
23 input: Expr,
24 from_index: Expr,
25 to_index: Option<Expr>,
26}
27
28impl Slice {
29 pub(crate) fn get_type(&self) -> Type {
31 self.input.get_type()
32 }
33
34 fn evaluate_for_array_input(array: &[Value], from_index_value: i32, to_index_value: i32) -> Value {
35 let length = array.len() as i32;
36 let mut to_index_value = to_index_value;
37 if to_index_value == i32::MAX {
38 to_index_value = length;
39 }
40 let from_index_value = normalize_index(from_index_value, length);
41 to_index_value = normalize_index(to_index_value, length);
42
43 if from_index_value >= to_index_value {
44 return Value::Array(Vec::new());
45 }
46 to_index_value = to_index_value.min(length);
47
48 let mut result = Vec::with_capacity((to_index_value - from_index_value) as usize);
51 for index in from_index_value.max(0)..to_index_value {
52 result.push(array[index as usize].clone());
53 }
54 Value::Array(result)
55 }
56
57 fn evaluate_for_string_input(string: &str, from_index_value: i32, to_index_value: i32) -> Value {
58 let length_bytes = string.len();
59 let length = unicode_length_on_validated_utf8(string) as i32;
60 let to_index_value_bytes = if to_index_value == i32::MAX {
61 length_bytes
62 } else {
63 let to_index_value_chars = normalize_index(to_index_value, length);
64 get_unicode_character_offset_on_validated_utf8(string, to_index_value_chars as isize as usize)
66 };
67 let from_index_value_chars = normalize_index(from_index_value, length);
68 let from_index_value_bytes =
69 get_unicode_character_offset_on_validated_utf8(string, from_index_value_chars as isize as usize);
70
71 if from_index_value_bytes >= length_bytes || from_index_value_bytes >= to_index_value_bytes {
72 return Value::String(String::new());
73 }
74
75 Value::String(string[from_index_value_bytes..to_index_value_bytes].to_owned())
76 }
77
78 pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
79 debug_assert!(value.is_array());
80
81 let length = value.array_length();
82 if length != 3 && length != 4 {
83 ctx.error(format!("Expected 2 or 3 arguments, but found {} instead.", length - 1));
84 return None;
85 }
86
87 let input = ctx.parse(&value.array_member(1), 1, None, None);
88 let from_index = ctx.parse(&value.array_member(2), 2, Some(Type::Number), None);
89 let (Some(input), Some(from_index)) = (input, from_index) else {
90 return None;
91 };
92
93 let input_type = input.get_type();
94 if !(input_type.is_array() || input_type == Type::String || input_type == Type::Value) {
95 ctx.error(format!(
96 "Expected first argument to be of type array or string, but found {} instead",
97 type_::to_string(&input_type)
98 ));
99 return None;
100 }
101
102 let to_index =
103 if length == 4 { Some(ctx.parse(&value.array_member(3), 3, Some(Type::Number), None)?) } else { None };
104
105 Some(Expr::new(Node::Slice(Box::new(Slice { input, from_index, to_index }))))
106 }
107
108 pub(crate) fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
109 let evaluated_input = self.input.evaluate_ref(params)?;
110 let from_index_value = static_cast_int(self.from_index.eval_num(params)?);
111 let to_index_value = match &self.to_index {
112 Some(to_index) => static_cast_int(to_index.eval_num(params)?),
113 None => i32::MAX,
114 };
115
116 match &*evaluated_input {
117 Value::String(s) => Ok(Self::evaluate_for_string_input(s, from_index_value, to_index_value)),
118 Value::Array(v) => Ok(Self::evaluate_for_array_input(v, from_index_value, to_index_value)),
119 _ => Err(EvaluationError::new(format!(
120 "Expected first argument to be of type array or string, but found {} instead.",
121 type_::to_string(&type_of(&evaluated_input))
122 ))),
123 }
124 }
125
126 pub(crate) fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
127 visit(&self.input);
128 visit(&self.from_index);
129 if let Some(to_index) = &self.to_index {
130 visit(to_index);
131 }
132 }
133}