mln-rs-expression 0.0.15

Part of mln-rs, a Rust port of the MapLibre Native map rendering core. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
use std::hash::{Hash, Hasher};

use feature::{Value as MbglValue, ValueObject};
use mln_conversion::value_to_json;
use mln_style_types::{
    AlignmentType, CirclePitchScaleType, HillshadeIlluminationAnchorType, HillshadeMethodType, IconOverlapType,
    IconTextFitType, LayerBlendType, LightAnchorType, LineCapType, LineJoinType, Position, ProjectionDefinition,
    RasterResamplingType, ResamplingType, RotateAnchorType, Rotation, SymbolAnchorType, SymbolPlacementType,
    SymbolZOrderType, TextJustifyType, TextRotationAlignmentType, TextTransformType, TextWritingModeType,
    TranslateAnchorType, VariableAnchorOffsetCollection, VisibilityType,
};
use mln_util::string::to_string_double;
use mln_util::{Color, Padding};
use serde::Serialize;

use crate::collator::Collator;
use crate::expression::{EvaluationContext, Expr};
use crate::formatted::Formatted;
use crate::image::Image;
use crate::type_::Type;

/// The object alternative of `expression::Value`.
// C++ uses std::unordered_map, whose iteration order is libstdc++-hash
// dependent; a VecMap iterates in key order.
pub type ObjectType = mln_vec_map::VecMap<String, Value>;

/// An expression value, with the variants in the C++ variant's order.
#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
pub enum Value {
    #[default]
    Null,
    Bool(bool),
    Number(f64),
    String(String),
    Color(Color),
    VariableAnchorOffsetCollection(VariableAnchorOffsetCollection),
    /// Only made while evaluating, so never part of an expression's data.
    Collator(#[wire(with = "no_collator")] Collator),
    Formatted(Formatted),
    Image(Image),
    Padding(Padding),
    ProjectionDefinition(ProjectionDefinition),
    Array(Vec<Value>),
    Object(ObjectType),
}

/// A collator value has no wire form: collators exist only while an
/// expression evaluates.
mod no_collator {

    use crate::collator::Collator;

    pub(super) fn write(_: &Collator, w: &mut mln_wire::Writer) {
        w.fail("a collator value doesn't cross".to_owned());
    }

    pub(super) fn read(r: &mut mln_wire::Reader<'_>) -> Option<Collator> {
        r.fail("a collator value doesn't cross")
    }
}

impl Value {
    /// Javascript's `Number.MAX_SAFE_INTEGER`.
    #[must_use]
    pub(crate) const fn max_safe_integer() -> u64 {
        9_007_199_254_740_991
    }

    #[must_use]
    pub(crate) const fn is_safe_integer_u64(x: u64) -> bool {
        x <= Self::max_safe_integer()
    }

    #[must_use]
    pub(crate) const fn is_safe_integer_i64(x: i64) -> bool {
        // `-x` wraps for INT64_MIN as the C++ compiles.
        (if x > 0 { x } else { x.wrapping_neg() }) as u64 <= Self::max_safe_integer()
    }

    #[must_use]
    pub(crate) fn is_safe_integer_f64(x: f64) -> bool {
        // `static_cast<uint64_t>` of |x| >= 2^64 is UB in C++;
        // `as` saturates.
        ((if x > 0.0 { x } else { -x }) as u64) <= Self::max_safe_integer()
    }

    #[must_use]
    pub(crate) fn as_number(&self) -> Option<f64> {
        match self {
            Value::Number(n) => Some(*n),
            _ => None,
        }
    }

    #[must_use]
    pub(crate) fn as_bool(&self) -> Option<bool> {
        match self {
            Value::Bool(b) => Some(*b),
            _ => None,
        }
    }

    #[must_use]
    pub(crate) fn as_str(&self) -> Option<&str> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }
}

