mln_expression/
index_of.rs1use crate::expression::{
5 EvaluationContext, EvaluationError, EvaluationResult, Expression, ExpressionBase, Kind,
6 downcast,
7};
8use crate::parsing_context::{ParseResult, ParsingContext};
9use crate::type_::{self, 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;
15use mln_util::string::to_string_double;
16
17pub struct IndexOf {
18 base: ExpressionBase,
19 keyword: Box<dyn Expression>,
20 input: Box<dyn Expression>,
21 from_index: Option<Box<dyn Expression>>,
22}
23
24impl IndexOf {
25 pub fn new(
26 keyword: Box<dyn Expression>,
27 input: Box<dyn Expression>,
28 from_index: Option<Box<dyn Expression>>,
29 ) -> Self {
30 let deps = keyword.dependencies()
31 | input.dependencies()
32 | from_index.as_ref().map_or(Default::default(), |e| e.dependencies());
33 IndexOf {
34 base: ExpressionBase::new(Kind::IndexOf, Type::Number, deps),
35 keyword,
36 input,
37 from_index,
38 }
39 }
40
41 fn evaluate_for_array_input(&self, array: &[Value], keyword_value: &Value, from_index_value: usize) -> EvaluationResult {
42 for index in from_index_value..array.len() {
43 if array[index] == *keyword_value {
44 return Ok(Value::Number(index as f64));
45 }
46 }
47 Ok(Value::Number(-1.0))
48 }
49
50 fn evaluate_for_string_input(&self, string: &str, keyword_value: &Value, from_index_value: usize) -> EvaluationResult {
51 let keyword_string = match keyword_value {
52 Value::String(s) => s.clone(),
53 Value::Bool(b) => if *b { "true" } else { "false" }.to_owned(),
54 Value::Null => "null".to_owned(),
55 Value::Number(n) => to_string_double(*n),
56 _ => {
57 debug_assert!(false);
60 String::new()
61 }
62 };
63 let from_index_byte_offset = get_unicode_character_offset_on_validated_utf8(string, from_index_value);
64 let Some(byte_index) = string[from_index_byte_offset..]
65 .find(keyword_string.as_str())
66 .map(|i| i + from_index_byte_offset)
67 else {
68 return Ok(Value::Number(-1.0));
69 };
70 let prefix = &string[..byte_index];
71 let index = unicode_length_on_validated_utf8(prefix);
72 Ok(Value::Number(index as f64))
73 }
74
75 pub fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
76 debug_assert!(value.is_array());
77
78 let length = value.array_length();
79 if length != 3 && length != 4 {
80 ctx.error(format!("Expected 2 or 3 arguments, but found {} instead.", length - 1));
81 return None;
82 }
83
84 let keyword = ctx.parse(&value.array_member(1), 1, None, None);
85 let input = ctx.parse(&value.array_member(2), 2, None, None);
86
87 let from_index = if length == 4 {
88 ctx.parse(&value.array_member(3), 3, None, None)
89 } else {
90 None
91 };
92
93 let (Some(keyword), Some(input)) = (keyword, input) else {
94 return None;
95 };
96
97 Some(Box::new(IndexOf::new(keyword, input, from_index)))
98 }
99}
100
101impl Expression for IndexOf {
102 fn base(&self) -> &ExpressionBase {
103 &self.base
104 }
105
106 fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
107 let evaluated_keyword = self.keyword.evaluate(params);
108 let evaluated_input = self.input.evaluate(params);
109 let evaluated_keyword = evaluated_keyword?;
110 let evaluated_input = evaluated_input?;
111
112 if !matches!(
113 evaluated_keyword,
114 Value::Number(_) | Value::String(_) | Value::Bool(_) | Value::Null
115 ) {
116 return Err(EvaluationError::new(format!(
117 "Expected first argument to be of type boolean, string, number or null, but found {} instead.",
118 type_::to_string(&type_of(&evaluated_keyword))
119 )));
120 }
121
122 let mut from_index_value: usize = 0;
123 if let Some(from_index) = &self.from_index {
124 let evaluated_from_index = from_index.evaluate(params)?;
125 let Value::Number(f) = evaluated_from_index else {
126 return Err(EvaluationError::new(format!(
127 "Expected third argument to be of type number, but found {} instead.",
128 type_::to_string(&type_of(&evaluated_from_index))
129 )));
130 };
131 let f = if f < 0.0 { 0.0 } else { f };
133 from_index_value = f as usize;
134 }
135
136 match &evaluated_input {
137 Value::String(s) => self.evaluate_for_string_input(s, &evaluated_keyword, from_index_value),
138 Value::Array(v) => self.evaluate_for_array_input(v, &evaluated_keyword, from_index_value),
139 _ => Err(EvaluationError::new(format!(
140 "Expected second argument to be of type array or string, but found {} instead.",
141 type_::to_string(&type_of(&evaluated_input))
142 ))),
143 }
144 }
145
146 fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression)) {
147 visit(&*self.keyword);
148 visit(&*self.input);
149 if let Some(from_index) = &self.from_index {
150 visit(&**from_index);
151 }
152 }
153
154 fn equals(&self, e: &dyn Expression) -> bool {
155 if e.get_kind() == Kind::IndexOf {
156 let rhs = downcast::<IndexOf>(e).expect("IndexOf");
157 let from_index_equal = match (&self.from_index, &rhs.from_index) {
158 (Some(l), Some(r)) => l.equals(&**r),
159 (None, None) => true,
160 _ => false,
161 };
162 return self.keyword.equals(&*rhs.keyword) && self.input.equals(&*rhs.input) && from_index_equal;
163 }
164 false
165 }
166
167 fn possible_outputs(&self) -> Vec<Option<Value>> {
168 vec![None]
169 }
170
171 fn get_operator(&self) -> String {
172 "index-of".to_owned()
173 }
174}