Skip to main content

mln_expression/
assertion.rs

1use std::borrow::Cow;
2
3use feature::Value as MbglValue;
4use mln_conversion::Convertible;
5
6use crate::check_subtype::check_subtype;
7use crate::expression::{EvalResult, EvaluationContext, EvaluationError, EvaluationResult, Expr, Node, Output};
8use crate::functions::Role;
9use crate::functions::builtin::{feature_unavailable, identifier_to_mbgl};
10use crate::parsing_context::{ParseResult, ParsingContext};
11use crate::type_::{self, Type};
12use crate::value::{Value, type_of};
13
14/// `["number", ...]` and the other type assertions: the first input whose
15/// value has the type, or an error.
16#[derive(Clone, PartialEq, mln_wire::Wire)]
17pub(crate) struct Assertion {
18    type_: Type,
19    inputs: Box<[Expr]>,
20    /// Whether each input has the asserted type, so its typed evaluation
21    /// needs no check.
22    typed: Box<[bool]>,
23}
24
25fn assertion_type(name: &str) -> Option<Type> {
26    match name {
27        "string" => Some(Type::String),
28        "number" => Some(Type::Number),
29        "boolean" => Some(Type::Boolean),
30        "object" => Some(Type::Object),
31        _ => None,
32    }
33}
34
35impl Assertion {
36    pub(crate) fn new_expr(type_: Type, inputs: Vec<Expr>) -> Expr {
37        assert!(!inputs.is_empty(), "Assertion without inputs");
38        let typed = inputs.iter().map(|input| input.get_type() == type_).collect();
39        Expr::new(Node::Assertion(Box::new(Assertion { type_, inputs: inputs.into(), typed })))
40    }
41
42    pub(crate) fn get_type(&self) -> &Type {
43        &self.type_
44    }
45
46    pub(crate) fn inputs(&self) -> &[Expr] {
47        &self.inputs
48    }
49
50    pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
51        let length = value.array_length();
52
53        if length < 2 {
54            ctx.error("Expected at least one argument.".to_owned());
55            return None;
56        }
57
58        let mut i = 1;
59
60        let Some(name) = value.array_member(0).to_string() else {
61            ctx.error("Expected the assertion name to be a string.".to_owned());
62            return None;
63        };
64        let type_ = if name == "array" {
65            let item_type;
66            if length > 2 {
67                let item_type_name = value.array_member(1).to_string();
68                let it = item_type_name.as_deref().and_then(assertion_type);
69                match it {
70                    Some(t) if t != Type::Object => item_type = t,
71                    _ => {
72                        ctx.error_at(
73                            r#"The item type argument of "array" must be one of string, number, boolean"#.to_owned(),
74                            1,
75                        );
76                        return None;
77                    }
78                }
79                i += 1;
80            } else {
81                item_type = Type::Value;
82            }
83
84            let mut n = None;
85            if length > 3 {
86                let m = value.array_member(2);
87                let num = m.to_number();
88                if !m.is_undefined() && num.is_none_or(|v| v < 0.0 || v != v.floor()) {
89                    ctx.error_at(r#"The length argument to "array" must be a positive integer literal."#.to_owned(), 2);
90                    return None;
91                }
92                if let Some(num) = num {
93                    n = Some(num as usize);
94                }
95                i += 1;
96            }
97
98            type_::Array::with_n(item_type, n).into()
99        } else {
100            let Some(type_) = assertion_type(&name) else {
101                ctx.error(format!("Unknown assertion type {name}."));
102                return None;
103            };
104            type_
105        };
106
107        let mut parsed = Vec::with_capacity(length - 1);
108        while i < length {
109            let input = ctx.parse(&value.array_member(i), i, Some(Type::Value), None)?;
110            parsed.push(input);
111            i += 1;
112        }
113
114        Some(Assertion::new_expr(type_, parsed))
115    }
116
117    pub(crate) fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
118        // The parser makes an assertion of at least one input.
119        let mut mismatch = Value::Null;
120        for input in &self.inputs {
121            let value = input.evaluate(params)?;
122            if check_subtype(&self.type_, &type_of(&value)).is_none() {
123                return Ok(value);
124            }
125            mismatch = value;
126        }
127        Err(self.mismatch(&mismatch))
128    }
129
130    fn mismatch(&self, value: &Value) -> EvaluationError {
131        EvaluationError::type_mismatch(&self.type_, value)
132    }
133
134    /// The typed evaluations: an input of the asserted type evaluates typed,
135    /// and a feature accessor (`["get", k]`, `["id"]`) is read without
136    /// building a value first.
137    fn eval_typed<'e, T: Output<'e>>(
138        &'e self,
139        params: &EvaluationContext<'_>,
140        from_feature: impl Fn(&MbglValue) -> Option<T>,
141    ) -> EvalResult<T> {
142        let mut mismatch = Value::Null;
143        for (input, &typed) in self.inputs.iter().zip(&self.typed) {
144            if typed {
145                return T::eval(input, params);
146            }
147            if let Some(read) = read_feature(input, params) {
148                match read? {
149                    Some(value) => match from_feature(&value) {
150                        Some(typed) => return Ok(typed),
151                        None => mismatch = crate::value::from_mbgl_value_owned(value),
152                    },
153                    None => mismatch = Value::Null,
154                }
155                continue;
156            }
157            let value = input.evaluate(params)?;
158            if check_subtype(&self.type_, &type_of(&value)).is_none() {
159                return T::from_value(value);
160            }
161            mismatch = value;
162        }
163        Err(self.mismatch(&mismatch))
164    }
165
166    pub(crate) fn eval_num(&self, params: &EvaluationContext<'_>) -> EvalResult<f64> {
167        self.eval_typed(params, |v| match *v {
168            MbglValue::Double(n) => Some(n),
169            MbglValue::Uint(n) => Some(n as f64),
170            MbglValue::Int(n) => Some(n as f64),
171            _ => None,
172        })
173    }
174
175    pub(crate) fn eval_bool(&self, params: &EvaluationContext<'_>) -> EvalResult<bool> {
176        self.eval_typed(params, |v| match *v {
177            MbglValue::Bool(b) => Some(b),
178            _ => None,
179        })
180    }
181
182    pub(crate) fn eval_str<'e>(&'e self, params: &EvaluationContext<'_>) -> EvalResult<Cow<'e, str>> {
183        self.eval_typed(params, |v| match v {
184            MbglValue::String(s) => Some(Cow::Owned(s.clone())),
185            _ => None,
186        })
187    }
188
189    pub(crate) fn serialize(&self) -> MbglValue {
190        let mut serialized = vec![MbglValue::String(self.get_operator().to_owned())];
191
192        if let Type::Array(array) = &self.type_
193            && matches!(array.item_type, Type::String | Type::Number | Type::Boolean)
194        {
195            serialized.push(MbglValue::String(type_::to_string(&array.item_type)));
196            if let Some(n) = array.n {
197                serialized.push(MbglValue::Uint(n as u64));
198            } else if self.inputs.len() > 1 {
199                serialized.push(MbglValue::Null);
200            }
201        }
202
203        for input in &self.inputs {
204            serialized.push(input.serialize());
205        }
206
207        MbglValue::Array(serialized)
208    }
209
210    pub(crate) fn get_operator(&self) -> &'static str {
211        match self.type_ {
212            Type::Array(_) => "array",
213            Type::String => "string",
214            Type::Number => "number",
215            Type::Boolean => "boolean",
216            Type::Object => "object",
217            _ => unreachable!("assertion to {}", self.type_),
218        }
219    }
220}
221
222/// The feature value or id that `input` reads, when it is `["get", key]`
223/// with a literal key or `["id"]`: `Some(Ok(None))` when the feature lacks
224/// it, and `None` when `input` is another expression.
225fn read_feature(input: &Expr, params: &EvaluationContext<'_>) -> Option<EvalResult<Option<MbglValue>>> {
226    let compound = input.as_compound()?;
227    let overload = compound.overload();
228    match overload.role {
229        Role::FeatureProperty if overload.result == Type::Value => {
230            let key = compound.args()[0].literal_value()?.as_str()?;
231            Some(match params.feature {
232                Some(feature) => Ok(feature.get_value(key)),
233                None => Err(feature_unavailable()),
234            })
235        }
236        Role::FeatureId => Some(match params.feature {
237            Some(feature) => Ok(identifier_to_mbgl(feature.get_id())),
238            None => Err(feature_unavailable()),
239        }),
240        _ => None,
241    }
242}