Skip to main content

vortex_array/scalar_fn/
erased.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Type-erased scalar function ([`ScalarFnRef`]).
5
6use std::any::type_name;
7use std::fmt::Debug;
8use std::fmt::Display;
9use std::fmt::Formatter;
10use std::hash::Hash;
11use std::hash::Hasher;
12use std::sync::Arc;
13
14use vortex_error::VortexExpect;
15use vortex_error::VortexResult;
16use vortex_error::vortex_err;
17use vortex_utils::debug_with::DebugWith;
18
19use crate::ArrayRef;
20use crate::ExecutionCtx;
21use crate::dtype::DType;
22use crate::expr::BoundExpression;
23use crate::expr::display::ExprDisplay;
24use crate::scalar_fn::ArrayReduceNode;
25use crate::scalar_fn::ExecutionArgs;
26use crate::scalar_fn::ExpressionReduceNode;
27use crate::scalar_fn::ReduceNodeValidity;
28use crate::scalar_fn::ScalarFnExecutionResult;
29use crate::scalar_fn::ScalarFnId;
30use crate::scalar_fn::ScalarFnVTable;
31use crate::scalar_fn::options::ScalarFnOptions;
32use crate::scalar_fn::signature::ScalarFnSignature;
33use crate::scalar_fn::typed::DynScalarFn;
34use crate::scalar_fn::typed::TypedScalarFnInstance;
35
36/// A type-erased scalar function, pairing a vtable with bound options behind a trait object.
37///
38/// This stores a [`ScalarFnVTable`] and its options behind an `Arc<dyn DynScalarFn>`, allowing
39/// heterogeneous storage inside [`crate::arrays::ScalarFnArray`].
40///
41/// Use [`super::TypedScalarFnInstance::new()`] to construct, and [`super::TypedScalarFnInstance::erased()`] to
42/// obtain a [`ScalarFnRef`].
43#[derive(Clone)]
44pub struct ScalarFnRef(pub(super) Arc<dyn DynScalarFn>);
45
46impl ScalarFnRef {
47    /// Returns the ID of this scalar function.
48    pub fn id(&self) -> ScalarFnId {
49        self.0.id()
50    }
51
52    /// Returns whether the scalar function is of the given vtable type.
53    pub fn is<V: ScalarFnVTable>(&self) -> bool {
54        self.0.as_any().is::<TypedScalarFnInstance<V>>()
55    }
56
57    /// Returns the typed options for this scalar function if it matches the given vtable type.
58    pub fn as_opt<V: ScalarFnVTable>(&self) -> Option<&V::Options> {
59        self.0
60            .as_any()
61            .downcast_ref::<TypedScalarFnInstance<V>>()
62            .map(|sf| sf.options())
63    }
64
65    /// Returns the typed options for this scalar function if it matches the given vtable type.
66    ///
67    /// # Panics
68    ///
69    /// Panics if the vtable type does not match.
70    pub fn as_<V: ScalarFnVTable>(&self) -> &V::Options {
71        self.as_opt::<V>()
72            .vortex_expect("Expression options type mismatch")
73    }
74
75    /// Downcast to the concrete [`TypedScalarFnInstance`].
76    ///
77    /// Returns `Err(self)` if the downcast fails.
78    pub fn try_downcast<V: ScalarFnVTable>(
79        self,
80    ) -> Result<Arc<TypedScalarFnInstance<V>>, ScalarFnRef> {
81        if self.0.as_any().is::<TypedScalarFnInstance<V>>() {
82            let ptr = Arc::into_raw(self.0) as *const TypedScalarFnInstance<V>;
83            Ok(unsafe { Arc::from_raw(ptr) })
84        } else {
85            Err(self)
86        }
87    }
88
89    /// Downcast to the concrete [`TypedScalarFnInstance`].
90    ///
91    /// # Panics
92    ///
93    /// Panics if the downcast fails.
94    pub fn downcast<V: ScalarFnVTable>(self) -> Arc<TypedScalarFnInstance<V>> {
95        self.try_downcast::<V>()
96            .map_err(|this| {
97                vortex_err!(
98                    "Failed to downcast ScalarFnRef {} to {}",
99                    this.0.id(),
100                    type_name::<V>(),
101                )
102            })
103            .vortex_expect("Failed to downcast ScalarFnRef")
104    }
105
106    /// Try to downcast into a typed [`TypedScalarFnInstance`].
107    pub fn downcast_ref<V: ScalarFnVTable>(&self) -> Option<&TypedScalarFnInstance<V>> {
108        self.0.as_any().downcast_ref::<TypedScalarFnInstance<V>>()
109    }
110
111    /// The type-erased options for this scalar function.
112    pub fn options(&self) -> ScalarFnOptions<'_> {
113        ScalarFnOptions { inner: &*self.0 }
114    }
115
116    /// Signature information for this scalar function.
117    pub fn signature(&self) -> ScalarFnSignature<'_> {
118        ScalarFnSignature { inner: &*self.0 }
119    }
120
121    /// Compute the return [`DType`] of this expression given the input argument types.
122    pub fn return_dtype(&self, arg_types: &[DType]) -> VortexResult<DType> {
123        self.0.return_dtype(arg_types)
124    }
125
126    /// Bind whatever in the options depends on the argument types, or keep this function if
127    /// nothing does. See [`ScalarFnVTable::bind_options`].
128    pub(crate) fn bind_options(self, arg_types: &[DType]) -> VortexResult<ScalarFnRef> {
129        Ok(self.0.bind_options(arg_types)?.unwrap_or(self))
130    }
131
132    /// Symbolic validity of this node in an expression tree
133    pub(crate) fn validity_expression<'a>(
134        &self,
135        node: &ExpressionReduceNode<'a>,
136    ) -> VortexResult<ReduceNodeValidity<ExpressionReduceNode<'a>>> {
137        self.0.validity_expression(node)
138    }
139
140    /// Symbolic validity of this in an array tree
141    pub(crate) fn validity_array<'a>(
142        &self,
143        node: &ArrayReduceNode<'a>,
144    ) -> VortexResult<ReduceNodeValidity<ArrayReduceNode<'a>>> {
145        self.0.validity_array(node)
146    }
147
148    /// Execute the expression given the input arguments.
149    pub fn execute(
150        &self,
151        args: &dyn ExecutionArgs,
152        ctx: &mut ExecutionCtx,
153    ) -> VortexResult<ArrayRef> {
154        self.0.execute(args, ctx)
155    }
156
157    /// Perform a single step of execution given the input arguments.
158    ///
159    /// See [`ScalarFnVTable::execute_step`].
160    pub fn execute_step(
161        &self,
162        args: &dyn ExecutionArgs,
163        ctx: &mut ExecutionCtx,
164    ) -> VortexResult<ScalarFnExecutionResult> {
165        self.0.execute_step(args, ctx)
166    }
167
168    /// Perform abstract reduction on this scalar function node in an expression tree.
169    pub fn reduce_expression<'a>(
170        &self,
171        node: &ExpressionReduceNode<'a>,
172    ) -> VortexResult<Option<ExpressionReduceNode<'a>>> {
173        self.0.reduce_expression(node)
174    }
175
176    /// Perform abstract reduction on this scalar function node in an array tree.
177    pub fn reduce_array<'a>(
178        &self,
179        node: &ArrayReduceNode<'a>,
180    ) -> VortexResult<Option<ArrayReduceNode<'a>>> {
181        self.0.reduce_array(node)
182    }
183
184    // ------------------------------------------------------------------
185    // Expression-taking methods — used by expr/ module via pub(crate)
186    // ------------------------------------------------------------------
187
188    /// Format an expression tree in SQL-style format.
189    pub(crate) fn fmt_sql(
190        &self,
191        expr: &dyn ExprDisplay,
192        f: &mut Formatter<'_>,
193    ) -> std::fmt::Result {
194        self.0.fmt_sql(expr, f)
195    }
196
197    /// Simplify a bound expression using the dtypes carried by its nodes.
198    pub(crate) fn simplify(&self, expr: &BoundExpression) -> VortexResult<Option<BoundExpression>> {
199        self.0.simplify(expr)
200    }
201}
202
203impl Debug for ScalarFnRef {
204    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
205        f.debug_struct("ScalarFnRef")
206            .field("vtable", &self.0.id())
207            .field("options", &DebugWith(|fmt| self.0.options_debug(fmt)))
208            .finish()
209    }
210}
211
212impl Display for ScalarFnRef {
213    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
214        write!(f, "{}(", self.0.id())?;
215        self.0.options_display(f)?;
216        write!(f, ")")
217    }
218}
219
220impl PartialEq for ScalarFnRef {
221    fn eq(&self, other: &Self) -> bool {
222        self.0.id() == other.0.id() && self.0.options_eq(other.0.options_any())
223    }
224}
225impl Eq for ScalarFnRef {}
226
227impl Hash for ScalarFnRef {
228    fn hash<H: Hasher>(&self, state: &mut H) {
229        self.0.id().hash(state);
230        self.0.options_hash(state);
231    }
232}