Skip to main content

mln_expression/
case.rs

1// Ports include/mln/style/expression/case.hpp and
2// src/mln/style/expression/case.cpp.
3
4use crate::expression::{
5    Dependency, EvaluationContext, EvaluationResult, Expression, ExpressionBase, Kind, downcast,
6};
7use crate::parsing_context::{ParseResult, ParsingContext};
8use crate::type_::Type;
9use crate::value::Value;
10use mln_conversion::Convertible;
11
12pub type Branch = (Box<dyn Expression>, Box<dyn Expression>);
13
14pub struct Case {
15    base: ExpressionBase,
16    branches: Vec<Branch>,
17    otherwise: Box<dyn Expression>,
18}
19
20impl Case {
21    pub fn new(type_: Type, branches: Vec<Branch>, otherwise: Box<dyn Expression>) -> Self {
22        let deps = branches
23            .iter()
24            .fold(Dependency::NONE, |a, b| a | b.0.dependencies() | b.1.dependencies())
25            | otherwise.dependencies();
26        Case {
27            base: ExpressionBase::new(Kind::Case, type_, deps),
28            branches,
29            otherwise,
30        }
31    }
32
33    pub fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
34        debug_assert!(value.is_array());
35        let length = value.array_length();
36        if length < 4 {
37            ctx.error(format!(
38                "Expected at least 3 arguments, but found only {}.",
39                length - 1
40            ));
41            return None;
42        }
43
44        // Expect even-length array: ["case", 2 * (n pairs)..., otherwise]
45        if length % 2 != 0 {
46            ctx.error("Expected an odd number of arguments".to_owned());
47            return None;
48        }
49
50        let mut output_type: Option<Type> = None;
51        if let Some(expected) = ctx.get_expected() {
52            if expected != Type::Value {
53                output_type = Some(expected);
54            }
55        }
56
57        let mut branches = Vec::with_capacity((length - 2) / 2);
58        let mut i = 1;
59        while i + 1 < length {
60            let test = ctx.parse(&value.array_member(i), i, Some(Type::Boolean), None)?;
61            let output = ctx.parse(&value.array_member(i + 1), i + 1, output_type.clone(), None)?;
62
63            if output_type.is_none() {
64                output_type = Some(output.get_type().clone());
65            }
66
67            branches.push((test, output));
68            i += 2;
69        }
70
71        let output_type = output_type.expect("case output type");
72
73        let otherwise = ctx.parse(&value.array_member(length - 1), length - 1, Some(output_type.clone()), None)?;
74
75        Some(Box::new(Case::new(output_type, branches, otherwise)))
76    }
77}
78
79impl Expression for Case {
80    fn base(&self) -> &ExpressionBase {
81        &self.base
82    }
83
84    fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
85        for branch in &self.branches {
86            let evaluated_test = branch.0.evaluate(params)?;
87            if evaluated_test.as_bool().expect("boolean test") {
88                return branch.1.evaluate(params);
89            }
90        }
91
92        self.otherwise.evaluate(params)
93    }
94
95    fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression)) {
96        for branch in &self.branches {
97            visit(&*branch.0);
98            visit(&*branch.1);
99        }
100        visit(&*self.otherwise);
101    }
102
103    fn equals(&self, e: &dyn Expression) -> bool {
104        if e.get_kind() == Kind::Case {
105            let rhs = downcast::<Case>(e).expect("Case");
106            return self.otherwise.equals(&*rhs.otherwise)
107                && self.branches.len() == rhs.branches.len()
108                && self
109                    .branches
110                    .iter()
111                    .zip(&rhs.branches)
112                    .all(|(l, r)| l.0.equals(&*r.0) && l.1.equals(&*r.1));
113        }
114        false
115    }
116
117    fn possible_outputs(&self) -> Vec<Option<Value>> {
118        let mut result = Vec::new();
119        for branch in &self.branches {
120            result.extend(branch.1.possible_outputs());
121        }
122        result.extend(self.otherwise.possible_outputs());
123        result
124    }
125
126    fn get_operator(&self) -> String {
127        "case".to_owned()
128    }
129}