1use std::hash::Hash;
8use std::sync::Arc;
9
10use crate::{
11 ScalarFunctionExpr,
12 expressions::{Column, LambdaVariable},
13 physical_expr::PhysicalExpr,
14};
15use arrow::{
16 datatypes::{DataType, Schema},
17 record_batch::RecordBatch,
18};
19use datafusion_common::{
20 HashMap, plan_err,
21 tree_node::{Transformed, TreeNode, TreeNodeRecursion, TreeNodeVisitor},
22};
23use datafusion_common::{HashSet, Result, internal_err};
24use datafusion_expr::ColumnarValue;
25
26#[derive(Debug, Eq, Clone)]
28pub struct LambdaExpr {
29 params: Vec<String>,
30 body: Arc<dyn PhysicalExpr>,
31 projected_body: Arc<dyn PhysicalExpr>,
32 projection: Vec<usize>,
33 used_param_indices: Vec<usize>,
34}
35
36impl PartialEq for LambdaExpr {
38 fn eq(&self, other: &Self) -> bool {
39 self.params.eq(&other.params) && self.body.eq(&other.body)
40 }
41}
42
43impl Hash for LambdaExpr {
44 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
45 self.params.hash(state);
46 self.body.hash(state);
47 }
48}
49
50impl LambdaExpr {
51 pub fn try_new(params: Vec<String>, body: Arc<dyn PhysicalExpr>) -> Result<Self> {
53 if !all_unique(¶ms) {
54 return plan_err!(
55 "lambda params must be unique, got ({})",
56 params.join(", ")
57 );
58 }
59
60 check_async_udf(&body)?;
61
62 Ok(Self::new(params, body))
63 }
64
65 fn new(params: Vec<String>, body: Arc<dyn PhysicalExpr>) -> Self {
66 let own_params: HashSet<String> = params.iter().cloned().collect();
67
68 let mut visitor = CollectUsedVisitor {
69 own_params: &own_params,
70 used_indices: HashSet::new(),
71 used_param_names: HashSet::new(),
72 shadow_stack: Vec::new(),
73 };
74 body.visit(&mut visitor).expect("visitor is infallible");
75 let CollectUsedVisitor {
76 used_indices,
77 used_param_names,
78 ..
79 } = visitor;
80
81 let mut projection = used_indices.into_iter().collect::<Vec<_>>();
82
83 projection.sort_unstable();
84
85 let column_index_map = projection
86 .iter()
87 .copied()
88 .enumerate()
89 .map(|(new_idx, original)| (original, new_idx))
90 .collect::<HashMap<_, _>>();
91
92 let projected_body = Arc::clone(&body)
93 .transform_down(|e| {
94 if let Some(column) = e.downcast_ref::<Column>() {
95 let original = column.index();
96 let projected = *column_index_map.get(&original).unwrap();
97 if projected != original {
98 return Ok(Transformed::yes(Arc::new(Column::new(
99 column.name(),
100 projected,
101 ))));
102 }
103 } else if let Some(lambda_variable) = e.downcast_ref::<LambdaVariable>() {
104 let original = lambda_variable.index();
105 let projected = *column_index_map.get(&original).unwrap();
106 if projected != original {
107 return Ok(Transformed::yes(Arc::new(LambdaVariable::new(
108 projected,
109 Arc::clone(lambda_variable.field()),
110 ))));
111 }
112 }
113 Ok(Transformed::no(e))
114 })
115 .expect("closure should be infallible")
116 .data;
117
118 let used_param_indices = params
119 .iter()
120 .enumerate()
121 .filter(|(_, name)| used_param_names.contains(*name))
122 .map(|(i, _)| i)
123 .collect();
124
125 Self {
126 params,
127 body,
128 projected_body,
129 projection,
130 used_param_indices,
131 }
132 }
133
134 pub fn params(&self) -> &[String] {
136 &self.params
137 }
138
139 pub fn body(&self) -> &Arc<dyn PhysicalExpr> {
141 &self.body
142 }
143
144 #[cfg(feature = "proto")]
145 pub fn try_from_proto(
147 node: &datafusion_proto_models::protobuf::PhysicalExprNode,
148 ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
149 ) -> Result<Arc<dyn PhysicalExpr>> {
150 use datafusion_physical_expr_common::expect_expr_variant;
151 use datafusion_proto_models::protobuf;
152
153 let lambda = expect_expr_variant!(
154 node,
155 protobuf::physical_expr_node::ExprType::Lambda,
156 "LambdaExpr",
157 );
158 let protobuf::PhysicalLambdaExprNode { params, body } = &**lambda;
159
160 Ok(Arc::new(LambdaExpr::try_new(
161 params.clone(),
162 ctx.decode_required_expression(body.as_deref(), "LambdaExpr", "body")?,
163 )?))
164 }
165
166 pub(crate) fn projection(&self) -> &[usize] {
167 &self.projection
168 }
169
170 pub(crate) fn projected_body(&self) -> &Arc<dyn PhysicalExpr> {
171 &self.projected_body
172 }
173
174 pub fn used_param_indices(&self) -> &[usize] {
182 &self.used_param_indices
183 }
184}
185
186struct CollectUsedVisitor<'a> {
208 own_params: &'a HashSet<String>,
209 used_indices: HashSet<usize>,
210 used_param_names: HashSet<String>,
211 shadow_stack: Vec<HashSet<String>>,
212}
213
214impl TreeNodeVisitor<'_> for CollectUsedVisitor<'_> {
215 type Node = Arc<dyn PhysicalExpr>;
216
217 fn f_down(&mut self, node: &Self::Node) -> Result<TreeNodeRecursion> {
218 if let Some(col) = node.downcast_ref::<Column>() {
219 self.used_indices.insert(col.index());
220 } else if let Some(var) = node.downcast_ref::<LambdaVariable>() {
221 self.used_indices.insert(var.index());
222
223 let name = var.name();
224 let shadowed = self.shadow_stack.iter().any(|frame| frame.contains(name));
225 if !shadowed && self.own_params.contains(name) {
226 self.used_param_names.insert(name.to_string());
227 }
228 } else if let Some(nested) = node.downcast_ref::<LambdaExpr>() {
229 self.shadow_stack
230 .push(nested.params.iter().cloned().collect());
231 }
232
233 Ok(TreeNodeRecursion::Continue)
234 }
235
236 fn f_up(&mut self, node: &Self::Node) -> Result<TreeNodeRecursion> {
237 if node.downcast_ref::<LambdaExpr>().is_some() {
238 self.shadow_stack.pop();
239 }
240 Ok(TreeNodeRecursion::Continue)
241 }
242}
243
244impl std::fmt::Display for LambdaExpr {
245 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
246 write!(f, "({}) -> {}", self.params.join(", "), self.body)
247 }
248}
249
250impl PhysicalExpr for LambdaExpr {
251 fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
252 Ok(DataType::Null)
253 }
254
255 fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
256 Ok(true)
257 }
258
259 fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {
260 internal_err!("LambdaExpr::evaluate() should not be called")
261 }
262
263 fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
264 vec![&self.body]
265 }
266
267 fn with_new_children(
268 self: Arc<Self>,
269 children: Vec<Arc<dyn PhysicalExpr>>,
270 ) -> Result<Arc<dyn PhysicalExpr>> {
271 let [body] = children.as_slice() else {
272 return internal_err!(
273 "LambdaExpr expects exactly 1 child, got {}",
274 children.len()
275 );
276 };
277
278 check_async_udf(body)?;
279
280 Ok(Arc::new(Self::new(self.params.clone(), Arc::clone(body))))
281 }
282
283 fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284 write!(f, "({}) -> {}", self.params.join(", "), self.body)
285 }
286
287 #[cfg(feature = "proto")]
288 fn try_to_proto(
289 &self,
290 ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
291 ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
292 use datafusion_proto_models::protobuf;
293
294 let Self {
298 params,
299 body,
300 projected_body: _,
302 projection: _,
303 used_param_indices: _,
304 } = self;
305
306 Ok(Some(protobuf::PhysicalExprNode {
307 expr_id: None,
308 expr_type: Some(protobuf::physical_expr_node::ExprType::Lambda(Box::new(
309 protobuf::PhysicalLambdaExprNode {
310 params: params.clone(),
311 body: Some(Box::new(ctx.encode_child(body)?)),
312 },
313 ))),
314 }))
315 }
316}
317
318pub fn lambda(
320 params: impl IntoIterator<Item = impl Into<String>>,
321 body: Arc<dyn PhysicalExpr>,
322) -> Result<Arc<dyn PhysicalExpr>> {
323 Ok(Arc::new(LambdaExpr::try_new(
324 params.into_iter().map(Into::into).collect(),
325 body,
326 )?))
327}
328
329fn all_unique(params: &[String]) -> bool {
330 match params.len() {
331 0 | 1 => true,
332 2 => params[0] != params[1],
333 _ => {
334 let mut set = HashSet::with_capacity(params.len());
335
336 params.iter().all(|p| set.insert(p.as_str()))
337 }
338 }
339}
340
341fn check_async_udf(body: &Arc<dyn PhysicalExpr>) -> Result<()> {
342 if body.exists(|expr| {
343 Ok(expr
344 .downcast_ref::<ScalarFunctionExpr>()
345 .is_some_and(|udf| udf.fun().as_async().is_some()))
346 })? {
347 return plan_err!(
348 "Async functions in lambdas aren't supported, see https://github.com/apache/datafusion/issues/22091"
349 );
350 }
351
352 Ok(())
353}
354
355#[cfg(test)]
356mod tests {
357 use crate::expressions::{Column, LambdaVariable, NoOp, lambda::lambda};
358 use arrow::{
359 array::RecordBatch,
360 datatypes::{DataType, Field, Schema},
361 };
362 use std::sync::Arc;
363
364 use super::LambdaExpr;
365
366 #[test]
367 fn test_lambda_evaluate() {
368 let lambda = lambda(["a"], Arc::new(NoOp::new())).unwrap();
369 let batch = RecordBatch::new_empty(Arc::new(Schema::empty()));
370 assert!(lambda.evaluate(&batch).is_err());
371 }
372
373 #[test]
374 fn test_lambda_duplicate_name() {
375 assert!(lambda(["a", "a"], Arc::new(NoOp::new())).is_err());
376 }
377
378 #[test]
384 fn test_used_params_collects_only_referenced_param() {
385 let v_field = Arc::new(Field::new("v", DataType::Int32, true));
386 let body = Arc::new(LambdaVariable::new(1, Arc::clone(&v_field)));
387
388 let lambda =
389 LambdaExpr::try_new(vec!["k".to_string(), "v".to_string()], body).unwrap();
390
391 assert_eq!(lambda.projection(), &[1]);
392 assert_eq!(lambda.used_param_indices(), &[1]);
393 }
394
395 #[test]
397 fn test_used_params_all_unused() {
398 let body = Arc::new(NoOp::new());
399
400 let lambda =
401 LambdaExpr::try_new(vec!["k".to_string(), "v".to_string()], body).unwrap();
402
403 assert!(lambda.projection().is_empty());
404 assert!(lambda.used_param_indices().is_empty());
405 }
406
407 #[test]
409 fn test_used_params_three_params_middle_unused() {
410 let a_field = Arc::new(Field::new("a", DataType::Int32, true));
411 let c_field = Arc::new(Field::new("c", DataType::Int32, true));
412 let body = Arc::new(crate::expressions::BinaryExpr::new(
413 Arc::new(LambdaVariable::new(0, Arc::clone(&a_field))),
414 datafusion_expr::Operator::Plus,
415 Arc::new(LambdaVariable::new(2, Arc::clone(&c_field))),
416 ));
417
418 let lambda = LambdaExpr::try_new(
419 vec!["a".to_string(), "b".to_string(), "c".to_string()],
420 body,
421 )
422 .unwrap();
423
424 assert_eq!(lambda.used_param_indices(), &[0, 2]);
425 }
426
427 #[test]
429 fn test_used_params_both_used_in_reverse_reference_order() {
430 let k_field = Arc::new(Field::new("k", DataType::Int32, true));
431 let v_field = Arc::new(Field::new("v", DataType::Int32, true));
432 let body = Arc::new(crate::expressions::BinaryExpr::new(
433 Arc::new(LambdaVariable::new(1, Arc::clone(&v_field))),
434 datafusion_expr::Operator::Plus,
435 Arc::new(LambdaVariable::new(0, Arc::clone(&k_field))),
436 ));
437
438 let lambda =
439 LambdaExpr::try_new(vec!["k".to_string(), "v".to_string()], body).unwrap();
440
441 assert_eq!(lambda.projection(), &[0, 1]);
442 assert_eq!(lambda.used_param_indices(), &[0, 1]);
443 }
444
445 #[test]
451 fn test_used_params_handles_shadowing_inside_nested_lambda() {
452 let outer_k_field = Arc::new(Field::new("k", DataType::Int32, true));
453 let outer_v_field = Arc::new(Field::new("v", DataType::Int32, true));
454 let inner_v2_field = Arc::new(Field::new("v2", DataType::Int32, true));
455
456 let inner_body: Arc<dyn crate::PhysicalExpr> =
462 Arc::new(crate::expressions::BinaryExpr::new(
463 Arc::new(crate::expressions::BinaryExpr::new(
464 Arc::new(LambdaVariable::new(1, Arc::clone(&outer_k_field))),
465 datafusion_expr::Operator::Plus,
466 Arc::new(LambdaVariable::new(2, Arc::clone(&inner_v2_field))),
467 )),
468 datafusion_expr::Operator::Plus,
469 Arc::new(LambdaVariable::new(0, Arc::clone(&outer_v_field))),
470 ));
471 let inner_lambda = Arc::new(
472 LambdaExpr::try_new(vec!["k".to_string(), "v2".to_string()], inner_body)
473 .unwrap(),
474 );
475
476 let outer_body: Arc<dyn crate::PhysicalExpr> =
481 Arc::new(crate::expressions::BinaryExpr::new(
482 Arc::new(Column::new("col", 0)),
483 datafusion_expr::Operator::Plus,
484 inner_lambda,
485 ));
486
487 let outer_lambda =
488 LambdaExpr::try_new(vec!["k".to_string(), "v".to_string()], outer_body)
489 .unwrap();
490
491 assert_eq!(
492 outer_lambda.used_param_indices(),
493 &[1],
494 "only outer's `v` (index 1) should be reported as used; `k` (index 0) is \
495 shadowed inside the nested lambda"
496 );
497 }
498}
499
500#[cfg(all(test, feature = "proto"))]
502mod proto_tests {
503 use super::*;
504 use crate::proto_test_util::{
505 StubDecoder, StubEncoder, UnreachableDecoder, column_node,
506 };
507 use arrow::datatypes::Field;
508 use datafusion_common::DataFusionError;
509 use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
510 use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
511 use datafusion_proto_models::protobuf::{self, PhysicalExprNode};
512
513 fn proto_lambda_fixture() -> LambdaExpr {
515 let v_field = Arc::new(Field::new("v", DataType::Int32, true));
516 LambdaExpr::try_new(
517 vec!["v".to_string()],
518 Arc::new(LambdaVariable::new(0, v_field)),
519 )
520 .unwrap()
521 }
522
523 fn proto_lambda_node(
524 params: Vec<String>,
525 body: Option<Box<PhysicalExprNode>>,
526 ) -> PhysicalExprNode {
527 PhysicalExprNode {
528 expr_id: None,
529 expr_type: Some(protobuf::physical_expr_node::ExprType::Lambda(Box::new(
530 protobuf::PhysicalLambdaExprNode { params, body },
531 ))),
532 }
533 }
534
535 #[test]
536 fn try_to_proto_encodes_lambda() {
537 let lambda = proto_lambda_fixture();
538 let encoder = StubEncoder::ok();
539 let ctx = PhysicalExprEncodeCtx::new(&encoder);
540
541 let node = lambda
542 .try_to_proto(&ctx)
543 .unwrap()
544 .expect("LambdaExpr should encode to Some(node)");
545
546 assert!(node.expr_id.is_none());
547 let lambda_node = match node.expr_type {
548 Some(protobuf::physical_expr_node::ExprType::Lambda(boxed)) => *boxed,
549 other => panic!("expected a LambdaExpr node, got {other:?}"),
550 };
551 assert_eq!(lambda_node.params, vec!["v".to_string()]);
552 assert!(lambda_node.body.is_some());
553 }
554
555 #[test]
556 fn try_to_proto_propagates_body_encode_error() {
557 let lambda = proto_lambda_fixture();
558 let encoder = StubEncoder::failing_on(1);
559 let ctx = PhysicalExprEncodeCtx::new(&encoder);
560
561 let err = lambda.try_to_proto(&ctx).unwrap_err();
562 assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
563 }
564
565 #[test]
569 fn try_from_proto_recomputes_derived_state() {
570 let node =
571 proto_lambda_node(vec!["v".to_string()], Some(Box::new(column_node("body"))));
572 let schema = Schema::empty();
573 let decoder = StubDecoder::ok();
574 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
575
576 let decoded = LambdaExpr::try_from_proto(&node, &ctx).unwrap();
577 let lambda = decoded
578 .downcast_ref::<LambdaExpr>()
579 .expect("decoded expr should be a LambdaExpr");
580
581 assert_eq!(lambda.params(), &["v".to_string()]);
582 assert_eq!(lambda.projection(), &[0]);
586 assert!(lambda.used_param_indices().is_empty());
587 assert!(lambda.projected_body().eq(lambda.body()));
588 }
589
590 #[test]
591 fn try_from_proto_rejects_non_lambda_node() {
592 let node = column_node("a");
593 let schema = Schema::empty();
594 let decoder = UnreachableDecoder;
595 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
596
597 let err = LambdaExpr::try_from_proto(&node, &ctx).unwrap_err();
598 assert!(
599 matches!(err, DataFusionError::Internal(msg) if msg.contains("PhysicalExprNode is not a LambdaExpr"))
600 );
601 }
602
603 #[test]
604 fn try_from_proto_rejects_missing_body() {
605 let node = proto_lambda_node(vec!["v".to_string()], None);
606 let schema = Schema::empty();
607 let decoder = UnreachableDecoder;
608 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
609
610 let err = LambdaExpr::try_from_proto(&node, &ctx).unwrap_err();
611 assert!(
612 matches!(err, DataFusionError::Internal(msg) if msg.contains("LambdaExpr is missing required field 'body'"))
613 );
614 }
615
616 #[test]
617 fn try_from_proto_rejects_duplicate_params() {
618 let node = proto_lambda_node(
619 vec!["v".to_string(), "v".to_string()],
620 Some(Box::new(column_node("body"))),
621 );
622 let schema = Schema::empty();
623 let decoder = StubDecoder::ok();
624 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
625
626 let err = LambdaExpr::try_from_proto(&node, &ctx).unwrap_err();
627 assert!(
628 matches!(err, DataFusionError::Plan(msg) if msg.contains("lambda params must be unique"))
629 );
630 }
631
632 #[test]
633 fn try_from_proto_propagates_body_decode_error() {
634 let node =
635 proto_lambda_node(vec!["v".to_string()], Some(Box::new(column_node("body"))));
636 let schema = Schema::empty();
637 let decoder = StubDecoder::failing_on(1);
638 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
639
640 let err = LambdaExpr::try_from_proto(&node, &ctx).unwrap_err();
641 assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
642 }
643}