impl From<bool> for Value {
    fn from(v: bool) -> Self {
        Value::Bool(v)
    }
}
impl From<f64> for Value {
    fn from(v: f64) -> Self {
        Value::Number(v)
    }
}
impl From<&str> for Value {
    fn from(v: &str) -> Self {
        Value::String(v.to_owned())
    }
}
impl From<String> for Value {
    fn from(v: String) -> Self {
        Value::String(v)
    }
}
impl From<Color> for Value {
    fn from(v: Color) -> Self {
        Value::Color(v)
    }
}
impl From<Padding> for Value {
    fn from(v: Padding) -> Self {
        Value::Padding(v)
    }
}
impl From<ProjectionDefinition> for Value {
    fn from(v: ProjectionDefinition) -> Self {
        Value::ProjectionDefinition(v)
    }
}
impl From<VariableAnchorOffsetCollection> for Value {
    fn from(v: VariableAnchorOffsetCollection) -> Self {
        Value::VariableAnchorOffsetCollection(v)
    }
}
impl From<Collator> for Value {
    fn from(v: Collator) -> Self {
        Value::Collator(v)
    }
}
impl From<Formatted> for Value {
    fn from(v: Formatted) -> Self {
        Value::Formatted(v)
    }
}
impl From<Image> for Value {
    fn from(v: Image) -> Self {
        Value::Image(v)
    }
}
impl From<Vec<Value>> for Value {
    fn from(v: Vec<Value>) -> Self {
        Value::Array(v)
    }
}
impl From<ObjectType> for Value {
    fn from(v: ObjectType) -> Self {
        Value::Object(v)
    }
}

/// Feeds `state` the value, so that values that `==` each other hash alike:
/// a null, boolean, number or string in full, an array by its elements, and
/// any other value by its variant alone.
pub(crate) fn hash_value(value: &Value, mut state: &mut dyn Hasher) {
    std::mem::discriminant(value).hash(&mut state);
    match value {
        Value::Bool(b) => b.hash(&mut state),
        // 0.0 == -0.0.
        Value::Number(n) => (if *n == 0.0 { 0.0_f64 } else { *n }).to_bits().hash(&mut state),
        Value::String(s) => s.hash(&mut state),
        Value::Array(values) => {
            values.len().hash(&mut state);
            for value in values {
                hash_value(value, state);
            }
        }
        _ => {}
    }
}

#[must_use]
pub fn type_of(value: &Value) -> Type {
    match value {
        Value::Bool(_) => Type::Boolean,
        Value::Number(_) => Type::Number,
        Value::String(_) => Type::String,
        Value::Color(_) => Type::Color,
        Value::Padding(_) => Type::Padding,
        Value::ProjectionDefinition(_) => Type::ProjectionDefinition,
        Value::VariableAnchorOffsetCollection(_) => Type::VariableAnchorOffsetCollection,
        Value::Collator(_) => Type::Collator,
        Value::Formatted(_) => Type::Formatted,
        Value::Image(_) => Type::Image,
        Value::Null => Type::Null,
        Value::Object(_) => Type::Object,
        Value::Array(arr) => {
            let mut item_type: Option<Type> = None;
            for item in arr {
                let t = type_of(item);
                match &item_type {
                    None => item_type = Some(t),
                    Some(it) if *it == t => {}
                    Some(_) => {
                        item_type = Some(Type::Value);
                        break;
                    }
                }
            }

            Type::array_n(item_type.unwrap_or(Type::Value), arr.len())
        }
    }
}

/// Converts a value to a string as GL JS `toString(value)` does: strings,
/// numbers and booleans as `String(value)`, colors as `rgba(...)`, `null` as
/// `""`, and every other value as [`stringify()`] writes it.
#[must_use]
pub(crate) fn to_string(value: &Value) -> String {
    match value {
        Value::Null => String::new(),
        Value::Number(n) => to_string_double(*n),
        Value::Color(c) => c.stringify(),                          // avoid quoting
        Value::VariableAnchorOffsetCollection(v) => v.to_string(), // avoid quoting
        Value::Formatted(f) => f.to_string(),
        Value::Image(i) => i.id().to_owned(),
        Value::String(s) => s.clone(), // avoid quoting
        v => stringify(v),
    }
}

/// A JSON number, or `null` for NaN and infinities, as `JSON.stringify`
/// writes them.
fn json_number(n: f64) -> serde_json::Value {
    serde_json::Number::from_f64(n).map_or(serde_json::Value::Null, serde_json::Value::Number)
}

