Skip to main content

mln_expression/
expression.rs

1// Ports include/mln/style/expression/expression.hpp and
2// src/mln/style/expression/expression.cpp.
3//
4// C++ `Expression` is an abstract base class with `kind`, `type` and
5// `dependencies` fields; here every expression type embeds an
6// `ExpressionBase` and implements the `Expression` trait. C++ downcasts with
7// `getKind()` + `static_cast`; the port uses `downcast` (`Any`).
8
9use std::any::Any;
10use std::borrow::Cow;
11use std::fmt;
12
13use feature::{Feature, Identifier as FeatureIdentifier, Value as MbglValue, ValueObject};
14use mln_text::glyph::FontFaces;
15use mln_tile_id::CanonicalTileID;
16use mln_tile_id::geometry_tile_data::{GeometryCollection, GeometryTileFeature};
17use mln_util::geometry::{FeatureType, to_feature_type};
18use mln_vec_map::VecSet;
19
20use crate::compound_expression::CompoundExpression;
21use crate::literal::Literal;
22use crate::type_::Type;
23use crate::value::{Value, from_mbgl_value};
24
25/// `mln::FeatureState` (util/feature.hpp).
26pub type FeatureState = ValueObject;
27/// `mln::GlobalStateMap` (util/feature.hpp).
28pub type GlobalStateMap = ValueObject;
29
30/// `expression::EvaluationError`.
31#[derive(Clone, Debug, Default, PartialEq, Eq, thiserror::Error)]
32#[error("{message}")]
33pub struct EvaluationError {
34    pub message: String,
35}
36
37impl EvaluationError {
38    pub fn new(message: impl Into<String>) -> Self {
39        EvaluationError { message: message.into() }
40    }
41}
42
43/// `expression::Result<T>`.
44pub type EvalResult<T> = Result<T, EvaluationError>;
45
46/// `expression::EvaluationResult`.
47pub type EvaluationResult = Result<Value, EvaluationError>;
48
49/// `expression::EvaluationContext`. The C++ pointers are borrows.
50#[derive(Clone, Copy, Default)]
51pub struct EvaluationContext<'a> {
52    pub zoom: Option<f32>,
53    pub accumulated: Option<&'a MbglValue>,
54    pub feature: Option<&'a dyn GeometryTileFeature>,
55    pub color_ramp_parameter: Option<f64>,
56    pub elevation: Option<f32>,
57    /// Contains formatted section object, `std::unordered_map<std::string, Value>`.
58    pub formatted_section: Option<&'a Value>,
59    pub feature_state: Option<&'a FeatureState>,
60    pub available_images: Option<&'a VecSet<String>>,
61    pub canonical: Option<&'a CanonicalTileID>,
62    pub global_state: Option<&'a GlobalStateMap>,
63    /// The style's font faces, which let "is-supported-script" accept the
64    /// scripts that they cover.
65    pub font_faces: Option<&'a FontFaces>,
66}
67
68impl<'a> EvaluationContext<'a> {
69    /// `EvaluationContext(float zoom)`.
70    #[must_use]
71    pub fn new(zoom: f32) -> Self {
72        EvaluationContext { zoom: Some(zoom), ..Default::default() }
73    }
74
75    /// `EvaluationContext(GeometryTileFeature const*)`.
76    #[must_use]
77    pub fn from_feature(feature: Option<&'a dyn GeometryTileFeature>) -> Self {
78        EvaluationContext { feature, ..Default::default() }
79    }
80
81    /// `EvaluationContext(float zoom, GeometryTileFeature const*)`.
82    #[must_use]
83    pub fn with_zoom_feature(zoom: f32, feature: Option<&'a dyn GeometryTileFeature>) -> Self {
84        EvaluationContext { zoom: Some(zoom), feature, ..Default::default() }
85    }
86
87    /// `EvaluationContext(std::optional<mln::Value> accumulated, GeometryTileFeature const*)`.
88    #[must_use]
89    pub fn from_accumulated(accumulated: Option<&'a MbglValue>, feature: Option<&'a dyn GeometryTileFeature>) -> Self {
90        EvaluationContext { accumulated, feature, ..Default::default() }
91    }
92
93    /// `EvaluationContext(float zoom, GeometryTileFeature const*, const FeatureState*)`.
94    #[must_use]
95    pub fn with_zoom_feature_state(
96        zoom: f32,
97        feature: Option<&'a dyn GeometryTileFeature>,
98        state: Option<&'a FeatureState>,
99    ) -> Self {
100        EvaluationContext { zoom: Some(zoom), feature, feature_state: state, ..Default::default() }
101    }
102
103    /// `EvaluationContext(std::optional<float> zoom, GeometryTileFeature const*,
104    /// std::optional<double> colorRampParameter)`.
105    #[must_use]
106    pub fn with_color_ramp(
107        zoom: Option<f32>,
108        feature: Option<&'a dyn GeometryTileFeature>,
109        color_ramp_parameter: Option<f64>,
110    ) -> Self {
111        EvaluationContext { zoom, feature, color_ramp_parameter, ..Default::default() }
112    }
113
114    /// The four-argument constructor with `elevation`.
115    #[must_use]
116    pub fn with_color_ramp_elevation(
117        zoom: Option<f32>,
118        feature: Option<&'a dyn GeometryTileFeature>,
119        color_ramp_parameter: Option<f64>,
120        elevation: Option<f32>,
121    ) -> Self {
122        EvaluationContext { zoom, feature, color_ramp_parameter, elevation, ..Default::default() }
123    }
124
125    #[must_use]
126    pub fn with_formatted_section(mut self, formatted_section: Option<&'a Value>) -> Self {
127        self.formatted_section = formatted_section;
128        self
129    }
130
131    #[must_use]
132    pub fn with_feature_state(mut self, feature_state: Option<&'a FeatureState>) -> Self {
133        self.feature_state = feature_state;
134        self
135    }
136
137    #[must_use]
138    pub fn with_available_images(mut self, available_images: Option<&'a VecSet<String>>) -> Self {
139        self.available_images = available_images;
140        self
141    }
142
143    #[must_use]
144    pub fn with_canonical_tile_id(mut self, canonical: Option<&'a CanonicalTileID>) -> Self {
145        self.canonical = canonical;
146        self
147    }
148
149    #[must_use]
150    pub fn with_elevation(mut self, elevation: f32) -> Self {
151        self.elevation = Some(elevation);
152        self
153    }
154
155    #[must_use]
156    pub fn with_global_state(mut self, global_state: Option<&'a GlobalStateMap>) -> Self {
157        self.global_state = global_state;
158        self
159    }
160
161    #[must_use]
162    pub fn with_font_faces(mut self, font_faces: Option<&'a FontFaces>) -> Self {
163        self.font_faces = font_faces;
164        self
165    }
166}
167
168/// `expression::Kind`.
169#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
170#[repr(i32)]
171pub enum Kind {
172    Coalesce,
173    CompoundExpression,
174    Literal,
175    At,
176    Interpolate,
177    Assertion,
178    Length,
179    Step,
180    Let,
181    Var,
182    CollatorExpression,
183    Coercion,
184    Match,
185    Error,
186    Case,
187    Any,
188    All,
189    Comparison,
190    FormatExpression,
191    FormatSectionOverride,
192    NumberFormat,
193    ImageExpression,
194    In,
195    Within,
196    Distance,
197    IndexOf,
198    Slice,
199    Semiliteral,
200}
201
202/// `expression::Dependency`, a bit set.
203#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
204pub struct Dependency(pub u32);
205
206impl Dependency {
207    pub const NONE: Dependency = Dependency(0);
208    /// Data reference
209    pub const FEATURE: Dependency = Dependency(1 << 0);
210    /// Image reference (equivalent to not "runtime constant")
211    pub const IMAGE: Dependency = Dependency(1 << 1);
212    /// Zoom level
213    pub const ZOOM: Dependency = Dependency(1 << 2);
214    /// Not used yet, "distance-from-center" not supported
215    pub const LOCATION: Dependency = Dependency(1 << 3);
216    /// Create variable binding ("let")
217    pub const BIND: Dependency = Dependency(1 << 4);
218    /// Use variable binding
219    pub const VAR: Dependency = Dependency(1 << 5);
220    /// Property override
221    pub const OVERRIDE: Dependency = Dependency(1 << 6);
222    /// Elevation from DEM
223    pub const ELEVATION: Dependency = Dependency(1 << 7);
224    /// Global state ("global-state")
225    pub const GLOBAL_STATE: Dependency = Dependency(1 << 8);
226    pub const MASK_COUNT: u32 = 9;
227    pub const ALL: Dependency = Dependency((1 << Self::MASK_COUNT) - 1);
228
229    /// `bool(a & b)` (`util/bitmask_operations.hpp`).
230    #[must_use]
231    pub fn intersects(self, other: Dependency) -> bool {
232        (self.0 & other.0) != 0
233    }
234}
235
236impl std::ops::BitOr for Dependency {
237    type Output = Dependency;
238    fn bitor(self, rhs: Dependency) -> Dependency {
239        Dependency(self.0 | rhs.0)
240    }
241}
242
243impl std::ops::BitOrAssign for Dependency {
244    fn bitor_assign(&mut self, rhs: Dependency) {
245        self.0 |= rhs.0;
246    }
247}
248
249/// `operator<<(std::ostream&, Dependency)`.
250impl fmt::Display for Dependency {
251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252        if *self == Dependency::NONE {
253            return f.write_str("None");
254        }
255        let mut any = false;
256        for (dep, name) in [
257            (Dependency::FEATURE, "Feature"),
258            (Dependency::IMAGE, "Image"),
259            (Dependency::ZOOM, "Zoom"),
260            (Dependency::LOCATION, "Location"),
261            (Dependency::BIND, "Bind"),
262            (Dependency::VAR, "Var"),
263            (Dependency::OVERRIDE, "Override"),
264            (Dependency::ELEVATION, "Elevation"),
265            (Dependency::GLOBAL_STATE, "GlobalState"),
266        ] {
267            if self.intersects(dep) {
268                if any {
269                    f.write_str("|")?;
270                }
271                f.write_str(name)?;
272                any = true;
273            }
274        }
275        Ok(())
276    }
277}
278
279impl fmt::Debug for Dependency {
280    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281        fmt::Display::fmt(self, f)
282    }
283}
284
285/// The fields of the C++ `Expression` base class.
286#[derive(Clone, Debug)]
287pub struct ExpressionBase {
288    pub dependencies: Dependency,
289    kind: Kind,
290    type_: Type,
291}
292
293impl ExpressionBase {
294    #[must_use]
295    pub fn new(kind: Kind, type_: Type, dependencies: Dependency) -> Self {
296        ExpressionBase { dependencies, kind, type_ }
297    }
298}
299
300/// Gives trait objects of any lifetime an `&dyn Any` of the concrete type
301/// (all expressions are `'static` types).
302pub trait AsAny {
303    fn as_any(&self) -> &dyn Any;
304}
305
306impl<T: Any> AsAny for T {
307    fn as_any(&self) -> &dyn Any {
308        self
309    }
310}
311
312/// `expression::Expression`.
313pub trait Expression: AsAny + Send + Sync {
314    fn base(&self) -> &ExpressionBase;
315
316    fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult;
317
318    /// The value a literal always evaluates to, which callers can borrow
319    /// instead of cloning it on each evaluation. `None` for any other
320    /// expression.
321    fn literal_value(&self) -> Option<&Value> {
322        None
323    }
324
325    fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression));
326
327    /// `operator==`.
328    fn equals(&self, other: &dyn Expression) -> bool;
329
330    /// Statically analyze the expression, attempting to enumerate possible
331    /// outputs. Returns an array of values plus the sentinel null optional
332    /// value, used to indicate that the complete set of outputs is
333    /// statically undecidable.
334    fn possible_outputs(&self) -> Vec<Option<Value>>;
335
336    fn serialize(&self) -> MbglValue {
337        default_serialize(self)
338    }
339
340    fn get_operator(&self) -> String;
341
342    fn get_kind(&self) -> Kind {
343        self.base().kind
344    }
345
346    fn get_type(&self) -> &Type {
347        &self.base().type_
348    }
349
350    fn dependencies(&self) -> Dependency {
351        self.base().dependencies
352    }
353
354    /// Test the expression's dependencies for any of one or more values.
355    fn has(&self, dep: Dependency) -> bool {
356        self.base().dependencies.intersects(dep)
357    }
358}
359
360/// The base-class `Expression::serialize()`.
361pub fn default_serialize<E: Expression + ?Sized>(e: &E) -> MbglValue {
362    let mut serialized = vec![MbglValue::String(e.get_operator())];
363    e.each_child(&mut |child| serialized.push(child.serialize()));
364    MbglValue::Array(serialized)
365}
366
367impl PartialEq for dyn Expression {
368    fn eq(&self, other: &dyn Expression) -> bool {
369        self.equals(other)
370    }
371}
372
373impl fmt::Debug for dyn Expression {
374    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375        write!(f, "Expression({:?})", self.serialize())
376    }
377}
378
379/// `static_cast<const T*>(&expression)` after a kind check.
380pub fn downcast<T: Expression + Any>(e: &dyn Expression) -> Option<&T> {
381    e.as_any().downcast_ref::<T>()
382}
383
384/// `Expression::depsOf` for an optional child.
385pub fn deps_of_opt<E: std::ops::Deref<Target = dyn Expression>>(e: &Option<E>) -> Dependency {
386    e.as_ref().map_or(Dependency::NONE, |e| e.dependencies())
387}
388
389/// `Expression::collectDependencies` over a container of children.
390pub fn collect_dependencies<'a, I, E>(container: I) -> Dependency
391where
392    I: IntoIterator<Item = &'a E>,
393    E: std::ops::Deref<Target = dyn Expression> + 'a,
394{
395    container.into_iter().fold(Dependency::NONE, |a, e| a | e.dependencies())
396}
397
398/// `Expression::childrenEqual` for vectors of expressions.
399pub fn children_equal<E, F>(lhs: &[E], rhs: &[F]) -> bool
400where
401    E: std::ops::Deref<Target = dyn Expression>,
402    F: std::ops::Deref<Target = dyn Expression>,
403{
404    if lhs.len() != rhs.len() {
405        return false;
406    }
407    lhs.iter().zip(rhs).all(|(l, r)| l.equals(&**r))
408}
409
410/// Collect the names of the global-state properties referenced by
411/// "global-state" expressions in the given expression tree.
412pub fn collect_global_state_refs(expression: &dyn Expression, refs: &mut VecSet<String>) {
413    if !expression.has(Dependency::GLOBAL_STATE) {
414        return;
415    }
416    if expression.get_kind() == Kind::CompoundExpression {
417        let compound = downcast::<CompoundExpression>(expression).expect("CompoundExpression");
418        if compound.get_operator() == "global-state" {
419            // The property name argument is enforced to be a string literal
420            // at parse time.
421            expression.each_child(&mut |child| {
422                if child.get_kind() == Kind::Literal {
423                    let value = downcast::<Literal>(child).expect("Literal").get_value();
424                    if let Value::String(s) = value {
425                        refs.insert(s.clone());
426                    }
427                }
428            });
429            return;
430        }
431    }
432    expression.each_child(&mut |child| collect_global_state_refs(child, refs));
433}
434
435/// Whether any of the global-state keys referenced by an expression is among
436/// the changed keys. A null set on either side means "unknown" and is
437/// conservatively treated as a match.
438#[must_use]
439pub fn global_state_refs_intersect(refs: Option<&VecSet<String>>, changed_keys: Option<&VecSet<String>>) -> bool {
440    match (refs, changed_keys) {
441        (Some(refs), Some(changed_keys)) => refs.iter().any(|key| changed_keys.contains(key)),
442        _ => true,
443    }
444}
445
446/// The `GeoJSONFeature` adapter of expression.cpp: a `GeometryTileFeature`
447/// view of an `mln::Feature`.
448struct GeoJSONFeature<'a> {
449    feature: &'a Feature<f64>,
450    geometry: GeometryCollection,
451}
452
453impl<'a> GeoJSONFeature<'a> {
454    fn new(feature: &'a Feature<f64>) -> Self {
455        GeoJSONFeature { feature, geometry: GeometryCollection::default() }
456    }
457
458    fn with_canonical(feature: &'a Feature<f64>, canonical: &CanonicalTileID) -> Self {
459        let mut geometry = mln_tile::geometry_tile_data::convert_geometry_to_tile(&feature.geometry, canonical);
460        // https://github.com/mapbox/geojson-vt-cpp/issues/44
461        if to_feature_type(&feature.geometry) == FeatureType::Polygon {
462            // C++ lets wagyu's exception escape `evaluate`; the unfixed
463            // rings are kept here instead.
464            if let Ok(fixed) = mln_tile::geometry_tile_data::fixup_polygons(&geometry) {
465                geometry = fixed;
466            }
467        }
468        GeoJSONFeature { feature, geometry }
469    }
470}
471
472impl GeometryTileFeature for GeoJSONFeature<'_> {
473    fn get_type(&self) -> FeatureType {
474        to_feature_type(&self.feature.geometry)
475    }
476
477    fn get_properties(&self) -> &ValueObject {
478        &self.feature.properties
479    }
480
481    fn get_id(&self) -> FeatureIdentifier {
482        self.feature.id.clone()
483    }
484
485    fn get_value(&self, key: &str) -> Option<MbglValue> {
486        self.feature.properties.get(key).cloned()
487    }
488
489    fn get_geometries(&self) -> &GeometryCollection {
490        &self.geometry
491    }
492}
493
494/// `Expression::evaluate(zoom, feature, colorRampParameter)`.
495pub fn evaluate_feature(
496    e: &dyn Expression,
497    zoom: Option<f32>,
498    feature: &Feature<f64>,
499    color_ramp_parameter: Option<f64>,
500) -> EvaluationResult {
501    let f = GeoJSONFeature::new(feature);
502    e.evaluate(&EvaluationContext::with_color_ramp(zoom, Some(&f), color_ramp_parameter))
503}
504
505/// `Expression::evaluate(zoom, feature, colorRampParameter, availableImages)`.
506pub fn evaluate_feature_with_images(
507    e: &dyn Expression,
508    zoom: Option<f32>,
509    feature: &Feature<f64>,
510    color_ramp_parameter: Option<f64>,
511    available_images: &VecSet<String>,
512) -> EvaluationResult {
513    let f = GeoJSONFeature::new(feature);
514    e.evaluate(
515        &EvaluationContext::with_color_ramp(zoom, Some(&f), color_ramp_parameter)
516            .with_available_images(Some(available_images)),
517    )
518}
519
520/// `Expression::evaluate(zoom, feature, colorRampParameter, availableImages, canonical)`.
521pub fn evaluate_feature_with_canonical(
522    e: &dyn Expression,
523    zoom: Option<f32>,
524    feature: &Feature<f64>,
525    color_ramp_parameter: Option<f64>,
526    available_images: &VecSet<String>,
527    canonical: &CanonicalTileID,
528) -> EvaluationResult {
529    let f = GeoJSONFeature::with_canonical(feature, canonical);
530    e.evaluate(
531        &EvaluationContext::with_color_ramp(zoom, Some(&f), color_ramp_parameter)
532            .with_available_images(Some(available_images))
533            .with_canonical_tile_id(Some(canonical)),
534    )
535}
536
537/// `Expression::evaluate(accumulated, feature)`.
538pub fn evaluate_accumulated(
539    e: &dyn Expression,
540    accumulated: Option<&MbglValue>,
541    feature: &Feature<f64>,
542) -> EvaluationResult {
543    let f = GeoJSONFeature::new(feature);
544    e.evaluate(&EvaluationContext::from_accumulated(accumulated, Some(&f)))
545}
546
547/// `Expression::evaluate(feature, params)`: evaluates against a GeoJSON
548/// feature and every other input of `params`, whose own feature is ignored.
549/// When `params` names a canonical tile, the feature's geometry is placed in
550/// that tile, as the within and distance expressions need.
551pub fn evaluate_feature_with_context(
552    e: &dyn Expression,
553    feature: &Feature<f64>,
554    params: EvaluationContext<'_>,
555) -> EvaluationResult {
556    let f = match params.canonical {
557        Some(canonical) => GeoJSONFeature::with_canonical(feature, canonical),
558        None => GeoJSONFeature::new(feature),
559    };
560    e.evaluate(&EvaluationContext { feature: Some(&f), ..params })
561}
562
563/// `evaluate`, borrowing a literal's value instead of cloning it.
564pub(crate) fn evaluate_ref<'a>(
565    expression: &'a dyn Expression,
566    params: &EvaluationContext<'_>,
567) -> Result<Cow<'a, Value>, EvaluationError> {
568    match expression.literal_value() {
569        Some(value) => Ok(Cow::Borrowed(value)),
570        None => expression.evaluate(params).map(Cow::Owned),
571    }
572}
573
574/// `toExpressionValue(mln::Value)`, used by the feature accessors.
575pub(crate) fn mbgl_to_expression_value(v: &MbglValue) -> Value {
576    from_mbgl_value(v)
577}