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