fn to_json(value: &Value) -> serde_json::Value {
    use serde_json::Value as Json;
    match value {
        Value::Null => Json::Null,
        Value::Bool(b) => Json::Bool(*b),
        Value::Number(n) => json_number(*n),
        Value::String(s) => Json::String(s.clone()),
        Value::Color(c) => Json::String(c.stringify()),
        // `toArray()`: top, right, bottom, left.
        Value::Padding(p) => Json::Array([p.top, p.right, p.bottom, p.left].map(|v| json_number(v.into())).into()),
        Value::ProjectionDefinition(p) => value_to_json(&p.serialize()),
        Value::VariableAnchorOffsetCollection(v) => value_to_json(&v.serialize()),
        Value::Collator(_) => {
            // Collators are excluded from constant folding and there's no
            // Literal parser for them so there shouldn't be any way to
            // serialize this value.
            debug_assert!(false, "stringify of a Collator");
            Json::Null
        }
        // Serialization strategy for Formatted objects is to return the
        // constant expression that would generate them.
        Value::Formatted(_) | Value::Image(_) => value_to_json(&to_mbgl_value(value)),
        Value::Array(arr) => Json::Array(arr.iter().map(to_json).collect()),
        Value::Object(obj) => Json::Object(obj.iter().map(|(k, v)| (k.clone(), to_json(v))).collect()),
    }
}

/// Writes numbers as JavaScript does (see [`to_string_double`]).
struct JsNumbers;

impl serde_json::ser::Formatter for JsNumbers {
    fn write_f64<W: ?Sized + std::io::Write>(&mut self, writer: &mut W, value: f64) -> std::io::Result<()> {
        writer.write_all(to_string_double(value).as_bytes())
    }
}

/// `value` as GL JS's `JSON.stringify(value)` writes it: compact, with
/// JavaScript's number formatting, and `null` for NaN and infinities.
#[must_use]
pub fn stringify(value: &Value) -> String {
    let mut json = Vec::new();
    // Writing to a Vec doesn't fail, and serde_json writes UTF-8.
    let _ = to_json(value).serialize(&mut serde_json::Serializer::with_formatter(&mut json, JsNumbers));
    String::from_utf8(json).unwrap_or_default()
}

pub fn from_mbgl_value(value: &MbglValue) -> Value {
    match value {
        MbglValue::Array(v) => Value::Array(v.iter().map(from_mbgl_value).collect()),
        MbglValue::Object(v) => Value::Object(v.iter().map(|(k, v)| (k.clone(), from_mbgl_value(v))).collect()),
        MbglValue::String(s) => Value::String(s.clone()),
        MbglValue::Bool(b) => Value::Bool(*b),
        MbglValue::Null => Value::Null,
        MbglValue::Double(v) => Value::Number(*v),
        MbglValue::Uint(v) => Value::Number(*v as f64),
        MbglValue::Int(v) => Value::Number(*v as f64),
    }
}

/// [`from_mbgl_value`] for an owned value, moving its strings, arrays and
/// objects instead of cloning them.
pub(crate) fn from_mbgl_value_owned(value: MbglValue) -> Value {
    match value {
        MbglValue::Array(v) => Value::Array(v.into_iter().map(from_mbgl_value_owned).collect()),
        MbglValue::Object(v) => Value::Object(v.into_iter().map(|(k, v)| (k, from_mbgl_value_owned(v))).collect()),
        MbglValue::String(s) => Value::String(s),
        other => from_mbgl_value(&other),
    }
}

