1use 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::unicode_length_on_validated_utf8;
11use crate::value::{Value, type_of};
12use mln_conversion::Convertible;
13
14pub struct Length {
15 base: ExpressionBase,
16 input: Box<dyn Expression>,
17}
18
19impl Length {
20 pub fn new(input: Box<dyn Expression>) -> Self {
21 Length {
22 base: ExpressionBase::new(Kind::Length, Type::Number, input.dependencies()),
23 input,
24 }
25 }
26
27 pub fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
28 let length = value.array_length();
29
30 if length != 2 {
31 ctx.error(format!("Expected one argument, but found {length} instead."));
32 return None;
33 }
34
35 let input = ctx.parse(&value.array_member(1), 1, None, None)?;
36
37 let t = input.get_type();
38 if !t.is_array() && *t != Type::String && *t != Type::Value {
39 ctx.error(format!(
40 "Expected argument of type string or array, but found {} instead.",
41 type_::to_string(t)
42 ));
43 return None;
44 }
45
46 Some(Box::new(Length::new(input)))
47 }
48}
49
50impl Expression for Length {
51 fn base(&self) -> &ExpressionBase {
52 &self.base
53 }
54
55 fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
56 let value = self.input.evaluate(params)?;
57 match &value {
58 Value::String(s) => Ok(Value::Number(unicode_length_on_validated_utf8(s) as f64)),
59 Value::Array(v) => Ok(Value::Number(v.len() as f64)),
60 _ => Err(EvaluationError::new(format!(
61 "Expected value to be of type string or array, but found {} instead.",
62 type_::to_string(&type_of(&value))
63 ))),
64 }
65 }
66
67 fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression)) {
68 visit(&*self.input);
69 }
70
71 fn equals(&self, e: &dyn Expression) -> bool {
72 if e.get_kind() == Kind::Length {
73 let eq = downcast::<Length>(e).expect("Length");
74 return eq.input.equals(&*self.input);
75 }
76 false
77 }
78
79 fn possible_outputs(&self) -> Vec<Option<Value>> {
80 vec![None]
81 }
82
83 fn get_operator(&self) -> String {
84 "length".to_owned()
85 }
86}