1use 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
21pub type FeatureState = ValueObject;
23pub type GlobalStateMap = ValueObject;
25
26#[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
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 {
66 zoom: Some(zoom),
67 ..Default::default()
68 }
69 }
70
71 pub fn from_feature(feature: Option<&'a dyn GeometryTileFeature>) -> Self {
73 EvaluationContext {
74 feature,
75 ..Default::default()
76 }
77 }
78
79 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 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 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 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 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#[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#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
212pub struct Dependency(pub u32);
213
214impl Dependency {
215 pub const NONE: Dependency = Dependency(0);
216 pub const FEATURE: Dependency = Dependency(1 << 0);
218 pub const IMAGE: Dependency = Dependency(1 << 1);
220 pub const ZOOM: Dependency = Dependency(1 << 2);
222 pub const LOCATION: Dependency = Dependency(1 << 3);
224 pub const BIND: Dependency = Dependency(1 << 4);
226 pub const VAR: Dependency = Dependency(1 << 5);
228 pub const OVERRIDE: Dependency = Dependency(1 << 6);
230 pub const ELEVATION: Dependency = Dependency(1 << 7);
232 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 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
256impl 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#[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
310pub 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
322pub 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 fn equals(&self, other: &dyn Expression) -> bool;
331
332 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 fn has(&self, dep: Dependency) -> bool {
358 self.base().dependencies.intersects(dep)
359 }
360}
361
362pub 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
381pub fn downcast<T: Expression + Any>(e: &dyn Expression) -> Option<&T> {
383 e.as_any().downcast_ref::<T>()
384}
385
386pub fn deps_of(e: &dyn Expression) -> Dependency {
388 e.dependencies()
389}
390
391pub 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
396pub 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
407pub 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
419pub 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 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
444pub 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
457pub fn dependency_to_string(deps: Dependency) -> String {
459 deps.to_string()
460}
461
462struct 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 if to_feature_type(&feature.geometry) == FeatureType::Polygon {
481 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
513pub 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
524pub 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
539pub 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
556pub 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
566pub(crate) fn mbgl_to_expression_value(v: &MbglValue) -> Value {
568 from_mbgl_value(v)
569}