pub fn to_mbgl_value(value: &Value) -> MbglValue {
    match value {
        Value::Color(color) => color.serialize(),
        Value::Padding(padding) => padding.serialize(),
        Value::ProjectionDefinition(projection) => projection.serialize(),
        Value::VariableAnchorOffsetCollection(anchor_offset) => anchor_offset.serialize(),
        Value::Collator(_) => {
            // fromExpressionValue can't be used for Collator values, because
            // they have no meaningful representation as an mln::Value
            debug_assert!(false, "to_mbgl_value of a Collator");
            MbglValue::Null
        }
        Value::Formatted(formatted) => {
            // Serialization strategy for Formatted objects is to return the
            // constant expression that would generate them.
            let mut serialized = vec![MbglValue::String("format".to_owned())];
            for section in &formatted.sections {
                let mut options = ValueObject::new();
                if let Some(vertical_align) = section.vertical_align {
                    options.insert("vertical-align".to_owned(), MbglValue::String(vertical_align.as_str().to_owned()));
                }

                if let Some(image) = &section.image {
                    serialized.push(MbglValue::Array(vec![
                        MbglValue::String("image".to_owned()),
                        MbglValue::String(image.id().to_owned()),
                    ]));
                    if !options.is_empty() {
                        serialized.push(MbglValue::Object(options));
                    }
                    continue;
                }

                serialized.push(MbglValue::String(section.text.clone()));

                if let Some(font_scale) = section.font_scale {
                    options.insert("font-scale".to_owned(), MbglValue::Double(font_scale));
                }

                if let Some(font_stack) = &section.font_stack {
                    let font_stack: Vec<MbglValue> = font_stack.iter().map(|f| MbglValue::String(f.clone())).collect();
                    options.insert(
                        "text-font".to_owned(),
                        MbglValue::Array(vec![MbglValue::String("literal".to_owned()), MbglValue::Array(font_stack)]),
                    );
                }

                if let Some(text_color) = &section.text_color {
                    options.insert("text-color".to_owned(), to_mbgl_value(&Value::Color(*text_color)));
                }

                serialized.push(MbglValue::Object(options));
            }
            MbglValue::Array(serialized)
        }
        Value::Image(i) => i.to_value(),
        Value::Array(values) => MbglValue::Array(values.iter().map(to_mbgl_value).collect()),
        Value::Object(values) => MbglValue::Object(values.iter().map(|(k, v)| (k.clone(), to_mbgl_value(v))).collect()),
        Value::Null => MbglValue::Null,
        Value::Bool(b) => MbglValue::Bool(*b),
        Value::Number(d) => MbglValue::Double(*d),
        Value::String(s) => MbglValue::String(s.clone()),
    }
}

/// Conversions between a style value type and expression `Value`s, and the
/// type's expression type.
pub trait ValueConverter: Sized {
    fn expression_type() -> Type;
    fn to_expression_value(&self) -> Value;
    fn from_expression_value(value: &Value) -> Option<Self>;

    /// Evaluates `expression`, of this type, to a `Self`: `None` when it
    /// fails or gives another type. The types that typed evaluation covers
    /// skip building a [`Value`].
    #[must_use]
    fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
        Self::from_expression_value(&expression.evaluate(context).ok()?)
    }

    /// Converts an array element-wise. The `Color` implementation also wraps a
    /// single color.
    fn vec_from_expression_value(value: &Value) -> Option<Vec<Self>> {
        match value {
            Value::Array(v) => v.iter().map(Self::from_expression_value).collect(),
            _ => None,
        }
    }
}

#[must_use]
pub fn from_expression_value<T: ValueConverter>(value: &Value) -> Option<T> {
    T::from_expression_value(value)
}

#[must_use]
pub fn from_expression_values<T: ValueConverter>(values: &[Option<Value>]) -> Vec<Option<T>> {
    values.iter().map(|value| value.as_ref().and_then(from_expression_value::<T>)).collect()
}

impl ValueConverter for Value {
    fn expression_type() -> Type {
        Type::Value
    }
    fn to_expression_value(&self) -> Value {
        self.clone()
    }
    fn from_expression_value(value: &Value) -> Option<Self> {
        Some(value.clone())
    }
}

impl ValueConverter for MbglValue {
    // C++ has no expressionType() for mln::Value.
    fn expression_type() -> Type {
        Type::Value
    }
    fn to_expression_value(&self) -> Value {
        from_mbgl_value(self)
    }
    fn from_expression_value(value: &Value) -> Option<Self> {
        Some(to_mbgl_value(value))
    }
}

