Skip to main content

mln_expression/
parsing_context.rs

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