1use mln_conversion::Convertible;
5
6use crate::expression::{EvalResult, EvaluationContext, EvaluationError, Expr, Node};
7use crate::parsing_context::{ParseResult, ParsingContext};
8use crate::type_::{self, Type};
9use crate::utf8_op_helpers::unicode_length_on_validated_utf8;
10use crate::value::{Value, type_of};
11
12pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
13 let length = value.array_length();
14
15 if length != 2 {
16 ctx.error(format!("Expected one argument, but found {length} instead."));
17 return None;
18 }
19
20 let input = ctx.parse(&value.array_member(1), 1, None, None)?;
21
22 let t = &input.get_type();
23 if !t.is_array() && *t != Type::String && *t != Type::Value {
24 ctx.error(format!("Expected argument of type string or array, but found {} instead.", type_::to_string(t)));
25 return None;
26 }
27
28 Some(Expr::new(Node::Length(Box::new(input))))
29}
30
31pub(crate) fn evaluate(input: &Expr, params: &EvaluationContext<'_>) -> EvalResult<f64> {
33 let value = input.evaluate_ref(params)?;
34 match &*value {
35 Value::String(s) => Ok(unicode_length_on_validated_utf8(s) as f64),
36 Value::Array(v) => Ok(v.len() as f64),
37 _ => Err(EvaluationError::new(format!(
38 "Expected value to be of type string or array, but found {} instead.",
39 type_::to_string(&type_of(&value))
40 ))),
41 }
42}