Skip to main content

mln_expression/
coalesce.rs

1use mln_conversion::Convertible;
2
3use crate::check_subtype::check_subtype;
4use crate::expression::{EvalResult, EvaluationContext, EvaluationResult, Expr, Node, Output};
5use crate::image::Image;
6use crate::parsing_context::{ParseResult, ParsingContext, TypeAnnotationOption};
7use crate::type_::Type;
8use crate::value::{Value, from_expression_value};
9
10/// `["coalesce", ...]`: the first operand that is not null.
11#[derive(Clone, PartialEq, mln_wire::Wire)]
12pub(crate) struct Coalesce {
13    type_: Type,
14    args: Box<[Expr]>,
15}
16
17impl Coalesce {
18    pub(crate) fn new_expr(type_: Type, args: Vec<Expr>) -> Expr {
19        Expr::new(Node::Coalesce(Box::new(Coalesce { type_, args: args.into() })))
20    }
21
22    pub(crate) fn get_type(&self) -> &Type {
23        &self.type_
24    }
25
26    pub(crate) fn args(&self) -> &[Expr] {
27        &self.args
28    }
29
30    pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
31        debug_assert!(value.is_array());
32        let length = value.array_length();
33        if length < 2 {
34            ctx.error("Expected at least one argument.".to_owned());
35            return None;
36        }
37
38        let mut output_type: Option<Type> = None;
39        let expected_type = ctx.get_expected();
40        if let Some(expected) = &expected_type
41            && *expected != Type::Value
42        {
43            output_type = Some(expected.clone());
44        }
45
46        let mut args = Vec::with_capacity(length - 1);
47        for i in 1..length {
48            let parsed = ctx.parse(&value.array_member(i), i, output_type.clone(), Some(TypeAnnotationOption::Omit))?;
49            if output_type.is_none() {
50                output_type = Some(parsed.get_type());
51            }
52            args.push(parsed);
53        }
54        let Some(output_type) = output_type else {
55            ctx.error("Expected at least one argument.".to_owned());
56            return None;
57        };
58
59        // Above, we parse arguments without inferred type annotation so that
60        // they don't produce a runtime error for `null` input, which would
61        // preempt the desired null-coalescing behavior. Thus, if any of our
62        // arguments would have needed an annotation, we need to wrap the
63        // enclosing coalesce expression with it instead.
64        let needs_annotation = expected_type
65            .as_ref()
66            .is_some_and(|expected| args.iter().any(|arg| check_subtype(expected, &arg.get_type()).is_some()));
67
68        Some(Coalesce::new_expr(if needs_annotation { Type::Value } else { output_type }, args))
69    }
70
71    pub(crate) fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
72        let mut result: EvaluationResult = Ok(Value::Null);
73        let mut args_count = self.args.len();
74        let mut requested_image: Option<Image> = None;
75        for arg in &self.args {
76            args_count -= 1;
77            result = arg.evaluate(params);
78            // We need to keep track of the first requested image in a
79            // coalesce statement. If coalesce can't find a valid image, we
80            // return the first requested image.
81            if self.type_ == Type::Image
82                && let Ok(r) = &result
83                && let Some(image) = from_expression_value::<Image>(r)
84                && !image.is_available()
85            {
86                let requested_image = requested_image.get_or_insert_with(|| Image::new(image.id()));
87                if args_count == 0 {
88                    result = Ok(Value::Image(requested_image.clone()));
89                }
90                continue;
91            }
92
93            match &result {
94                Err(_) => break,
95                Ok(v) if *v != Value::Null => break,
96                Ok(_) => {}
97            }
98        }
99        result
100    }
101
102    /// The typed evaluation, for a coalesce of type `type_`. An operand of
103    /// that type is never null, so the first one decides; an operand that
104    /// the parser left a value (it omits annotations here) is skipped while
105    /// it is null.
106    pub(crate) fn eval_typed<'e, T: Output<'e>>(
107        &'e self,
108        params: &EvaluationContext<'_>,
109        type_: &Type,
110    ) -> EvalResult<T> {
111        debug_assert_eq!(&self.type_, type_);
112        for arg in &self.args {
113            if arg.get_type() == *type_ {
114                return T::eval(arg, params);
115            }
116            match arg.evaluate(params)? {
117                Value::Null => {}
118                value => return T::from_value(value),
119            }
120        }
121        T::from_value(Value::Null)
122    }
123}