vortex-expr 0.94.0

Analyses and rewrites over Vortex expression trees
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! Factory functions for creating [`Expression`]s from scalar function vtables.

use vortex_array::dtype::DType;
use vortex_array::dtype::FieldName;
use vortex_array::dtype::Nullability;
use vortex_array::scalar::NumericOperator;
use vortex_array::scalar::Scalar;
use vortex_array::scalar_fn::EmptyOptions;
use vortex_array::scalar_fn::builtin::boolean::Boolean;
use vortex_array::scalar_fn::builtin::cast::Cast;
use vortex_array::scalar_fn::builtin::compare::Compare;
use vortex_array::scalar_fn::builtin::fill_null::FillNull;
use vortex_array::scalar_fn::builtin::get_item::GetItem;
use vortex_array::scalar_fn::builtin::is_not_null::IsNotNull;
use vortex_array::scalar_fn::builtin::literal::Literal;
use vortex_array::scalar_fn::builtin::mask::Mask;
use vortex_array::scalar_fn::builtin::not::Not;
use vortex_array::scalar_fn::builtin::numeric::Numeric;
use vortex_array::scalar_fn::builtin::operators::BinaryOperator;
use vortex_array::scalar_fn::builtin::operators::BooleanOperator;
use vortex_array::scalar_fn::builtin::operators::CompareOperator;
use vortex_array::scalar_fn::builtin::pack::Pack;
use vortex_array::scalar_fn::builtin::pack::PackOptions;
use vortex_error::VortexExpect;
use vortex_utils::iter::ReduceBalancedIterExt;

use crate::BoundExpression;
use crate::Expression;
use crate::ScalarFnExprExt;

/// Creates an expression that references the root scope.
///
/// Returns the entire input array as passed to the expression evaluator.
/// This is commonly used as the starting point for field access and other operations.
pub fn root() -> Expression {
    Expression::Root
}

/// Creates a bound expression that references a root scope with the given dtype.
pub fn bound_root(dtype: DType) -> BoundExpression {
    BoundExpression::new_root(dtype)
}

/// Return whether the expression is a root expression.
pub fn is_root(expr: &Expression) -> bool {
    expr.is_root()
}

// ---- Literal ----

/// Create a new `Literal` expression from a type that coerces to `Scalar`.
///
///
/// ## Example usage
///
/// ```
/// use vortex_array::arrays::PrimitiveArray;
/// use vortex_array::dtype::Nullability;
/// use vortex_expr::lit;
/// use vortex_array::scalar_fn::builtin::literal::Literal;
/// use vortex_array::scalar::Scalar;
///
/// let number = lit(34i32);
///
/// let scalar = number.as_::<Literal>();
/// assert_eq!(scalar, &Scalar::primitive(34i32, Nullability::NonNullable));
/// ```
pub fn lit(value: impl Into<Scalar>) -> Expression {
    Literal.new_expr(value.into(), [])
}

/// Creates a bound literal expression.
pub fn bound_lit(value: impl Into<Scalar>) -> BoundExpression {
    Literal
        .try_new_bound_expr(value.into(), [])
        .vortex_expect("literal expressions are always well-typed")
}

// ---- GetItem / Col ----

/// Creates an expression that accesses a field from the root array.
///
/// Equivalent to `get_item(field, root())` - extracts a named field from the input array.
///
/// ```rust
/// # use vortex_expr::col;
/// let expr = col("name");
/// ```
pub fn col(field: impl Into<FieldName>) -> Expression {
    GetItem.new_expr(field.into(), vec![root()])
}

/// Creates a bound expression that accesses a field from a root scope with the given dtype.
pub fn bound_col(field: impl Into<FieldName>, scope: DType) -> BoundExpression {
    bound_get_item(field, bound_root(scope))
}

/// Creates an expression that extracts a named field from a struct expression.
///
/// Accesses the specified field from the result of the child expression.
///
/// ```rust
/// # use vortex_expr::{get_item, root};
/// let expr = get_item("user_id", root());
/// ```
pub fn get_item(field: impl Into<FieldName>, child: Expression) -> Expression {
    GetItem.new_expr(field.into(), vec![child])
}

