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