Skip to main content

vortex_expr/lambda/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Lambdas, the function arguments of higher-order scalar functions such as `list_transform`.
5//!
6//! A [`Lambda`] is a list of parameter names and a body that reads them with
7//! [`var`](crate::var). A function that takes a lambda keeps it in its options. When the
8//! function's node is bound, it binds the lambda to its parameters' dtypes, once, and keeps the
9//! [`BoundLambda`] instead.
10//!
11//! Binding turns the lambda into an ordinary expression over a struct of its inputs, one field per
12//! parameter: `@x` becomes `$.x`. To run it, the function puts the parameters' arrays in that
13//! struct, such as one row per list element, and applies the bound body to it. The body reads
14//! nothing but its parameters, so the function's children are everything it reads.
15
16#[cfg(test)]
17mod tests;
18
19pub mod row_count;
20
21use std::fmt;
22use std::fmt::Display;
23use std::fmt::Formatter;
24
25use itertools::Itertools;
26use vortex_array::ArrayRef;
27use vortex_array::IntoArray;
28use vortex_array::arrays::StructArray;
29use vortex_array::dtype::DType;
30use vortex_array::dtype::FieldName;
31use vortex_array::dtype::FieldNames;
32use vortex_array::dtype::Nullability;
33use vortex_array::dtype::StructFields;
34use vortex_array::validity::Validity;
35use vortex_error::VortexExpect;
36use vortex_error::VortexResult;
37use vortex_error::vortex_bail;
38use vortex_error::vortex_ensure;
39
40use crate::ArrayExprExt;
41use crate::BoundExpression;
42use crate::Expression;
43use crate::get_item;
44use crate::lambda::row_count::RowCount;
45use crate::root;
46use crate::traversal::NodeExt;
47use crate::traversal::Transformed;
48use crate::traversal::TraversalOrder;
49use crate::traversal::pre_order_visit_down;
50
51/// Parameter names and a body: the function argument of a higher-order scalar function, as
52/// written.
53///
54/// The body is an ordinary [`Expression`] that reads its parameters with
55/// [`var`](crate::var), and nothing else from outside the lambda.
56///
57/// ```rust
58/// # use vortex_expr::{Lambda, checked_add, lit, var};
59/// let lambda = Lambda::new(["x"], checked_add(var("x"), lit(1_i32))).unwrap();
60/// assert_eq!(lambda.to_string(), "(x) -> (@x + 1i32)");
61/// ```
62#[derive(Clone, Debug, PartialEq, Eq, Hash)]
63pub struct Lambda {
64    params: FieldNames,
65    body: Expression,
66}
67
68impl Lambda {
69    /// Create a lambda with these parameters and body.
70    ///
71    /// Returns an error when a parameter repeats, or when the body reads from outside the lambda:
72    /// `$` or a column, another lambda's parameter, or the scan's `row_idx()` or `row_count()`.
73    pub fn new(
74        params: impl IntoIterator<Item = impl Into<FieldName>>,
75        body: Expression,
76    ) -> VortexResult<Self> {
77        let params: FieldNames = params.into_iter().map(Into::into).collect();
78        if let Some(param) = params.iter().duplicates().next() {
79            vortex_bail!("lambda parameter {param} is declared more than once");
80        }
81        pre_order_visit_down(&body, |node: &Expression| {
82            vortex_ensure!(
83                !reads_outside_lambda(node, params.as_ref()),
84                "lambda ({}) can only read its parameters, not {node}; reading anything else is \
85                 not supported yet",
86                params.iter().format(", ")
87            );
88            Ok(TraversalOrder::Continue)
89        })?;
90
91        Ok(Self { params, body })
92    }
93
94    /// The parameter names, in order.
95    pub fn params(&self) -> &[FieldName] {
96        self.params.as_ref()
97    }
98
99    /// The body, as written.
100    pub fn body(&self) -> &Expression {
101        &self.body
102    }
103
104    /// The dtype of the body, given the parameters' dtypes, without binding it.
105    pub fn return_dtype(&self, param_dtypes: &[DType]) -> VortexResult<DType> {
106        let inputs = inputs_dtype(self.param_fields(param_dtypes)?);
107        self.body_over_inputs().return_dtype(&inputs)
108    }
109
110    /// Bind the body to these parameter dtypes: `@x` becomes `$.x`, a field of the struct of the
111    /// lambda's inputs.
112    ///
113    /// A function that takes a lambda calls this from its `bind_options`, so the body is bound
114    /// once, with the node that holds it, and never while the function runs.
115    pub fn bind(&self, param_dtypes: &[DType]) -> VortexResult<BoundLambda> {
116        let params = self.param_fields(param_dtypes)?;
117        let body = self
118            .body_over_inputs()
119            .bind(&inputs_dtype(params.clone()))?;
120        Ok(BoundLambda { params, body })
121    }
122
123    /// Whether nothing in the body can fail, so that the body may run over values whose results
124    /// are never read, such as dictionary values that no row uses.
125    pub fn is_infallible(&self) -> bool {
126        let mut infallible = true;
127        pre_order_visit_down(&self.body, |node: &Expression| {
128            infallible &= node
129                .as_scalar()
130                .is_none_or(|scalar_fn| scalar_fn.signature().is_infallible());
131            Ok(if infallible {
132                TraversalOrder::Continue
133            } else {
134                TraversalOrder::Stop
135            })
136        })
137        .vortex_expect("expression traversal cannot fail");
138        infallible
139    }
140
141    fn param_fields(&self, param_dtypes: &[DType]) -> VortexResult<StructFields> {
142        vortex_ensure!(
143            param_dtypes.len() == self.params.len(),
144            "lambda {self} needs one dtype per parameter, got {}",
145            param_dtypes.len()
146        );
147        Ok(StructFields::new(
148            self.params.clone(),
149            param_dtypes.to_vec(),
150        ))
151    }
152
153    /// The body over the struct of the lambda's inputs, where `@x` reads the field `x`.
154    ///
155    /// A lambda in the body is a function's options, which this leaves alone: its variables are its
156    /// own parameters.
157    fn body_over_inputs(&self) -> Expression {
158        self.body
159            .clone()
160            .transform_down(|node| {
161                Ok(match &node {
162                    Expression::Variable(name) => Transformed {
163                        value: get_item(name.clone(), root()),
164                        changed: true,
165                        order: TraversalOrder::Skip,
166                    },
167                    _ => Transformed::no(node),
168                })
169            })
170            .vortex_expect("expression traversal cannot fail")
171            .into_inner()
172    }
173}
174
175/// The struct of a lambda's inputs, one field per parameter.
176fn inputs_dtype(params: StructFields) -> DType {
177    DType::Struct(params, Nullability::NonNullable)
178}
179
180impl Display for Lambda {
181    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
182        write!(f, "({}) -> {}", self.params.iter().format(", "), self.body)
183    }
184}
185
186/// A [`Lambda`] bound to its parameters' dtypes, ready to run.
187///
188/// The body is a [`BoundExpression`] over the struct of the lambda's inputs, one field per
189/// parameter: `@x` was bound as `$.x`.
190#[derive(Clone, Debug, PartialEq, Eq, Hash)]
191pub struct BoundLambda {
192    params: StructFields,
193    body: BoundExpression,
194}
195
196impl BoundLambda {
197    /// The parameters' names and dtypes, in order.
198    pub fn params(&self) -> &StructFields {
199        &self.params
200    }
201
202    /// The bound body, over the struct of the lambda's inputs.
203    pub fn body(&self) -> &BoundExpression {
204        &self.body
205    }
206
207    /// The dtype of the body.
208    pub fn dtype(&self) -> &DType {
209        self.body.dtype()
210    }
211
212    /// Whether the lambda is bound to these parameter dtypes.
213    pub fn is_bound_to(&self, param_dtypes: &[DType]) -> bool {
214        self.params.fields().eq(param_dtypes.iter().cloned())
215    }
216
217    /// Whether nothing in the body can fail. See [`Lambda::is_infallible`].
218    pub fn is_infallible(&self) -> bool {
219        let mut infallible = true;
220        pre_order_visit_down(&self.body, |node: &BoundExpression| {
221            infallible &= node
222                .as_scalar()
223                .is_none_or(|scalar_fn| scalar_fn.signature().is_infallible());
224            Ok(if infallible {
225                TraversalOrder::Continue
226            } else {
227                TraversalOrder::Stop
228            })
229        })
230        .vortex_expect("bound expression traversal cannot fail");
231        infallible
232    }
233
234    /// Evaluate the body over `len` rows of `args`, one array per parameter, with the dtypes the
235    /// lambda is bound to. They become the fields of the struct the body is applied to.
236    ///
237    /// The result is computed later, like any applied expression, so errors from running the body
238    /// come from executing it.
239    pub fn evaluate(&self, args: Vec<ArrayRef>, len: usize) -> VortexResult<ArrayRef> {
240        vortex_ensure!(
241            args.len() == self.params.nfields(),
242            "lambda {self} needs one array per parameter, got {}",
243            args.len()
244        );
245        for ((name, dtype), arg) in self
246            .params
247            .names()
248            .iter()
249            .zip(self.params.fields())
250            .zip(&args)
251        {
252            vortex_ensure!(
253                arg.dtype() == &dtype,
254                "lambda {self}: parameter {name} is bound to {dtype}, not {}",
255                arg.dtype()
256            );
257        }
258        let inputs = StructArray::try_new(
259            self.params.names().clone(),
260            args,
261            len,
262            Validity::NonNullable,
263        )?
264        .into_array();
265        inputs.apply_bound(&self.body)
266    }
267}
268
269impl Display for BoundLambda {
270    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
271        write!(
272            f,
273            "({}) -> {}",
274            self.params.names().iter().format(", "),
275            self.body
276        )
277    }
278}
279
280/// Whether `node`, in the body of a lambda with these parameters, reads a value from outside the
281/// lambda, which lambdas can't do yet: `$`, another lambda's parameter, or the scan's `row_idx()`
282/// or `row_count()`. The scan replaces those two before anything runs, but never looks inside a
283/// lambda's body.
284fn reads_outside_lambda(node: &Expression, params: &[FieldName]) -> bool {
285    match node {
286        Expression::Root => true,
287        Expression::Variable(name) => !params.contains(name),
288        // `row_idx` is defined in vortex-layout, so it is recognized by its id.
289        Expression::Scalar { scalar_fn, .. } => {
290            scalar_fn.is::<RowCount>() || scalar_fn.id().as_ref() == "vortex.row_idx"
291        }
292    }
293}