impl ValueConverter for f32 {
    fn expression_type() -> Type {
        Type::Number
    }
    fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
        if expression.get_type() != Type::Number {
            return Self::from_expression_value(&expression.evaluate(context).ok()?);
        }
        expression.eval_num(context).ok().map(|n| n as f32)
    }
    fn to_expression_value(&self) -> Value {
        Value::Number(f64::from(*self))
    }
    fn from_expression_value(value: &Value) -> Option<Self> {
        value.as_number().map(|d| d as f32)
    }
}

fn evaluate_as_value<T: ValueConverter>(expression: &Expr, context: &EvaluationContext<'_>) -> Option<T> {
    T::from_expression_value(&expression.evaluate(context).ok()?)
}

fn evaluate_bool(expression: &Expr, context: &EvaluationContext<'_>) -> Option<bool> {
    expression.eval_bool(context).ok()
}

fn evaluate_number(expression: &Expr, context: &EvaluationContext<'_>) -> Option<f64> {
    expression.eval_num(context).ok()
}

fn evaluate_string(expression: &Expr, context: &EvaluationContext<'_>) -> Option<String> {
    expression.eval_str(context).ok().map(std::borrow::Cow::into_owned)
}

macro_rules! simple_value_converter {
    ($t:ty, $variant:ident, $type_:expr) => {
        simple_value_converter!($t, $variant, $type_, evaluate_as_value);
    };
    ($t:ty, $variant:ident, $type_:expr, $evaluate:path) => {
        impl ValueConverter for $t {
            fn expression_type() -> Type {
                $type_
            }
            fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
                if expression.get_type() != $type_ {
                    return Self::from_expression_value(&expression.evaluate(context).ok()?);
                }
                $evaluate(expression, context)
            }
            fn to_expression_value(&self) -> Value {
                Value::$variant(self.clone())
            }
            fn from_expression_value(value: &Value) -> Option<Self> {
                match value {
                    Value::$variant(v) => Some(v.clone()),
                    _ => None,
                }
            }
        }
    };
}

simple_value_converter!(bool, Bool, Type::Boolean, evaluate_bool);
simple_value_converter!(f64, Number, Type::Number, evaluate_number);
simple_value_converter!(String, String, Type::String, evaluate_string);
impl ValueConverter for Color {
    fn expression_type() -> Type {
        Type::Color
    }
    fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
        if expression.get_type() != Type::Color {
            return Self::from_expression_value(&expression.evaluate(context).ok()?);
        }
        expression.eval_color(context).ok()
    }
    fn to_expression_value(&self) -> Value {
        Value::Color(*self)
    }
    fn from_expression_value(value: &Value) -> Option<Self> {
        match value {
            Value::Color(v) => Some(*v),
            _ => None,
        }
    }

    /// An array converts element-wise; a single color is wrapped in a
    /// one-element vector.
    fn vec_from_expression_value(value: &Value) -> Option<Vec<Self>> {
        if let Value::Array(values) = value {
            let mut result = Vec::with_capacity(values.len());
            for v in values {
                result.push(Color::from_expression_value(v)?);
            }
            return Some(result);
        }

        // Handle single color - wrap in array
        let color = Color::from_expression_value(value)?;
        Some(vec![color])
    }
}
simple_value_converter!(Padding, Padding, Type::Padding);
simple_value_converter!(ProjectionDefinition, ProjectionDefinition, Type::ProjectionDefinition);
simple_value_converter!(
    VariableAnchorOffsetCollection,
    VariableAnchorOffsetCollection,
    Type::VariableAnchorOffsetCollection
);
simple_value_converter!(Collator, Collator, Type::Collator);
simple_value_converter!(Formatted, Formatted, Type::Formatted);
simple_value_converter!(Image, Image, Type::Image);
simple_value_converter!(ObjectType, Object, Type::Object);

impl<T: ValueConverter> ValueConverter for Vec<T> {
    fn expression_type() -> Type {
        Type::array(T::expression_type())
    }
    fn to_expression_value(&self) -> Value {
        Value::Array(self.iter().map(T::to_expression_value).collect())
    }
    fn from_expression_value(value: &Value) -> Option<Self> {
        T::vec_from_expression_value(value)
    }
}

