1use crate::expression::{
5 Dependency, EvaluationContext, EvaluationError, EvaluationResult, Expression, ExpressionBase,
6 Kind, children_equal, collect_dependencies, default_serialize, downcast,
7};
8use crate::formatted::Formatted;
9use crate::image::Image;
10use crate::parsing_context::{ParseResult, ParsingContext};
11use crate::type_::Type;
12use crate::util::rgba;
13use crate::value::{Value, stringify, to_string};
14use maplibre_native_base::{Value as MbglValue, ValueObject};
15use mln_conversion::Convertible;
16use mln_style_types::{AnchorOffsetPair, SymbolAnchorType, VariableAnchorOffsetCollection};
17use mln_util::Padding;
18use mln_util::enum_::Enum;
19
20type CoerceFunction = fn(&Value) -> EvaluationResult;
21
22fn to_boolean(v: &Value) -> EvaluationResult {
23 Ok(Value::Bool(match v {
24 Value::Number(f) => *f != 0.0,
25 Value::String(s) => !s.is_empty(),
26 Value::Bool(b) => *b,
27 Value::Null => false,
28 Value::Image(i) => i.is_available(),
29 _ => true,
30 }))
31}
32
33fn stof(s: &str) -> Option<f32> {
36 mln_util::string::stof(s).ok()
37}
38
39fn to_number(v: &Value) -> EvaluationResult {
40 let result = match v {
41 Value::Null => Some(0.0),
42 Value::Number(f) => Some(*f),
43 Value::String(s) => stof(s).map(|f| f as f64),
44 _ => None,
45 };
46 match result {
47 Some(r) => Ok(Value::Number(r)),
48 None => Err(EvaluationError::new(format!("Could not convert {} to number.", stringify(v)))),
49 }
50}
51
52fn to_color(color_value: &Value) -> EvaluationResult {
53 match color_value {
54 Value::Color(color) => Ok(Value::Color(*color)),
55 Value::String(color_string) => match mln_util::Color::parse(color_string) {
56 Some(result) => Ok(Value::Color(result)),
57 None => Err(EvaluationError::new(format!(
58 "Could not parse color from value '{color_string}'"
59 ))),
60 },
61 Value::Array(components) => {
62 let len = components.len();
63 let is_numeric = components.iter().all(|item| matches!(item, Value::Number(_)));
64 if (len == 3 || len == 4) && is_numeric {
65 let n = |i: usize| components[i].as_number().unwrap();
66 let c = rgba(n(0), n(1), n(2), if len == 4 { n(3) } else { 1.0 })?;
67 Ok(Value::Color(c))
68 } else {
69 Err(EvaluationError::new(format!(
70 "Invalid rbga value {}: expected an array containing either three or four numeric values.",
71 stringify(color_value)
72 )))
73 }
74 }
75 _ => Err(EvaluationError::new(format!(
76 "Could not parse color from value '{}'",
77 stringify(color_value)
78 ))),
79 }
80}
81
82fn padding_from_span(values: &[f32]) -> Padding {
84 match values.len() {
85 1 => Padding::new(values[0], values[0], values[0], values[0]),
86 2 => Padding::new(values[0], values[1], values[0], values[1]),
87 3 => Padding::new(values[0], values[1], values[2], values[1]),
88 4 => Padding::new(values[0], values[1], values[2], values[3]),
89 _ => panic!("Padding must have between 1 and 4 elements"),
90 }
91}
92
93fn to_padding(padding_value: &Value) -> EvaluationResult {
94 match padding_value {
95 Value::Padding(padding) => Ok(Value::Padding(*padding)),
96 Value::Array(components) => {
97 let len = components.len();
98 let is_numeric = components.iter().all(|item| matches!(item, Value::Number(_)));
99 if (1..=4).contains(&len) && is_numeric {
100 let components_as_floats: Vec<f32> = components
101 .iter()
102 .map(|c| c.as_number().unwrap() as f32)
103 .collect();
104 Ok(Value::Padding(padding_from_span(&components_as_floats)))
105 } else {
106 Err(EvaluationError::new(format!(
107 "Invalid padding value {}: expected an array containing from one to four numeric values.",
108 stringify(padding_value)
109 )))
110 }
111 }
112 Value::Number(number) => {
113 let v = *number as f32;
114 Ok(Value::Padding(Padding::new(v, v, v, v)))
115 }
116 _ => Err(EvaluationError::new(format!(
117 "Could not parse padding from value '{}'",
118 stringify(padding_value)
119 ))),
120 }
121}
122
123fn to_variable_anchor_offset(value: &Value) -> EvaluationResult {
124 match value {
125 Value::VariableAnchorOffsetCollection(anchor_offset) => {
126 Ok(Value::VariableAnchorOffsetCollection(anchor_offset.clone()))
127 }
128 Value::Array(components) => {
129 let components_value = || stringify(&Value::Array(components.clone()));
130 if components.len() % 2 != 0 {
131 return Err(EvaluationError::new(format!(
132 "Invalid variableAnchorOffset value {}: expected an array containing an even number of values.",
133 components_value()
134 )));
135 }
136
137 let mut anchor_offsets = Vec::new();
138 let mut i = 0;
139 while i < components.len() {
140 let anchor_type_value = &components[i];
141 let offset_array = &components[i + 1];
142
143 let (Value::String(anchor_type_string), Value::Array(offset)) =
144 (anchor_type_value, offset_array)
145 else {
146 return Err(EvaluationError::new(format!(
147 "Invalid variableAnchorOffset value {}: expected a string value as the first and an array with two elements as the second element of each pair.",
148 components_value()
149 )));
150 };
151 if offset.len() != 2 {
152 return Err(EvaluationError::new(format!(
153 "Invalid variableAnchorOffset value {}: expected a string value as the first and an array with two elements as the second element of each pair.",
154 components_value()
155 )));
156 }
157
158 let Some(anchor) = SymbolAnchorType::to_enum(anchor_type_string) else {
159 return Err(EvaluationError::new(format!(
160 "Invalid variableAnchorOffsetCollection value {}: unknown anchor type '{}'",
161 components_value(),
162 anchor_type_string
163 )));
164 };
165
166 let x = offset[0].as_number().expect("numeric offset") as f32;
170 let y = offset[1].as_number().expect("numeric offset") as f32;
171
172 anchor_offsets.push(AnchorOffsetPair::new(anchor, [x, y]));
173 i += 2;
174 }
175
176 Ok(Value::VariableAnchorOffsetCollection(VariableAnchorOffsetCollection::new(
177 anchor_offsets,
178 )))
179 }
180 _ => Err(EvaluationError::new(format!(
181 "Could not parse variableAnchorOffset from '{}'",
182 stringify(value)
183 ))),
184 }
185}
186
187fn to_formatted(formatted_value: &Value) -> EvaluationResult {
188 Ok(Value::Formatted(Formatted::from_plain(&to_string(formatted_value))))
189}
190
191fn to_image(image_value: &Value) -> EvaluationResult {
192 Ok(Value::Image(Image::new(to_string(image_value))))
193}
194
195fn to_string_value(value: &Value) -> EvaluationResult {
196 Ok(Value::String(to_string(value)))
197}
198
199fn get_coerce_function(t: &Type) -> CoerceFunction {
200 match t {
201 Type::Boolean => to_boolean,
202 Type::Color => to_color,
203 Type::Padding => to_padding,
204 Type::VariableAnchorOffsetCollection => to_variable_anchor_offset,
205 Type::Number => to_number,
206 Type::String => to_string_value,
207 Type::Formatted => to_formatted,
208 Type::Image => to_image,
209 _ => {
210 debug_assert!(false, "no coercion to {t}");
211 to_string_value
212 }
213 }
214}
215
216pub struct Coercion {
217 base: ExpressionBase,
218 coerce_single_value: CoerceFunction,
219 inputs: Vec<Box<dyn Expression>>,
220}
221
222impl Coercion {
223 pub fn new(type_: Type, inputs: Vec<Box<dyn Expression>>) -> Self {
224 assert!(!inputs.is_empty());
225 let coerce_single_value = get_coerce_function(&type_);
229 Coercion {
230 base: ExpressionBase::new(
231 Kind::Coercion,
232 type_,
233 collect_dependencies(&inputs) | Dependency::NONE,
234 ),
235 coerce_single_value,
236 inputs,
237 }
238 }
239
240 pub fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
241 let length = value.array_length();
242
243 if length < 2 {
244 ctx.error("Expected at least one argument.".to_owned());
245 return None;
246 }
247
248 let op = value.array_member(0).to_string().expect("operator name");
249 let type_ = match op.as_str() {
250 "to-boolean" => Type::Boolean,
251 "to-color" => Type::Color,
252 "to-padding" => Type::Padding,
253 "to-number" => Type::Number,
254 "to-string" => Type::String,
255 "to-variableanchoroffset" => Type::VariableAnchorOffsetCollection,
256 _ => unreachable!("unknown coercion {op}"),
257 };
258
259 if (type_ == Type::Boolean
260 || type_ == Type::String
261 || type_ == Type::Formatted
262 || type_ == Type::Image)
263 && length != 2
264 {
265 ctx.error("Expected one argument.".to_owned());
266 return None;
267 }
268
269 let mut parsed = Vec::with_capacity(length - 1);
274 for i in 1..length {
275 let input = ctx.parse(&value.array_member(i), i, Some(Type::Value), None)?;
276 parsed.push(input);
277 }
278
279 Some(Box::new(Coercion::new(type_, parsed)))
280 }
281}
282
283impl Expression for Coercion {
284 fn base(&self) -> &ExpressionBase {
285 &self.base
286 }
287
288 fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
289 for (i, input) in self.inputs.iter().enumerate() {
290 let value = input.evaluate(params)?;
291 let coerced = (self.coerce_single_value)(&value);
292 if coerced.is_ok() || i == self.inputs.len() - 1 {
293 return coerced;
294 }
295 }
296
297 unreachable!("Coercion without inputs")
298 }
299
300 fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression)) {
301 for input in &self.inputs {
302 visit(&**input);
303 }
304 }
305
306 fn serialize(&self) -> MbglValue {
307 match self.get_type() {
308 Type::Formatted => {
309 MbglValue::Array(vec![
313 MbglValue::String("format".to_owned()),
314 self.inputs[0].serialize(),
315 MbglValue::Object(ValueObject::new()),
316 ])
317 }
318 Type::Image => MbglValue::Array(vec![
319 MbglValue::String("image".to_owned()),
320 self.inputs[0].serialize(),
321 ]),
322 _ => default_serialize(self),
323 }
324 }
325
326 fn equals(&self, e: &dyn Expression) -> bool {
327 if e.get_kind() == Kind::Coercion {
328 let rhs = downcast::<Coercion>(e).expect("Coercion");
329 return self.get_type() == rhs.get_type() && children_equal(&self.inputs, &rhs.inputs);
330 }
331 false
332 }
333
334 fn possible_outputs(&self) -> Vec<Option<Value>> {
335 let mut result = Vec::new();
336 for input in &self.inputs {
337 result.extend(input.possible_outputs());
338 }
339 result
340 }
341
342 fn get_operator(&self) -> String {
343 match self.get_type() {
344 Type::Boolean => "to-boolean",
345 Type::Color => "to-color",
346 Type::Padding => "to-padding",
347 Type::Number => "to-number",
348 Type::String => "to-string",
349 Type::VariableAnchorOffsetCollection => "to-variableanchoroffset",
350 _ => {
351 debug_assert!(false);
352 ""
353 }
354 }
355 .to_owned()
356 }
357}