Skip to main content

mln_expression/
index_of.rs

1use mln_conversion::Convertible;
2use mln_util::string::to_string_double;
3
4use crate::expression::{EvalResult, EvaluationContext, EvaluationError, Expr, Node};
5use crate::parsing_context::{ParseResult, ParsingContext};
6use crate::type_;
7use crate::type_::Type;
8use crate::utf8_op_helpers::{get_unicode_character_offset_on_validated_utf8, unicode_length_on_validated_utf8};
9use crate::value::{Value, type_of};
10
11/// `["index-of", keyword, input, from_index?]`.
12#[derive(Clone, PartialEq, mln_wire::Wire)]
13pub(crate) struct IndexOf {
14    keyword: Expr,
15    input: Expr,
16    from_index: Option<Expr>,
17}
18
19impl IndexOf {
20    fn evaluate_for_array_input(array: &[Value], keyword_value: &Value, from_index_value: usize) -> f64 {
21        for (index, value) in array.iter().enumerate().skip(from_index_value) {
22            if *value == *keyword_value {
23                return index as f64;
24            }
25        }
26        -1.0
27    }
28
29    fn evaluate_for_string_input(string: &str, keyword_value: &Value, from_index_value: usize) -> f64 {
30        let keyword_string = match keyword_value {
31            Value::String(s) => s.clone(),
32            Value::Bool(b) => if *b { "true" } else { "false" }.to_owned(),
33            Value::Null => "null".to_owned(),
34            Value::Number(n) => to_string_double(*n),
35            _ => {
36                // it should be impossible to get here - we do validation in
37                // evaluate()
38                debug_assert!(false);
39                String::new()
40            }
41        };
42        let from_index_byte_offset = get_unicode_character_offset_on_validated_utf8(string, from_index_value);
43        let Some(byte_index) =
44            string[from_index_byte_offset..].find(keyword_string.as_str()).map(|i| i + from_index_byte_offset)
45        else {
46            return -1.0;
47        };
48        let prefix = &string[..byte_index];
49        let index = unicode_length_on_validated_utf8(prefix);
50        index as f64
51    }
52
53    pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
54        debug_assert!(value.is_array());
55
56        let length = value.array_length();
57        if length != 3 && length != 4 {
58            ctx.error(format!("Expected 2 or 3 arguments, but found {} instead.", length - 1));
59            return None;
60        }
61
62        let keyword = ctx.parse(&value.array_member(1), 1, None, None);
63        let input = ctx.parse(&value.array_member(2), 2, None, None);
64        let (Some(keyword), Some(input)) = (keyword, input) else {
65            return None;
66        };
67
68        let keyword_type = keyword.get_type();
69        if ![Type::Boolean, Type::String, Type::Number, Type::Null, Type::Value].contains(&keyword_type) {
70            ctx.error(format!(
71                "Expected first argument to be of type boolean, string, number or null, but found {} instead",
72                type_::to_string(&keyword_type)
73            ));
74            return None;
75        }
76
77        let from_index =
78            if length == 4 { Some(ctx.parse(&value.array_member(3), 3, Some(Type::Number), None)?) } else { None };
79
80        Some(Expr::new(Node::IndexOf(Box::new(IndexOf { keyword, input, from_index }))))
81    }
82
83    pub(crate) fn eval_num(&self, params: &EvaluationContext<'_>) -> EvalResult<f64> {
84        let evaluated_keyword = self.keyword.evaluate_ref(params);
85        let evaluated_input = self.input.evaluate_ref(params);
86        let evaluated_keyword = evaluated_keyword?;
87        let evaluated_input = evaluated_input?;
88
89        if !matches!(*evaluated_keyword, Value::Number(_) | Value::String(_) | Value::Bool(_) | Value::Null) {
90            return Err(EvaluationError::new(format!(
91                "Expected first argument to be of type boolean, string, number or null, but found {} instead.",
92                type_::to_string(&type_of(&evaluated_keyword))
93            )));
94        }
95
96        // A negative or NaN index starts at 0.
97        let from_index_value = match &self.from_index {
98            Some(from_index) => from_index.eval_num(params)?.max(0.0) as usize,
99            None => 0,
100        };
101
102        match &*evaluated_input {
103            Value::String(s) => Ok(Self::evaluate_for_string_input(s, &evaluated_keyword, from_index_value)),
104            Value::Array(v) => Ok(Self::evaluate_for_array_input(v, &evaluated_keyword, from_index_value)),
105            _ => Err(EvaluationError::new(format!(
106                "Expected second argument to be of type array or string, but found {} instead.",
107                type_::to_string(&type_of(&evaluated_input))
108            ))),
109        }
110    }
111
112    pub(crate) fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
113        visit(&self.keyword);
114        visit(&self.input);
115        if let Some(from_index) = &self.from_index {
116            visit(from_index);
117        }
118    }
119}