Skip to main content

mln_expression/
assertion.rs

1// Ports include/mln/style/expression/assertion.hpp and
2// src/mln/style/expression/assertion.cpp.
3
4use crate::check_subtype::check_subtype;
5use crate::expression::{
6    EvaluationContext, EvaluationError, EvaluationResult, Expression, ExpressionBase, Kind,
7    children_equal, collect_dependencies, downcast,
8};
9use crate::parsing_context::{ParseResult, ParsingContext};
10use crate::type_::{self, Type};
11use crate::value::{Value, type_of};
12use maplibre_native_base::Value as MbglValue;
13use mln_conversion::Convertible;
14
15pub struct Assertion {
16    base: ExpressionBase,
17    inputs: Vec<Box<dyn Expression>>,
18}
19
20fn assertion_type(name: &str) -> Option<Type> {
21    match name {
22        "string" => Some(Type::String),
23        "image" => Some(Type::String), // TODO: replace once we implement image expressions
24        "number" => Some(Type::Number),
25        "boolean" => Some(Type::Boolean),
26        "object" => Some(Type::Object),
27        _ => None,
28    }
29}
30
31impl Assertion {
32    pub fn new(type_: Type, inputs: Vec<Box<dyn Expression>>) -> Self {
33        assert!(!inputs.is_empty());
34        Assertion {
35            base: ExpressionBase::new(Kind::Assertion, type_, collect_dependencies(&inputs)),
36            inputs,
37        }
38    }
39
40    pub fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
41        let length = value.array_length();
42
43        if length < 2 {
44            ctx.error("Expected at least one argument.".to_owned());
45            return None;
46        }
47
48        let mut i = 1;
49        let type_;
50
51        let name = value.array_member(0).to_string().expect("operator name");
52        if name == "array" {
53            let item_type;
54            if length > 2 {
55                let item_type_name = value.array_member(1).to_string();
56                let it = item_type_name.as_deref().and_then(assertion_type);
57                match it {
58                    Some(t) if t != Type::Object => item_type = t,
59                    _ => {
60                        ctx.error_at(
61                            r#"The item type argument of "array" must be one of string, number, boolean"#
62                                .to_owned(),
63                            1,
64                        );
65                        return None;
66                    }
67                }
68                i += 1;
69            } else {
70                item_type = Type::Value;
71            }
72
73            let mut n = None;
74            if length > 3 {
75                let m = value.array_member(2);
76                let num = m.to_number();
77                if !m.is_undefined() && num.is_none_or(|v| v < 0.0 || v != v.floor()) {
78                    ctx.error_at(
79                        r#"The length argument to "array" must be a positive integer literal."#
80                            .to_owned(),
81                        2,
82                    );
83                    return None;
84                }
85                if let Some(num) = num {
86                    n = Some(num as usize);
87                }
88                i += 1;
89            }
90
91            type_ = type_::Array::with_n(item_type, n).into();
92        } else {
93            type_ = assertion_type(&name).expect("assertion type");
94        }
95
96        let mut parsed = Vec::with_capacity(length - 1);
97        while i < length {
98            let input = ctx.parse(&value.array_member(i), i, Some(Type::Value), None)?;
99            parsed.push(input);
100            i += 1;
101        }
102
103        Some(Box::new(Assertion::new(type_, parsed)))
104    }
105}
106
107impl Expression for Assertion {
108    fn base(&self) -> &ExpressionBase {
109        &self.base
110    }
111
112    fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
113        for (i, input) in self.inputs.iter().enumerate() {
114            let value = input.evaluate(params)?;
115            if check_subtype(self.get_type(), &type_of(&value)).is_none() {
116                return Ok(value);
117            } else if i == self.inputs.len() - 1 {
118                return Err(EvaluationError::new(format!(
119                    "Expected value to be of type {}, but found {} instead.",
120                    type_::to_string(self.get_type()),
121                    type_::to_string(&type_of(&value))
122                )));
123            }
124        }
125
126        unreachable!("Assertion without inputs")
127    }
128
129    fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression)) {
130        for input in &self.inputs {
131            visit(&**input);
132        }
133    }
134
135    fn equals(&self, e: &dyn Expression) -> bool {
136        if e.get_kind() == Kind::Assertion {
137            let rhs = downcast::<Assertion>(e).expect("Assertion");
138            return self.get_type() == rhs.get_type() && children_equal(&self.inputs, &rhs.inputs);
139        }
140        false
141    }
142
143    fn possible_outputs(&self) -> Vec<Option<Value>> {
144        let mut result = Vec::new();
145        for input in &self.inputs {
146            result.extend(input.possible_outputs());
147        }
148        result
149    }
150
151    fn serialize(&self) -> MbglValue {
152        let mut serialized = vec![MbglValue::String(self.get_operator())];
153
154        if let Type::Array(array) = self.get_type() {
155            if matches!(array.item_type, Type::String | Type::Number | Type::Boolean) {
156                serialized.push(MbglValue::String(type_::to_string(&array.item_type)));
157                if let Some(n) = array.n {
158                    serialized.push(MbglValue::Uint(n as u64));
159                } else if self.inputs.len() > 1 {
160                    serialized.push(MbglValue::Null);
161                }
162            }
163        }
164
165        for input in &self.inputs {
166            serialized.push(input.serialize());
167        }
168
169        MbglValue::Array(serialized)
170    }
171
172    fn get_operator(&self) -> String {
173        if self.get_type().is_array() {
174            "array".to_owned()
175        } else {
176            type_::to_string(self.get_type())
177        }
178    }
179}