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