1use 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
25pub type FeatureState = ValueObject;
27pub type GlobalStateMap = ValueObject;
29
30#[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
43pub type EvalResult<T> = Result<T, EvaluationError>;
45
46pub type EvaluationResult = Result<Value, EvaluationError>;
48
49#[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 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 pub font_faces: Option<&'a FontFaces>,
66}
67
68impl<'a> EvaluationContext<'a> {
69 #[must_use]
71 pub fn new(zoom: f32) -> Self {
72 EvaluationContext { zoom: Some(zoom), ..Default::default() }
73 }
74
75 #[must_use]
77 pub fn from_feature(feature: Option<&'a dyn GeometryTileFeature>) -> Self {
78 EvaluationContext { feature, ..Default::default() }
79 }
80
81 #[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 #[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 #[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 #[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 #[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#[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#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
204pub struct Dependency(pub u32);
205
206impl Dependency {
207 pub const NONE: Dependency = Dependency(0);
208 pub const FEATURE: Dependency = Dependency(1 << 0);
210 pub const IMAGE: Dependency = Dependency(1 << 1);
212 pub const ZOOM: Dependency = Dependency(1 << 2);
214 pub const LOCATION: Dependency = Dependency(1 << 3);
216 pub const BIND: Dependency = Dependency(1 << 4);
218 pub const VAR: Dependency = Dependency(1 << 5);
220 pub const OVERRIDE: Dependency = Dependency(1 << 6);
222 pub const ELEVATION: Dependency = Dependency(1 << 7);
224 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 #[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
249impl 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#[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
300pub 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
312pub trait Expression: AsAny + Send + Sync {
314 fn base(&self) -> &ExpressionBase;
315
316 fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult;
317
318 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 fn equals(&self, other: &dyn Expression) -> bool;
329
330 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 fn has(&self, dep: Dependency) -> bool {
356 self.base().dependencies.intersects(dep)
357 }
358}
359
360pub 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
379pub fn downcast<T: Expression + Any>(e: &dyn Expression) -> Option<&T> {
381 e.as_any().downcast_ref::<T>()
382}
383
384pub 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
389pub 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
398pub 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
410pub 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 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#[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
446struct 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 if to_feature_type(&feature.geometry) == FeatureType::Polygon {
462 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
494pub 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
505pub 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
520pub 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
537pub 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
547pub 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
563pub(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
574pub(crate) fn mbgl_to_expression_value(v: &MbglValue) -> Value {
576 from_mbgl_value(v)
577}