vortex_array/scalar_fn/vtable.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::borrow::Cow;
5use std::fmt;
6use std::fmt::Debug;
7use std::fmt::Display;
8use std::fmt::Formatter;
9use std::hash::Hash;
10
11use arcref::ArcRef;
12use vortex_error::VortexExpect;
13use vortex_error::VortexResult;
14use vortex_error::vortex_bail;
15use vortex_error::vortex_err;
16use vortex_session::VortexSession;
17use vortex_utils::iter::ReduceBalancedIterExt;
18
19use crate::ArrayRef;
20use crate::ExecutionCtx;
21use crate::IntoArray;
22use crate::arrays::ConstantArray;
23use crate::arrays::ScalarFn;
24use crate::arrays::ScalarFnArray;
25use crate::dtype::DType;
26use crate::executor::DonePredicate;
27use crate::expr::BoundExpression;
28use crate::expr::Expression;
29use crate::expr::bound;
30use crate::expr::display::ExprDisplay;
31use crate::matcher::Matcher;
32use crate::scalar::Scalar;
33use crate::scalar_fn::ScalarFnId;
34use crate::scalar_fn::ScalarFnRef;
35use crate::scalar_fn::TypedScalarFnInstance;
36use crate::scalar_fn::fns::binary::Binary;
37use crate::scalar_fn::fns::is_not_null::IsNotNull;
38use crate::scalar_fn::fns::literal::Literal;
39use crate::scalar_fn::fns::operators::Operator;
40use crate::validity::Validity;
41
42// Here and beyond we use validity(x) interchangeably with is_not_null(x).
43#[derive(Clone)]
44pub enum ReduceNodeValidity<T: ReduceNode> {
45 /// Validity of T can be symbolically reduced (i.e. without evaluating T)
46 /// to a function over validities of this node's children. For an
47 /// expression reduce node, one example is byte_length(x).
48 /// validity(byte_length(x)) can be symbolically reduced to validity(x)
49 /// since byte_length doesn't change validity.
50 Reduced(T),
51 /// Validity of T can't be symbolically reduced to anything, and all
52 /// further reductions require evaluating T first. For an expression reduce
53 /// node, one example is list_contains(x, C) since you can't reduce
54 /// validity(list_contains(x, C)). list_contains([], null) is false, but to
55 /// know that, you need to evaluate x's offsets.
56 ///
57 /// This is also the default case.
58 Irreducible,
59}
60
61/// IsNotNull(child) as a reducible node
62pub(crate) fn is_not_null_node<T: ReduceNode>(child: &T) -> VortexResult<T> {
63 child.new_node(IsNotNull.bind(EmptyOptions), std::slice::from_ref(child))
64}
65
66/// "And" over "node's" non-nullable children
67pub fn union_child_validities<T: ReduceNode>(node: &T) -> VortexResult<T> {
68 let mut parts = Vec::with_capacity(node.child_count());
69 for i in 0..node.child_count() {
70 let child = node.child(i);
71 if child.node_dtype()?.is_nullable() {
72 parts.push(is_not_null_node(&child)?);
73 }
74 }
75 let parts = parts
76 .into_iter()
77 .try_reduce_balanced(|lhs, rhs| {
78 lhs.new_node(Binary.bind(Operator::And), &[lhs.clone(), rhs])
79 })?
80 .unwrap_or_else(|| node.new_constant(true.into()));
81 Ok(parts)
82}
83
84/// This trait defines the interface for scalar function vtables, including methods for
85/// serialization, deserialization, validation, child naming, return type computation,
86/// and evaluation.
87///
88/// This trait is non-object safe and allows the implementer to make use of associated types
89/// for improved type safety, while allowing Vortex to enforce runtime checks on the inputs and
90/// outputs of each function.
91///
92/// The [`ScalarFnVTable`] trait should be implemented for a struct that holds global data across
93/// all instances of the expression. In almost all cases, this struct will be an empty unit
94/// struct, since most expressions do not require any global state.
95pub trait ScalarFnVTable: 'static + Sized + Clone + Send + Sync {
96 /// Options for this expression.
97 type Options: 'static + Send + Sync + Clone + Debug + Display + PartialEq + Eq + Hash;
98
99 /// Returns the ID of the scalar function vtable.
100 fn id(&self) -> ScalarFnId;
101
102 /// Serialize the options for this expression.
103 ///
104 /// Should return `Ok(None)` if the expression is not serializable, and `Ok(vec![])` if it is
105 /// serializable but has no metadata.
106 fn serialize(&self, options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
107 _ = options;
108 Ok(None)
109 }
110
111 /// Deserialize the options of this expression.
112 fn deserialize(
113 &self,
114 _metadata: &[u8],
115 _session: &VortexSession,
116 ) -> VortexResult<Self::Options> {
117 vortex_bail!("Expression {} is not deserializable", self.id());
118 }
119
120 /// Returns the arity of this expression.
121 fn arity(&self, options: &Self::Options) -> Arity;
122
123 /// Returns the name of the nth child of the expr.
124 fn child_name(&self, options: &Self::Options, child_idx: usize) -> ChildName;
125
126 /// Format an expression tree in a human-readable SQL-style format.
127 ///
128 /// The expression may be either an [`Expression`] or a
129 /// [`bound expression`](crate::expr::BoundExpression).
130 fn fmt_sql(
131 &self,
132 options: &Self::Options,
133 expr: &dyn ExprDisplay,
134 f: &mut Formatter<'_>,
135 ) -> fmt::Result {
136 write!(f, "{}(", self.id())?;
137 let nchildren = expr.display_children_count();
138 for i in 0..nchildren {
139 Display::fmt(expr.display_child(i), f)?;
140 if i + 1 < nchildren {
141 write!(f, ", ")?;
142 }
143 }
144 let opts = format!("{}", options);
145 if !opts.is_empty() {
146 write!(f, ", opts={}", opts)?;
147 }
148 write!(f, ")")
149 }
150
151 /// Compute the return [`DType`] of the expression if evaluated over the given input types.
152 ///
153 /// # Preconditions
154 ///
155 /// The length of `args` must match the [`Arity`] of this function. Callers are responsible
156 /// for validating this (e.g., [`Expression::try_new`] checks arity at construction time).
157 /// Implementations may assume correct arity and will panic or return nonsensical results if
158 /// violated.
159 ///
160 /// [`Expression::try_new`]: crate::expr::Expression::try_new
161 fn return_dtype(&self, options: &Self::Options, args: &[DType]) -> VortexResult<DType>;
162
163 /// Bind whatever in the options depends on the argument dtypes, such as the body of a
164 /// [`Lambda`](crate::expr::Lambda), returning the bound options.
165 ///
166 /// This is called whenever a bound node is built and whenever a
167 /// [`ScalarFnArray`] is built from its children, before
168 /// [`return_dtype`](Self::return_dtype), so [`execute`](Self::execute) finds the options bound.
169 /// A rebuilt node calls it again, possibly with other dtypes: options that are already bound
170 /// must be checked against these dtypes, returning `None` if they fit and an error if they
171 /// don't. Return `None` to keep the options as they are, which the default does.
172 #[doc(hidden)]
173 fn bind_options(
174 &self,
175 options: &Self::Options,
176 args: &[DType],
177 ) -> VortexResult<Option<Self::Options>> {
178 _ = (options, args);
179 Ok(None)
180 }
181
182 /// Execute the expression over the input arguments.
183 ///
184 /// Superseded by [`execute_step`](Self::execute_step). Vortex only calls this method through
185 /// the default `execute_step`. A function that implements `execute_step` either implements
186 /// `execute` with [`vortex_panic!`], or keeps its logic here and calls it from `execute_step`
187 /// once [`require_input!`](crate::require_input) has its inputs in the form it needs.
188 ///
189 /// [`vortex_panic!`]: vortex_error::vortex_panic
190 ///
191 /// Implementations are encouraged to check their inputs for constant arrays to perform
192 /// more optimized execution.
193 ///
194 /// If the input arguments cannot be directly used for execution (for example, an expression
195 /// may require canonical input arrays), then the implementation should perform a single
196 /// child execution and return a new [`crate::arrays::ScalarFnArray`] wrapping up the new child.
197 ///
198 /// This provides maximum opportunities for array-level optimizations using execute_parent
199 /// kernels.
200 fn execute(
201 &self,
202 options: &Self::Options,
203 args: &dyn ExecutionArgs,
204 ctx: &mut ExecutionCtx,
205 ) -> VortexResult<ArrayRef>;
206
207 /// Perform a single step of execution over the input arguments.
208 ///
209 /// This is used by the iterative executor when executing a
210 /// [`ScalarFnArray`]. Instead of executing an input itself, an implementation can return
211 /// [`ScalarFnExecutionResult::execute_input`] to ask the scheduler to execute that input until
212 /// it matches a [`Matcher`]. The scheduler then calls `execute_step` again with the executed
213 /// input in its place, so deep trees of scalar functions run without recursion.
214 ///
215 /// Only request an input that does not already match, otherwise execution cannot make
216 /// progress and fails.
217 ///
218 /// The default delegates to [`execute`](Self::execute), for functions that have not been
219 /// migrated yet. [`ScalarFnRef::execute`] is defined in terms of this method, so once a
220 /// function overrides it, its [`execute`](Self::execute) is never called.
221 fn execute_step(
222 &self,
223 options: &Self::Options,
224 args: &dyn ExecutionArgs,
225 ctx: &mut ExecutionCtx,
226 ) -> VortexResult<ScalarFnExecutionResult> {
227 self.execute(options, args, ctx)
228 .map(ScalarFnExecutionResult::done)
229 }
230
231 /// Implement an abstract reduction rule over a tree of scalar functions.
232 ///
233 /// The [`ReduceNode`] can be used to traverse children, inspect their types, and
234 /// construct the result via [`ReduceNode::new_node`]. The rule is generic over the node
235 /// type and is instantiated once per reducible tree kind (expressions and arrays).
236 ///
237 /// Return `Ok(None)` if no reduction is possible.
238 fn reduce<T: ReduceNode>(&self, options: &Self::Options, node: &T) -> VortexResult<Option<T>> {
239 _ = options;
240 _ = node;
241 Ok(None)
242 }
243
244 /// For node, returns node' which is exactly the result of evaluating
245 /// validity(node). Returned node' is either a lazy computation over
246 /// children of node, a constant, or Irreducible which means you need to
247 /// evaluate node to get its validity.
248 fn validity<T: ReduceNode>(
249 &self,
250 options: &Self::Options,
251 node: &T,
252 ) -> VortexResult<ReduceNodeValidity<T>> {
253 if !self.is_strict(options) {
254 return Ok(ReduceNodeValidity::Irreducible);
255 }
256
257 let mut dtypes = Vec::with_capacity(node.child_count());
258 for i in 0..node.child_count() {
259 let dtype = node.child(i).node_dtype()?;
260 if matches!(dtype, DType::Null) {
261 return Ok(ReduceNodeValidity::Irreducible);
262 }
263 dtypes.push(dtype.as_nonnullable());
264 }
265
266 let res = if let Ok(dtype) = self.return_dtype(options, &dtypes)
267 && !dtype.is_nullable()
268 {
269 ReduceNodeValidity::Reduced(union_child_validities(node)?)
270 } else {
271 ReduceNodeValidity::Irreducible
272 };
273 Ok(res)
274 }
275
276 /// Simplify the bound expression if possible.
277 ///
278 /// Every node of `expr` carries its dtype, so rules read types directly from the tree.
279 fn simplify(
280 &self,
281 options: &Self::Options,
282 expr: &BoundExpression,
283 ) -> VortexResult<Option<BoundExpression>> {
284 _ = options;
285 _ = expr;
286 Ok(None)
287 }
288
289 /// Returns whether this scalar function is strict.
290 ///
291 /// A strict function returns null for a row when any argument is null for that row. This
292 /// matches [PostgreSQL's `STRICT` convention](https://www.postgresql.org/docs/current/sql-createfunction.html)
293 /// for null propagation.
294 ///
295 /// Return `true` only when this holds for every argument. `add` is strict, but Kleene `AND`
296 /// is not because `false AND null` returns `false`. `is_null` is also not strict.
297 ///
298 /// Strictness does not require valid inputs to produce a valid output. For example,
299 /// [`crate::expr::list_sum`] returns null for a valid empty list. Implement
300 /// [`ScalarFnVTable::validity`] only when the output validity can be derived without
301 /// evaluation.
302 ///
303 /// [`ScalarFnVTable::return_dtype`] must return a nullable output dtype when any input dtype is
304 /// nullable. A `cast` that forces a non-nullable output dtype is therefore not strict.
305 ///
306 /// This property applies only to the scalar function, not its child expressions. Nullary
307 /// functions are vacuously strict. The default is conservatively `false`.
308 fn is_strict(&self, options: &Self::Options) -> bool {
309 _ = options;
310 false
311 }
312
313 /// Returns whether this scalar function can never raise a semantic error.
314 ///
315 /// Return `true` only when a well-typed call cannot error because of its values. `checked_add`
316 /// is fallible on integer overflow, and integer division is fallible when its divisor is zero.
317 /// A null result is not an error: [`crate::expr::list_sum`] is infallible for an empty list.
318 ///
319 /// Ignore incidental execution errors, such as canonicalization failures, allocation errors,
320 /// and encoding mismatches. They are not part of the function's semantics.
321 ///
322 /// Returning `true` permits optimizations that evaluate the function over values that no input
323 /// row references. Dictionary push-down, for example, evaluates every dictionary value, so a
324 /// fallible function could error on a value that row-wise evaluation would never reach.
325 ///
326 /// This applies only to the scalar function, not its child expressions, and only to inputs
327 /// accepted by [`ScalarFnVTable::return_dtype`]. The default is conservatively `false`.
328 fn is_infallible(&self, options: &Self::Options) -> bool {
329 _ = options;
330 false
331 }
332}
333
334/// A node used for implementing abstract reduction rules over a tree of scalar functions.
335///
336/// Reduction rules are generic over the node type, so a rule is written once and monomorphized
337/// per reducible tree kind: [`ExpressionReduceNode`] for bound expression trees and
338/// [`ArrayReduceNode`] for array trees. Nodes borrow from the tree being reduced, making
339/// traversal allocation-free, while nodes produced by [`ReduceNode::new_node`] own their
340/// freshly-built subtrees.
341pub trait ReduceNode: Clone {
342 /// Return the data type of this node.
343 fn node_dtype(&self) -> VortexResult<DType>;
344
345 /// Return this node's scalar function if it is indeed a scalar fn.
346 fn scalar_fn(&self) -> Option<&ScalarFnRef>;
347
348 /// Descend to the child of this node.
349 fn child(&self, idx: usize) -> Self;
350
351 /// Returns the number of children of this node.
352 fn child_count(&self) -> usize;
353
354 /// Create a new node from the given scalar function and children, inheriting this node's
355 /// reduction context (e.g. the expression scope, or the array row count).
356 fn new_node(&self, scalar_fn: ScalarFnRef, children: &[Self]) -> VortexResult<Self>;
357
358 /// Return a scalar value if this node is constant
359 fn as_constant(&self) -> Option<&Scalar> {
360 None
361 }
362
363 /// Produce a new constant node in the same scope as "self"
364 fn new_constant(&self, value: Scalar) -> Self;
365
366 /// Symbolic validity of this node. Reduced() if you can get from node's
367 /// validity to validity of its children or a constant without evaluating
368 /// node.
369 fn validity(&self) -> VortexResult<ReduceNodeValidity<Self>>
370 where
371 Self: Sized;
372}
373
374/// A [`ReduceNode`] over a bound expression tree.
375#[derive(Clone)]
376pub struct ExpressionReduceNode<'a> {
377 expression: Cow<'a, BoundExpression>,
378}
379
380impl<'a> ExpressionReduceNode<'a> {
381 /// Creates a node borrowing the given bound expression.
382 pub fn new(expression: &'a BoundExpression) -> Self {
383 Self {
384 expression: Cow::Borrowed(expression),
385 }
386 }
387
388 /// Returns the bound expression backing this node.
389 pub fn expression(&self) -> &BoundExpression {
390 &self.expression
391 }
392
393 /// Consumes this node and returns the backing bound expression.
394 pub fn into_expression(self) -> BoundExpression {
395 self.expression.into_owned()
396 }
397}
398
399impl ReduceNode for ExpressionReduceNode<'_> {
400 fn node_dtype(&self) -> VortexResult<DType> {
401 Ok(self.expression.dtype().clone())
402 }
403
404 fn scalar_fn(&self) -> Option<&ScalarFnRef> {
405 self.expression.as_scalar()
406 }
407
408 fn child(&self, idx: usize) -> Self {
409 let expression = match &self.expression {
410 Cow::Borrowed(expression) => Cow::Borrowed(expression.child(idx)),
411 Cow::Owned(expression) => Cow::Owned(expression.child(idx).clone()),
412 };
413 Self { expression }
414 }
415
416 fn child_count(&self) -> usize {
417 self.expression.children().len()
418 }
419
420 fn new_node(&self, scalar_fn: ScalarFnRef, children: &[Self]) -> VortexResult<Self> {
421 let expression = BoundExpression::try_new(
422 scalar_fn,
423 children.iter().map(|c| c.expression.as_ref().clone()),
424 )?;
425 Ok(Self {
426 expression: Cow::Owned(expression),
427 })
428 }
429
430 fn as_constant(&self) -> Option<&Scalar> {
431 self.expression.as_opt::<Literal>()
432 }
433
434 fn new_constant(&self, value: Scalar) -> Self {
435 Self {
436 expression: Cow::Owned(bound::lit(value)),
437 }
438 }
439
440 fn validity(&self) -> VortexResult<ReduceNodeValidity<Self>> {
441 match self.expression.as_scalar() {
442 Some(scalar_fn) => scalar_fn.validity_expression(self),
443 None => Ok(ReduceNodeValidity::Irreducible),
444 }
445 }
446}
447
448/// A [`ReduceNode`] over an array tree.
449#[derive(Clone)]
450pub struct ArrayReduceNode<'a> {
451 array: Cow<'a, ArrayRef>,
452}
453
454impl<'a> ArrayReduceNode<'a> {
455 /// Creates a node borrowing the given array.
456 pub fn new(array: &'a ArrayRef) -> Self {
457 Self {
458 array: Cow::Borrowed(array),
459 }
460 }
461
462 /// Returns the array backing this node.
463 pub fn array(&self) -> &ArrayRef {
464 &self.array
465 }
466
467 /// Consumes this node and returns the backing array.
468 pub fn into_array(self) -> ArrayRef {
469 self.array.into_owned()
470 }
471}
472
473impl ReduceNode for ArrayReduceNode<'_> {
474 fn node_dtype(&self) -> VortexResult<DType> {
475 Ok(self.array.dtype().clone())
476 }
477
478 fn scalar_fn(&self) -> Option<&ScalarFnRef> {
479 self.array
480 .as_opt::<ScalarFn>()
481 .map(|a| a.data().scalar_fn())
482 }
483
484 fn child(&self, idx: usize) -> Self {
485 let array = match &self.array {
486 Cow::Borrowed(array) => Cow::Borrowed(
487 array
488 .nth_child(idx)
489 .vortex_expect("child idx out of bounds"),
490 ),
491 Cow::Owned(array) => Cow::Owned(
492 array
493 .nth_child(idx)
494 .vortex_expect("child idx out of bounds")
495 .clone(),
496 ),
497 };
498 Self { array }
499 }
500
501 fn child_count(&self) -> usize {
502 self.array.nchildren()
503 }
504
505 fn new_node(&self, scalar_fn: ScalarFnRef, children: &[Self]) -> VortexResult<Self> {
506 let array = ScalarFnArray::try_new_with_len(
507 scalar_fn,
508 children.iter().map(|c| c.array.as_ref().clone()),
509 self.array.len(),
510 )?;
511 Ok(Self {
512 array: Cow::Owned(array.into_array()),
513 })
514 }
515
516 fn as_constant(&self) -> Option<&Scalar> {
517 self.array.as_constant()
518 }
519
520 fn new_constant(&self, value: Scalar) -> Self {
521 let array = ConstantArray::new(value, self.array.len());
522 Self {
523 array: Cow::Owned(array.into_array()),
524 }
525 }
526
527 fn validity(&self) -> VortexResult<ReduceNodeValidity<Self>> {
528 if let Some(scalar_fn) = self.array.as_opt::<ScalarFn>() {
529 return scalar_fn.data().scalar_fn().validity_array(self);
530 }
531 Ok(ReduceNodeValidity::Reduced(
532 match self.array.validity()? {
533 Validity::NonNullable | Validity::AllValid => self.new_constant(true.into()),
534 Validity::AllInvalid => self.new_constant(false.into()),
535 Validity::Array(array) => Self {
536 array: Cow::Owned(array),
537 },
538 },
539 ))
540 }
541}
542
543/// The arity (number of arguments) of a function.
544#[derive(Clone, Copy, Debug, PartialEq, Eq)]
545pub enum Arity {
546 Exact(usize),
547 Variadic { min: usize, max: Option<usize> },
548}
549
550impl Display for Arity {
551 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
552 match self {
553 Arity::Exact(n) => write!(f, "{}", n),
554 Arity::Variadic { min, max } => match max {
555 Some(max) if min == max => write!(f, "{}", min),
556 Some(max) => write!(f, "{}..{}", min, max),
557 None => write!(f, "{}+", min),
558 },
559 }
560 }
561}
562
563impl Arity {
564 /// Whether the given argument count matches this arity.
565 pub fn matches(&self, arg_count: usize) -> bool {
566 match self {
567 Arity::Exact(m) => *m == arg_count,
568 Arity::Variadic { min, max } => {
569 if arg_count < *min {
570 return false;
571 }
572 if let Some(max) = max
573 && arg_count > *max
574 {
575 return false;
576 }
577 true
578 }
579 }
580 }
581}
582
583/// Arguments for expression execution.
584pub trait ExecutionArgs {
585 /// Returns the input array at the given index.
586 fn get(&self, index: usize) -> VortexResult<ArrayRef>;
587
588 /// Returns the number of inputs.
589 fn num_inputs(&self) -> usize;
590
591 /// Returns the row count of the execution scope.
592 fn row_count(&self) -> usize;
593
594 /// Whether the input at the given index satisfies `predicate`.
595 ///
596 /// Implementations that hold their inputs override this to test the input in place, without
597 /// the clone [`get`](Self::get) makes, since it runs on every scalar function execution step.
598 fn input_matches(&self, index: usize, predicate: fn(&ArrayRef) -> bool) -> VortexResult<bool> {
599 Ok(predicate(&self.get(index)?))
600 }
601}
602
603/// The result of a single [`ScalarFnVTable::execute_step`].
604pub struct ScalarFnExecutionResult(ScalarFnExecutionStep);
605
606/// What the scheduler should do after a [`ScalarFnVTable::execute_step`].
607#[derive(Clone)]
608pub enum ScalarFnExecutionStep {
609 /// Execution finished with this result.
610 Done(ArrayRef),
611 /// Execute the input at this index until the predicate matches, then call
612 /// [`ScalarFnVTable::execute_step`] again.
613 ExecuteInput(usize, DonePredicate),
614}
615
616impl ScalarFnExecutionResult {
617 /// Execution finished with the given result.
618 pub fn done(result: impl IntoArray) -> Self {
619 Self(ScalarFnExecutionStep::Done(result.into_array()))
620 }
621
622 /// Ask the scheduler to execute the input at `input_idx` until it matches `M`, then call
623 /// [`ScalarFnVTable::execute_step`] again.
624 pub fn execute_input<M: Matcher>(input_idx: usize) -> Self {
625 Self(ScalarFnExecutionStep::ExecuteInput(input_idx, M::matches))
626 }
627
628 /// Returns the requested step.
629 pub fn step(&self) -> &ScalarFnExecutionStep {
630 &self.0
631 }
632
633 /// Returns the requested step.
634 pub fn into_step(self) -> ScalarFnExecutionStep {
635 self.0
636 }
637}
638
639impl Debug for ScalarFnExecutionResult {
640 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
641 match &self.0 {
642 ScalarFnExecutionStep::Done(array) => f.debug_tuple("Done").field(array).finish(),
643 ScalarFnExecutionStep::ExecuteInput(idx, _) => {
644 f.debug_tuple("ExecuteInput").field(idx).finish()
645 }
646 }
647 }
648}
649
650/// A concrete [`ExecutionArgs`] backed by a `Vec<ArrayRef>`.
651pub struct VecExecutionArgs {
652 inputs: Vec<ArrayRef>,
653 row_count: usize,
654}
655
656impl VecExecutionArgs {
657 /// Create a new `VecExecutionArgs`.
658 pub fn new(inputs: Vec<ArrayRef>, row_count: usize) -> Self {
659 Self { inputs, row_count }
660 }
661}
662
663impl ExecutionArgs for VecExecutionArgs {
664 fn get(&self, index: usize) -> VortexResult<ArrayRef> {
665 self.inputs.get(index).cloned().ok_or_else(|| {
666 vortex_err!(
667 "Input index {} out of bounds (num_inputs={})",
668 index,
669 self.inputs.len()
670 )
671 })
672 }
673
674 fn num_inputs(&self) -> usize {
675 self.inputs.len()
676 }
677
678 fn row_count(&self) -> usize {
679 self.row_count
680 }
681
682 fn input_matches(&self, index: usize, predicate: fn(&ArrayRef) -> bool) -> VortexResult<bool> {
683 let input = self.inputs.get(index).ok_or_else(|| {
684 vortex_err!(
685 "Input index {} out of bounds (num_inputs={})",
686 index,
687 self.inputs.len()
688 )
689 })?;
690 Ok(predicate(input))
691 }
692}
693
694#[derive(Clone, Debug, PartialEq, Eq, Hash)]
695pub struct EmptyOptions;
696impl Display for EmptyOptions {
697 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
698 write!(f, "")
699 }
700}
701
702/// Factory functions for vtables.
703pub trait ScalarFnVTableExt: ScalarFnVTable {
704 /// Bind this vtable with the given options into a [`ScalarFnRef`].
705 fn bind(&self, options: Self::Options) -> ScalarFnRef {
706 TypedScalarFnInstance::new(self.clone(), options).erased()
707 }
708
709 /// Create a new expression with this vtable and the given options and children.
710 fn new_expr(
711 &self,
712 options: Self::Options,
713 children: impl IntoIterator<Item = Expression>,
714 ) -> Expression {
715 Self::try_new_expr(self, options, children).vortex_expect("Failed to create expression")
716 }
717
718 /// Try to create a new expression with this vtable and the given options and children.
719 fn try_new_expr(
720 &self,
721 options: Self::Options,
722 children: impl IntoIterator<Item = Expression>,
723 ) -> VortexResult<Expression> {
724 Expression::try_new(self.bind(options), children)
725 }
726
727 /// Try to create a bound expression with this vtable, the given options, and bound children.
728 fn try_new_bound_expr(
729 &self,
730 options: Self::Options,
731 children: impl IntoIterator<Item = BoundExpression>,
732 ) -> VortexResult<BoundExpression> {
733 BoundExpression::try_new(self.bind(options), children)
734 }
735}
736impl<V: ScalarFnVTable> ScalarFnVTableExt for V {}
737
738/// A reference to the name of a child expression.
739pub type ChildName = ArcRef<str>;