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