Skip to main content

vortex_expr/
exprs.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Factory functions for creating [`Expression`]s from scalar function vtables.
5
6use vortex_array::dtype::DType;
7use vortex_array::dtype::FieldName;
8use vortex_array::dtype::Nullability;
9use vortex_array::scalar::NumericOperator;
10use vortex_array::scalar::Scalar;
11use vortex_array::scalar_fn::EmptyOptions;
12use vortex_array::scalar_fn::builtin::boolean::Boolean;
13use vortex_array::scalar_fn::builtin::cast::Cast;
14use vortex_array::scalar_fn::builtin::compare::Compare;
15use vortex_array::scalar_fn::builtin::fill_null::FillNull;
16use vortex_array::scalar_fn::builtin::get_item::GetItem;
17use vortex_array::scalar_fn::builtin::is_not_null::IsNotNull;
18use vortex_array::scalar_fn::builtin::literal::Literal;
19use vortex_array::scalar_fn::builtin::mask::Mask;
20use vortex_array::scalar_fn::builtin::not::Not;
21use vortex_array::scalar_fn::builtin::numeric::Numeric;
22use vortex_array::scalar_fn::builtin::operators::BinaryOperator;
23use vortex_array::scalar_fn::builtin::operators::BooleanOperator;
24use vortex_array::scalar_fn::builtin::operators::CompareOperator;
25use vortex_array::scalar_fn::builtin::pack::Pack;
26use vortex_array::scalar_fn::builtin::pack::PackOptions;
27use vortex_error::VortexExpect;
28use vortex_utils::iter::ReduceBalancedIterExt;
29
30use crate::BoundExpression;
31use crate::Expression;
32use crate::ScalarFnExprExt;
33
34/// Creates an expression that references the root scope.
35///
36/// Returns the entire input array as passed to the expression evaluator.
37/// This is commonly used as the starting point for field access and other operations.
38pub fn root() -> Expression {
39    Expression::Root
40}
41
42/// Creates a bound expression that references a root scope with the given dtype.
43pub fn bound_root(dtype: DType) -> BoundExpression {
44    BoundExpression::new_root(dtype)
45}
46
47/// Return whether the expression is a root expression.
48pub fn is_root(expr: &Expression) -> bool {
49    expr.is_root()
50}
51
52// ---- Literal ----
53
54/// Create a new `Literal` expression from a type that coerces to `Scalar`.
55///
56///
57/// ## Example usage
58///
59/// ```
60/// use vortex_array::arrays::PrimitiveArray;
61/// use vortex_array::dtype::Nullability;
62/// use vortex_expr::lit;
63/// use vortex_array::scalar_fn::builtin::literal::Literal;
64/// use vortex_array::scalar::Scalar;
65///
66/// let number = lit(34i32);
67///
68/// let scalar = number.as_::<Literal>();
69/// assert_eq!(scalar, &Scalar::primitive(34i32, Nullability::NonNullable));
70/// ```
71pub fn lit(value: impl Into<Scalar>) -> Expression {
72    Literal.new_expr(value.into(), [])
73}
74
75/// Creates a bound literal expression.
76pub fn bound_lit(value: impl Into<Scalar>) -> BoundExpression {
77    Literal
78        .try_new_bound_expr(value.into(), [])
79        .vortex_expect("literal expressions are always well-typed")
80}
81
82// ---- GetItem / Col ----
83
84/// Creates an expression that accesses a field from the root array.
85///
86/// Equivalent to `get_item(field, root())` - extracts a named field from the input array.
87///
88/// ```rust
89/// # use vortex_expr::col;
90/// let expr = col("name");
91/// ```
92pub fn col(field: impl Into<FieldName>) -> Expression {
93    GetItem.new_expr(field.into(), vec![root()])
94}
95
96/// Creates a bound expression that accesses a field from a root scope with the given dtype.
97pub fn bound_col(field: impl Into<FieldName>, scope: DType) -> BoundExpression {
98    bound_get_item(field, bound_root(scope))
99}
100
101/// Creates an expression that extracts a named field from a struct expression.
102///
103/// Accesses the specified field from the result of the child expression.
104///
105/// ```rust
106/// # use vortex_expr::{get_item, root};
107/// let expr = get_item("user_id", root());
108/// ```
109pub fn get_item(field: impl Into<FieldName>, child: Expression) -> Expression {
110    GetItem.new_expr(field.into(), vec![child])
111}
112
113/// Creates a bound expression that extracts a named field from a struct expression.
114pub fn bound_get_item(field: impl Into<FieldName>, child: BoundExpression) -> BoundExpression {
115    GetItem
116        .try_new_bound_expr(field.into(), [child])
117        .vortex_expect("get-item expressions must reference a field in the child dtype")
118}
119
120// ---- Variable ----
121
122/// Creates an expression that reads the parameter `name` of the enclosing lambda.
123///
124/// It is only meaningful in the body of a [`Lambda`](crate::Lambda). Anywhere else it fails
125/// to bind.
126///
127/// ```rust
128/// # use vortex_array::dtype::{DType, Nullability, PType};
129/// # use vortex_expr::{checked_add, lit, var};
130/// let expr = checked_add(var("x"), lit(1_i32));
131/// assert_eq!(expr.to_string(), "(@x + 1i32)");
132/// // Outside a lambda body, nothing gives `x` a value.
133/// assert!(expr.bind(&DType::Primitive(PType::I32, Nullability::NonNullable)).is_err());
134/// ```
135pub fn var(name: impl Into<FieldName>) -> Expression {
136    Expression::Variable(name.into())
137}
138
139// ---- Binary operators ----
140
141/// Creates a comparison with the given operator.
142pub fn compare(operator: CompareOperator, lhs: Expression, rhs: Expression) -> Expression {
143    Compare
144        .try_new_expr(operator, [lhs, rhs])
145        .vortex_expect("Failed to create compare expression")
146}
147
148/// Creates a bound comparison with the given operator.
149pub fn bound_compare(
150    operator: CompareOperator,
151    lhs: BoundExpression,
152    rhs: BoundExpression,
153) -> BoundExpression {
154    Compare
155        .try_new_bound_expr(operator, [lhs, rhs])
156        .vortex_expect("compare expressions must have compatible operand dtypes")
157}
158
159/// Creates a Kleene boolean expression with the given operator.
160pub fn boolean(operator: BooleanOperator, lhs: Expression, rhs: Expression) -> Expression {
161    Boolean
162        .try_new_expr(operator, [lhs, rhs])
163        .vortex_expect("Failed to create boolean expression")
164}
165
166/// Creates a bound Kleene boolean expression with the given operator.
167pub fn bound_boolean(
168    operator: BooleanOperator,
169    lhs: BoundExpression,
170    rhs: BoundExpression,
171) -> BoundExpression {
172    Boolean
173        .try_new_bound_expr(operator, [lhs, rhs])
174        .vortex_expect("boolean expressions must have compatible operand dtypes")
175}
176
177/// Creates an arithmetic expression with the given operator.
178pub fn numeric(operator: NumericOperator, lhs: Expression, rhs: Expression) -> Expression {
179    Numeric
180        .try_new_expr(operator, [lhs, rhs])
181        .vortex_expect("Failed to create numeric expression")
182}
183
184/// Creates a bound arithmetic expression with the given operator.
185pub fn bound_numeric(
186    operator: NumericOperator,
187    lhs: BoundExpression,
188    rhs: BoundExpression,
189) -> BoundExpression {
190    Numeric
191        .try_new_bound_expr(operator, [lhs, rhs])
192        .vortex_expect("numeric expressions must have compatible operand dtypes")
193}
194
195/// Creates the expression `lhs <operator> rhs` with the function that owns the operator.
196///
197/// ```rust
198/// # use vortex_expr::{binary, col, lit};
199/// # use vortex_array::scalar::NumericOperator;
200/// # use vortex_array::scalar_fn::builtin::operators::CompareOperator;
201/// let sum = binary(NumericOperator::Add, col("x"), lit(1_i32));
202/// let expr = binary(CompareOperator::Gt, sum, lit(10_i32));
203/// assert_eq!(expr.to_string(), "(($.x + 1i32) > 10i32)");
204/// ```
205pub fn binary(operator: impl Into<BinaryOperator>, lhs: Expression, rhs: Expression) -> Expression {
206    match operator.into() {
207        BinaryOperator::Compare(operator) => compare(operator, lhs, rhs),
208        BinaryOperator::Boolean(operator) => boolean(operator, lhs, rhs),
209        BinaryOperator::Numeric(operator) => numeric(operator, lhs, rhs),
210    }
211}
212
213/// Create a new [`Compare`] using the [`Eq`](CompareOperator::Eq) operator.
214///
215/// ## Example usage
216///
217/// ```
218/// # use vortex_array::arrays::{BoolArray, PrimitiveArray};
219/// # use vortex_expr::ArrayExprExt;
220/// # use vortex_array::arrays::bool::BoolArrayExt;
221/// # use vortex_array::IntoArray;
222/// # use vortex_array::{VortexSessionExecute};
223/// # use vortex_session::VortexSession;
224/// # use vortex_array::validity::Validity;
225/// # use vortex_buffer::buffer;
226/// # use vortex_expr::{eq, root, lit};
227/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
228/// let result = xs.into_array().apply(&eq(root(), lit(3))).unwrap();
229/// let mut ctx = VortexSession::empty().create_execution_ctx();
230///
231/// assert_eq!(
232///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
233///     BoolArray::from_iter(vec![false, false, true]).to_bit_buffer(),
234/// );
235/// ```
236pub fn eq(lhs: Expression, rhs: Expression) -> Expression {
237    Compare
238        .try_new_expr(CompareOperator::Eq, [lhs, rhs])
239        .vortex_expect("Failed to create Eq comparison expression")
240}
241
242/// Creates a bound equality expression.
243pub fn bound_eq(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
244    bound_compare(CompareOperator::Eq, lhs, rhs)
245}
246
247/// Create a new [`Compare`] using the [`NotEq`](CompareOperator::NotEq) operator.
248///
249/// ## Example usage
250///
251/// ```
252/// # use vortex_array::arrays::{BoolArray, PrimitiveArray};
253/// # use vortex_expr::ArrayExprExt;
254/// # use vortex_array::arrays::bool::BoolArrayExt;
255/// # use vortex_array::IntoArray;
256/// # use vortex_array::{VortexSessionExecute};
257/// # use vortex_session::VortexSession;
258/// # use vortex_array::validity::Validity;
259/// # use vortex_buffer::buffer;
260/// # use vortex_expr::{root, lit, not_eq};
261/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
262/// let result = xs.into_array().apply(&not_eq(root(), lit(3))).unwrap();
263/// let mut ctx = VortexSession::empty().create_execution_ctx();
264///
265/// assert_eq!(
266///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
267///     BoolArray::from_iter(vec![true, true, false]).to_bit_buffer(),
268/// );
269/// ```
270pub fn not_eq(lhs: Expression, rhs: Expression) -> Expression {
271    Compare
272        .try_new_expr(CompareOperator::NotEq, [lhs, rhs])
273        .vortex_expect("Failed to create NotEq comparison expression")
274}
275
276/// Creates a bound inequality expression.
277pub fn bound_not_eq(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
278    bound_compare(CompareOperator::NotEq, lhs, rhs)
279}
280
281/// Create a new [`Compare`] using the [`Gte`](CompareOperator::Gte) operator.
282///
283/// ## Example usage
284///
285/// ```
286/// # use vortex_array::arrays::{BoolArray, PrimitiveArray };
287/// # use vortex_expr::ArrayExprExt;
288/// # use vortex_array::arrays::bool::BoolArrayExt;
289/// # use vortex_array::IntoArray;
290/// # use vortex_array::{VortexSessionExecute};
291/// # use vortex_session::VortexSession;
292/// # use vortex_array::validity::Validity;
293/// # use vortex_buffer::buffer;
294/// # use vortex_expr::{gt_eq, root, lit};
295/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
296/// let result = xs.into_array().apply(&gt_eq(root(), lit(3))).unwrap();
297/// let mut ctx = VortexSession::empty().create_execution_ctx();
298///
299/// assert_eq!(
300///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
301///     BoolArray::from_iter(vec![false, false, true]).to_bit_buffer(),
302/// );
303/// ```
304pub fn gt_eq(lhs: Expression, rhs: Expression) -> Expression {
305    Compare
306        .try_new_expr(CompareOperator::Gte, [lhs, rhs])
307        .vortex_expect("Failed to create Gte comparison expression")
308}
309
310/// Creates a bound greater-than-or-equal expression.
311pub fn bound_gt_eq(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
312    bound_compare(CompareOperator::Gte, lhs, rhs)
313}
314
315/// Create a new [`Compare`] using the [`Gt`](CompareOperator::Gt) operator.
316///
317/// ## Example usage
318///
319/// ```
320/// # use vortex_array::arrays::{BoolArray, PrimitiveArray };
321/// # use vortex_expr::ArrayExprExt;
322/// # use vortex_array::arrays::bool::BoolArrayExt;
323/// # use vortex_array::IntoArray;
324/// # use vortex_array::{VortexSessionExecute};
325/// # use vortex_session::VortexSession;
326/// # use vortex_array::validity::Validity;
327/// # use vortex_buffer::buffer;
328/// # use vortex_expr::{gt, root, lit};
329/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
330/// let result = xs.into_array().apply(&gt(root(), lit(2))).unwrap();
331/// let mut ctx = VortexSession::empty().create_execution_ctx();
332///
333/// assert_eq!(
334///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
335///     BoolArray::from_iter(vec![false, false, true]).to_bit_buffer(),
336/// );
337/// ```
338pub fn gt(lhs: Expression, rhs: Expression) -> Expression {
339    Compare
340        .try_new_expr(CompareOperator::Gt, [lhs, rhs])
341        .vortex_expect("Failed to create Gt comparison expression")
342}
343
344/// Creates a bound greater-than expression.
345pub fn bound_gt(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
346    bound_compare(CompareOperator::Gt, lhs, rhs)
347}
348
349/// Create a new [`Compare`] using the [`Lte`](CompareOperator::Lte) operator.
350///
351/// ## Example usage
352///
353/// ```
354/// # use vortex_array::arrays::{BoolArray, PrimitiveArray };
355/// # use vortex_expr::ArrayExprExt;
356/// # use vortex_array::arrays::bool::BoolArrayExt;
357/// # use vortex_array::IntoArray;
358/// # use vortex_array::{VortexSessionExecute};
359/// # use vortex_session::VortexSession;
360/// # use vortex_array::validity::Validity;
361/// # use vortex_buffer::buffer;
362/// # use vortex_expr::{root, lit, lt_eq};
363/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
364/// let result = xs.into_array().apply(&lt_eq(root(), lit(2))).unwrap();
365/// let mut ctx = VortexSession::empty().create_execution_ctx();
366///
367/// assert_eq!(
368///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
369///     BoolArray::from_iter(vec![true, true, false]).to_bit_buffer(),
370/// );
371/// ```
372pub fn lt_eq(lhs: Expression, rhs: Expression) -> Expression {
373    Compare
374        .try_new_expr(CompareOperator::Lte, [lhs, rhs])
375        .vortex_expect("Failed to create Lte comparison expression")
376}
377
378/// Creates a bound less-than-or-equal expression.
379pub fn bound_lt_eq(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
380    bound_compare(CompareOperator::Lte, lhs, rhs)
381}
382
383/// Create a new [`Compare`] using the [`Lt`](CompareOperator::Lt) operator.
384///
385/// ## Example usage
386///
387/// ```
388/// # use vortex_array::arrays::{BoolArray, PrimitiveArray };
389/// # use vortex_expr::ArrayExprExt;
390/// # use vortex_array::arrays::bool::BoolArrayExt;
391/// # use vortex_array::IntoArray;
392/// # use vortex_array::{VortexSessionExecute};
393/// # use vortex_session::VortexSession;
394/// # use vortex_array::validity::Validity;
395/// # use vortex_buffer::buffer;
396/// # use vortex_expr::{root, lit, lt};
397/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
398/// let result = xs.into_array().apply(&lt(root(), lit(3))).unwrap();
399/// let mut ctx = VortexSession::empty().create_execution_ctx();
400///
401/// assert_eq!(
402///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
403///     BoolArray::from_iter(vec![true, true, false]).to_bit_buffer(),
404/// );
405/// ```
406pub fn lt(lhs: Expression, rhs: Expression) -> Expression {
407    Compare
408        .try_new_expr(CompareOperator::Lt, [lhs, rhs])
409        .vortex_expect("Failed to create Lt comparison expression")
410}
411
412/// Creates a bound less-than expression.
413pub fn bound_lt(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
414    bound_compare(CompareOperator::Lt, lhs, rhs)
415}
416
417/// Create a new [`Boolean`] using the [`Or`](BooleanOperator::Or) operator.
418///
419/// ## Example usage
420///
421/// ```
422/// # use vortex_array::arrays::BoolArray;
423/// # use vortex_expr::ArrayExprExt;
424/// # use vortex_array::arrays::bool::BoolArrayExt;
425/// # use vortex_array::IntoArray;
426/// # use vortex_array::{VortexSessionExecute};
427/// # use vortex_session::VortexSession;
428/// # use vortex_expr::{root, lit, or};
429/// let xs = BoolArray::from_iter(vec![true, false, true]);
430/// let result = xs.into_array().apply(&or(root(), lit(false))).unwrap();
431/// let mut ctx = VortexSession::empty().create_execution_ctx();
432///
433/// assert_eq!(
434///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
435///     BoolArray::from_iter(vec![true, false, true]).to_bit_buffer(),
436/// );
437/// ```
438pub fn or(lhs: Expression, rhs: Expression) -> Expression {
439    Boolean
440        .try_new_expr(BooleanOperator::Or, [lhs, rhs])
441        .vortex_expect("Failed to create Or boolean expression")
442}
443
444/// Creates a bound boolean OR expression.
445pub fn bound_or(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
446    bound_boolean(BooleanOperator::Or, lhs, rhs)
447}
448
449/// Collects a list of `or`ed values into a single expression using a balanced tree.
450///
451/// This creates a balanced binary tree to avoid deep nesting that could cause
452/// stack overflow during drop or evaluation.
453///
454/// [a, b, c, d] => or(or(a, b), or(c, d))
455pub fn or_collect<I>(iter: I) -> Option<Expression>
456where
457    I: IntoIterator<Item = Expression>,
458{
459    iter.into_iter().reduce_balanced(or)
460}
461
462/// Collects bound expressions into a balanced tree of boolean OR expressions.
463pub fn bound_or_collect<I>(iter: I) -> Option<BoundExpression>
464where
465    I: IntoIterator<Item = BoundExpression>,
466{
467    iter.into_iter().reduce_balanced(bound_or)
468}
469
470/// Create a new [`Boolean`] using the [`And`](BooleanOperator::And) operator.
471///
472/// ## Example usage
473///
474/// ```
475/// # use vortex_array::arrays::BoolArray;
476/// # use vortex_expr::ArrayExprExt;
477/// # use vortex_array::arrays::bool::BoolArrayExt;
478/// # use vortex_array::IntoArray;
479/// # use vortex_array::{VortexSessionExecute};
480/// # use vortex_session::VortexSession;
481/// # use vortex_expr::{and, root, lit};
482/// let xs = BoolArray::from_iter(vec![true, false, true]).into_array();
483/// let result = xs.apply(&and(root(), lit(true))).unwrap();
484/// let mut ctx = VortexSession::empty().create_execution_ctx();
485///
486/// assert_eq!(
487///     result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
488///     BoolArray::from_iter(vec![true, false, true]).to_bit_buffer(),
489/// );
490/// ```
491pub fn and(lhs: Expression, rhs: Expression) -> Expression {
492    Boolean
493        .try_new_expr(BooleanOperator::And, [lhs, rhs])
494        .vortex_expect("Failed to create And boolean expression")
495}
496
497/// Creates a bound boolean AND expression.
498pub fn bound_and(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
499    bound_boolean(BooleanOperator::And, lhs, rhs)
500}
501
502/// Collects a list of `and`ed values into a single expression using a balanced tree.
503///
504/// This creates a balanced binary tree to avoid deep nesting that could cause
505/// stack overflow during drop or evaluation.
506///
507/// [a, b, c, d] => and(and(a, b), and(c, d))
508pub fn and_collect<I>(iter: I) -> Option<Expression>
509where
510    I: IntoIterator<Item = Expression>,
511{
512    iter.into_iter().reduce_balanced(and)
513}
514
515/// Collects bound expressions into a balanced tree of boolean AND expressions.
516pub fn bound_and_collect<I>(iter: I) -> Option<BoundExpression>
517where
518    I: IntoIterator<Item = BoundExpression>,
519{
520    iter.into_iter().reduce_balanced(bound_and)
521}
522
523/// Create a new [`Numeric`] using the [`Add`](NumericOperator::Add) operator.
524///
525/// ## Example usage
526///
527/// ```
528/// # use vortex_array::IntoArray;
529/// # use vortex_expr::ArrayExprExt;
530/// # use vortex_array::arrays::PrimitiveArray;
531/// # use vortex_array::builtins::ArrayBuiltins;
532/// # use vortex_array::{VortexSessionExecute};
533/// # use vortex_session::VortexSession;
534/// # use vortex_buffer::buffer;
535/// # use vortex_expr::{checked_add, lit, root};
536/// let xs = buffer![1, 2, 3].into_array();
537/// let result = xs.apply(&checked_add(root(), lit(5))).unwrap();
538///
539/// let mut ctx = VortexSession::empty().create_execution_ctx();
540/// let result = result.execute::<PrimitiveArray>(&mut ctx).unwrap();
541/// assert_eq!(result.as_slice::<i32>(), [6, 7, 8]);
542/// ```
543pub fn checked_add(lhs: Expression, rhs: Expression) -> Expression {
544    Numeric
545        .try_new_expr(NumericOperator::Add, [lhs, rhs])
546        .vortex_expect("Failed to create Add arithmetic expression")
547}
548
549/// Creates a bound checked-add expression.
550pub fn bound_checked_add(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
551    bound_numeric(NumericOperator::Add, lhs, rhs)
552}
553
554// ---- Not ----
555
556/// Creates an expression that logically inverts boolean values.
557///
558/// Returns the logical negation of the input boolean expression.
559///
560/// ```rust
561/// # use vortex_expr::{not, root};
562/// let expr = not(root());
563/// ```
564pub fn not(operand: Expression) -> Expression {
565    Not.new_expr(EmptyOptions, vec![operand])
566}
567
568/// Creates a bound expression that logically inverts boolean values.
569pub fn bound_not(operand: BoundExpression) -> BoundExpression {
570    Not.try_new_bound_expr(EmptyOptions, [operand])
571        .vortex_expect("not expressions require a boolean operand")
572}
573
574// ---- Pack ----
575
576/// Creates an expression that packs values into a struct with named fields.
577///
578/// ```rust
579/// # use vortex_array::dtype::Nullability;
580/// # use vortex_expr::{pack, col, lit};
581/// let expr = pack([("id", col("user_id")), ("constant", lit(42))], Nullability::NonNullable);
582/// ```
583pub fn pack(
584    elements: impl IntoIterator<Item = (impl Into<FieldName>, Expression)>,
585    nullability: Nullability,
586) -> Expression {
587    let (names, values): (Vec<_>, Vec<_>) = elements
588        .into_iter()
589        .map(|(name, value)| (name.into(), value))
590        .unzip();
591    Pack.new_expr(
592        PackOptions {
593            names: names.into(),
594            nullability,
595        },
596        values,
597    )
598}
599
600/// Creates a bound expression that packs values into a struct with named fields.
601pub fn bound_pack(
602    elements: impl IntoIterator<Item = (impl Into<FieldName>, BoundExpression)>,
603    nullability: Nullability,
604) -> BoundExpression {
605    let (names, values): (Vec<_>, Vec<_>) = elements
606        .into_iter()
607        .map(|(name, value)| (name.into(), value))
608        .unzip();
609    Pack.try_new_bound_expr(
610        PackOptions {
611            names: names.into(),
612            nullability,
613        },
614        values,
615    )
616    .vortex_expect("pack expressions must have one name per child")
617}
618
619// ---- Cast ----
620
621/// Creates an expression that casts values to a target data type.
622///
623/// Converts the input expression's values to the specified target type.
624///
625/// ```rust
626/// # use vortex_array::dtype::{DType, Nullability, PType};
627/// # use vortex_expr::{cast, root};
628/// let expr = cast(root(), DType::Primitive(PType::I64, Nullability::NonNullable));
629/// ```
630pub fn cast(child: Expression, target: DType) -> Expression {
631    Cast.try_new_expr(target, [child])
632        .vortex_expect("Failed to create Cast expression")
633}
634
635/// Creates a bound expression that casts values to a target dtype.
636pub fn bound_cast(child: BoundExpression, target: DType) -> BoundExpression {
637    Cast.try_new_bound_expr(target, [child])
638        .vortex_expect("cast expressions require a supported source and target dtype")
639}
640
641// ---- FillNull ----
642
643/// Creates an expression that replaces null values with a fill value.
644///
645/// ```rust
646/// # use vortex_expr::{fill_null, root, lit};
647/// let expr = fill_null(root(), lit(0i32));
648/// ```
649pub fn fill_null(child: Expression, fill_value: Expression) -> Expression {
650    FillNull.new_expr(EmptyOptions, [child, fill_value])
651}
652
653/// Creates a bound expression that replaces null values with a fill value.
654pub fn bound_fill_null(child: BoundExpression, fill_value: BoundExpression) -> BoundExpression {
655    FillNull
656        .try_new_bound_expr(EmptyOptions, [child, fill_value])
657        .vortex_expect("fill-null expressions require compatible child and fill dtypes")
658}
659
660// ---- IsNotNull ----
661
662/// Creates an expression that checks for non-null values.
663///
664/// Returns a boolean array indicating which positions contain non-null values.
665///
666/// ```rust
667/// # use vortex_expr::{is_not_null, root};
668/// let expr = is_not_null(root());
669/// ```
670pub fn is_not_null(child: Expression) -> Expression {
671    IsNotNull.new_expr(EmptyOptions, vec![child])
672}
673
674/// Creates a bound expression that checks for non-null values.
675pub fn bound_is_not_null(child: BoundExpression) -> BoundExpression {
676    IsNotNull
677        .try_new_bound_expr(EmptyOptions, [child])
678        .vortex_expect("is-not-null expressions are always well-typed")
679}
680
681// ---- Mask ----
682
683/// Creates a mask expression that applies the given boolean mask to the input array.
684pub fn mask(array: Expression, mask: Expression) -> Expression {
685    Mask.new_expr(EmptyOptions, [array, mask])
686}
687
688/// Creates a bound mask expression.
689pub fn bound_mask(array: BoundExpression, mask: BoundExpression) -> BoundExpression {
690    Mask.try_new_bound_expr(EmptyOptions, [array, mask])
691        .vortex_expect("mask expressions require a boolean mask")
692}
693
694/// Constructors for expressions whose children have already been bound and type-checked.
695///
696/// These mirror the unbound constructors in this crate and panic when the supplied children do not
697/// form a well-typed expression. Use [`BoundExpression::try_new`] when construction must be
698/// fallible.
699pub mod bound {
700    pub use super::bound_and as and;
701    pub use super::bound_and_collect as and_collect;
702    pub use super::bound_boolean as boolean;
703    pub use super::bound_cast as cast;
704    pub use super::bound_checked_add as checked_add;
705    pub use super::bound_col as col;
706    pub use super::bound_compare as compare;
707    pub use super::bound_eq as eq;
708    pub use super::bound_fill_null as fill_null;
709    pub use super::bound_get_item as get_item;
710    pub use super::bound_gt as gt;
711    pub use super::bound_gt_eq as gt_eq;
712    pub use super::bound_is_not_null as is_not_null;
713    pub use super::bound_lit as lit;
714    pub use super::bound_lt as lt;
715    pub use super::bound_lt_eq as lt_eq;
716    pub use super::bound_mask as mask;
717    pub use super::bound_not as not;
718    pub use super::bound_not_eq as not_eq;
719    pub use super::bound_numeric as numeric;
720    pub use super::bound_or as or;
721    pub use super::bound_or_collect as or_collect;
722    pub use super::bound_pack as pack;
723    pub use super::bound_root as root;
724}