Skip to main content

mln_expression/
case.rs

1use mln_conversion::Convertible;
2
3use crate::expression::{EvalResult, EvaluationContext, Expr, Node, Output};
4use crate::parsing_context::{ParseResult, ParsingContext};
5use crate::type_::Type;
6
7/// `["case", test, output, ..., otherwise]`.
8#[derive(Clone, PartialEq, mln_wire::Wire)]
9pub struct Case {
10    type_: Type,
11    branches: Box<[(Expr, Expr)]>,
12    otherwise: Expr,
13}
14
15impl Case {
16    /// A `case` of `type_`, with `(test, output)` branches.
17    #[must_use]
18    pub fn new_expr(type_: Type, branches: Vec<(Expr, Expr)>, otherwise: Expr) -> Expr {
19        Expr::new(Node::Case(Box::new(Case { type_, branches: branches.into(), otherwise })))
20    }
21
22    pub(crate) fn get_type(&self) -> &Type {
23        &self.type_
24    }
25
26    pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
27        debug_assert!(value.is_array());
28        let length = value.array_length();
29        if length < 4 {
30            ctx.error(format!("Expected at least 3 arguments, but found only {}.", length - 1));
31            return None;
32        }
33
34        // Expect even-length array: ["case", 2 * (n pairs)..., otherwise]
35        if !length.is_multiple_of(2) {
36            ctx.error("Expected an odd number of arguments".to_owned());
37            return None;
38        }
39
40        let mut output_type: Option<Type> = None;
41        if let Some(expected) = ctx.get_expected()
42            && expected != Type::Value
43        {
44            output_type = Some(expected);
45        }
46
47        let mut branches = Vec::with_capacity((length - 2) / 2);
48        let mut i = 1;
49        while i + 1 < length {
50            let test = ctx.parse(&value.array_member(i), i, Some(Type::Boolean), None)?;
51            let output = ctx.parse(&value.array_member(i + 1), i + 1, output_type.clone(), None)?;
52
53            if output_type.is_none() {
54                output_type = Some(output.get_type());
55            }
56
57            branches.push((test, output));
58            i += 2;
59        }
60
61        let otherwise = ctx.parse(&value.array_member(length - 1), length - 1, output_type.clone(), None)?;
62        let output_type = output_type.unwrap_or_else(|| otherwise.get_type());
63
64        Some(Case::new_expr(output_type, branches, otherwise))
65    }
66
67    /// The output of the first branch whose test passes, or the fallback's.
68    pub(crate) fn eval<'e, T: Output<'e>>(&'e self, params: &EvaluationContext<'_>) -> EvalResult<T> {
69        for (test, output) in &self.branches {
70            if test.eval_bool(params)? {
71                return T::eval(output, params);
72            }
73        }
74        T::eval(&self.otherwise, params)
75    }
76
77    pub(crate) fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
78        for (test, output) in &self.branches {
79            visit(test);
80            visit(output);
81        }
82        visit(&self.otherwise);
83    }
84
85    /// Visits each output, the fallback last.
86    pub(crate) fn each_output<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
87        for (_, output) in &self.branches {
88            visit(output);
89        }
90        visit(&self.otherwise);
91    }
92}