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