1use std::borrow::Cow;
11use std::fmt;
12use std::hash::{Hash, Hasher};
13use std::mem::discriminant;
14use std::sync::Arc;
15
16use feature::{Feature, Identifier as FeatureIdentifier, Value as MbglValue, ValueObject};
17use mln_text::glyph::FontFaces;
18use mln_tile_id::CanonicalTileID;
19use mln_tile_id::geometry_tile_data::{GeometryCollection, GeometryTileFeature};
20use mln_util::Color;
21use mln_util::geometry::{FeatureType, to_feature_type};
22use mln_vec_map::VecSet;
23
24use crate::assertion::Assertion;
25use crate::at::At;
26use crate::case::Case;
27use crate::coalesce::Coalesce;
28use crate::coercion::Coercion;
29use crate::collator_expression::CollatorExpression;
30use crate::comparison::Comparison;
31use crate::compound_expression::CompoundExpression;
32use crate::distance::Distance;
33use crate::format_expression::FormatExpression;
34use crate::format_section_override::FormatSectionOverride;
35use crate::functions::Role;
36use crate::image_expression::{ImageExpression, UnavailableImages};
37use crate::in_::In;
38use crate::index_of::IndexOf;
39use crate::interpolate::Interpolate;
40use crate::let_::{Let, Var};
41use crate::literal::Literal;
42use crate::match_::Match;
43use crate::number_format::NumberFormat;
44use crate::semiliteral::Semiliteral;
45use crate::slice::Slice;
46use crate::step::Step;
47use crate::type_::Type;
48use crate::value::{Value, from_mbgl_value, hash_value, type_of};
49use crate::within::Within;
50
51pub type FeatureState = ValueObject;
52pub type GlobalStateMap = ValueObject;
53
54#[derive(Clone, PartialEq, Eq, thiserror::Error)]
57#[error("{}", .0.message)]
58pub struct EvaluationError(Box<ErrorMessage>);
59
60#[derive(Clone, PartialEq, Eq)]
61struct ErrorMessage {
62 message: String,
63}
64
65impl EvaluationError {
66 pub(crate) fn new(message: impl Into<String>) -> Self {
67 EvaluationError(Box::new(ErrorMessage { message: message.into() }))
68 }
69
70 pub(crate) fn type_mismatch(expected: &Type, value: &Value) -> Self {
72 EvaluationError::new(format!(
73 "Expected value to be of type {}, but found {} instead.",
74 crate::type_::to_string(expected),
75 crate::type_::to_string(&type_of(value))
76 ))
77 }
78
79 #[must_use]
81 pub fn message(&self) -> &str {
82 &self.0.message
83 }
84}
85
86impl fmt::Debug for EvaluationError {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 write!(f, "EvaluationError({:?})", self.0.message)
89 }
90}
91
92pub type EvalResult<T> = Result<T, EvaluationError>;
94
95pub type EvaluationResult = Result<Value, EvaluationError>;
96
97#[derive(Clone, Copy, Default)]
99pub struct EvaluationContext<'a> {
100 pub zoom: Option<f32>,
101 pub accumulated: Option<&'a MbglValue>,
102 pub feature: Option<&'a dyn GeometryTileFeature>,
103 pub color_ramp_parameter: Option<f64>,
104 pub elevation: Option<f32>,
105 pub formatted_section: Option<&'a Value>,
108 pub feature_state: Option<&'a FeatureState>,
109 pub available_images: Option<&'a VecSet<String>>,
110 pub unavailable_images: Option<&'a UnavailableImages>,
113 pub canonical: Option<&'a CanonicalTileID>,
114 pub global_state: Option<&'a GlobalStateMap>,
115 pub font_faces: Option<&'a FontFaces>,
118}
119
120impl<'a> EvaluationContext<'a> {
121 #[must_use]
122 pub fn new(zoom: f32) -> Self {
123 EvaluationContext { zoom: Some(zoom), ..Default::default() }
124 }
125
126 #[must_use]
127 pub fn from_feature(feature: Option<&'a dyn GeometryTileFeature>) -> Self {
128 EvaluationContext { feature, ..Default::default() }
129 }
130
131 #[must_use]
132 pub fn with_zoom_feature(zoom: f32, feature: Option<&'a dyn GeometryTileFeature>) -> Self {
133 EvaluationContext { zoom: Some(zoom), feature, ..Default::default() }
134 }
135
136 #[must_use]
137 pub(crate) fn from_accumulated(
138 accumulated: Option<&'a MbglValue>,
139 feature: Option<&'a dyn GeometryTileFeature>,
140 ) -> Self {
141 EvaluationContext { accumulated, feature, ..Default::default() }
142 }
143
144 #[must_use]
145 pub fn with_zoom_feature_state(
146 zoom: f32,
147 feature: Option<&'a dyn GeometryTileFeature>,
148 state: Option<&'a FeatureState>,
149 ) -> Self {
150 EvaluationContext { zoom: Some(zoom), feature, feature_state: state, ..Default::default() }
151 }
152
153 #[must_use]
154 pub fn with_color_ramp(
155 zoom: Option<f32>,
156 feature: Option<&'a dyn GeometryTileFeature>,
157 color_ramp_parameter: Option<f64>,
158 ) -> Self {
159 EvaluationContext { zoom, feature, color_ramp_parameter, ..Default::default() }
160 }
161
162 #[must_use]
163 pub fn with_formatted_section(mut self, formatted_section: Option<&'a Value>) -> Self {
164 self.formatted_section = formatted_section;
165 self
166 }
167
168 #[must_use]
169 pub fn with_feature_state(mut self, feature_state: Option<&'a FeatureState>) -> Self {
170 self.feature_state = feature_state;
171 self
172 }
173
174 #[must_use]
175 pub fn with_available_images(mut self, available_images: Option<&'a VecSet<String>>) -> Self {
176 self.available_images = available_images;
177 self
178 }
179
180 #[must_use]
181 pub fn with_unavailable_images(mut self, unavailable_images: Option<&'a UnavailableImages>) -> Self {
182 self.unavailable_images = unavailable_images;
183 self
184 }
185
186 #[must_use]
187 pub fn with_canonical_tile_id(mut self, canonical: Option<&'a CanonicalTileID>) -> Self {
188 self.canonical = canonical;
189 self
190 }
191
192 #[cfg(test)]
193 #[must_use]
194 pub(crate) fn with_elevation(mut self, elevation: f32) -> Self {
195 self.elevation = Some(elevation);
196 self
197 }
198
199 #[must_use]
200 pub fn with_global_state(mut self, global_state: Option<&'a GlobalStateMap>) -> Self {
201 self.global_state = global_state;
202 self
203 }
204
205 #[must_use]
206 pub fn with_font_faces(mut self, font_faces: Option<&'a FontFaces>) -> Self {
207 self.font_faces = font_faces;
208 self
209 }
210}
211
212#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
214pub struct Dependency(pub u32);
215
216impl Dependency {
217 pub const NONE: Dependency = Dependency(0);
218 pub const FEATURE: Dependency = Dependency(1 << 0);
220 pub const IMAGE: Dependency = Dependency(1 << 1);
222 pub const ZOOM: Dependency = Dependency(1 << 2);
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 FEATURE_STATE: Dependency = Dependency(1 << 9);
236 pub const PROPERTY_INPUT: Dependency = Dependency(1 << 10);
239
240 #[must_use]
242 pub fn intersects(self, other: Dependency) -> bool {
243 (self.0 & other.0) != 0
244 }
245}
246
247impl std::ops::BitOr for Dependency {
248 type Output = Dependency;
249 fn bitor(self, rhs: Dependency) -> Dependency {
250 Dependency(self.0 | rhs.0)
251 }
252}
253
254impl std::ops::BitOrAssign for Dependency {
255 fn bitor_assign(&mut self, rhs: Dependency) {
256 self.0 |= rhs.0;
257 }
258}
259
260impl fmt::Display for Dependency {
261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 if *self == Dependency::NONE {
263 return f.write_str("None");
264 }
265 let mut any = false;
266 for (dep, name) in [
267 (Dependency::FEATURE, "Feature"),
268 (Dependency::IMAGE, "Image"),
269 (Dependency::ZOOM, "Zoom"),
270 (Dependency::BIND, "Bind"),
271 (Dependency::VAR, "Var"),
272 (Dependency::OVERRIDE, "Override"),
273 (Dependency::ELEVATION, "Elevation"),
274 (Dependency::GLOBAL_STATE, "GlobalState"),
275 (Dependency::FEATURE_STATE, "FeatureState"),
276 (Dependency::PROPERTY_INPUT, "PropertyInput"),
277 ] {
278 if self.intersects(dep) {
279 if any {
280 f.write_str("|")?;
281 }
282 f.write_str(name)?;
283 any = true;
284 }
285 }
286 Ok(())
287 }
288}
289
290impl fmt::Debug for Dependency {
291 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292 fmt::Display::fmt(self, f)
293 }
294}
295
296#[derive(Clone, PartialEq, mln_wire::Wire)]
298pub(crate) enum Node {
299 Literal(Box<Literal>),
300 Compound(Box<CompoundExpression>),
301 Assertion(Box<Assertion>),
302 Coercion(Box<Coercion>),
303 Comparison(Box<Comparison>),
304 All(Box<[Expr]>),
305 Any(Box<[Expr]>),
306 At(Box<At>),
307 In(Box<In>),
308 IndexOf(Box<IndexOf>),
309 Slice(Box<Slice>),
310 Length(Box<Expr>),
311 Case(Box<Case>),
312 Coalesce(Box<Coalesce>),
313 Match(Box<Match>),
314 Step(Box<Step>),
315 Interpolate(Box<Interpolate>),
316 Let(Box<Let>),
317 Var(Box<Var>),
318 Collator(Box<CollatorExpression>),
319 Format(Box<FormatExpression>),
320 Image(Box<ImageExpression>),
321 NumberFormat(Box<NumberFormat>),
322 Within(Box<Within>),
323 Distance(Box<Distance>),
324 Semiliteral(Box<Semiliteral>),
325 FormatSectionOverride(Box<FormatSectionOverride>),
326}
327
328#[derive(Clone)]
330pub struct Expr {
331 node: Node,
332 deps: Dependency,
334}
335
336impl mln_wire::Wire for Expr {
338 fn write(&self, w: &mut mln_wire::Writer) {
339 self.node.write(w);
340 }
341
342 fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
343 Node::read(r).map(Expr::new)
344 }
345}
346
347impl PartialEq for Expr {
348 fn eq(&self, other: &Self) -> bool {
349 self.node == other.node
350 }
351}
352
353impl fmt::Debug for Expr {
354 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355 write!(f, "Expression({:?})", self.serialize())
356 }
357}
358
359pub(crate) trait Output<'e>: Sized {
363 fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self>;
365
366 fn from_value(value: Value) -> EvalResult<Self>;
368}
369
370fn wrong_type(expected: &str, value: &Value) -> EvaluationError {
371 EvaluationError::new(format!(
372 "Expected value to be of type {expected}, but found {} instead.",
373 crate::type_::to_string(&type_of(value))
374 ))
375}
376
377impl<'e> Output<'e> for f64 {
378 fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
379 e.eval_num(cx)
380 }
381 fn from_value(value: Value) -> EvalResult<Self> {
382 match value {
383 Value::Number(n) => Ok(n),
384 other => Err(wrong_type("number", &other)),
385 }
386 }
387}
388
389impl<'e> Output<'e> for bool {
390 fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
391 e.eval_bool(cx)
392 }
393 fn from_value(value: Value) -> EvalResult<Self> {
394 match value {
395 Value::Bool(b) => Ok(b),
396 other => Err(wrong_type("boolean", &other)),
397 }
398 }
399}
400
401impl<'e> Output<'e> for Cow<'e, str> {
402 fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
403 e.eval_str(cx)
404 }
405 fn from_value(value: Value) -> EvalResult<Self> {
406 match value {
407 Value::String(s) => Ok(Cow::Owned(s)),
408 other => Err(wrong_type("string", &other)),
409 }
410 }
411}
412
413impl<'e> Output<'e> for Color {
414 fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
415 e.eval_color(cx)
416 }
417 fn from_value(value: Value) -> EvalResult<Self> {
418 match value {
419 Value::Color(c) => Ok(c),
420 other => Err(wrong_type("color", &other)),
421 }
422 }
423}
424
425impl<'e> Output<'e> for Value {
426 fn eval(e: &'e Expr, cx: &EvaluationContext<'_>) -> EvalResult<Self> {
427 e.evaluate(cx)
428 }
429 fn from_value(value: Value) -> EvalResult<Self> {
430 Ok(value)
431 }
432}
433
434fn via_value<'e, T: Output<'e>>(e: &Expr, cx: &EvaluationContext<'_>) -> EvalResult<T> {
437 T::from_value(e.evaluate(cx)?)
438}
439
440impl Expr {
441 pub(crate) fn new(node: Node) -> Self {
442 let mut deps = node.own_dependencies();
443 node.each_child(&mut |child| deps |= child.deps);
444 Expr { node, deps }
445 }
446
447 pub(crate) fn node(&self) -> &Node {
448 &self.node
449 }
450
451 #[must_use]
453 pub fn literal(value: Value) -> Self {
454 Expr::new(Node::Literal(Box::new(Literal::new(value))))
455 }
456
457 #[must_use]
459 pub fn all(inputs: Vec<Expr>) -> Self {
460 Expr::new(Node::All(inputs.into()))
461 }
462
463 #[must_use]
465 pub fn any(inputs: Vec<Expr>) -> Self {
466 Expr::new(Node::Any(inputs.into()))
467 }
468
469 #[must_use]
471 pub fn get_type(&self) -> Type {
472 match &self.node {
473 Node::Literal(l) => l.get_type().clone(),
474 Node::Compound(c) => c.overload().result.clone(),
475 Node::Assertion(a) => a.get_type().clone(),
476 Node::Coercion(c) => c.get_type().clone(),
477 Node::Comparison(_) | Node::All(_) | Node::Any(_) | Node::In(_) | Node::Within(_) => Type::Boolean,
478 Node::At(a) => a.get_type(),
479 Node::IndexOf(_) | Node::Length(_) | Node::Distance(_) => Type::Number,
480 Node::Slice(s) => s.get_type(),
481 Node::Case(c) => c.get_type().clone(),
482 Node::Coalesce(c) => c.get_type().clone(),
483 Node::Match(m) => m.get_type().clone(),
484 Node::Step(s) => s.get_type().clone(),
485 Node::Interpolate(i) => i.get_type().clone(),
486 Node::Let(l) => l.result().get_type(),
487 Node::Var(v) => v.bound_expression().get_type(),
488 Node::Collator(_) => Type::Collator,
489 Node::Format(_) => Type::Formatted,
490 Node::Image(_) => Type::Image,
491 Node::NumberFormat(_) => Type::String,
492 Node::Semiliteral(s) => s.get_type(),
493 Node::FormatSectionOverride(_) => Type::Color,
494 }
495 }
496
497 #[must_use]
499 pub fn dependencies(&self) -> Dependency {
500 self.deps
501 }
502
503 #[must_use]
505 pub fn has(&self, dep: Dependency) -> bool {
506 self.deps.intersects(dep)
507 }
508
509 pub fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
512 self.node.each_child(visit);
513 }
514
515 #[must_use]
518 pub fn literal_value(&self) -> Option<&Value> {
519 match &self.node {
520 Node::Literal(l) => Some(l.get_value()),
521 _ => None,
522 }
523 }
524
525 #[must_use]
527 pub fn get_operator(&self) -> &str {
528 match &self.node {
529 Node::Literal(_) => "literal",
530 Node::Compound(c) => c.overload().name(),
531 Node::Assertion(a) => a.get_operator(),
532 Node::Coercion(c) => c.get_operator(),
533 Node::Comparison(c) => c.get_operator(),
534 Node::All(_) => "all",
535 Node::Any(_) => "any",
536 Node::At(_) => "at",
537 Node::In(_) => "in",
538 Node::IndexOf(_) => "index-of",
539 Node::Slice(_) => "slice",
540 Node::Length(_) => "length",
541 Node::Case(_) => "case",
542 Node::Coalesce(_) => "coalesce",
543 Node::Match(_) => "match",
544 Node::Step(_) => "step",
545 Node::Interpolate(i) => i.get_operator(),
546 Node::Let(_) => "let",
547 Node::Var(_) => "var",
548 Node::Collator(_) => "collator",
549 Node::Format(_) => "format",
550 Node::Image(_) => "image",
551 Node::NumberFormat(_) => "number-format",
552 Node::Within(_) => "within",
553 Node::Distance(_) => "distance",
554 Node::Semiliteral(_) => "semiliteral",
555 Node::FormatSectionOverride(_) => "format-section-override",
556 }
557 }
558
559 #[must_use]
562 pub fn serialize(&self) -> MbglValue {
563 match &self.node {
564 Node::Literal(l) => l.serialize(),
565 Node::Compound(c) => c.serialize(),
566 Node::Assertion(a) => a.serialize(),
567 Node::Coercion(c) => c.serialize(),
568 Node::Comparison(c) => c.serialize(),
569 Node::Interpolate(i) => i.serialize(),
570 Node::Step(s) => s.serialize(),
571 Node::Match(m) => m.serialize(),
572 Node::Let(l) => l.serialize(),
573 Node::Var(v) => v.serialize(),
574 Node::Collator(c) => c.serialize(),
575 Node::Format(f) => f.serialize(),
576 Node::Image(i) => i.serialize(),
577 Node::NumberFormat(n) => n.serialize(),
578 Node::Within(w) => w.serialize(),
579 Node::Distance(d) => d.serialize(),
580 Node::Semiliteral(s) => s.serialize(),
581 Node::FormatSectionOverride(o) => o.serialize(),
582 Node::All(_)
583 | Node::Any(_)
584 | Node::At(_)
585 | Node::In(_)
586 | Node::Length(_)
587 | Node::Case(_)
588 | Node::Coalesce(_)
589 | Node::IndexOf(_)
590 | Node::Slice(_) => self.default_serialize(),
591 }
592 }
593
594 pub(crate) fn default_serialize(&self) -> MbglValue {
596 let mut serialized = vec![MbglValue::String(self.get_operator().to_owned())];
597 self.each_child(&mut |child| serialized.push(child.serialize()));
598 MbglValue::Array(serialized)
599 }
600
601 #[must_use]
604 pub fn possible_outputs(&self) -> Vec<Option<Value>> {
605 match &self.node {
606 Node::Literal(l) => vec![Some(l.get_value().clone())],
607 Node::Compound(c) => {
608 if c.overload().result == Type::Error {
609 Vec::new()
610 } else {
611 vec![None]
612 }
613 }
614 Node::All(_) | Node::Any(_) | Node::In(_) | Node::Comparison(_) | Node::Within(_) => {
615 vec![Some(Value::Bool(true)), Some(Value::Bool(false))]
616 }
617 Node::Assertion(_)
618 | Node::Coercion(_)
619 | Node::Case(_)
620 | Node::Coalesce(_)
621 | Node::Match(_)
622 | Node::Step(_) => {
623 let mut result = Vec::new();
624 match &self.node {
625 Node::Case(c) => c.each_output(&mut |e| result.extend(e.possible_outputs())),
626 Node::Match(m) => m.each_output(&mut |e| result.extend(e.possible_outputs())),
627 Node::Step(s) => s.each_output(&mut |e| result.extend(e.possible_outputs())),
628 _ => self.each_child(&mut |e| result.extend(e.possible_outputs())),
629 }
630 result
631 }
632 Node::Let(l) => l.result().possible_outputs(),
633 _ => vec![None],
634 }
635 }
636
637 pub fn hash_structure(&self, state: &mut dyn Hasher) {
640 let mut state = state;
641 discriminant(&self.node).hash(&mut state);
642 match &self.node {
643 Node::Literal(l) => hash_value(l.get_value(), state),
644 Node::Compound(c) => c.overload().name().hash(&mut state),
645 Node::Comparison(c) => c.get_operator().hash(&mut state),
646 Node::Assertion(_) | Node::Coercion(_) => self.get_type().hash(&mut state),
647 Node::Var(v) => v.name().hash(&mut state),
648 _ => {}
649 }
650 self.each_child(&mut |child| child.hash_structure(state));
651 }
652
653 pub(crate) fn as_compound(&self) -> Option<&CompoundExpression> {
655 match &self.node {
656 Node::Compound(c) => Some(c),
657 _ => None,
658 }
659 }
660
661 #[must_use]
666 pub fn as_equality(&self) -> Option<(&Expr, &Value)> {
667 match &self.node {
668 Node::Comparison(c) => c.as_equality(),
669 _ => None,
670 }
671 }
672
673 #[must_use]
675 pub fn as_interpolate(&self) -> Option<&Interpolate> {
676 match &self.node {
677 Node::Interpolate(i) => Some(i),
678 _ => None,
679 }
680 }
681
682 #[must_use]
684 pub fn as_format(&self) -> Option<&FormatExpression> {
685 match &self.node {
686 Node::Format(f) => Some(f),
687 _ => None,
688 }
689 }
690
691 #[must_use]
693 pub fn as_format_section_override(&self) -> Option<&FormatSectionOverride> {
694 match &self.node {
695 Node::FormatSectionOverride(o) => Some(o),
696 _ => None,
697 }
698 }
699
700 pub fn evaluate(&self, cx: &EvaluationContext<'_>) -> EvaluationResult {
702 match &self.node {
703 Node::Literal(l) => Ok(l.get_value().clone()),
704 Node::Compound(c) => c.evaluate(cx),
705 Node::Assertion(a) => a.evaluate(cx),
706 Node::Coercion(c) => c.evaluate(cx),
707 Node::Comparison(c) => c.eval_bool(cx).map(Value::Bool),
708 Node::All(_) | Node::Any(_) | Node::In(_) | Node::Within(_) => self.eval_bool(cx).map(Value::Bool),
709 Node::IndexOf(_) | Node::Length(_) | Node::Distance(_) => self.eval_num(cx).map(Value::Number),
710 Node::NumberFormat(_) => self.eval_str(cx).map(|s| Value::String(s.into_owned())),
711 Node::FormatSectionOverride(_) => self.eval_color(cx).map(Value::Color),
712 Node::At(a) => a.evaluate(cx),
713 Node::Slice(s) => s.evaluate(cx),
714 Node::Case(c) => c.eval::<Value>(cx),
715 Node::Coalesce(c) => c.evaluate(cx),
716 Node::Match(m) => m.eval::<Value>(cx),
717 Node::Step(s) => s.eval::<Value>(cx),
718 Node::Interpolate(i) => i.evaluate(cx),
719 Node::Let(l) => l.result().evaluate(cx),
720 Node::Var(v) => v.bound_expression().evaluate(cx),
721 Node::Collator(c) => c.evaluate(cx),
722 Node::Format(f) => f.evaluate(cx),
723 Node::Image(i) => i.evaluate(cx),
724 Node::Semiliteral(s) => s.evaluate(cx),
725 }
726 }
727
728 pub fn evaluate_typed(&self, cx: &EvaluationContext<'_>) -> EvaluationResult {
734 match self.get_type() {
735 Type::Number => self.eval_num(cx).map(Value::Number),
736 Type::Boolean => self.eval_bool(cx).map(Value::Bool),
737 Type::String => self.eval_str(cx).map(|s| Value::String(s.into_owned())),
738 Type::Color => self.eval_color(cx).map(Value::Color),
739 _ => self.evaluate(cx),
740 }
741 }
742
743 pub(crate) fn evaluate_ref<'e>(&'e self, cx: &EvaluationContext<'_>) -> EvalResult<Cow<'e, Value>> {
746 match &self.node {
747 Node::Literal(l) => Ok(Cow::Borrowed(l.get_value())),
748 _ => self.evaluate(cx).map(Cow::Owned),
749 }
750 }
751
752 pub fn eval_num(&self, cx: &EvaluationContext<'_>) -> EvalResult<f64> {
754 match &self.node {
755 Node::Literal(l) => match l.get_value() {
756 Value::Number(n) => Ok(*n),
757 other => f64::from_value(other.clone()),
758 },
759 Node::Compound(c) => c.eval_num(cx),
760 Node::Assertion(a) => a.eval_num(cx),
761 Node::Coercion(c) => c.eval_num(cx),
762 Node::Case(c) => c.eval(cx),
763 Node::Match(m) => m.eval(cx),
764 Node::Step(s) => s.eval(cx),
765 Node::Coalesce(c) => c.eval_typed(cx, &Type::Number),
766 Node::Interpolate(i) => i.eval_num(cx),
767 Node::Let(l) => l.result().eval_num(cx),
768 Node::Var(v) => v.bound_expression().eval_num(cx),
769 Node::Length(input) => crate::length::evaluate(input, cx),
770 Node::IndexOf(i) => i.eval_num(cx),
771 Node::Distance(d) => d.eval_num(cx),
772 _ => via_value(self, cx),
773 }
774 }
775
776 pub fn eval_bool(&self, cx: &EvaluationContext<'_>) -> EvalResult<bool> {
778 match &self.node {
779 Node::Literal(l) => match l.get_value() {
780 Value::Bool(b) => Ok(*b),
781 other => bool::from_value(other.clone()),
782 },
783 Node::Compound(c) => c.eval_bool(cx),
784 Node::Comparison(c) => c.eval_bool(cx),
785 Node::All(inputs) => {
786 for input in inputs {
787 if !input.eval_bool(cx)? {
788 return Ok(false);
789 }
790 }
791 Ok(true)
792 }
793 Node::Any(inputs) => {
794 for input in inputs {
795 if input.eval_bool(cx)? {
796 return Ok(true);
797 }
798 }
799 Ok(false)
800 }
801 Node::Assertion(a) => a.eval_bool(cx),
802 Node::Coercion(c) => c.eval_bool(cx),
803 Node::Case(c) => c.eval(cx),
804 Node::Match(m) => m.eval(cx),
805 Node::Step(s) => s.eval(cx),
806 Node::Coalesce(c) => c.eval_typed(cx, &Type::Boolean),
807 Node::Let(l) => l.result().eval_bool(cx),
808 Node::Var(v) => v.bound_expression().eval_bool(cx),
809 Node::In(i) => i.eval_bool(cx),
810 Node::Within(w) => Ok(w.eval_bool(cx)),
811 _ => via_value(self, cx),
812 }
813 }
814
815 pub fn eval_str<'e>(&'e self, cx: &EvaluationContext<'_>) -> EvalResult<Cow<'e, str>> {
817 match &self.node {
818 Node::Literal(l) => match l.get_value() {
819 Value::String(s) => Ok(Cow::Borrowed(s)),
820 other => Cow::from_value(other.clone()),
821 },
822 Node::Compound(c) => c.eval_str(cx),
823 Node::Assertion(a) => a.eval_str(cx),
824 Node::Coercion(c) => c.eval_str(cx),
825 Node::Case(c) => c.eval(cx),
826 Node::Match(m) => m.eval(cx),
827 Node::Step(s) => s.eval(cx),
828 Node::Coalesce(c) => c.eval_typed(cx, &Type::String),
829 Node::Let(l) => l.result().eval_str(cx),
830 Node::Var(v) => v.bound_expression().eval_str(cx),
831 Node::NumberFormat(n) => n.eval_str(cx).map(Cow::Owned),
832 _ => via_value(self, cx),
833 }
834 }
835
836 pub fn eval_color(&self, cx: &EvaluationContext<'_>) -> EvalResult<Color> {
838 match &self.node {
839 Node::Literal(l) => match l.get_value() {
840 Value::Color(c) => Ok(*c),
841 other => Color::from_value(other.clone()),
842 },
843 Node::Compound(c) => c.eval_color(cx),
844 Node::Coercion(c) => c.eval_color(cx),
845 Node::Case(c) => c.eval(cx),
846 Node::Match(m) => m.eval(cx),
847 Node::Step(s) => s.eval(cx),
848 Node::Coalesce(c) => c.eval_typed(cx, &Type::Color),
849 Node::Interpolate(i) => i.eval_color(cx),
850 Node::Let(l) => l.result().eval_color(cx),
851 Node::Var(v) => v.bound_expression().eval_color(cx),
852 Node::FormatSectionOverride(o) => o.eval_color(cx),
853 _ => via_value(self, cx),
854 }
855 }
856}
857
858impl Node {
859 fn own_dependencies(&self) -> Dependency {
861 match self {
862 Node::Compound(c) => c.overload().dependencies,
863 Node::Let(_) => Dependency::BIND,
864 Node::Var(v) => Dependency::VAR | v.bound_expression().deps,
865 Node::Collator(_) | Node::Within(_) | Node::Distance(_) => Dependency::FEATURE,
866 Node::Image(_) => Dependency::IMAGE,
867 Node::FormatSectionOverride(_) => Dependency::OVERRIDE | Dependency::FEATURE,
868 _ => Dependency::NONE,
869 }
870 }
871
872 fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
873 match self {
874 Node::Literal(_) | Node::Var(_) | Node::Within(_) | Node::Distance(_) => {}
875 Node::FormatSectionOverride(o) => o.each_child(visit),
876 Node::Compound(c) => c.args().iter().for_each(visit),
877 Node::Assertion(a) => a.inputs().iter().for_each(visit),
878 Node::Coercion(c) => c.inputs().iter().for_each(visit),
879 Node::Comparison(c) => c.each_child(visit),
880 Node::All(inputs) | Node::Any(inputs) => inputs.iter().for_each(visit),
881 Node::At(a) => a.each_child(visit),
882 Node::In(i) => i.each_child(visit),
883 Node::IndexOf(i) => i.each_child(visit),
884 Node::Slice(s) => s.each_child(visit),
885 Node::Length(input) => visit(input),
886 Node::Case(c) => c.each_child(visit),
887 Node::Coalesce(c) => c.args().iter().for_each(visit),
888 Node::Match(m) => m.each_child(visit),
889 Node::Step(s) => s.each_child(visit),
890 Node::Interpolate(i) => i.each_child(visit),
891 Node::Let(l) => l.each_child(visit),
892 Node::Collator(c) => c.each_child(visit),
893 Node::Format(f) => f.each_child(visit),
894 Node::Image(i) => visit(i.image_id()),
895 Node::NumberFormat(n) => n.each_child(visit),
896 Node::Semiliteral(s) => s.elements().iter().for_each(visit),
897 }
898 }
899}
900
901pub fn collect_global_state_refs(expression: &Expr, refs: &mut VecSet<String>) {
904 if !expression.has(Dependency::GLOBAL_STATE) {
905 return;
906 }
907 if let Some(compound) = expression.as_compound()
908 && compound.overload().role == Role::GlobalState
909 {
910 if let Some(Value::String(s)) = compound.args().first().and_then(Expr::literal_value) {
913 refs.insert(s.clone());
914 }
915 return;
916 }
917 expression.each_child(&mut |child| collect_global_state_refs(child, refs));
918}
919
920#[must_use]
924pub fn global_state_refs_intersect(refs: Option<&VecSet<String>>, changed_keys: Option<&VecSet<String>>) -> bool {
925 match (refs, changed_keys) {
926 (Some(refs), Some(changed_keys)) => refs.iter().any(|key| changed_keys.contains(key)),
927 _ => true,
928 }
929}
930
931struct GeoJSONFeature<'a> {
933 feature: &'a Feature<f64>,
934 geometry: GeometryCollection,
935}
936
937impl<'a> GeoJSONFeature<'a> {
938 fn new(feature: &'a Feature<f64>) -> Self {
939 GeoJSONFeature { feature, geometry: GeometryCollection::default() }
940 }
941
942 fn with_canonical(feature: &'a Feature<f64>, canonical: &CanonicalTileID) -> Self {
943 let geometry = feature.geometry.as_ref().map_or_else(GeometryCollection::default, |g| {
944 mln_tile::geometry_tile_data::convert_geometry_to_tile(g, canonical)
945 });
946 GeoJSONFeature { feature, geometry }
947 }
948}
949
950impl GeometryTileFeature for GeoJSONFeature<'_> {
951 fn get_type(&self) -> FeatureType {
952 to_feature_type(self.feature.geometry.as_ref())
953 }
954
955 fn get_properties(&self) -> Cow<'_, ValueObject> {
956 Cow::Borrowed(&self.feature.properties)
957 }
958
959 fn get_id(&self) -> FeatureIdentifier {
960 self.feature.id.clone()
961 }
962
963 fn get_value(&self, key: &str) -> Option<MbglValue> {
964 self.feature.properties.get(key).cloned()
965 }
966
967 fn get_geometries(&self) -> Result<Cow<'_, GeometryCollection>, mln_util::error::Error> {
968 Ok(Cow::Borrowed(&self.geometry))
969 }
970}
971
972#[cfg(test)]
973pub(crate) fn evaluate_feature(
974 e: &Expr,
975 zoom: Option<f32>,
976 feature: &Feature<f64>,
977 color_ramp_parameter: Option<f64>,
978) -> EvaluationResult {
979 let f = GeoJSONFeature::new(feature);
980 e.evaluate(&EvaluationContext::with_color_ramp(zoom, Some(&f), color_ramp_parameter))
981}
982
983pub fn evaluate_accumulated(e: &Expr, accumulated: Option<&MbglValue>, feature: &Feature<f64>) -> EvaluationResult {
984 let f = GeoJSONFeature::new(feature);
985 e.evaluate(&EvaluationContext::from_accumulated(accumulated, Some(&f)))
986}
987
988pub fn evaluate_feature_with_context(
993 e: &Expr,
994 feature: &Feature<f64>,
995 params: EvaluationContext<'_>,
996) -> EvaluationResult {
997 with_geojson_feature(feature, params, |cx| e.evaluate(cx))
998}
999
1000pub fn with_geojson_feature<R>(
1003 feature: &Feature<f64>,
1004 params: EvaluationContext<'_>,
1005 f: impl FnOnce(&EvaluationContext<'_>) -> R,
1006) -> R {
1007 let view = match params.canonical {
1008 Some(canonical) => GeoJSONFeature::with_canonical(feature, canonical),
1009 None => GeoJSONFeature::new(feature),
1010 };
1011 f(&EvaluationContext { feature: Some(&view), ..params })
1012}
1013
1014pub(crate) fn mbgl_to_expression_value(v: &MbglValue) -> Value {
1017 from_mbgl_value(v)
1018}
1019
1020pub(crate) type SharedExpr = Arc<Expr>;