Skip to main content

mln_expression/
coercion.rs

1use std::borrow::Cow;
2
3use feature::{Value as MbglValue, ValueObject};
4use mln_conversion::Convertible;
5use mln_style_types::{
6    AnchorOffsetPair, ProjectionDefinition, SymbolAnchorType, VariableAnchorOffsetCollection, projection_type_from_name,
7};
8use mln_util::{Color, Padding};
9
10use crate::expression::{EvalResult, EvaluationContext, EvaluationError, EvaluationResult, Expr, Node};
11use crate::formatted::Formatted;
12use crate::image::Image;
13use crate::parsing_context::{ParseResult, ParsingContext};
14use crate::type_::Type;
15use crate::util::rgba;
16use crate::value::{Value, stringify, to_string};
17
18type CoerceFunction = fn(&Value) -> EvaluationResult;
19
20fn to_boolean(v: &Value) -> bool {
21    match v {
22        Value::Number(f) => *f != 0.0,
23        Value::String(s) => !s.is_empty(),
24        Value::Bool(b) => *b,
25        Value::Null => false,
26        Value::Image(i) => i.is_available(),
27        _ => true,
28    }
29}
30
31/// A string as a number: what ECMAScript's `ToNumber` reads gives the same
32/// value, except `0x`, `0o` and `0b` literals above `u64::MAX`, and the extras
33/// Rust's `str::parse` reads, such as `inf`, are accepted too. Anything else
34/// is NaN.
35fn string_to_number(s: &str) -> f64 {
36    let s = s.trim_matches(|c: char| c.is_whitespace() || c == '\u{feff}');
37    let radix = match s.get(..2) {
38        _ if s.is_empty() => return 0.0,
39        Some("0x" | "0X") => 16,
40        Some("0o" | "0O") => 8,
41        Some("0b" | "0B") => 2,
42        _ => return s.parse().unwrap_or(f64::NAN),
43    };
44    u64::from_str_radix(&s[2..], radix).map_or(f64::NAN, |n| n as f64)
45}
46
47/// JS `Number(value)`, as GL JS's `to-number` applies it: null and booleans
48/// convert, and a value that gives NaN, or isn't a string, number, boolean or
49/// null, fails.
50///
51/// The style spec defines `to-number` on a string as ECMAScript's `ToNumber`
52/// (<https://maplibre.org/maplibre-style-spec/expressions/#to-number>,
53/// <https://tc39.es/ecma262/#sec-tonumber-applied-to-the-string-type>). As a
54/// consumer of styles rather than a validator, this reads a superset of it.
55fn to_number(v: &Value) -> EvalResult<f64> {
56    let result = match v {
57        Value::Null => Some(0.0),
58        Value::Bool(b) => Some(f64::from(u8::from(*b))),
59        Value::Number(f) => Some(*f),
60        Value::String(s) => Some(string_to_number(s)),
61        _ => None,
62    };
63    match result.filter(|r| !r.is_nan()) {
64        Some(r) => Ok(r),
65        None => Err(EvaluationError::new(format!("Could not convert {} to number.", stringify(v)))),
66    }
67}
68
69fn to_color(color_value: &Value) -> EvalResult<Color> {
70    match color_value {
71        Value::Color(color) => Ok(*color),
72        Value::String(color_string) => match Color::parse(color_string) {
73            Some(result) => Ok(result),
74            None => Err(EvaluationError::new(format!("Could not parse color from value '{color_string}'"))),
75        },
76        Value::Array(components) => match components.as_slice() {
77            [Value::Number(r), Value::Number(g), Value::Number(b)] => rgba(*r, *g, *b, 1.0),
78            [Value::Number(r), Value::Number(g), Value::Number(b), Value::Number(a)] => rgba(*r, *g, *b, *a),
79            _ => Err(EvaluationError::new(format!(
80                "Invalid rbga value {}: expected an array containing either three or four numeric values.",
81                stringify(color_value)
82            ))),
83        },
84        _ => Err(EvaluationError::new(format!("Could not parse color from value '{}'", stringify(color_value)))),
85    }
86}
87
88/// A padding from 1 to 4 values, in CSS order, or `None` for any other count.
89fn padding_from_span(values: &[f32]) -> Option<Padding> {
90    match *values {
91        [all] => Some(Padding::new(all, all, all, all)),
92        [vertical, horizontal] => Some(Padding::new(vertical, horizontal, vertical, horizontal)),
93        [top, horizontal, bottom] => Some(Padding::new(top, horizontal, bottom, horizontal)),
94        [top, right, bottom, left] => Some(Padding::new(top, right, bottom, left)),
95        _ => None,
96    }
97}
98
99fn to_projection_definition(value: &Value) -> EvaluationResult {
100    let error =
101        || Err(EvaluationError::new(format!("Could not parse projectionDefinition from value '{}'", stringify(value))));
102    match value {
103        Value::ProjectionDefinition(projection) => Ok(Value::ProjectionDefinition(*projection)),
104        Value::String(name) => match projection_type_from_name(name) {
105            Some(type_) => Ok(Value::ProjectionDefinition(ProjectionDefinition::new(type_))),
106            None => error(),
107        },
108        Value::Array(components) => {
109            if let [Value::String(from), Value::String(to), Value::Number(transition)] = components.as_slice()
110                && let (Some(from), Some(to)) = (projection_type_from_name(from), projection_type_from_name(to))
111            {
112                return Ok(Value::ProjectionDefinition(ProjectionDefinition::between(from, to, *transition)));
113            }
114            error()
115        }
116        _ => error(),
117    }
118}
119
120fn to_padding(padding_value: &Value) -> EvaluationResult {
121    match padding_value {
122        Value::Padding(padding) => Ok(Value::Padding(*padding)),
123        Value::Array(components) => {
124            let components_as_floats: Option<Vec<f32>> =
125                components.iter().map(|c| c.as_number().map(|n| n as f32)).collect();
126            if let Some(padding) = components_as_floats.as_deref().and_then(padding_from_span) {
127                Ok(Value::Padding(padding))
128            } else {
129                Err(EvaluationError::new(format!(
130                    "Invalid padding value {}: expected an array containing from one to four numeric values.",
131                    stringify(padding_value)
132                )))
133            }
134        }
135        Value::Number(number) => {
136            let v = *number as f32;
137            Ok(Value::Padding(Padding::new(v, v, v, v)))
138        }
139        _ => Err(EvaluationError::new(format!("Could not parse padding from value '{}'", stringify(padding_value)))),
140    }
141}
142
143fn to_variable_anchor_offset(value: &Value) -> EvaluationResult {
144    match value {
145        Value::VariableAnchorOffsetCollection(anchor_offset) => {
146            Ok(Value::VariableAnchorOffsetCollection(anchor_offset.clone()))
147        }
148        Value::Array(components) => {
149            let components_value = || stringify(&Value::Array(components.clone()));
150            if components.len() % 2 != 0 {
151                return Err(EvaluationError::new(format!(
152                    "Invalid variableAnchorOffset value {}: expected an array containing an even number of values.",
153                    components_value()
154                )));
155            }
156
157            let mut anchor_offsets = Vec::new();
158            let mut i = 0;
159            while i < components.len() {
160                let anchor_type_value = &components[i];
161                let offset_array = &components[i + 1];
162
163                let (Value::String(anchor_type_string), Value::Array(offset)) = (anchor_type_value, offset_array)
164                else {
165                    return Err(EvaluationError::new(format!(
166                        "Invalid variableAnchorOffset value {}: expected a string value as the first and an array with two elements as the second element of each pair.",
167                        components_value()
168                    )));
169                };
170                let [Value::Number(x), Value::Number(y)] = offset.as_slice() else {
171                    return Err(EvaluationError::new(format!(
172                        "Invalid variableAnchorOffset value {}: expected a string value as the first and an array with two elements as the second element of each pair.",
173                        components_value()
174                    )));
175                };
176
177                let Ok(anchor) = anchor_type_string.parse::<SymbolAnchorType>() else {
178                    return Err(EvaluationError::new(format!(
179                        "Invalid variableAnchorOffsetCollection value {}: unknown anchor type '{}'",
180                        components_value(),
181                        anchor_type_string
182                    )));
183                };
184
185                anchor_offsets.push(AnchorOffsetPair::new(anchor, [*x as f32, *y as f32]));
186                i += 2;
187            }
188
189            Ok(Value::VariableAnchorOffsetCollection(VariableAnchorOffsetCollection::new(anchor_offsets)))
190        }
191        _ => Err(EvaluationError::new(format!("Could not parse variableAnchorOffset from '{}'", stringify(value)))),
192    }
193}
194
195fn to_formatted(formatted_value: &Value) -> Value {
196    Value::Formatted(Formatted::from_plain(&to_string(formatted_value)))
197}
198
199fn to_image(image_value: &Value) -> Value {
200    Value::Image(Image::new(to_string(image_value)))
201}
202
203fn to_string_value(value: &Value) -> Value {
204    Value::String(to_string(value))
205}
206
207fn get_coerce_function(t: &Type) -> CoerceFunction {
208    match t {
209        Type::Boolean => |v| Ok(Value::Bool(to_boolean(v))),
210        Type::Color => |v| to_color(v).map(Value::Color),
211        Type::Padding => to_padding,
212        Type::ProjectionDefinition => to_projection_definition,
213        Type::VariableAnchorOffsetCollection => to_variable_anchor_offset,
214        Type::Number => |v| to_number(v).map(Value::Number),
215        Type::String => |v| Ok(to_string_value(v)),
216        Type::Formatted => |v| Ok(to_formatted(v)),
217        Type::Image => |v| Ok(to_image(v)),
218        _ => {
219            debug_assert!(false, "no coercion to {t}");
220            |v| Ok(to_string_value(v))
221        }
222    }
223}
224
225/// `["to-number", ...]` and the other coercions, explicit or inserted by
226/// the parser: the first input that converts, or the last one's error.
227#[derive(Clone, PartialEq, mln_wire::Wire)]
228pub(crate) struct Coercion {
229    type_: Type,
230    inputs: Box<[Expr]>,
231}
232
233impl Coercion {
234    pub(crate) fn new_expr(type_: Type, inputs: Vec<Expr>) -> Expr {
235        assert!(!inputs.is_empty(), "Coercion without inputs");
236        // `isRuntimeConstant` does not consider values coerced to `Type`
237        // image to be of `Kind` image, so we don't either (no extra
238        // dependency).
239        Expr::new(Node::Coercion(Box::new(Coercion { type_, inputs: inputs.into() })))
240    }
241
242    pub(crate) fn get_type(&self) -> &Type {
243        &self.type_
244    }
245
246    pub(crate) fn inputs(&self) -> &[Expr] {
247        &self.inputs
248    }
249
250    pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
251        let length = value.array_length();
252
253        if length < 2 {
254            ctx.error("Expected at least one argument.".to_owned());
255            return None;
256        }
257
258        let op = value.array_member(0).to_string();
259        let type_ = match op.as_deref() {
260            Some("to-boolean") => Type::Boolean,
261            Some("to-color") => Type::Color,
262            Some("to-padding") => Type::Padding,
263            Some("to-number") => Type::Number,
264            Some("to-string") => Type::String,
265            _ => {
266                ctx.error(format!("Unknown coercion {}.", op.as_deref().unwrap_or_default()));
267                return None;
268            }
269        };
270
271        if (type_ == Type::Boolean || type_ == Type::String || type_ == Type::Formatted || type_ == Type::Image)
272            && length != 2
273        {
274            ctx.error("Expected one argument.".to_owned());
275            return None;
276        }
277
278        // Special form for error-coalescing coercion expressions "to-number",
279        // "to-color", "to-padding". Since these coercions can fail at
280        // runtime, they accept multiple arguments, only evaluating one at a
281        // time until one succeeds.
282        let mut parsed = Vec::with_capacity(length - 1);
283        for i in 1..length {
284            let input = ctx.parse(&value.array_member(i), i, Some(Type::Value), None)?;
285            parsed.push(input);
286        }
287
288        Some(Coercion::new_expr(type_, parsed))
289    }
290
291    /// Converts each input's value with `coerce` until one converts.
292    fn coerce<T>(&self, params: &EvaluationContext<'_>, coerce: impl Fn(&Value) -> EvalResult<T>) -> EvalResult<T> {
293        for (i, input) in self.inputs.iter().enumerate() {
294            let value = input.evaluate_ref(params)?;
295            let coerced = coerce(&value);
296            if coerced.is_ok() || i == self.inputs.len() - 1 {
297                return coerced;
298            }
299        }
300        unreachable!("Coercion without inputs")
301    }
302
303    pub(crate) fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
304        self.coerce(params, get_coerce_function(&self.type_))
305    }
306
307    pub(crate) fn eval_num(&self, params: &EvaluationContext<'_>) -> EvalResult<f64> {
308        debug_assert_eq!(self.type_, Type::Number);
309        self.coerce(params, to_number)
310    }
311
312    pub(crate) fn eval_bool(&self, params: &EvaluationContext<'_>) -> EvalResult<bool> {
313        debug_assert_eq!(self.type_, Type::Boolean);
314        self.coerce(params, |v| Ok(to_boolean(v)))
315    }
316
317    pub(crate) fn eval_str<'e>(&'e self, params: &EvaluationContext<'_>) -> EvalResult<Cow<'e, str>> {
318        debug_assert_eq!(self.type_, Type::String);
319        // The input of a string coercion that is already a string is
320        // borrowed, not converted.
321        let input = &self.inputs[0];
322        if input.get_type() == Type::String {
323            return input.eval_str(params);
324        }
325        self.coerce(params, |v| Ok(Cow::Owned(to_string(v))))
326    }
327
328    pub(crate) fn eval_color(&self, params: &EvaluationContext<'_>) -> EvalResult<Color> {
329        debug_assert_eq!(self.type_, Type::Color);
330        self.coerce(params, to_color)
331    }
332
333    pub(crate) fn serialize(&self) -> MbglValue {
334        match &self.type_ {
335            Type::Formatted => {
336                // Since there's no explicit "to-formatted" coercion, the only
337                // coercions should be created by string expressions that get
338                // implicitly coerced to "formatted".
339                MbglValue::Array(vec![
340                    MbglValue::String("format".to_owned()),
341                    self.inputs[0].serialize(),
342                    MbglValue::Object(ValueObject::new()),
343                ])
344            }
345            // Port-only: there is no "to-image" either, and C++ writes
346            // `["image", input]`, which parses back to an image expression
347            // that asserts a string and checks availability, where the
348            // coercion takes any value. The parser makes the coercion
349            // implicitly where an image is expected and the input is a string
350            // or a value, so the input alone parses back to it. Later inputs
351            // never matter, since `to_image` can't fail.
352            Type::Image => self.inputs[0].serialize(),
353            // There is no coercion operator to these types either. The parser
354            // makes the coercion implicitly where one is expected and the
355            // input is an array or a value (or a string, for a projection
356            // definition), so the input alone parses back to it.
357            Type::ProjectionDefinition | Type::VariableAnchorOffsetCollection if self.inputs.len() == 1 => {
358                self.inputs[0].serialize()
359            }
360            _ => {
361                let mut serialized = vec![MbglValue::String(self.get_operator().to_owned())];
362                serialized.extend(self.inputs.iter().map(Expr::serialize));
363                MbglValue::Array(serialized)
364            }
365        }
366    }
367
368    pub(crate) fn get_operator(&self) -> &'static str {
369        match &self.type_ {
370            Type::Boolean => "to-boolean",
371            Type::Color => "to-color",
372            Type::Padding => "to-padding",
373            Type::ProjectionDefinition => "to-projection-definition",
374            Type::Number => "to-number",
375            Type::String => "to-string",
376            Type::VariableAnchorOffsetCollection => "to-variableanchoroffset",
377            _ => {
378                debug_assert!(false);
379                ""
380            }
381        }
382    }
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388    use crate::functions::Functions;
389    use crate::value::Value;
390
391    /// Strings `ToNumber` reads, with the values JS gives.
392    #[test]
393    fn strings_convert_as_to_number() {
394        let cases = [
395            ("12", 12.0),
396            (" \t\n\u{a0}\u{feff}\u{3000}-1.5e3\u{2028} ", -1500.0),
397            ("", 0.0),
398            ("  ", 0.0),
399            ("+.5", 0.5),
400            ("5.", 5.0),
401            ("1e400", f64::INFINITY),
402            ("-1e-400", -0.0),
403            ("Infinity", f64::INFINITY),
404            ("-Infinity", f64::NEG_INFINITY),
405            ("0x1F", 31.0),
406            ("0o17", 15.0),
407            ("0B101", 5.0),
408            ("0xFFFFFFFFFFFFFFFF", 2f64.powi(64)),
409        ];
410        for (s, expected) in cases {
411            let n = string_to_number(s);
412            assert!(n == expected && n.is_sign_negative() == expected.is_sign_negative(), "{s:?}: {n}");
413        }
414        for nan in ["12px", "50 mph", "1e", ".", "+", "-0x10", "0x", "0xg", "0b2", "NaN", "1_000"] {
415            assert!(string_to_number(nan).is_nan(), "{nan:?}");
416        }
417    }
418
419    /// The strings `ToNumber` reads that `s.trim().parse::<f64>()` doesn't,
420    /// which `string_to_number` handles itself.
421    #[test]
422    fn strings_to_number_reads_and_str_parse_does_not() {
423        let cases = [("", 0.0), ("0x10", 16.0), ("0o17", 15.0), ("0b101", 5.0), ("\u{feff}1", 1.0)];
424        for (s, expected) in cases {
425            assert_eq!(string_to_number(s), expected, "{s:?}");
426            assert!(s.trim().parse::<f64>().is_err(), "{s:?}");
427        }
428    }
429
430    /// Strings JS rejects but `str::parse` reads, which are accepted.
431    #[test]
432    fn strings_beyond_to_number_are_accepted() {
433        let cases = [("inf", f64::INFINITY), ("-INFINITY", f64::NEG_INFINITY), ("\u{85}1", 1.0)];
434        for (s, expected) in cases {
435            assert_eq!(string_to_number(s), expected, "{s:?}");
436        }
437    }
438
439    /// A projection definition from a value serializes to an expression that
440    /// parses back to it.
441    #[test]
442    fn projection_definition_coercion_parses_back() {
443        let parse = |json: &serde_json::Value| {
444            ParsingContext::with_expected(&Functions::with_builtins(), Type::ProjectionDefinition)
445                .parse_expression(&Convertible::from(json), None)
446                .unwrap()
447        };
448        let json = serde_json::json!(["global-state", "projection"]);
449        let expression = parse(&json);
450        let serialized = mln_conversion::value_to_json(&expression.serialize());
451        assert_eq!(serialized, json);
452        assert_eq!(parse(&serialized).serialize(), expression.serialize());
453    }
454
455    #[test]
456    fn values_convert_as_gl_js_to_number() {
457        let number = |v: Value| to_number(&v).ok();
458        assert_eq!(number(Value::Null), Some(0.0));
459        assert_eq!(number(Value::Bool(true)), Some(1.0));
460        assert_eq!(number(Value::Bool(false)), Some(0.0));
461        assert_eq!(number(Value::String("0x10".into())), Some(16.0));
462        assert_eq!(number(Value::String("12px".into())), None);
463        assert_eq!(number(Value::String("nan".into())), None);
464        assert_eq!(number(Value::Number(f64::NAN)), None);
465        assert_eq!(number(Value::Array(vec![Value::Number(1.0)])), None);
466    }
467}