Skip to main content

mln_expression/
value.rs

1// Ports include/mln/style/expression/value.hpp and
2// src/mln/style/expression/value.cpp, plus the parts of
3// src/mln/style/conversion/stringify.hpp that `stringify` uses.
4
5use crate::collator::Collator;
6use crate::formatted::Formatted;
7use crate::image::Image;
8use crate::json_writer::Writer;
9use crate::type_::{self, Type};
10use maplibre_native_base::{Value as MbglValue, ValueObject};
11use mln_style_types::{
12    AlignmentType, CirclePitchScaleType, HillshadeIlluminationAnchorType, HillshadeMethodType,
13    IconTextFitType, LightAnchorType, LineCapType, LineJoinType, Position, RasterResamplingType,
14    RotateAnchorType, Rotation, SymbolAnchorType, SymbolPlacementType, SymbolZOrderType,
15    TextJustifyType, TextTransformType, TextWritingModeType, TranslateAnchorType,
16    VariableAnchorOffsetCollection, VisibilityType,
17};
18use mln_util::enum_::Enum;
19use mln_util::{Color, Padding};
20use std::collections::BTreeMap;
21
22/// The object alternative of `expression::Value`.
23// C++ uses std::unordered_map, whose iteration order is libstdc++-hash
24// dependent; a BTreeMap iterates in key order (see DEVIATIONS.md).
25pub type ObjectType = BTreeMap<String, Value>;
26
27/// `expression::Value`, same variant order as the C++ variant.
28#[derive(Clone, Debug, Default, PartialEq)]
29pub enum Value {
30    #[default]
31    Null,
32    Bool(bool),
33    Number(f64),
34    String(String),
35    Color(Color),
36    VariableAnchorOffsetCollection(VariableAnchorOffsetCollection),
37    Collator(Collator),
38    Formatted(Formatted),
39    Image(Image),
40    Padding(Padding),
41    Array(Vec<Value>),
42    Object(ObjectType),
43}
44
45impl Value {
46    /// Javascript's Number.MAX_SAFE_INTEGER.
47    pub const fn max_safe_integer() -> u64 {
48        9007199254740991
49    }
50
51    pub const fn is_safe_integer_u64(x: u64) -> bool {
52        x <= Self::max_safe_integer()
53    }
54
55    pub const fn is_safe_integer_i64(x: i64) -> bool {
56        // `-x` wraps for INT64_MIN as the C++ compiles.
57        (if x > 0 { x } else { x.wrapping_neg() }) as u64 <= Self::max_safe_integer()
58    }
59
60    pub fn is_safe_integer_f64(x: f64) -> bool {
61        // TODO(port): `static_cast<uint64_t>` of |x| >= 2^64 is UB in C++;
62        // `as` saturates.
63        ((if x > 0.0 { x } else { -x }) as u64) <= Self::max_safe_integer()
64    }
65
66    pub fn is_null(&self) -> bool {
67        matches!(self, Value::Null)
68    }
69
70    pub fn as_number(&self) -> Option<f64> {
71        match self {
72            Value::Number(n) => Some(*n),
73            _ => None,
74        }
75    }
76
77    pub fn as_bool(&self) -> Option<bool> {
78        match self {
79            Value::Bool(b) => Some(*b),
80            _ => None,
81        }
82    }
83
84    pub fn as_str(&self) -> Option<&str> {
85        match self {
86            Value::String(s) => Some(s),
87            _ => None,
88        }
89    }
90
91    pub fn as_array(&self) -> Option<&Vec<Value>> {
92        match self {
93            Value::Array(a) => Some(a),
94            _ => None,
95        }
96    }
97
98    pub fn as_object(&self) -> Option<&ObjectType> {
99        match self {
100            Value::Object(o) => Some(o),
101            _ => None,
102        }
103    }
104}
105
106impl From<bool> for Value {
107    fn from(v: bool) -> Self {
108        Value::Bool(v)
109    }
110}
111impl From<f64> for Value {
112    fn from(v: f64) -> Self {
113        Value::Number(v)
114    }
115}
116impl From<&str> for Value {
117    fn from(v: &str) -> Self {
118        Value::String(v.to_owned())
119    }
120}
121impl From<String> for Value {
122    fn from(v: String) -> Self {
123        Value::String(v)
124    }
125}
126impl From<Color> for Value {
127    fn from(v: Color) -> Self {
128        Value::Color(v)
129    }
130}
131impl From<Padding> for Value {
132    fn from(v: Padding) -> Self {
133        Value::Padding(v)
134    }
135}
136impl From<VariableAnchorOffsetCollection> for Value {
137    fn from(v: VariableAnchorOffsetCollection) -> Self {
138        Value::VariableAnchorOffsetCollection(v)
139    }
140}
141impl From<Collator> for Value {
142    fn from(v: Collator) -> Self {
143        Value::Collator(v)
144    }
145}
146impl From<Formatted> for Value {
147    fn from(v: Formatted) -> Self {
148        Value::Formatted(v)
149    }
150}
151impl From<Image> for Value {
152    fn from(v: Image) -> Self {
153        Value::Image(v)
154    }
155}
156impl From<Vec<Value>> for Value {
157    fn from(v: Vec<Value>) -> Self {
158        Value::Array(v)
159    }
160}
161impl From<ObjectType> for Value {
162    fn from(v: ObjectType) -> Self {
163        Value::Object(v)
164    }
165}
166
167/// `typeOf`.
168pub fn type_of(value: &Value) -> Type {
169    match value {
170        Value::Bool(_) => Type::Boolean,
171        Value::Number(_) => Type::Number,
172        Value::String(_) => Type::String,
173        Value::Color(_) => Type::Color,
174        Value::Padding(_) => Type::Padding,
175        Value::VariableAnchorOffsetCollection(_) => Type::VariableAnchorOffsetCollection,
176        Value::Collator(_) => Type::Collator,
177        Value::Formatted(_) => Type::Formatted,
178        Value::Image(_) => Type::Image,
179        Value::Null => Type::Null,
180        Value::Object(_) => Type::Object,
181        Value::Array(arr) => {
182            let mut item_type: Option<Type> = None;
183            for item in arr {
184                let t = type_of(item);
185                match &item_type {
186                    None => item_type = Some(t),
187                    Some(it) if *it == t => continue,
188                    Some(_) => {
189                        item_type = Some(Type::Value);
190                        break;
191                    }
192                }
193            }
194
195            Type::array_n(item_type.unwrap_or(Type::Value), arr.len())
196        }
197    }
198}
199
200/// `expression::toString(const Value&)`.
201pub fn to_string(value: &Value) -> String {
202    match value {
203        Value::Null => String::new(),
204        Value::Color(c) => c.stringify(), // avoid quoting
205        Value::VariableAnchorOffsetCollection(v) => v.to_string(), // avoid quoting
206        Value::Formatted(f) => f.to_string(),
207        Value::Image(i) => i.id().to_owned(),
208        Value::String(s) => s.clone(), // avoid quoting
209        v => stringify(v),
210    }
211}
212
213fn write_json(writer: &mut Writer, value: &Value) {
214    match value {
215        Value::Null => writer.null(),
216        Value::Bool(b) => writer.bool_(*b),
217        Value::Number(f) => {
218            // make sure integer values are stringified without trailing ".0".
219            if *f == f.floor() {
220                writer.int(static_cast_int(*f));
221            } else {
222                writer.double(*f);
223            }
224        }
225        Value::String(s) => writer.string(s),
226        Value::Color(c) => writer.string(&c.stringify()),
227        Value::Padding(p) => stringify_padding(writer, p),
228        Value::VariableAnchorOffsetCollection(v) => {
229            stringify_variable_anchor_offset_collection(writer, v)
230        }
231        Value::Collator(_) => {
232            // Collators are excluded from constant folding and there's no
233            // Literal parser for them so there shouldn't be any way to
234            // serialize this value.
235            debug_assert!(false, "stringify of a Collator");
236        }
237        // `stringify` in turns calls ValueConverter::fromExpressionValue
238        // below. Serialization strategy for Formatted objects is to return
239        // the constant expression that would generate them.
240        Value::Formatted(f) => stringify_mbgl(writer, &to_mbgl_value(&Value::Formatted(f.clone()))),
241        Value::Image(i) => stringify_mbgl(writer, &to_mbgl_value(&Value::Image(i.clone()))),
242        Value::Array(arr) => {
243            writer.start_array();
244            for item in arr {
245                write_json(writer, item);
246            }
247            writer.end_array();
248        }
249        Value::Object(obj) => {
250            writer.start_object();
251            for (k, v) in obj {
252                writer.key(k);
253                write_json(writer, v);
254            }
255            writer.end_object();
256        }
257    }
258}
259
260/// `static_cast<int>(double)` for an integral double as clang compiles it on
261/// x86-64 (`cvttsd2si`): out-of-range values become INT_MIN.
262fn static_cast_int(f: f64) -> i32 {
263    if f >= -2147483648.0 && f < 2147483648.0 {
264        f as i32
265    } else {
266        i32::MIN
267    }
268}
269
270/// `conversion::stringify(writer, const Padding&)` (via `toArray()`).
271fn stringify_padding(writer: &mut Writer, p: &Padding) {
272    writer.start_array();
273    writer.double(p.top as f64);
274    writer.double(p.right as f64);
275    writer.double(p.bottom as f64);
276    writer.double(p.left as f64);
277    writer.end_array();
278}
279
280/// `conversion::stringify(writer, const VariableAnchorOffsetCollection&)`.
281fn stringify_variable_anchor_offset_collection(
282    writer: &mut Writer,
283    v: &VariableAnchorOffsetCollection,
284) {
285    writer.start_array();
286    for pair in v.iter() {
287        writer.string(pair.anchor_type.to_string());
288        writer.start_array();
289        writer.double(pair.offset[0] as f64);
290        writer.double(pair.offset[1] as f64);
291        writer.end_array();
292    }
293    writer.end_array();
294}
295
296/// `conversion::stringify(writer, const mln::Value&)`.
297pub(crate) fn stringify_mbgl(writer: &mut Writer, v: &MbglValue) {
298    match v {
299        MbglValue::Null => writer.null(),
300        MbglValue::Bool(b) => writer.bool_(*b),
301        MbglValue::Uint(u) => writer.uint64(*u),
302        MbglValue::Int(i) => writer.int64(*i),
303        MbglValue::Double(d) => {
304            writer.double(*d);
305        }
306        MbglValue::String(s) => writer.string(s),
307        MbglValue::Array(a) => {
308            writer.start_array();
309            for e in a {
310                stringify_mbgl(writer, e);
311            }
312            writer.end_array();
313        }
314        MbglValue::Object(m) => {
315            writer.start_object();
316            for (k, v) in m {
317                writer.key(k);
318                stringify_mbgl(writer, v);
319            }
320            writer.end_object();
321        }
322    }
323}
324
325/// `expression::stringify(const Value&)`.
326pub fn stringify(value: &Value) -> String {
327    let mut writer = Writer::new();
328    write_json(&mut writer, value);
329    writer.into_string()
330}
331
332/// `ValueConverter<mln::Value>::toExpressionValue` (`FromMBGLValue`).
333pub fn from_mbgl_value(value: &MbglValue) -> Value {
334    match value {
335        MbglValue::Array(v) => Value::Array(v.iter().map(from_mbgl_value).collect()),
336        MbglValue::Object(v) => Value::Object(
337            v.iter()
338                .map(|(k, v)| (k.clone(), from_mbgl_value(v)))
339                .collect(),
340        ),
341        MbglValue::String(s) => Value::String(s.clone()),
342        MbglValue::Bool(b) => Value::Bool(*b),
343        MbglValue::Null => Value::Null,
344        MbglValue::Double(v) => Value::Number(*v),
345        MbglValue::Uint(v) => Value::Number(*v as f64),
346        MbglValue::Int(v) => Value::Number(*v as f64),
347    }
348}
349
350/// `ValueConverter<mln::Value>::fromExpressionValue`.
351pub fn to_mbgl_value(value: &Value) -> MbglValue {
352    match value {
353        Value::Color(color) => color.serialize(),
354        Value::Padding(padding) => padding.serialize(),
355        Value::VariableAnchorOffsetCollection(anchor_offset) => anchor_offset.serialize(),
356        Value::Collator(_) => {
357            // fromExpressionValue can't be used for Collator values, because
358            // they have no meaningful representation as an mln::Value
359            debug_assert!(false, "to_mbgl_value of a Collator");
360            MbglValue::Null
361        }
362        Value::Formatted(formatted) => {
363            // Serialization strategy for Formatted objects is to return the
364            // constant expression that would generate them.
365            let mut serialized = vec![MbglValue::String("format".to_owned())];
366            for section in &formatted.sections {
367                if let Some(image) = &section.image {
368                    serialized.push(MbglValue::Array(vec![
369                        MbglValue::String("image".to_owned()),
370                        MbglValue::String(image.id().to_owned()),
371                    ]));
372                    continue;
373                }
374
375                serialized.push(MbglValue::String(section.text.clone()));
376                let mut options = ValueObject::new();
377
378                if let Some(font_scale) = section.font_scale {
379                    options.insert("font-scale".to_owned(), MbglValue::Double(font_scale));
380                }
381
382                if let Some(font_stack) = &section.font_stack {
383                    let font_stack: Vec<MbglValue> =
384                        font_stack.iter().map(|f| MbglValue::String(f.clone())).collect();
385                    options.insert(
386                        "text-font".to_owned(),
387                        MbglValue::Array(vec![
388                            MbglValue::String("literal".to_owned()),
389                            MbglValue::Array(font_stack),
390                        ]),
391                    );
392                }
393
394                if let Some(text_color) = &section.text_color {
395                    options.insert(
396                        "text-color".to_owned(),
397                        to_mbgl_value(&Value::Color(*text_color)),
398                    );
399                }
400
401                serialized.push(MbglValue::Object(options));
402            }
403            MbglValue::Array(serialized)
404        }
405        Value::Image(i) => i.to_value(),
406        Value::Array(values) => MbglValue::Array(values.iter().map(to_mbgl_value).collect()),
407        Value::Object(values) => MbglValue::Object(
408            values
409                .iter()
410                .map(|(k, v)| (k.clone(), to_mbgl_value(v)))
411                .collect(),
412        ),
413        Value::Null => MbglValue::Null,
414        Value::Bool(b) => MbglValue::Bool(*b),
415        Value::Number(d) => MbglValue::Double(*d),
416        Value::String(s) => MbglValue::String(s.clone()),
417    }
418}
419
420/// `ValueConverter<T>`: conversions between style value types and
421/// `expression::Value`, plus `valueTypeToExpressionType<T>()`.
422pub trait ValueConverter: Sized {
423    fn expression_type() -> Type;
424    fn to_expression_value(&self) -> Value;
425    fn from_expression_value(value: &Value) -> Option<Self>;
426
427    /// `ValueConverter<std::vector<T>>::fromExpressionValue`: an array,
428    /// element-wise. C++ specializes it for `std::vector<Color>`
429    /// (hillshade_conversions.cpp), which also wraps a single color.
430    fn vec_from_expression_value(value: &Value) -> Option<Vec<Self>> {
431        match value {
432            Value::Array(v) => v.iter().map(Self::from_expression_value).collect(),
433            _ => None,
434        }
435    }
436}
437
438pub fn to_expression_value<T: ValueConverter>(value: &T) -> Value {
439    value.to_expression_value()
440}
441
442pub fn from_expression_value<T: ValueConverter>(value: &Value) -> Option<T> {
443    T::from_expression_value(value)
444}
445
446pub fn value_type_to_expression_type<T: ValueConverter>() -> Type {
447    T::expression_type()
448}
449
450/// `fromExpressionValues<T>`.
451pub fn from_expression_values<T: ValueConverter>(values: &[Option<Value>]) -> Vec<Option<T>> {
452    values
453        .iter()
454        .map(|value| value.as_ref().and_then(from_expression_value::<T>))
455        .collect()
456}
457
458impl ValueConverter for Value {
459    fn expression_type() -> Type {
460        Type::Value
461    }
462    fn to_expression_value(&self) -> Value {
463        self.clone()
464    }
465    fn from_expression_value(value: &Value) -> Option<Self> {
466        Some(value.clone())
467    }
468}
469
470impl ValueConverter for MbglValue {
471    // C++ has no expressionType() for mln::Value.
472    fn expression_type() -> Type {
473        Type::Value
474    }
475    fn to_expression_value(&self) -> Value {
476        from_mbgl_value(self)
477    }
478    fn from_expression_value(value: &Value) -> Option<Self> {
479        Some(to_mbgl_value(value))
480    }
481}
482
483impl ValueConverter for f32 {
484    fn expression_type() -> Type {
485        Type::Number
486    }
487    fn to_expression_value(&self) -> Value {
488        Value::Number(*self as f64)
489    }
490    fn from_expression_value(value: &Value) -> Option<Self> {
491        value.as_number().map(|d| d as f32)
492    }
493}
494
495macro_rules! simple_value_converter {
496    ($t:ty, $variant:ident, $type_:expr) => {
497        impl ValueConverter for $t {
498            fn expression_type() -> Type {
499                $type_
500            }
501            fn to_expression_value(&self) -> Value {
502                Value::$variant(self.clone())
503            }
504            fn from_expression_value(value: &Value) -> Option<Self> {
505                match value {
506                    Value::$variant(v) => Some(v.clone()),
507                    _ => None,
508                }
509            }
510        }
511    };
512}
513
514simple_value_converter!(bool, Bool, Type::Boolean);
515simple_value_converter!(f64, Number, Type::Number);
516simple_value_converter!(String, String, Type::String);
517impl ValueConverter for Color {
518    fn expression_type() -> Type {
519        Type::Color
520    }
521    fn to_expression_value(&self) -> Value {
522        Value::Color(*self)
523    }
524    fn from_expression_value(value: &Value) -> Option<Self> {
525        match value {
526            Value::Color(v) => Some(*v),
527            _ => None,
528        }
529    }
530
531    /// `ValueConverter<std::vector<Color>>::fromExpressionValue`
532    /// (hillshade_conversions.cpp): an array converts element-wise; a single
533    /// color is wrapped in a one-element vector.
534    fn vec_from_expression_value(value: &Value) -> Option<Vec<Self>> {
535        if let Value::Array(values) = value {
536            let mut result = Vec::with_capacity(values.len());
537            for v in values {
538                result.push(Color::from_expression_value(v)?);
539            }
540            return Some(result);
541        }
542
543        // Handle single color - wrap in array
544        let color = Color::from_expression_value(value)?;
545        Some(vec![color])
546    }
547}
548simple_value_converter!(Padding, Padding, Type::Padding);
549simple_value_converter!(
550    VariableAnchorOffsetCollection,
551    VariableAnchorOffsetCollection,
552    Type::VariableAnchorOffsetCollection
553);
554simple_value_converter!(Collator, Collator, Type::Collator);
555simple_value_converter!(Formatted, Formatted, Type::Formatted);
556simple_value_converter!(Image, Image, Type::Image);
557simple_value_converter!(ObjectType, Object, Type::Object);
558
559impl<T: ValueConverter> ValueConverter for Vec<T> {
560    fn expression_type() -> Type {
561        Type::array(T::expression_type())
562    }
563    fn to_expression_value(&self) -> Value {
564        Value::Array(self.iter().map(T::to_expression_value).collect())
565    }
566    fn from_expression_value(value: &Value) -> Option<Self> {
567        T::vec_from_expression_value(value)
568    }
569}
570
571impl<T: ValueConverter, const N: usize> ValueConverter for [T; N] {
572    fn expression_type() -> Type {
573        Type::array_n(T::expression_type(), N)
574    }
575    fn to_expression_value(&self) -> Value {
576        Value::Array(self.iter().map(T::to_expression_value).collect())
577    }
578    fn from_expression_value(value: &Value) -> Option<Self> {
579        match value {
580            Value::Array(v) => {
581                if v.len() != N {
582                    return None;
583                }
584                let items: Option<Vec<T>> = v.iter().map(T::from_expression_value).collect();
585                items.and_then(|items| items.try_into().ok())
586            }
587            _ => None,
588        }
589    }
590}
591
592impl ValueConverter for Position {
593    fn expression_type() -> Type {
594        Type::array_n(Type::Number, 3)
595    }
596    fn to_expression_value(&self) -> Value {
597        self.get_spherical().to_expression_value()
598    }
599    fn from_expression_value(value: &Value) -> Option<Self> {
600        <[f32; 3]>::from_expression_value(value).map(Position::new)
601    }
602}
603
604impl ValueConverter for Rotation {
605    fn expression_type() -> Type {
606        Type::Number
607    }
608    fn to_expression_value(&self) -> Value {
609        (self.get_angle() as f32).to_expression_value()
610    }
611    fn from_expression_value(value: &Value) -> Option<Self> {
612        f32::from_expression_value(value).map(|angle| Rotation::new(angle as f64))
613    }
614}
615
616macro_rules! enum_value_converter {
617    ($($t:ty),* $(,)?) => {
618        $(
619            impl ValueConverter for $t {
620                fn expression_type() -> Type {
621                    Type::String
622                }
623                fn to_expression_value(&self) -> Value {
624                    Value::String(Enum::to_string(*self).to_owned())
625                }
626                fn from_expression_value(value: &Value) -> Option<Self> {
627                    match value {
628                        Value::String(v) => <$t as Enum>::to_enum(v),
629                        _ => None,
630                    }
631                }
632            }
633        )*
634    };
635}
636
637enum_value_converter!(
638    AlignmentType,
639    CirclePitchScaleType,
640    HillshadeIlluminationAnchorType,
641    HillshadeMethodType,
642    IconTextFitType,
643    LightAnchorType,
644    LineCapType,
645    LineJoinType,
646    RasterResamplingType,
647    RotateAnchorType,
648    SymbolAnchorType,
649    SymbolPlacementType,
650    SymbolZOrderType,
651    TextJustifyType,
652    TextTransformType,
653    TextWritingModeType,
654    TranslateAnchorType,
655    VisibilityType,
656);
657
658/// `type::toString` re-exported next to the value helpers, as the C++ code
659/// calls both unqualified.
660pub fn type_to_string(t: &Type) -> String {
661    type_::to_string(t)
662}
663
664#[cfg(test)]
665mod tests {
666    use super::*;
667
668    #[test]
669    fn type_of_arrays() {
670        let v = Value::Array(vec![Value::Number(1.0), Value::Number(2.0)]);
671        assert_eq!(type_of(&v), Type::array_n(Type::Number, 2));
672        let v = Value::Array(vec![Value::Number(1.0), Value::String("a".into())]);
673        assert_eq!(type_of(&v), Type::array_n(Type::Value, 2));
674        assert_eq!(type_of(&Value::Array(vec![])), Type::array_n(Type::Value, 0));
675    }
676
677    #[test]
678    fn safe_integers() {
679        assert!(Value::is_safe_integer_f64(9007199254740991.0));
680        assert!(!Value::is_safe_integer_f64(9007199254740992.0));
681        assert!(!Value::is_safe_integer_i64(i64::MIN));
682    }
683}