/// Creates a bound expression that extracts a named field from a struct expression.
pub fn bound_get_item(field: impl Into<FieldName>, child: BoundExpression) -> BoundExpression {
    GetItem
        .try_new_bound_expr(field.into(), [child])
        .vortex_expect("get-item expressions must reference a field in the child dtype")
}

// ---- Variable ----

/// Creates an expression that reads the parameter `name` of the enclosing lambda.
///
/// It is only meaningful in the body of a [`Lambda`](crate::Lambda). Anywhere else it fails
/// to bind.
///
/// ```rust
/// # use vortex_array::dtype::{DType, Nullability, PType};
/// # use vortex_expr::{checked_add, lit, var};
/// let expr = checked_add(var("x"), lit(1_i32));
/// assert_eq!(expr.to_string(), "(@x + 1i32)");
/// // Outside a lambda body, nothing gives `x` a value.
/// assert!(expr.bind(&DType::Primitive(PType::I32, Nullability::NonNullable)).is_err());
/// ```
pub fn var(name: impl Into<FieldName>) -> Expression {
    Expression::Variable(name.into())
}

// ---- Binary operators ----

/// Creates a comparison with the given operator.
pub fn compare(operator: CompareOperator, lhs: Expression, rhs: Expression) -> Expression {
    Compare
        .try_new_expr(operator, [lhs, rhs])
        .vortex_expect("Failed to create compare expression")
}

/// Creates a bound comparison with the given operator.
pub fn bound_compare(
    operator: CompareOperator,
    lhs: BoundExpression,
    rhs: BoundExpression,
) -> BoundExpression {
    Compare
        .try_new_bound_expr(operator, [lhs, rhs])
        .vortex_expect("compare expressions must have compatible operand dtypes")
}

/// Creates a Kleene boolean expression with the given operator.
pub fn boolean(operator: BooleanOperator, lhs: Expression, rhs: Expression) -> Expression {
    Boolean
        .try_new_expr(operator, [lhs, rhs])
        .vortex_expect("Failed to create boolean expression")
}

/// Creates a bound Kleene boolean expression with the given operator.
pub fn bound_boolean(
    operator: BooleanOperator,
    lhs: BoundExpression,
    rhs: BoundExpression,
) -> BoundExpression {
    Boolean
        .try_new_bound_expr(operator, [lhs, rhs])
        .vortex_expect("boolean expressions must have compatible operand dtypes")
}

/// Creates an arithmetic expression with the given operator.
pub fn numeric(operator: NumericOperator, lhs: Expression, rhs: Expression) -> Expression {
    Numeric
        .try_new_expr(operator, [lhs, rhs])
        .vortex_expect("Failed to create numeric expression")
}

/// Creates a bound arithmetic expression with the given operator.
pub fn bound_numeric(
    operator: NumericOperator,
    lhs: BoundExpression,
    rhs: BoundExpression,
) -> BoundExpression {
    Numeric
        .try_new_bound_expr(operator, [lhs, rhs])
        .vortex_expect("numeric expressions must have compatible operand dtypes")
}

/// Creates the expression `lhs <operator> rhs` with the function that owns the operator.
///
/// ```rust
/// # use vortex_expr::{binary, col, lit};
/// # use vortex_array::scalar::NumericOperator;
/// # use vortex_array::scalar_fn::builtin::operators::CompareOperator;
/// let sum = binary(NumericOperator::Add, col("x"), lit(1_i32));
/// let expr = binary(CompareOperator::Gt, sum, lit(10_i32));
/// assert_eq!(expr.to_string(), "(($.x + 1i32) > 10i32)");
/// ```
pub fn binary(operator: impl Into<BinaryOperator>, lhs: Expression, rhs: Expression) -> Expression {
    match operator.into() {
        BinaryOperator::Compare(operator) => compare(operator, lhs, rhs),
        BinaryOperator::Boolean(operator) => boolean(operator, lhs, rhs),
        BinaryOperator::Numeric(operator) => numeric(operator, lhs, rhs),
    }
}

