vortex_expr/lambda/
mod.rs1#[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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
64pub struct Lambda {
65 params: FieldNames,
66 body: Expression,
67}
68
69impl Lambda {
70 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 pub fn params(&self) -> &[FieldName] {
97 self.params.as_ref()
98 }
99
100 pub fn body(&self) -> &Expression {
102 &self.body
103 }
104
105 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 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 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 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
176fn 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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
192pub struct BoundLambda {
193 params: StructFields,
194 body: BoundExpression,
195}
196
197impl BoundLambda {
198 pub fn params(&self) -> &StructFields {
200 &self.params
201 }
202
203 pub fn body(&self) -> &BoundExpression {
205 &self.body
206 }
207
208 pub fn dtype(&self) -> &DType {
210 self.body.dtype()
211 }
212
213 pub fn is_bound_to(&self, param_dtypes: &[DType]) -> bool {
215 self.params.fields().eq(param_dtypes.iter().cloned())
216 }
217
218 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 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 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 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
329fn is_param_read(node: &BoundExpression) -> bool {
332 node.is::<GetItem>() && node.child(0).is_root()
333}
334
335fn reads_outside_lambda(node: &Expression, params: &[FieldName]) -> bool {
340 match node {
341 Expression::Root => true,
342 Expression::Variable(name) => !params.contains(name),
343 Expression::Scalar { scalar_fn, .. } => {
345 scalar_fn.is::<RowCount>() || scalar_fn.id().as_ref() == "vortex.row_idx"
346 }
347 }
348}