1use crate::expression::{
5 EvaluationContext, EvaluationError, EvaluationResult, Expression, ExpressionBase, Kind,
6 downcast,
7};
8use crate::parsing_context::{ParseResult, ParsingContext};
9use crate::type_;
10use crate::utf8_op_helpers::{
11 get_unicode_character_offset_on_validated_utf8, unicode_length_on_validated_utf8,
12};
13use crate::value::{Value, type_of};
14use mln_conversion::Convertible;
15
16fn normalize_index(index: i32, length: i32) -> i32 {
17 if index < 0 { index.wrapping_add(length) } else { index }
18}
19
20fn static_cast_int(f: f64) -> i32 {
23 if f > -2147483649.0 && f < 2147483648.0 {
24 f as i32
25 } else {
26 i32::MIN
27 }
28}
29
30pub struct Slice {
31 base: ExpressionBase,
32 input: Box<dyn Expression>,
33 from_index: Box<dyn Expression>,
34 to_index: Option<Box<dyn Expression>>,
35}
36
37impl Slice {
38 pub fn new(
39 input: Box<dyn Expression>,
40 from_index: Box<dyn Expression>,
41 to_index: Option<Box<dyn Expression>>,
42 ) -> Self {
43 let deps = input.dependencies()
44 | from_index.dependencies()
45 | to_index.as_ref().map_or(Default::default(), |e| e.dependencies());
46 Slice {
47 base: ExpressionBase::new(Kind::Slice, input.get_type().clone(), deps),
48 input,
49 from_index,
50 to_index,
51 }
52 }
53
54 fn evaluate_for_array_input(&self, array: &[Value], from_index_value: i32, to_index_value: i32) -> EvaluationResult {
55 let length = array.len() as i32;
56 let mut to_index_value = to_index_value;
57 if to_index_value == i32::MAX {
58 to_index_value = length;
59 }
60 let from_index_value = normalize_index(from_index_value, length);
61 to_index_value = normalize_index(to_index_value, length);
62
63 if from_index_value >= to_index_value {
64 return Ok(Value::Array(Vec::new()));
65 }
66 to_index_value = to_index_value.min(length);
67
68 let mut result = Vec::with_capacity((to_index_value - from_index_value) as usize);
71 for index in from_index_value.max(0)..to_index_value {
72 result.push(array[index as usize].clone());
73 }
74 Ok(Value::Array(result))
75 }
76
77 fn evaluate_for_string_input(&self, string: &str, from_index_value: i32, to_index_value: i32) -> EvaluationResult {
78 let length_bytes = string.len();
79 let length = unicode_length_on_validated_utf8(string) as i32;
80 let to_index_value_bytes = if to_index_value == i32::MAX {
81 length_bytes
82 } else {
83 let to_index_value_chars = normalize_index(to_index_value, length);
84 get_unicode_character_offset_on_validated_utf8(string, to_index_value_chars as isize as usize)
86 };
87 let from_index_value_chars = normalize_index(from_index_value, length);
88 let from_index_value_bytes =
89 get_unicode_character_offset_on_validated_utf8(string, from_index_value_chars as isize as usize);
90
91 if from_index_value_bytes >= length_bytes || from_index_value_bytes >= to_index_value_bytes {
92 return Ok(Value::String(String::new()));
93 }
94
95 Ok(Value::String(string[from_index_value_bytes..to_index_value_bytes].to_owned()))
96 }
97
98 pub fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
99 debug_assert!(value.is_array());
100
101 let length = value.array_length();
102 if length != 3 && length != 4 {
103 ctx.error(format!("Expected 2 or 3 arguments, but found {} instead.", length - 1));
104 return None;
105 }
106
107 let input = ctx.parse(&value.array_member(1), 1, None, None);
108 let from_index = ctx.parse(&value.array_member(2), 2, None, None);
109
110 let to_index = if length == 4 {
111 ctx.parse(&value.array_member(3), 3, None, None)
112 } else {
113 None
114 };
115
116 let (Some(input), Some(from_index)) = (input, from_index) else {
117 return None;
118 };
119
120 Some(Box::new(Slice::new(input, from_index, to_index)))
121 }
122}
123
124impl Expression for Slice {
125 fn base(&self) -> &ExpressionBase {
126 &self.base
127 }
128
129 fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
130 let evaluated_input = self.input.evaluate(params)?;
131 let evaluated_from_index = self.from_index.evaluate(params)?;
135 let Value::Number(from) = evaluated_from_index else {
136 return Err(EvaluationError::new(format!(
137 "Expected value to be of type number, but found {} instead.",
138 type_::to_string(&type_of(&evaluated_from_index))
139 )));
140 };
141
142 let from_index_value = static_cast_int(from);
143 let mut to_index_value = i32::MAX;
144
145 if let Some(to_index) = &self.to_index {
146 let evaluated_to_index = to_index.evaluate(params)?;
147 let Value::Number(to) = evaluated_to_index else {
148 return Err(EvaluationError::new(format!(
150 "Expected value to be of type number, but found {} instead.",
151 type_::to_string(&type_of(&evaluated_from_index))
152 )));
153 };
154 to_index_value = static_cast_int(to);
155 }
156
157 match &evaluated_input {
158 Value::String(s) => self.evaluate_for_string_input(s, from_index_value, to_index_value),
159 Value::Array(v) => self.evaluate_for_array_input(v, from_index_value, to_index_value),
160 _ => Err(EvaluationError::new(format!(
161 "Expected first argument to be of type array or string, but found {} instead.",
162 type_::to_string(&type_of(&evaluated_input))
163 ))),
164 }
165 }
166
167 fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression)) {
168 visit(&*self.input);
169 visit(&*self.from_index);
170 if let Some(to_index) = &self.to_index {
171 visit(&**to_index);
172 }
173 }
174
175 fn equals(&self, e: &dyn Expression) -> bool {
176 if e.get_kind() == Kind::Slice {
177 let rhs = downcast::<Slice>(e).expect("Slice");
178 let to_index_equal = match (&self.to_index, &rhs.to_index) {
179 (Some(l), Some(r)) => l.equals(&**r),
180 (None, None) => true,
181 _ => false,
182 };
183 return self.input.equals(&*rhs.input) && self.from_index.equals(&*rhs.from_index) && to_index_equal;
184 }
185 false
186 }
187
188 fn possible_outputs(&self) -> Vec<Option<Value>> {
189 vec![None]
190 }
191
192 fn get_operator(&self) -> String {
193 "slice".to_owned()
194 }
195}