Skip to main content

mln_expression/
parsing_context.rs

1// Ports include/mln/style/expression/parsing_context.hpp and
2// src/mln/style/expression/parsing_context.cpp.
3
4use crate::assertion::Assertion;
5use crate::at::At;
6use crate::boolean_operator::{All, Any};
7use crate::case::Case;
8use crate::check_subtype::check_subtype;
9use crate::coalesce::Coalesce;
10use crate::coercion::Coercion;
11use crate::collator_expression::CollatorExpression;
12use crate::comparison::parse_comparison;
13use crate::compound_expression::{CompoundExpression, parse_compound_expression};
14use crate::distance::Distance;
15use crate::expression::{EvaluationContext, Expression, Kind, downcast};
16use crate::find_zoom_curve::{ZoomCurve, find_zoom_curve};
17use crate::format_expression::FormatExpression;
18use crate::image_expression::ImageExpression;
19use crate::in_::In;
20use crate::index_of::IndexOf;
21use crate::interpolate::parse_interpolate;
22use crate::is_constant::{is_feature_constant, is_global_property_constant, is_zoom_constant};
23use crate::let_::{Let, Var};
24use crate::length::Length;
25use crate::literal::Literal;
26use crate::match_::parse_match;
27use crate::number_format::NumberFormat;
28use crate::semiliteral::Semiliteral;
29use crate::slice::Slice;
30use crate::step::Step;
31use crate::type_::Type;
32use crate::value::Value;
33use crate::within::Within;
34use mln_conversion::{Convertible, get_json_type};
35use std::cell::RefCell;
36use std::collections::BTreeMap;
37use std::rc::Rc;
38use std::sync::Arc;
39
40/// `expression::ParsingError`.
41#[derive(Clone, Debug, Default, PartialEq, Eq)]
42pub struct ParsingError {
43    pub message: String,
44    pub key: String,
45}
46
47/// `expression::ParseResult` (`std::optional<std::unique_ptr<Expression>>`).
48pub type ParseResult = Option<Box<dyn Expression>>;
49
50/// The bindings of a `let` scope (`std::map<std::string, std::shared_ptr<Expression>>`).
51pub type Bindings = BTreeMap<String, Arc<dyn Expression>>;
52
53/// `detail::Scope`.
54pub struct Scope {
55    bindings: Bindings,
56    parent: Option<Rc<Scope>>,
57}
58
59impl Scope {
60    pub fn new(bindings: Bindings, parent: Option<Rc<Scope>>) -> Self {
61        Scope { bindings, parent }
62    }
63
64    pub fn get(&self, name: &str) -> Option<Arc<dyn Expression>> {
65        if let Some(binding) = self.bindings.get(name) {
66            Some(binding.clone())
67        } else if let Some(parent) = &self.parent {
68            parent.get(name)
69        } else {
70            None
71        }
72    }
73}
74
75/// Controls the annotation behavior of the parser when encountering an
76/// expression whose type is not a subtype of the expected type. The default
77/// behavior, used when `Option<TypeAnnotationOption>` is `None`, is as
78/// follows:
79///
80/// When we expect a number, string, boolean, or array but have a value, wrap
81/// it in an assertion. When we expect a color or formatted string, but have a
82/// string or value, wrap it in a coercion. Otherwise, we do static
83/// type-checking.
84///
85/// These behaviors are overridable for:
86///   * The "coalesce" operator, which needs to omit type annotations.
87///   * String-valued properties (e.g. `text-field`), where coercion is more
88///     convenient than assertion.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub enum TypeAnnotationOption {
91    Coerce,
92    Assert,
93    Omit,
94}
95
96/// `expression::ParsingContext`.
97pub struct ParsingContext {
98    key: String,
99    expected: Option<Type>,
100    scope: Option<Rc<Scope>>,
101    errors: Rc<RefCell<Vec<ParsingError>>>,
102}
103
104impl Default for ParsingContext {
105    fn default() -> Self {
106        ParsingContext {
107            key: String::new(),
108            expected: None,
109            scope: None,
110            errors: Rc::new(RefCell::new(Vec::new())),
111        }
112    }
113}
114
115const REQUIRED_PROPS: [&str; 6] = [
116    "zoom",
117    "heatmap-density",
118    "line-progress",
119    "accumulated",
120    "elevation",
121    "global-state",
122];
123
124fn is_constant(expression: &dyn Expression) -> bool {
125    let kind = expression.get_kind();
126
127    if kind == Kind::Var {
128        let var_expression = downcast::<Var>(expression).expect("Var");
129        return is_constant(&**var_expression.get_bound_expression());
130    } else if kind == Kind::CompoundExpression {
131        let compound = downcast::<CompoundExpression>(expression).expect("CompoundExpression");
132        if compound.get_operator() == "error" {
133            return false;
134        }
135    }
136
137    let is_type_annotation = kind == Kind::Coercion || kind == Kind::Assertion;
138
139    let mut children_constant = true;
140    expression.each_child(&mut |child| {
141        // We can _almost_ assume that if `expressions` children are constant,
142        // they would already have been evaluated to Literal values when they
143        // were parsed. Type annotations are the exception, because they might
144        // have been inferred and added after a child was parsed.
145
146        // So we recurse into isConstant() for the children of type
147        // annotations, but otherwise simply check whether they are Literals.
148        if is_type_annotation {
149            children_constant = children_constant && is_constant(child);
150        } else {
151            children_constant = children_constant && child.get_kind() == Kind::Literal;
152        }
153    });
154
155    children_constant
156        && is_feature_constant(expression)
157        && is_global_property_constant(expression, &REQUIRED_PROPS)
158}
159
160type ParseFunction = fn(&Convertible<'_>, &mut ParsingContext) -> ParseResult;
161
162/// The `expressionRegistry` of parsing_context.cpp.
163fn expression_registry(name: &str) -> Option<ParseFunction> {
164    Some(match name {
165        "==" | "!=" | ">" | "<" | ">=" | "<=" => parse_comparison,
166        "all" => All::parse,
167        "any" => Any::parse,
168        "array" => Assertion::parse,
169        "at" => At::parse,
170        "in" => In::parse,
171        "boolean" => Assertion::parse,
172        "case" => Case::parse,
173        "coalesce" => Coalesce::parse,
174        "collator" => CollatorExpression::parse,
175        "distance" => Distance::parse,
176        "format" => FormatExpression::parse,
177        "image" => ImageExpression::parse,
178        "interpolate" | "interpolate-hcl" | "interpolate-lab" => parse_interpolate,
179        "length" => Length::parse,
180        "let" => Let::parse,
181        "literal" => Literal::parse,
182        "match" => parse_match,
183        "number" => Assertion::parse,
184        "number-format" => NumberFormat::parse,
185        "object" => Assertion::parse,
186        "step" => Step::parse,
187        "string" => Assertion::parse,
188        "to-boolean" | "to-color" | "to-padding" | "to-number" | "to-string" => Coercion::parse,
189        "var" => Var::parse,
190        "within" => Within::parse,
191        "index-of" => IndexOf::parse,
192        "slice" => Slice::parse,
193        "semiliteral" => Semiliteral::parse,
194        _ => return None,
195    })
196}
197
198/// `isExpression(const std::string&)`: whether `name` is in the expression
199/// registry (not the compound-expression registry).
200pub fn is_expression_name(name: &str) -> bool {
201    expression_registry(name).is_some()
202}
203
204impl ParsingContext {
205    pub fn new() -> Self {
206        Self::default()
207    }
208
209    /// `ParsingContext(std::string key)`.
210    pub fn with_key(key: impl Into<String>) -> Self {
211        ParsingContext {
212            key: key.into(),
213            ..Default::default()
214        }
215    }
216
217    /// `explicit ParsingContext(type::Type expected)`.
218    pub fn with_expected(expected: Type) -> Self {
219        ParsingContext {
220            expected: Some(expected),
221            ..Default::default()
222        }
223    }
224
225    fn child(
226        key: String,
227        errors: Rc<RefCell<Vec<ParsingError>>>,
228        expected: Option<Type>,
229        scope: Option<Rc<Scope>>,
230    ) -> Self {
231        ParsingContext {
232            key,
233            expected,
234            scope,
235            errors,
236        }
237    }
238
239    pub fn get_key(&self) -> String {
240        self.key.clone()
241    }
242
243    pub fn get_expected(&self) -> Option<Type> {
244        self.expected.clone()
245    }
246
247    pub fn get_errors(&self) -> Vec<ParsingError> {
248        self.errors.borrow().clone()
249    }
250
251    pub fn has_errors(&self) -> bool {
252        !self.errors.borrow().is_empty()
253    }
254
255    pub fn get_combined_errors(&self) -> String {
256        let mut combined_error = String::new();
257        for parsing_error in self.errors.borrow().iter() {
258            if !combined_error.is_empty() {
259                combined_error.push('\n');
260            }
261            if !parsing_error.key.is_empty() {
262                combined_error += &parsing_error.key;
263                combined_error += ": ";
264            }
265            combined_error += &parsing_error.message;
266        }
267        combined_error
268    }
269
270    /// Parse the given style-spec JSON value as an expression.
271    pub fn parse_expression(
272        &mut self,
273        value: &Convertible<'_>,
274        type_annotation_option: Option<TypeAnnotationOption>,
275    ) -> ParseResult {
276        self.parse_value(value, type_annotation_option)
277    }
278
279    /// Parse the given style-spec JSON value as an expression intended to be
280    /// used in a layout or paint property. This entails checking additional
281    /// constraints that exist in that context but not, e.g., for filters.
282    pub fn parse_layer_property_expression(&mut self, value: &Convertible<'_>) -> ParseResult {
283        let type_annotation_option = if self.expected.as_ref() == Some(&Type::String) {
284            Some(TypeAnnotationOption::Coerce)
285        } else {
286            None
287        };
288        let parsed = self.parse_value(value, type_annotation_option);
289
290        // If the expression is zoom-dependent, validate that we can resolve a
291        // zoom curve or treat it as an error
292        if let Some(p) = &parsed {
293            debug_assert_eq!(
294                !p.has(crate::expression::Dependency::ZOOM),
295                is_zoom_constant(&**p)
296            );
297            if p.has(crate::expression::Dependency::ZOOM) {
298                match find_zoom_curve(&**p) {
299                    Some(ZoomCurve::Error(err)) => {
300                        self.error(err.message);
301                        return None;
302                    }
303                    Some(_) => {}
304                    None => {
305                        self.error(
306                            r#""zoom" expression may only be used as input to a top-level "step" or "interpolate" expression."#
307                                .to_owned(),
308                        );
309                        return None;
310                    }
311                }
312            }
313        }
314        parsed
315    }
316
317    /// Parse a child expression. For use by individual Expression::parse()
318    /// methods.
319    pub fn parse(
320        &mut self,
321        value: &Convertible<'_>,
322        index: usize,
323        expected: Option<Type>,
324        type_annotation_option: Option<TypeAnnotationOption>,
325    ) -> ParseResult {
326        let mut child = ParsingContext::child(
327            format!("{}[{}]", self.key, index),
328            self.errors.clone(),
329            expected,
330            self.scope.clone(),
331        );
332        child.parse_value(value, type_annotation_option)
333    }
334
335    /// Parse a child expression with additional bindings in scope.
336    pub fn parse_with_bindings(
337        &mut self,
338        value: &Convertible<'_>,
339        index: usize,
340        expected: Option<Type>,
341        bindings: &Bindings,
342    ) -> ParseResult {
343        let mut child = ParsingContext::child(
344            format!("{}[{}]", self.key, index),
345            self.errors.clone(),
346            expected,
347            Some(Rc::new(Scope::new(bindings.clone(), self.scope.clone()))),
348        );
349        child.parse_value(value, None)
350    }
351
352    /// Check whether `t` is a subtype of `expected`, collecting an error if
353    /// not.
354    pub fn check_type(&mut self, t: &Type) -> Option<String> {
355        let expected = self.expected.as_ref().expect("check_type without an expected type");
356        let err = check_subtype(expected, t);
357        if let Some(err) = &err {
358            self.error(err.clone());
359        }
360        err
361    }
362
363    pub fn get_binding(&self, name: &str) -> Option<Arc<dyn Expression>> {
364        self.scope.as_ref()?.get(name)
365    }
366
367    pub fn error(&mut self, message: String) {
368        self.errors.borrow_mut().push(ParsingError {
369            message,
370            key: self.key.clone(),
371        });
372    }
373
374    pub fn error_at(&mut self, message: String, child: usize) {
375        self.errors.borrow_mut().push(ParsingError {
376            message,
377            key: format!("{}[{}]", self.key, child),
378        });
379    }
380
381    pub fn error_at2(&mut self, message: String, child: usize, grandchild: usize) {
382        self.errors.borrow_mut().push(ParsingError {
383            message,
384            key: format!("{}[{}][{}]", self.key, child, grandchild),
385        });
386    }
387
388    pub fn append_errors(&mut self, ctx: ParsingContext) {
389        let mut theirs = ctx.errors.borrow_mut();
390        self.errors.borrow_mut().append(&mut theirs);
391    }
392
393    pub fn clear_errors(&mut self) {
394        self.errors.borrow_mut().clear();
395    }
396
397    /// Parse the given style-spec JSON value into an Expression object.
398    /// Specifically, this function is responsible for determining the
399    /// expression type (either Literal, or the one named in value[0]) and
400    /// dispatching to the appropriate ParseXxxx::parse(const V&,
401    /// ParsingContext) method.
402    fn parse_value(
403        &mut self,
404        value: &Convertible<'_>,
405        type_annotation_option: Option<TypeAnnotationOption>,
406    ) -> ParseResult {
407        let mut parsed: ParseResult;
408
409        if value.is_array() {
410            let length = value.array_length();
411            if length == 0 {
412                self.error(
413                    r#"Expected an array with at least one element. If you wanted a literal array, use ["literal", []]."#
414                        .to_owned(),
415                );
416                return None;
417            }
418
419            let Some(op) = value.array_member(0).to_string() else {
420                self.error_at(
421                    format!(
422                        r#"Expression name must be a string, but found {} instead. If you wanted a literal array, use ["literal", [...]]."#,
423                        get_json_type(&value.array_member(0))
424                    ),
425                    0,
426                );
427                return None;
428            };
429
430            parsed = if let Some(parse_function) = expression_registry(&op) {
431                parse_function(value, self)
432            } else {
433                parse_compound_expression(&op, value, self)
434            };
435        } else {
436            parsed = Literal::parse(value, self);
437        }
438
439        let Some(mut expr) = parsed else {
440            debug_assert!(!self.errors.borrow().is_empty());
441            return None;
442        };
443
444        let annotate = |expression: Box<dyn Expression>,
445                        type_: Type,
446                        type_annotation: TypeAnnotationOption|
447         -> Box<dyn Expression> {
448            match type_annotation {
449                TypeAnnotationOption::Assert => Box::new(Assertion::new(type_, vec![expression])),
450                TypeAnnotationOption::Coerce => Box::new(Coercion::new(type_, vec![expression])),
451                TypeAnnotationOption::Omit => expression,
452            }
453        };
454
455        if let Some(expected) = self.expected.clone() {
456            let actual = expr.get_type().clone();
457            if (expected == Type::String
458                || expected == Type::Number
459                || expected == Type::Boolean
460                || expected == Type::Object
461                || expected.is_array())
462                && actual == Type::Value
463            {
464                expr = annotate(
465                    expr,
466                    expected,
467                    type_annotation_option.unwrap_or(TypeAnnotationOption::Assert),
468                );
469            } else if (expected == Type::Color
470                || expected == Type::Formatted
471                || expected == Type::Image)
472                && (actual == Type::Value || actual == Type::String)
473            {
474                expr = annotate(
475                    expr,
476                    expected,
477                    type_annotation_option.unwrap_or(TypeAnnotationOption::Coerce),
478                );
479            } else if expected == Type::Padding
480                && (actual == Type::Value || actual == Type::Number || actual.is_array())
481            {
482                expr = annotate(
483                    expr,
484                    expected,
485                    type_annotation_option.unwrap_or(TypeAnnotationOption::Coerce),
486                );
487            } else if expected == Type::VariableAnchorOffsetCollection
488                && (actual == Type::Value || actual.is_array())
489            {
490                expr = annotate(
491                    expr,
492                    expected,
493                    type_annotation_option.unwrap_or(TypeAnnotationOption::Coerce),
494                );
495            } else {
496                let t = expr.get_type().clone();
497                self.check_type(&t);
498                if !self.errors.borrow().is_empty() {
499                    return None;
500                }
501            }
502        }
503        parsed = Some(expr);
504        let expr = parsed.as_ref().unwrap();
505
506        // If an expression's arguments are all constant, we can evaluate it
507        // immediately and replace it with a literal value in the
508        // parsed/compiled result. Expressions that expect an image should not
509        // be resolved here so we can later get the available images.
510        if expr.get_kind() != Kind::Literal && *expr.get_type() != Type::Image && is_constant(&**expr) {
511            let params = EvaluationContext::from_feature(None);
512            let evaluated = expr.evaluate(&params);
513            let evaluated = match evaluated {
514                Ok(v) => v,
515                Err(e) => {
516                    self.error(e.message);
517                    return None;
518                }
519            };
520
521            let type_ = expr.get_type().clone();
522            if let Type::Array(array) = type_ {
523                // keep the original expression's array type, even if the
524                // evaluated type is more specific.
525                let Value::Array(items) = evaluated else {
526                    panic!("array-typed expression evaluated to a non-array");
527                };
528                return Some(Box::new(Literal::with_array_type(*array, items)));
529            } else {
530                return Some(Box::new(Literal::new(evaluated)));
531            }
532        }
533
534        parsed
535    }
536}