1use crate::check_subtype::check_subtype;
6use crate::expression::{
7 Dependency, EvaluationContext, EvaluationResult, Expression, ExpressionBase, Kind, downcast,
8};
9use crate::parsing_context::{ParseResult, ParsingContext};
10use crate::type_::Type;
11use crate::value::Value;
12use maplibre_native_base::Value as MbglValue;
13use mln_conversion::Convertible;
14use std::collections::BTreeMap;
15use std::sync::Arc;
16
17pub trait MatchLabel: Ord + Clone + Send + Sync + 'static {
19 fn from_input(input: &Value) -> Option<Option<Self>>;
21 fn to_mbgl(&self) -> MbglValue;
22 fn from_input_type(label: &InputType) -> Self;
23}
24
25impl MatchLabel for String {
26 fn from_input(input: &Value) -> Option<Option<Self>> {
27 match input {
28 Value::String(s) => Some(Some(s.clone())),
29 _ => None,
30 }
31 }
32 fn to_mbgl(&self) -> MbglValue {
33 MbglValue::String(self.clone())
34 }
35 fn from_input_type(label: &InputType) -> Self {
36 match label {
37 InputType::String(s) => s.clone(),
38 InputType::Int(_) => panic!("string label expected"),
39 }
40 }
41}
42
43impl MatchLabel for i64 {
44 fn from_input(input: &Value) -> Option<Option<Self>> {
45 match input {
46 Value::Number(numeric) => {
47 let floored = numeric.floor();
50 let rounded = if floored >= -9223372036854775808.0 && floored < 9223372036854775808.0 {
51 floored as i64
52 } else {
53 i64::MIN
54 };
55 if *numeric == rounded as f64 {
56 Some(Some(rounded))
57 } else {
58 Some(None)
59 }
60 }
61 _ => None,
62 }
63 }
64 fn to_mbgl(&self) -> MbglValue {
65 MbglValue::Int(*self)
66 }
67 fn from_input_type(label: &InputType) -> Self {
68 match label {
69 InputType::Int(i) => *i,
70 InputType::String(_) => panic!("integer label expected"),
71 }
72 }
73}
74
75pub type Branches<T> = BTreeMap<T, Arc<dyn Expression>>;
78
79pub struct Match<T: MatchLabel> {
80 base: ExpressionBase,
81 input: Box<dyn Expression>,
82 branches: Branches<T>,
83 otherwise: Box<dyn Expression>,
84}
85
86impl<T: MatchLabel> Match<T> {
87 pub fn new(
88 type_: Type,
89 input: Box<dyn Expression>,
90 branches: Branches<T>,
91 otherwise: Box<dyn Expression>,
92 ) -> Self {
93 let deps = input.dependencies()
94 | otherwise.dependencies()
95 | branches.values().fold(Dependency::NONE, |a, e| a | e.dependencies());
96 Match {
97 base: ExpressionBase::new(Kind::Match, type_, deps),
98 input,
99 branches,
100 otherwise,
101 }
102 }
103}
104
105impl<T: MatchLabel> Expression for Match<T> {
106 fn base(&self) -> &ExpressionBase {
107 &self.base
108 }
109
110 fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
111 let input_value = self.input.evaluate(params)?;
112
113 match T::from_input(&input_value) {
114 None => self.otherwise.evaluate(params),
115 Some(None) => self.otherwise.evaluate(params),
116 Some(Some(key)) => match self.branches.get(&key) {
117 Some(branch) => branch.evaluate(params),
118 None => self.otherwise.evaluate(params),
119 },
120 }
121 }
122
123 fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression)) {
124 visit(&*self.input);
125 for branch in self.branches.values() {
126 visit(&**branch);
127 }
128 visit(&*self.otherwise);
129 }
130
131 fn equals(&self, e: &dyn Expression) -> bool {
132 if e.get_kind() == Kind::Match {
133 if let Some(rhs) = downcast::<Match<T>>(e) {
134 return self.input.equals(&*rhs.input)
135 && self.otherwise.equals(&*rhs.otherwise)
136 && self.branches.len() == rhs.branches.len()
137 && self
138 .branches
139 .iter()
140 .zip(&rhs.branches)
141 .all(|(l, r)| l.0 == r.0 && l.1.equals(&**r.1));
142 }
143 }
144 false
145 }
146
147 fn possible_outputs(&self) -> Vec<Option<Value>> {
148 let mut result = Vec::new();
149 for branch in self.branches.values() {
150 result.extend(branch.possible_outputs());
151 }
152 result.extend(self.otherwise.possible_outputs());
153 result
154 }
155
156 fn serialize(&self) -> MbglValue {
157 let mut serialized = vec![MbglValue::String(self.get_operator()), self.input.serialize()];
158
159 let mut output_lookup: Vec<(*const (), usize)> = Vec::new();
165 let mut grouped_by_output: Vec<(&Arc<dyn Expression>, Vec<MbglValue>)> = Vec::new();
166 for (label, output) in &self.branches {
167 let key = Arc::as_ptr(output) as *const ();
168 if let Some((_, index)) = output_lookup.iter().find(|(p, _)| *p == key) {
169 grouped_by_output[*index].1.push(label.to_mbgl());
172 } else {
173 output_lookup.push((key, grouped_by_output.len()));
176 grouped_by_output.push((output, vec![label.to_mbgl()]));
177 }
178 }
179
180 for (output, labels) in grouped_by_output {
181 if labels.len() == 1 {
182 serialized.push(labels.into_iter().next().unwrap());
184 } else {
185 serialized.push(MbglValue::Array(labels));
187 }
188 serialized.push(output.serialize());
190 }
191
192 serialized.push(self.otherwise.serialize());
193 MbglValue::Array(serialized)
194 }
195
196 fn get_operator(&self) -> String {
197 "match".to_owned()
198 }
199}
200
201#[derive(Clone, Debug, PartialEq, Eq)]
203pub enum InputType {
204 Int(i64),
205 String(String),
206}
207
208fn parse_input_value(
209 input: &Convertible<'_>,
210 parent_context: &mut ParsingContext,
211 index: usize,
212 input_type: &mut Option<Type>,
213) -> Option<InputType> {
214 let mut result: Option<InputType> = None;
215 let mut type_: Option<Type> = None;
216
217 let not_safe = || {
218 format!(
219 "Branch labels must be integers no larger than {}.",
220 Value::max_safe_integer()
221 )
222 };
223
224 match input.to_value() {
225 Some(MbglValue::Uint(n)) => {
226 if !Value::is_safe_integer_u64(n) {
227 parent_context.error_at(not_safe(), index);
228 } else {
229 type_ = Some(Type::Number);
230 result = Some(InputType::Int(n as i64));
231 }
232 }
233 Some(MbglValue::Int(n)) => {
234 if !Value::is_safe_integer_i64(n) {
235 parent_context.error_at(not_safe(), index);
236 } else {
237 type_ = Some(Type::Number);
238 result = Some(InputType::Int(n));
239 }
240 }
241 Some(MbglValue::Double(n)) => {
242 if !Value::is_safe_integer_f64(n) {
243 parent_context.error_at(not_safe(), index);
244 } else if n != n.floor() {
245 parent_context.error_at("Numeric branch labels must be integer values.".to_owned(), index);
246 } else {
247 type_ = Some(Type::Number);
248 result = Some(InputType::Int(n as i64));
249 }
250 }
251 Some(MbglValue::String(s)) => {
252 type_ = Some(Type::String);
253 result = Some(InputType::String(s));
254 }
255 Some(_) | None => {
256 parent_context.error_at("Branch labels must be numbers or strings.".to_owned(), index);
257 }
258 }
259
260 let Some(type_) = type_ else {
261 return result;
262 };
263
264 if let Some(it) = input_type {
265 if let Some(err) = check_subtype(it, &type_) {
266 parent_context.error_at(err, index);
267 return None;
268 }
269 } else {
270 *input_type = Some(type_);
271 }
272
273 result
274}
275
276type ParsedBranches = Vec<(Vec<InputType>, Box<dyn Expression>)>;
277
278fn create<T: MatchLabel>(
279 output_type: Type,
280 input: Box<dyn Expression>,
281 branches: ParsedBranches,
282 otherwise: Box<dyn Expression>,
283 ctx: &mut ParsingContext,
284) -> ParseResult {
285 let mut typed_branches = Branches::<T>::new();
286
287 let mut index = 2;
288
289 for (labels, output) in branches {
290 let result: Arc<dyn Expression> = Arc::from(output);
291 for label in &labels {
292 let typed_label = T::from_input_type(label);
293 if typed_branches.contains_key(&typed_label) {
294 ctx.error_at("Branch labels must be unique.".to_owned(), index);
295 return None;
296 }
297 typed_branches.insert(typed_label, result.clone());
298 }
299
300 index += 2;
301 }
302 Some(Box::new(Match::<T>::new(output_type, input, typed_branches, otherwise)))
303}
304
305pub fn parse_match(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
306 debug_assert!(value.is_array());
307 let length = value.array_length();
308 if length < 5 {
309 ctx.error(format!(
310 "Expected at least 4 arguments, but found only {}.",
311 length - 1
312 ));
313 return None;
314 }
315
316 if length % 2 != 1 {
318 ctx.error("Expected an even number of arguments.".to_owned());
319 return None;
320 }
321
322 let mut input_type: Option<Type> = None;
323 let mut output_type: Option<Type> = None;
324 if let Some(expected) = ctx.get_expected() {
325 if expected != Type::Value {
326 output_type = Some(expected);
327 }
328 }
329
330 let mut branches: ParsedBranches = Vec::with_capacity((length - 3) / 2);
331 let mut i = 2;
332 while i + 1 < length {
333 let label = value.array_member(i);
334
335 let mut labels = Vec::new();
336 if label.is_array() {
339 let group_length = label.array_length();
340 if group_length == 0 {
341 ctx.error_at("Expected at least one branch label.".to_owned(), i);
342 return None;
343 }
344
345 labels.reserve(group_length);
346 for j in 0..group_length {
347 let input_value = parse_input_value(&label.array_member(j), ctx, i, &mut input_type)?;
348 labels.push(input_value);
349 }
350 } else {
351 let input_value = parse_input_value(&label, ctx, i, &mut input_type)?;
352 labels.push(input_value);
353 }
354
355 let output = ctx.parse(&value.array_member(i + 1), i + 1, output_type.clone(), None)?;
356
357 if output_type.is_none() {
358 output_type = Some(output.get_type().clone());
359 }
360
361 branches.push((labels, output));
362 i += 2;
363 }
364
365 let input = ctx.parse(&value.array_member(1), 1, Some(Type::Value), None)?;
366
367 let otherwise = ctx.parse(&value.array_member(length - 1), length - 1, output_type.clone(), None)?;
368
369 let input_type = input_type.expect("match input type");
370 let output_type = output_type.expect("match output type");
371
372 if *input.get_type() != Type::Value {
373 if let Some(err) = check_subtype(&input_type, input.get_type()) {
374 ctx.error_at(err, 1);
375 return None;
376 }
377 }
378
379 match input_type {
380 Type::Number => create::<i64>(output_type, input, branches, otherwise, ctx),
381 Type::String => create::<String>(output_type, input, branches, otherwise, ctx),
382 _ => {
383 debug_assert!(false);
386 None
387 }
388 }
389}