/// Create a new [`Compare`] using the [`Eq`](CompareOperator::Eq) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::{BoolArray, PrimitiveArray};
/// # use vortex_expr::ArrayExprExt;
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute};
/// # use vortex_session::VortexSession;
/// # use vortex_array::validity::Validity;
/// # use vortex_buffer::buffer;
/// # use vortex_expr::{eq, root, lit};
/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
/// let result = xs.into_array().apply(&eq(root(), lit(3))).unwrap();
/// let mut ctx = VortexSession::empty().create_execution_ctx();
///
/// assert_eq!(
///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
///     BoolArray::from_iter(vec![false, false, true]).to_bit_buffer(),
/// );
/// ```
pub fn eq(lhs: Expression, rhs: Expression) -> Expression {
    Compare
        .try_new_expr(CompareOperator::Eq, [lhs, rhs])
        .vortex_expect("Failed to create Eq comparison expression")
}

/// Creates a bound equality expression.
pub fn bound_eq(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
    bound_compare(CompareOperator::Eq, lhs, rhs)
}

/// Create a new [`Compare`] using the [`NotEq`](CompareOperator::NotEq) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::{BoolArray, PrimitiveArray};
/// # use vortex_expr::ArrayExprExt;
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute};
/// # use vortex_session::VortexSession;
/// # use vortex_array::validity::Validity;
/// # use vortex_buffer::buffer;
/// # use vortex_expr::{root, lit, not_eq};
/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
/// let result = xs.into_array().apply(&not_eq(root(), lit(3))).unwrap();
/// let mut ctx = VortexSession::empty().create_execution_ctx();
///
/// assert_eq!(
///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
///     BoolArray::from_iter(vec![true, true, false]).to_bit_buffer(),
/// );
/// ```
pub fn not_eq(lhs: Expression, rhs: Expression) -> Expression {
    Compare
        .try_new_expr(CompareOperator::NotEq, [lhs, rhs])
        .vortex_expect("Failed to create NotEq comparison expression")
}

/// Creates a bound inequality expression.
pub fn bound_not_eq(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
    bound_compare(CompareOperator::NotEq, lhs, rhs)
}

/// Create a new [`Compare`] using the [`Gte`](CompareOperator::Gte) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::{BoolArray, PrimitiveArray };
/// # use vortex_expr::ArrayExprExt;
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute};
/// # use vortex_session::VortexSession;
/// # use vortex_array::validity::Validity;
/// # use vortex_buffer::buffer;
/// # use vortex_expr::{gt_eq, root, lit};
/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
/// let result = xs.into_array().apply(&gt_eq(root(), lit(3))).unwrap();
/// let mut ctx = VortexSession::empty().create_execution_ctx();
///
/// assert_eq!(
///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
///     BoolArray::from_iter(vec![false, false, true]).to_bit_buffer(),
/// );
/// ```
pub fn gt_eq(lhs: Expression, rhs: Expression) -> Expression {
    Compare
        .try_new_expr(CompareOperator::Gte, [lhs, rhs])
        .vortex_expect("Failed to create Gte comparison expression")
}

/// Creates a bound greater-than-or-equal expression.
pub fn bound_gt_eq(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
    bound_compare(CompareOperator::Gte, lhs, rhs)
}

/// Create a new [`Compare`] using the [`Gt`](CompareOperator::Gt) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::{BoolArray, PrimitiveArray };
/// # use vortex_expr::ArrayExprExt;
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute};
/// # use vortex_session::VortexSession;
/// # use vortex_array::validity::Validity;
/// # use vortex_buffer::buffer;
/// # use vortex_expr::{gt, root, lit};
/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
/// let result = xs.into_array().apply(&gt(root(), lit(2))).unwrap();
/// let mut ctx = VortexSession::empty().create_execution_ctx();
///
/// assert_eq!(
///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
///     BoolArray::from_iter(vec![false, false, true]).to_bit_buffer(),
/// );
/// ```
pub fn gt(lhs: Expression, rhs: Expression) -> Expression {
    Compare
        .try_new_expr(CompareOperator::Gt, [lhs, rhs])
        .vortex_expect("Failed to create Gt comparison expression")
}

/// Creates a bound greater-than expression.
pub fn bound_gt(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
    bound_compare(CompareOperator::Gt, lhs, rhs)
}

