Skip to main content

mln_expression/
coalesce.rs

1// Ports include/mln/style/expression/coalesce.hpp and
2// src/mln/style/expression/coalesce.cpp.
3
4use crate::check_subtype::check_subtype;
5use crate::expression::{
6    EvaluationContext, EvaluationResult, Expression, ExpressionBase, Kind, children_equal,
7    collect_dependencies, downcast,
8};
9use crate::image::Image;
10use crate::parsing_context::{ParseResult, ParsingContext, TypeAnnotationOption};
11use crate::type_::Type;
12use crate::value::{Value, from_expression_value};
13use mln_conversion::Convertible;
14
15pub type Args = Vec<Box<dyn Expression>>;
16
17pub struct Coalesce {
18    base: ExpressionBase,
19    args: Args,
20}
21
22impl Coalesce {
23    pub fn new(type_: Type, args: Args) -> Self {
24        Coalesce {
25            base: ExpressionBase::new(Kind::Coalesce, type_, collect_dependencies(&args)),
26            args,
27        }
28    }
29
30    pub fn get_length(&self) -> usize {
31        self.args.len()
32    }
33
34    pub fn get_child(&self, i: usize) -> &dyn Expression {
35        &*self.args[i]
36    }
37
38    pub fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
39        debug_assert!(value.is_array());
40        let length = value.array_length();
41        if length < 2 {
42            ctx.error("Expected at least one argument.".to_owned());
43            return None;
44        }
45
46        let mut output_type: Option<Type> = None;
47        let expected_type = ctx.get_expected();
48        if let Some(expected) = &expected_type {
49            if *expected != Type::Value {
50                output_type = Some(expected.clone());
51            }
52        }
53
54        let mut args = Args::with_capacity(length - 1);
55        for i in 1..length {
56            let parsed = ctx.parse(
57                &value.array_member(i),
58                i,
59                output_type.clone(),
60                Some(TypeAnnotationOption::Omit),
61            )?;
62            if output_type.is_none() {
63                output_type = Some(parsed.get_type().clone());
64            }
65            args.push(parsed);
66        }
67        let output_type = output_type.expect("coalesce output type");
68
69        // Above, we parse arguments without inferred type annotation so that
70        // they don't produce a runtime error for `null` input, which would
71        // preempt the desired null-coalescing behavior. Thus, if any of our
72        // arguments would have needed an annotation, we need to wrap the
73        // enclosing coalesce expression with it instead.
74        let needs_annotation = expected_type
75            .as_ref()
76            .is_some_and(|expected| args.iter().any(|arg| check_subtype(expected, arg.get_type()).is_some()));
77
78        Some(Box::new(Coalesce::new(
79            if needs_annotation { Type::Value } else { output_type },
80            args,
81        )))
82    }
83}
84
85impl Expression for Coalesce {
86    fn base(&self) -> &ExpressionBase {
87        &self.base
88    }
89
90    fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
91        let mut result: EvaluationResult = Ok(Value::Null);
92        let mut args_count = self.args.len();
93        let mut requested_image: Option<Image> = None;
94        for arg in &self.args {
95            args_count -= 1;
96            result = arg.evaluate(params);
97            // We need to keep track of the first requested image in a
98            // coalesce statement. If coalesce can't find a valid image, we
99            // return the first requested image.
100            if *self.get_type() == Type::Image {
101                if let Ok(r) = &result {
102                    if let Some(image) = from_expression_value::<Image>(r) {
103                        if !image.is_available() {
104                            if requested_image.is_none() {
105                                requested_image = Some(Image::new(image.id()));
106                            }
107                            if args_count == 0 {
108                                result = Ok(Value::Image(requested_image.clone().unwrap()));
109                            }
110                            continue;
111                        }
112                    }
113                }
114            }
115
116            match &result {
117                Err(_) => break,
118                Ok(v) if *v != Value::Null => break,
119                Ok(_) => {}
120            }
121        }
122        result
123    }
124
125    fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression)) {
126        for arg in &self.args {
127            visit(&**arg);
128        }
129    }
130
131    fn equals(&self, e: &dyn Expression) -> bool {
132        if e.get_kind() == Kind::Coalesce {
133            let rhs = downcast::<Coalesce>(e).expect("Coalesce");
134            return children_equal(&self.args, &rhs.args);
135        }
136        false
137    }
138
139    fn possible_outputs(&self) -> Vec<Option<Value>> {
140        let mut result = Vec::new();
141        for arg in &self.args {
142            result.extend(arg.possible_outputs());
143        }
144        result
145    }
146
147    fn get_operator(&self) -> String {
148        "coalesce".to_owned()
149    }
150}