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::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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
63pub struct Lambda {
64 params: FieldNames,
65 body: Expression,
66}
67
68impl Lambda {
69 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 pub fn params(&self) -> &[FieldName] {
96 self.params.as_ref()
97 }
98
99 pub fn body(&self) -> &Expression {
101 &self.body
102 }
103
104 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 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 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 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
175fn 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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
191pub struct BoundLambda {
192 params: StructFields,
193 body: BoundExpression,
194}
195
196impl BoundLambda {
197 pub fn params(&self) -> &StructFields {
199 &self.params
200 }
201
202 pub fn body(&self) -> &BoundExpression {
204 &self.body
205 }
206
207 pub fn dtype(&self) -> &DType {
209 self.body.dtype()
210 }
211
212 pub fn is_bound_to(&self, param_dtypes: &[DType]) -> bool {
214 self.params.fields().eq(param_dtypes.iter().cloned())
215 }
216
217 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 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
280fn reads_outside_lambda(node: &Expression, params: &[FieldName]) -> bool {
285 match node {
286 Expression::Root => true,
287 Expression::Variable(name) => !params.contains(name),
288 Expression::Scalar { scalar_fn, .. } => {
290 scalar_fn.is::<RowCount>() || scalar_fn.id().as_ref() == "vortex.row_idx"
291 }
292 }
293}