1use 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
23pub type FeatureState = ValueObject;
25pub type GlobalStateMap = ValueObject;
27
28#[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
40pub type EvalResult<T> = Result<T, EvaluationError>;
42
43pub type EvaluationResult = Result<Value, EvaluationError>;
45
46#[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 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 pub fn new(zoom: f32) -> Self {
65 EvaluationContext { zoom: Some(zoom), ..Default::default() }
66 }
67
68 pub fn from_feature(feature: Option<&'a dyn GeometryTileFeature>) -> Self {
70 EvaluationContext { feature, ..Default::default() }
71 }
72
73 pub fn with_zoom_feature(zoom: f32, feature: Option<&'a dyn GeometryTileFeature>) -> Self {
75 EvaluationContext { zoom: Some(zoom), feature, ..Default::default() }
76 }
77
78 pub fn from_accumulated(accumulated: Option<&'a MbglValue>, feature: Option<&'a dyn GeometryTileFeature>) -> Self {
80 EvaluationContext { accumulated, feature, ..Default::default() }
81 }
82
83 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 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 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#[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#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
179pub struct Dependency(pub u32);
180
181impl Dependency {
182 pub const NONE: Dependency = Dependency(0);
183 pub const FEATURE: Dependency = Dependency(1 << 0);
185 pub const IMAGE: Dependency = Dependency(1 << 1);
187 pub const ZOOM: Dependency = Dependency(1 << 2);
189 pub const LOCATION: Dependency = Dependency(1 << 3);
191 pub const BIND: Dependency = Dependency(1 << 4);
193 pub const VAR: Dependency = Dependency(1 << 5);
195 pub const OVERRIDE: Dependency = Dependency(1 << 6);
197 pub const ELEVATION: Dependency = Dependency(1 << 7);
199 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 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
223impl 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#[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
273pub 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
285pub 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 fn equals(&self, other: &dyn Expression) -> bool;
294
295 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 fn has(&self, dep: Dependency) -> bool {
321 self.base().dependencies.intersects(dep)
322 }
323}
324
325pub 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
344pub fn downcast<T: Expression + Any>(e: &dyn Expression) -> Option<&T> {
346 e.as_any().downcast_ref::<T>()
347}
348
349pub fn deps_of(e: &dyn Expression) -> Dependency {
351 e.dependencies()
352}
353
354pub 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
359pub 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
368pub 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
380pub 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 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
405pub 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
415pub fn dependency_to_string(deps: Dependency) -> String {
417 deps.to_string()
418}
419
420struct 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 if to_feature_type(&feature.geometry) == FeatureType::Polygon {
436 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
468pub 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
479pub 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
494pub 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
511pub 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
521pub(crate) fn mbgl_to_expression_value(v: &MbglValue) -> Value {
523 from_mbgl_value(v)
524}