impl<T: ValueConverter, const N: usize> ValueConverter for [T; N] {
    fn expression_type() -> Type {
        Type::array_n(T::expression_type(), N)
    }
    fn to_expression_value(&self) -> Value {
        Value::Array(self.iter().map(T::to_expression_value).collect())
    }
    fn from_expression_value(value: &Value) -> Option<Self> {
        match value {
            Value::Array(v) => {
                if v.len() != N {
                    return None;
                }
                let items: Option<Vec<T>> = v.iter().map(T::from_expression_value).collect();
                items.and_then(|items| items.try_into().ok())
            }
            _ => None,
        }
    }
}

impl ValueConverter for Position {
    fn expression_type() -> Type {
        Type::array_n(Type::Number, 3)
    }
    fn to_expression_value(&self) -> Value {
        self.get_spherical().to_expression_value()
    }
    fn from_expression_value(value: &Value) -> Option<Self> {
        <[f32; 3]>::from_expression_value(value).map(Position::new)
    }
}

impl ValueConverter for Rotation {
    fn expression_type() -> Type {
        Type::Number
    }
    fn to_expression_value(&self) -> Value {
        (self.get_angle() as f32).to_expression_value()
    }
    fn from_expression_value(value: &Value) -> Option<Self> {
        f32::from_expression_value(value).map(|angle| Rotation::new(f64::from(angle)))
    }
}

macro_rules! enum_value_converter {
    ($($t:ty),* $(,)?) => {
        $(
            impl ValueConverter for $t {
                fn expression_type() -> Type {
                    Type::String
                }
                fn to_expression_value(&self) -> Value {
                    Value::String(self.as_str().to_owned())
                }
                fn from_expression_value(value: &Value) -> Option<Self> {
                    match value {
                        Value::String(v) => v.parse().ok(),
                        _ => None,
                    }
                }
            }
        )*
    };
}

enum_value_converter!(
    AlignmentType,
    CirclePitchScaleType,
    HillshadeIlluminationAnchorType,
    HillshadeMethodType,
    IconOverlapType,
    IconTextFitType,
    LayerBlendType,
    LightAnchorType,
    LineCapType,
    LineJoinType,
    RasterResamplingType,
    ResamplingType,
    RotateAnchorType,
    SymbolAnchorType,
    SymbolPlacementType,
    SymbolZOrderType,
    TextJustifyType,
    TextRotationAlignmentType,
    TextTransformType,
    TextWritingModeType,
    TranslateAnchorType,
    VisibilityType,
);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn type_of_arrays() {
        let v = Value::Array(vec![Value::Number(1.0), Value::Number(2.0)]);
        assert_eq!(type_of(&v), Type::array_n(Type::Number, 2));
        let v = Value::Array(vec![Value::Number(1.0), Value::String("a".into())]);
        assert_eq!(type_of(&v), Type::array_n(Type::Value, 2));
        assert_eq!(type_of(&Value::Array(vec![])), Type::array_n(Type::Value, 0));
    }

    #[test]
    fn safe_integers() {
        assert!(Value::is_safe_integer_f64(9_007_199_254_740_991.0));
        assert!(!Value::is_safe_integer_f64(9_007_199_254_740_992.0));
        assert!(!Value::is_safe_integer_i64(i64::MIN));
    }

    /// `to-string` follows GL JS: `String(n)` for a number, and
    /// `JSON.stringify` for an array or object.
    #[test]
    fn to_string_formats_numbers_as_javascript() {
        let n = Value::Number;
        assert_eq!(to_string(&n(1.0)), "1");
        assert_eq!(to_string(&n(1e21)), "1e+21");
        assert_eq!(to_string(&n(f64::NAN)), "NaN");
        let array = Value::Array(vec![n(1.0), n(0.5), n(1e10), n(f64::INFINITY)]);
        assert_eq!(to_string(&array), "[1,0.5,10000000000,null]");
        let object = Value::Object([("a\n".to_owned(), n(-0.0))].into_iter().collect());
        assert_eq!(to_string(&object), r#"{"a\n":0}"#);
    }
}