/// Create a new [`Compare`] using the [`Lte`](CompareOperator::Lte) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::{BoolArray, PrimitiveArray };
/// # use vortex_expr::ArrayExprExt;
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute};
/// # use vortex_session::VortexSession;
/// # use vortex_array::validity::Validity;
/// # use vortex_buffer::buffer;
/// # use vortex_expr::{root, lit, lt_eq};
/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
/// let result = xs.into_array().apply(&lt_eq(root(), lit(2))).unwrap();
/// let mut ctx = VortexSession::empty().create_execution_ctx();
///
/// assert_eq!(
///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
///     BoolArray::from_iter(vec![true, true, false]).to_bit_buffer(),
/// );
/// ```
pub fn lt_eq(lhs: Expression, rhs: Expression) -> Expression {
    Compare
        .try_new_expr(CompareOperator::Lte, [lhs, rhs])
        .vortex_expect("Failed to create Lte comparison expression")
}

/// Creates a bound less-than-or-equal expression.
pub fn bound_lt_eq(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
    bound_compare(CompareOperator::Lte, lhs, rhs)
}

/// Create a new [`Compare`] using the [`Lt`](CompareOperator::Lt) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::{BoolArray, PrimitiveArray };
/// # use vortex_expr::ArrayExprExt;
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute};
/// # use vortex_session::VortexSession;
/// # use vortex_array::validity::Validity;
/// # use vortex_buffer::buffer;
/// # use vortex_expr::{root, lit, lt};
/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
/// let result = xs.into_array().apply(&lt(root(), lit(3))).unwrap();
/// let mut ctx = VortexSession::empty().create_execution_ctx();
///
/// assert_eq!(
///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
///     BoolArray::from_iter(vec![true, true, false]).to_bit_buffer(),
/// );
/// ```
pub fn lt(lhs: Expression, rhs: Expression) -> Expression {
    Compare
        .try_new_expr(CompareOperator::Lt, [lhs, rhs])
        .vortex_expect("Failed to create Lt comparison expression")
}

/// Creates a bound less-than expression.
pub fn bound_lt(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
    bound_compare(CompareOperator::Lt, lhs, rhs)
}

/// Create a new [`Boolean`] using the [`Or`](BooleanOperator::Or) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::BoolArray;
/// # use vortex_expr::ArrayExprExt;
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute};
/// # use vortex_session::VortexSession;
/// # use vortex_expr::{root, lit, or};
/// let xs = BoolArray::from_iter(vec![true, false, true]);
/// let result = xs.into_array().apply(&or(root(), lit(false))).unwrap();
/// let mut ctx = VortexSession::empty().create_execution_ctx();
///
/// assert_eq!(
///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
///     BoolArray::from_iter(vec![true, false, true]).to_bit_buffer(),
/// );
/// ```
pub fn or(lhs: Expression, rhs: Expression) -> Expression {
    Boolean
        .try_new_expr(BooleanOperator::Or, [lhs, rhs])
        .vortex_expect("Failed to create Or boolean expression")
}

/// Creates a bound boolean OR expression.
pub fn bound_or(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
    bound_boolean(BooleanOperator::Or, lhs, rhs)
}

/// Collects a list of `or`ed values into a single expression using a balanced tree.
///
/// This creates a balanced binary tree to avoid deep nesting that could cause
/// stack overflow during drop or evaluation.
///
/// [a, b, c, d] => or(or(a, b), or(c, d))
pub fn or_collect<I>(iter: I) -> Option<Expression>
where
    I: IntoIterator<Item = Expression>,
{
    iter.into_iter().reduce_balanced(or)
}

/// Collects bound expressions into a balanced tree of boolean OR expressions.
pub fn bound_or_collect<I>(iter: I) -> Option<BoundExpression>
where
    I: IntoIterator<Item = BoundExpression>,
{
    iter.into_iter().reduce_balanced(bound_or)
}

/// Create a new [`Boolean`] using the [`And`](BooleanOperator::And) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::BoolArray;
/// # use vortex_expr::ArrayExprExt;
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute};
/// # use vortex_session::VortexSession;
/// # use vortex_expr::{and, root, lit};
/// let xs = BoolArray::from_iter(vec![true, false, true]).into_array();
/// let result = xs.apply(&and(root(), lit(true))).unwrap();
/// let mut ctx = VortexSession::empty().create_execution_ctx();
///
/// assert_eq!(
///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
///     BoolArray::from_iter(vec![true, false, true]).to_bit_buffer(),
/// );
/// ```
pub fn and(lhs: Expression, rhs: Expression) -> Expression {
    Boolean
        .try_new_expr(BooleanOperator::And, [lhs, rhs])
        .vortex_expect("Failed to create And boolean expression")
}

