Skip to main content

mln_style/expression/forms/
case.rs

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