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::scalar_fn::builtin::get_item::GetItem;
35use vortex_array::validity::Validity;
36use vortex_error::VortexExpect;
37use vortex_error::VortexResult;
38use vortex_error::vortex_bail;
39use vortex_error::vortex_ensure;
40
41use crate::ArrayExprExt;
42use crate::BoundExpression;
43use crate::Expression;
44use crate::get_item;
45use crate::lambda::row_count::RowCount;
46use crate::root;
47use crate::traversal::NodeExt;
48use crate::traversal::Transformed;
49use crate::traversal::TraversalOrder;
50use crate::traversal::pre_order_visit_down;
51
52/// Parameter names and a body: the function argument of a higher-order scalar function, as
53/// written.
54///
55/// The body is an ordinary [`Expression`] that reads its parameters with
56/// [`var`](crate::var), and nothing else from outside the lambda.
57///
58/// ```rust
59/// # use vortex_expr::{Lambda, checked_add, lit, var};
60/// let lambda = Lambda::new(["x"], checked_add(var("x"), lit(1_i32))).unwrap();
61/// assert_eq!(lambda.to_string(), "(x) -> (@x + 1i32)");
62/// ```
63#[derive(Clone, Debug, PartialEq, Eq, Hash)]
64pub struct Lambda {
65    params: FieldNames,
66    body: Expression,
67}
68
69impl Lambda {
70    /// Create a lambda with these parameters and body.
71    ///
72    /// Returns an error when a parameter repeats, or when the body reads from outside the lambda:
73    /// `$` or a column, another lambda's parameter, or the scan's `row_idx()` or `row_count()`.
74    pub fn new(
75        params: impl IntoIterator<Item = impl Into<FieldName>>,
76        body: Expression,
77    ) -> VortexResult<Self> {
78        let params: FieldNames = params.into_iter().map(Into::into).collect();
79        if let Some(param) = params.iter().duplicates().next() {
80            vortex_bail!("lambda parameter {param} is declared more than once");
81        }
82        pre_order_visit_down(&body, |node: &Expression| {
83            vortex_ensure!(
84                !reads_outside_lambda(node, params.as_ref()),
85                "lambda ({}) can only read its parameters, not {node}; reading anything else is \
86                 not supported yet",
87                params.iter().format(", ")
88            );
89            Ok(TraversalOrder::Continue)
90        })?;
91
92        Ok(Self { params, body })
93    }
94
95    /// The parameter names, in order.
96    pub fn params(&self) -> &[FieldName] {
97        self.params.as_ref()
98    }
99
100    /// The body, as written.
101    pub fn body(&self) -> &Expression {
102        &self.body
103    }
104
105    /// The dtype of the body, given the parameters' dtypes, without binding it.
106    pub fn return_dtype(&self, param_dtypes: &[DType]) -> VortexResult<DType> {
107        let inputs = inputs_dtype(self.param_fields(param_dtypes)?);
108        self.body_over_inputs().return_dtype(&inputs)
109    }
110
111    /// Bind the body to these parameter dtypes: `@x` becomes `$.x`, a field of the struct of the
112    /// lambda's inputs.
113    ///
114    /// A function that takes a lambda calls this from its `bind_options`, so the body is bound
115    /// once, with the node that holds it, and never while the function runs.
116    pub fn bind(&self, param_dtypes: &[DType]) -> VortexResult<BoundLambda> {
117        let params = self.param_fields(param_dtypes)?;
118        let body = self
119            .body_over_inputs()
120            .bind(&inputs_dtype(params.clone()))?;
121        Ok(BoundLambda { params, body })
122    }
123
124    /// Whether nothing in the body can fail, so that the body may run over values whose results
125    /// are never read, such as dictionary values that no row uses.
126    pub fn is_infallible(&self) -> bool {
127        let mut infallible = true;
128        pre_order_visit_down(&self.body, |node: &Expression| {
129            infallible &= node
130                .as_scalar()
131                .is_none_or(|scalar_fn| scalar_fn.signature().is_infallible());
132            Ok(if infallible {
133                TraversalOrder::Continue
134            } else {
135                TraversalOrder::Stop
136            })
137        })
138        .vortex_expect("expression traversal cannot fail");
139        infallible
140    }
141
142    fn param_fields(&self, param_dtypes: &[DType]) -> VortexResult<StructFields> {
143        vortex_ensure!(
144            param_dtypes.len() == self.params.len(),
145            "lambda {self} needs one dtype per parameter, got {}",
146            param_dtypes.len()
147        );
148        Ok(StructFields::new(
149            self.params.clone(),
150            param_dtypes.to_vec(),
151        ))
152    }
153
154    /// The body over the struct of the lambda's inputs, where `@x` reads the field `x`.
155    ///
156    /// A lambda in the body is a function's options, which this leaves alone: its variables are its
157    /// own parameters.
158    fn body_over_inputs(&self) -> Expression {
159        self.body
160            .clone()
161            .transform_down(|node| {
162                Ok(match &node {
163                    Expression::Variable(name) => Transformed {
164                        value: get_item(name.clone(), root()),
165                        changed: true,
166                        order: TraversalOrder::Skip,
167                    },
168                    _ => Transformed::no(node),
169                })
170            })
171            .vortex_expect("expression traversal cannot fail")
172            .into_inner()
173    }
174}
175
176/// The struct of a lambda's inputs, one field per parameter.
177fn inputs_dtype(params: StructFields) -> DType {
178    DType::Struct(params, Nullability::NonNullable)
179}
180
181impl Display for Lambda {
182    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
183        write!(f, "({}) -> {}", self.params.iter().format(", "), self.body)
184    }
185}
186
187/// A [`Lambda`] bound to its parameters' dtypes, ready to run.
188///
189/// The body is a [`BoundExpression`] over the struct of the lambda's inputs, one field per
190/// parameter: `@x` was bound as `$.x`.
191#[derive(Clone, Debug, PartialEq, Eq, Hash)]
192pub struct BoundLambda {
193    params: StructFields,
194    body: BoundExpression,
195}
196
197impl BoundLambda {
198    /// The parameters' names and dtypes, in order.
199    pub fn params(&self) -> &StructFields {
200        &self.params
201    }
202
203    /// The bound body, over the struct of the lambda's inputs.
204    pub fn body(&self) -> &BoundExpression {
205        &self.body
206    }
207
208    /// The dtype of the body.
209    pub fn dtype(&self) -> &DType {
210        self.body.dtype()
211    }
212
213    /// Whether the lambda is bound to these parameter dtypes.
214    pub fn is_bound_to(&self, param_dtypes: &[DType]) -> bool {
215        self.params.fields().eq(param_dtypes.iter().cloned())
216    }
217
218    /// Whether nothing in the body can fail. See [`Lambda::is_infallible`].
219    pub fn is_infallible(&self) -> bool {
220        let mut infallible = true;
221        pre_order_visit_down(&self.body, |node: &BoundExpression| {
222            infallible &= node
223                .as_scalar()
224                .is_none_or(|scalar_fn| scalar_fn.signature().is_infallible());
225            Ok(if infallible {
226                TraversalOrder::Continue
227            } else {
228                TraversalOrder::Stop
229            })
230        })
231        .vortex_expect("bound expression traversal cannot fail");
232        infallible
233    }
234
235    /// How many times the body reads a parameter.
236    pub fn param_reads(&self) -> usize {
237        let mut reads = 0;
238        pre_order_visit_down(&self.body, |node: &BoundExpression| {
239            Ok(if is_param_read(node) {
240                reads += 1;
241                TraversalOrder::Skip
242            } else {
243                TraversalOrder::Continue
244            })
245        })
246        .vortex_expect("bound expression traversal cannot fail");
247        reads
248    }
249
250    /// This lambda after `inner`: `(x) -> self(inner(x))`, with `inner`'s parameters.
251    ///
252    /// Returns `None` when this lambda reads its inputs in any other way than a parameter at a
253    /// time, and an error unless it has one parameter, bound to `inner`'s dtype.
254    pub fn compose(&self, inner: &BoundLambda) -> VortexResult<Option<BoundLambda>> {
255        vortex_ensure!(
256            self.is_bound_to(std::slice::from_ref(inner.dtype())),
257            "lambda {self} is bound to ({}), so it can't take the result of {inner}, a {}",
258            self.params.fields().format(", "),
259            inner.dtype()
260        );
261        let mut reads_inputs_whole = false;
262        let body = self
263            .body
264            .clone()
265            .transform_down(|node| {
266                if is_param_read(&node) {
267                    return Ok(Transformed {
268                        value: inner.body.clone(),
269                        changed: true,
270                        order: TraversalOrder::Skip,
271                    });
272                }
273                reads_inputs_whole |= node.is_root();
274                Ok(Transformed::no(node))
275            })?
276            .into_inner();
277        Ok((!reads_inputs_whole).then(|| BoundLambda {
278            params: inner.params.clone(),
279            body,
280        }))
281    }
282
283    /// Evaluate the body over `len` rows of `args`, one array per parameter, with the dtypes the
284    /// lambda is bound to. They become the fields of the struct the body is applied to.
285    ///
286    /// The result is computed later, like any applied expression, so errors from running the body
287    /// come from executing it.
288    pub fn evaluate(&self, args: Vec<ArrayRef>, len: usize) -> VortexResult<ArrayRef> {
289        vortex_ensure!(
290            args.len() == self.params.nfields(),
291            "lambda {self} needs one array per parameter, got {}",
292            args.len()
293        );
294        for ((name, dtype), arg) in self
295            .params
296            .names()
297            .iter()
298            .zip(self.params.fields())
299            .zip(&args)
300        {
301            vortex_ensure!(
302                arg.dtype() == &dtype,
303                "lambda {self}: parameter {name} is bound to {dtype}, not {}",
304                arg.dtype()
305            );
306        }
307        let inputs = StructArray::try_new(
308            self.params.names().clone(),
309            args,
310            len,
311            Validity::NonNullable,
312        )?
313        .into_array();
314        inputs.apply_bound(&self.body)
315    }
316}
317
318impl Display for BoundLambda {
319    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
320        write!(
321            f,
322            "({}) -> {}",
323            self.params.names().iter().format(", "),
324            self.body
325        )
326    }
327}
328
329/// Whether `node`, in the bound body of a lambda, reads one parameter: a field of the struct of
330/// the lambda's inputs.
331fn is_param_read(node: &BoundExpression) -> bool {
332    node.is::<GetItem>() && node.child(0).is_root()
333}
334
335/// Whether `node`, in the body of a lambda with these parameters, reads a value from outside the
336/// lambda, which lambdas can't do yet: `$`, another lambda's parameter, or the scan's `row_idx()`
337/// or `row_count()`. The scan replaces those two before anything runs, but never looks inside a
338/// lambda's body.
339fn reads_outside_lambda(node: &Expression, params: &[FieldName]) -> bool {
340    match node {
341        Expression::Root => true,
342        Expression::Variable(name) => !params.contains(name),
343        // `row_idx` is defined in vortex-layout, so it is recognized by its id.
344        Expression::Scalar { scalar_fn, .. } => {
345            scalar_fn.is::<RowCount>() || scalar_fn.id().as_ref() == "vortex.row_idx"
346        }
347    }
348}