/// Creates a bound boolean AND expression.
pub fn bound_and(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
    bound_boolean(BooleanOperator::And, lhs, rhs)
}

/// Collects a list of `and`ed values into a single expression using a balanced tree.
///
/// This creates a balanced binary tree to avoid deep nesting that could cause
/// stack overflow during drop or evaluation.
///
/// [a, b, c, d] => and(and(a, b), and(c, d))
pub fn and_collect<I>(iter: I) -> Option<Expression>
where
    I: IntoIterator<Item = Expression>,
{
    iter.into_iter().reduce_balanced(and)
}

/// Collects bound expressions into a balanced tree of boolean AND expressions.
pub fn bound_and_collect<I>(iter: I) -> Option<BoundExpression>
where
    I: IntoIterator<Item = BoundExpression>,
{
    iter.into_iter().reduce_balanced(bound_and)
}

/// Create a new [`Numeric`] using the [`Add`](NumericOperator::Add) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::IntoArray;
/// # use vortex_expr::ArrayExprExt;
/// # use vortex_array::arrays::PrimitiveArray;
/// # use vortex_array::builtins::ArrayBuiltins;
/// # use vortex_array::{VortexSessionExecute};
/// # use vortex_session::VortexSession;
/// # use vortex_buffer::buffer;
/// # use vortex_expr::{checked_add, lit, root};
/// let xs = buffer![1, 2, 3].into_array();
/// let result = xs.apply(&checked_add(root(), lit(5))).unwrap();
///
/// let mut ctx = VortexSession::empty().create_execution_ctx();
/// let result = result.execute::<PrimitiveArray>(&mut ctx).unwrap();
/// assert_eq!(result.as_slice::<i32>(), [6, 7, 8]);
/// ```
pub fn checked_add(lhs: Expression, rhs: Expression) -> Expression {
    Numeric
        .try_new_expr(NumericOperator::Add, [lhs, rhs])
        .vortex_expect("Failed to create Add arithmetic expression")
}

/// Creates a bound checked-add expression.
pub fn bound_checked_add(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
    bound_numeric(NumericOperator::Add, lhs, rhs)
}

// ---- Not ----

/// Creates an expression that logically inverts boolean values.
///
/// Returns the logical negation of the input boolean expression.
///
/// ```rust
/// # use vortex_expr::{not, root};
/// let expr = not(root());
/// ```
pub fn not(operand: Expression) -> Expression {
    Not.new_expr(EmptyOptions, vec![operand])
}

/// Creates a bound expression that logically inverts boolean values.
pub fn bound_not(operand: BoundExpression) -> BoundExpression {
    Not.try_new_bound_expr(EmptyOptions, [operand])
        .vortex_expect("not expressions require a boolean operand")
}

// ---- Pack ----

/// Creates an expression that packs values into a struct with named fields.
///
/// ```rust
/// # use vortex_array::dtype::Nullability;
/// # use vortex_expr::{pack, col, lit};
/// let expr = pack([("id", col("user_id")), ("constant", lit(42))], Nullability::NonNullable);
/// ```
pub fn pack(
    elements: impl IntoIterator<Item = (impl Into<FieldName>, Expression)>,
    nullability: Nullability,
) -> Expression {
    let (names, values): (Vec<_>, Vec<_>) = elements
        .into_iter()
        .map(|(name, value)| (name.into(), value))
        .unzip();
    Pack.new_expr(
        PackOptions {
            names: names.into(),
            nullability,
        },
        values,
    )
}

/// Creates a bound expression that packs values into a struct with named fields.
pub fn bound_pack(
    elements: impl IntoIterator<Item = (impl Into<FieldName>, BoundExpression)>,
    nullability: Nullability,
) -> BoundExpression {
    let (names, values): (Vec<_>, Vec<_>) = elements
        .into_iter()
        .map(|(name, value)| (name.into(), value))
        .unzip();
    Pack.try_new_bound_expr(
        PackOptions {
            names: names.into(),
            nullability,
        },
        values,
    )
    .vortex_expect("pack expressions must have one name per child")
}

