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