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