Skip to main content

vortex_expr/
apply.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use smallvec::SmallVec;
5use vortex_array::ArrayRef;
6use vortex_array::IntoArray;
7use vortex_array::arrays::ConstantArray;
8use vortex_array::arrays::ScalarFnArray;
9use vortex_array::scalar_fn::builtin::literal::Literal;
10use vortex_error::VortexExpect;
11use vortex_error::VortexResult;
12
13use crate::BoundExpression;
14use crate::Expression;
15use crate::expression::unbound_variable;
16
17/// Evaluation of expressions over arrays.
18pub trait ArrayExprExt: Sized {
19    /// Apply a bound expression to this array, producing a new array in constant time.
20    fn apply_bound(self, expr: &BoundExpression) -> VortexResult<ArrayRef>;
21
22    /// Apply the expression to this array, producing a new array in constant time.
23    fn apply(self, expr: &Expression) -> VortexResult<ArrayRef>;
24}
25
26impl ArrayExprExt for ArrayRef {
27    fn apply_bound(self, expr: &BoundExpression) -> VortexResult<ArrayRef> {
28        let BoundExpression::Scalar {
29            scalar_fn,
30            children,
31            ..
32        } = expr
33        else {
34            return Ok(self);
35        };
36
37        if let Some(scalar) = scalar_fn.as_opt::<Literal>() {
38            return Ok(ConstantArray::new(scalar.clone(), self.len()).into_array());
39        }
40
41        let len = self.len();
42        let children = children
43            .iter()
44            .map(|child| self.clone().apply_bound(child))
45            .collect::<VortexResult<SmallVec<[ArrayRef; 4]>>>()?;
46
47        Ok(ScalarFnArray::try_new_with_len(scalar_fn.clone(), children, len)?.into_array())
48    }
49
50    fn apply(self, expr: &Expression) -> VortexResult<ArrayRef> {
51        // If the expression is a root, return self.
52        if expr.is_root() {
53            return Ok(self);
54        }
55        if let Expression::Variable(name) = expr {
56            return Err(unbound_variable(name));
57        }
58
59        // Manually convert literals to ConstantArray.
60        if let Some(scalar) = expr.as_opt::<Literal>() {
61            return Ok(ConstantArray::new(scalar.clone(), self.len()).into_array());
62        }
63
64        // Otherwise, collect the child arrays.
65        let len = self.len();
66        let children = expr
67            .children()
68            .iter()
69            .map(|e| self.clone().apply(e))
70            .collect::<VortexResult<SmallVec<[ArrayRef; 4]>>>()?;
71
72        // And wrap the scalar function up in an array.
73        let scalar_fn = expr
74            .as_scalar()
75            .vortex_expect("leaves and literals were handled above, so this is a scalar node");
76        Ok(ScalarFnArray::try_new_with_len(scalar_fn.clone(), children, len)?.into_array())
77    }
78}