// ---- Cast ----

/// Creates an expression that casts values to a target data type.
///
/// Converts the input expression's values to the specified target type.
///
/// ```rust
/// # use vortex_array::dtype::{DType, Nullability, PType};
/// # use vortex_expr::{cast, root};
/// let expr = cast(root(), DType::Primitive(PType::I64, Nullability::NonNullable));
/// ```
pub fn cast(child: Expression, target: DType) -> Expression {
    Cast.try_new_expr(target, [child])
        .vortex_expect("Failed to create Cast expression")
}

/// Creates a bound expression that casts values to a target dtype.
pub fn bound_cast(child: BoundExpression, target: DType) -> BoundExpression {
    Cast.try_new_bound_expr(target, [child])
        .vortex_expect("cast expressions require a supported source and target dtype")
}

// ---- FillNull ----

/// Creates an expression that replaces null values with a fill value.
///
/// ```rust
/// # use vortex_expr::{fill_null, root, lit};
/// let expr = fill_null(root(), lit(0i32));
/// ```
pub fn fill_null(child: Expression, fill_value: Expression) -> Expression {
    FillNull.new_expr(EmptyOptions, [child, fill_value])
}

/// Creates a bound expression that replaces null values with a fill value.
pub fn bound_fill_null(child: BoundExpression, fill_value: BoundExpression) -> BoundExpression {
    FillNull
        .try_new_bound_expr(EmptyOptions, [child, fill_value])
        .vortex_expect("fill-null expressions require compatible child and fill dtypes")
}

// ---- IsNotNull ----

/// Creates an expression that checks for non-null values.
///
/// Returns a boolean array indicating which positions contain non-null values.
///
/// ```rust
/// # use vortex_expr::{is_not_null, root};
/// let expr = is_not_null(root());
/// ```
pub fn is_not_null(child: Expression) -> Expression {
    IsNotNull.new_expr(EmptyOptions, vec![child])
}

/// Creates a bound expression that checks for non-null values.
pub fn bound_is_not_null(child: BoundExpression) -> BoundExpression {
    IsNotNull
        .try_new_bound_expr(EmptyOptions, [child])
        .vortex_expect("is-not-null expressions are always well-typed")
}

// ---- Mask ----

/// Creates a mask expression that applies the given boolean mask to the input array.
pub fn mask(array: Expression, mask: Expression) -> Expression {
    Mask.new_expr(EmptyOptions, [array, mask])
}

/// Creates a bound mask expression.
pub fn bound_mask(array: BoundExpression, mask: BoundExpression) -> BoundExpression {
    Mask.try_new_bound_expr(EmptyOptions, [array, mask])
        .vortex_expect("mask expressions require a boolean mask")
}

/// Constructors for expressions whose children have already been bound and type-checked.
///
/// These mirror the unbound constructors in this crate and panic when the supplied children do not
/// form a well-typed expression. Use [`BoundExpression::try_new`] when construction must be
/// fallible.
pub mod bound {
    pub use super::bound_and as and;
    pub use super::bound_and_collect as and_collect;
    pub use super::bound_boolean as boolean;
    pub use super::bound_cast as cast;
    pub use super::bound_checked_add as checked_add;
    pub use super::bound_col as col;
    pub use super::bound_compare as compare;
    pub use super::bound_eq as eq;
    pub use super::bound_fill_null as fill_null;
    pub use super::bound_get_item as get_item;
    pub use super::bound_gt as gt;
    pub use super::bound_gt_eq as gt_eq;
    pub use super::bound_is_not_null as is_not_null;
    pub use super::bound_lit as lit;
    pub use super::bound_lt as lt;
    pub use super::bound_lt_eq as lt_eq;
    pub use super::bound_mask as mask;
    pub use super::bound_not as not;
    pub use super::bound_not_eq as not_eq;
    pub use super::bound_numeric as numeric;
    pub use super::bound_or as or;
    pub use super::bound_or_collect as or_collect;
    pub use super::bound_pack as pack;
    pub use super::bound_root as root;
}