Skip to main content

vortex_array/expr/
bound_expression.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::borrow::Borrow;
5use std::fmt;
6use std::fmt::Display;
7use std::fmt::Formatter;
8use std::hash::Hash;
9use std::hash::Hasher;
10use std::sync::Arc;
11use std::sync::Weak;
12
13use itertools::Itertools;
14use vortex_error::VortexExpect;
15use vortex_error::VortexResult;
16use vortex_error::vortex_ensure;
17
18use crate::dtype::DType;
19use crate::expr::display::DisplayTreeExpr;
20use crate::scalar::Scalar;
21use crate::scalar_fn::EmptyOptions;
22use crate::scalar_fn::ExpressionReduceNode;
23use crate::scalar_fn::ReduceNode;
24use crate::scalar_fn::ReduceNodeValidity;
25use crate::scalar_fn::ScalarFnRef;
26use crate::scalar_fn::ScalarFnVTable;
27use crate::scalar_fn::ScalarFnVTableExt;
28use crate::scalar_fn::builtin::is_not_null::IsNotNull;
29use crate::scalar_fn::builtin::literal::Literal;
30use crate::scalar_fn::display::ExprDisplay;
31
32/// An expression that has been type-checked against a scope's root dtype.
33///
34/// Every node carries its own dtype, so reading one is a field access rather than a walk of the
35/// subtree. Holding a `BoundExpression` is proof that the whole tree type-checked.
36///
37/// Binding is purely logical: it deals only in [`DType`]s and never sees an array, a length, or an
38/// encoding.
39#[derive(Clone, Debug, PartialEq, Eq, Hash)]
40pub enum BoundExpression {
41    /// A scalar function applied to bound children.
42    Scalar {
43        /// The dtype this node evaluates to.
44        dtype: DType,
45        /// The scalar function for this node.
46        scalar_fn: ScalarFnRef,
47        /// The bound children, in argument order.
48        ///
49        /// Sharing keeps clones cheap even though the iterative [`Drop`] implementation prevents
50        /// consumers from destructuring a `BoundExpression` by value.
51        children: Arc<Vec<BoundExpression>>,
52    },
53    /// The scope itself. Its dtype is the scope's root dtype.
54    Root {
55        /// The dtype this node evaluates to.
56        dtype: DType,
57    },
58}
59
60/// A bound-expression wrapper that compares shared tree identity instead of structure.
61#[derive(Clone, Debug)]
62pub struct ExactBoundExpr(pub BoundExpression);
63
64/// A bound expression compared by shared tree identity, as [`ExactBoundExpr`] compares it.
65///
66/// Maps keyed by [`ExactBoundExpr`] or [`WeakBoundExprKey`] can be probed with
67/// `expr as &dyn ExactKey` for a borrowed [`BoundExpression`], which spares cloning the
68/// expression for every lookup. Clones touch reference counts that every scan thread shares.
69pub trait ExactKey {
70    /// The identity of the expression that this key stands for.
71    fn identity(&self) -> ExactIdentity<'_>;
72}
73
74/// What identifies a bound expression to an [`ExactKey`]: the dtype of a root, or the function,
75/// dtype and shared children of a scalar node.
76pub enum ExactIdentity<'a> {
77    /// A root of the given dtype.
78    Root(&'a DType),
79    /// A scalar node, identified by the address of its shared children.
80    Scalar {
81        /// The address of the shared children of the node.
82        children: *const Vec<BoundExpression>,
83        /// The scalar function of the node.
84        scalar_fn: &'a ScalarFnRef,
85        /// The dtype of the node.
86        dtype: &'a DType,
87    },
88}
89
90impl BoundExpression {
91    fn exact_identity(&self) -> ExactIdentity<'_> {
92        match self {
93            BoundExpression::Root { dtype } => ExactIdentity::Root(dtype),
94            BoundExpression::Scalar {
95                dtype,
96                scalar_fn,
97                children,
98            } => ExactIdentity::Scalar {
99                children: Arc::as_ptr(children),
100                scalar_fn,
101                dtype,
102            },
103        }
104    }
105}
106
107impl ExactKey for ExactBoundExpr {
108    fn identity(&self) -> ExactIdentity<'_> {
109        self.0.exact_identity()
110    }
111}
112
113impl ExactKey for BoundExpression {
114    fn identity(&self) -> ExactIdentity<'_> {
115        self.exact_identity()
116    }
117}
118
119impl<'a> Borrow<dyn ExactKey + 'a> for ExactBoundExpr {
120    fn borrow(&self) -> &(dyn ExactKey + 'a) {
121        self
122    }
123}
124
125impl PartialEq for dyn ExactKey + '_ {
126    fn eq(&self, other: &Self) -> bool {
127        match (self.identity(), other.identity()) {
128            (ExactIdentity::Root(lhs_dtype), ExactIdentity::Root(rhs_dtype)) => {
129                lhs_dtype == rhs_dtype
130            }
131            (
132                ExactIdentity::Scalar {
133                    children: lhs_children,
134                    scalar_fn: lhs_fn,
135                    dtype: lhs_dtype,
136                },
137                ExactIdentity::Scalar {
138                    children: rhs_children,
139                    scalar_fn: rhs_fn,
140                    dtype: rhs_dtype,
141                },
142            ) => {
143                std::ptr::eq(lhs_children, rhs_children)
144                    && lhs_fn == rhs_fn
145                    && lhs_dtype == rhs_dtype
146            }
147            _ => false,
148        }
149    }
150}
151
152impl Eq for dyn ExactKey + '_ {}
153
154impl Hash for dyn ExactKey + '_ {
155    fn hash<H: Hasher>(&self, state: &mut H) {
156        // Equal keys share their children, so the identity of the children is enough to hash.
157        // Omitting the function's options and the potentially lazy dtype keeps identity-keyed
158        // cache lookups from hashing literal lists or deserializing an entire schema.
159        match self.identity() {
160            ExactIdentity::Root(_) => state.write_u8(0),
161            ExactIdentity::Scalar { children, .. } => {
162                state.write_u8(1);
163                children.hash(state);
164            }
165        }
166    }
167}
168
169/// A key that identifies a bound expression as [`ExactBoundExpr`] does, without keeping the
170/// expression alive.
171///
172/// Caches that outlive the scans they serve, such as those of layout readers reused across
173/// queries, key their entries by it. A key can only be looked up while something else holds its
174/// expression, so [`Self::is_live`] tells which entries can still be hit, and the caches drop the
175/// others. The weak reference keeps the allocation of the children, so no later expression can
176/// reuse their address and match a stale key.
177#[derive(Clone, Debug)]
178pub enum WeakBoundExprKey {
179    /// A root of the given dtype.
180    Root(DType),
181    /// A scalar node, identified by its shared children.
182    Scalar {
183        /// The shared children of the node.
184        children: Weak<Vec<BoundExpression>>,
185        /// The scalar function of the node.
186        scalar_fn: ScalarFnRef,
187        /// The dtype of the node.
188        dtype: DType,
189    },
190}
191
192impl WeakBoundExprKey {
193    /// The key of `expr`.
194    pub fn new(expr: &BoundExpression) -> Self {
195        match expr {
196            BoundExpression::Root { dtype } => Self::Root(dtype.clone()),
197            BoundExpression::Scalar {
198                dtype,
199                scalar_fn,
200                children,
201            } => Self::Scalar {
202                children: Arc::downgrade(children),
203                scalar_fn: scalar_fn.clone(),
204                dtype: dtype.clone(),
205            },
206        }
207    }
208
209    /// Whether the expression of this key is still alive, so that a lookup can still hit it.
210    pub fn is_live(&self) -> bool {
211        match self {
212            Self::Root(_) => true,
213            Self::Scalar { children, .. } => children.strong_count() > 0,
214        }
215    }
216}
217
218impl ExactKey for WeakBoundExprKey {
219    fn identity(&self) -> ExactIdentity<'_> {
220        match self {
221            Self::Root(dtype) => ExactIdentity::Root(dtype),
222            Self::Scalar {
223                children,
224                scalar_fn,
225                dtype,
226            } => ExactIdentity::Scalar {
227                children: children.as_ptr(),
228                scalar_fn,
229                dtype,
230            },
231        }
232    }
233}
234
235impl<'a> Borrow<dyn ExactKey + 'a> for WeakBoundExprKey {
236    fn borrow(&self) -> &(dyn ExactKey + 'a) {
237        self
238    }
239}
240
241impl PartialEq for WeakBoundExprKey {
242    fn eq(&self, other: &Self) -> bool {
243        (self as &dyn ExactKey) == (other as &dyn ExactKey)
244    }
245}
246
247impl Eq for WeakBoundExprKey {}
248
249impl Hash for WeakBoundExprKey {
250    fn hash<H: Hasher>(&self, state: &mut H) {
251        (self as &dyn ExactKey).hash(state);
252    }
253}
254
255impl PartialEq for ExactBoundExpr {
256    fn eq(&self, other: &Self) -> bool {
257        (self as &dyn ExactKey) == (other as &dyn ExactKey)
258    }
259}
260
261impl Eq for ExactBoundExpr {}
262
263impl Hash for ExactBoundExpr {
264    fn hash<H: Hasher>(&self, state: &mut H) {
265        (self as &dyn ExactKey).hash(state);
266    }
267}
268
269impl BoundExpression {
270    /// Create a bound root expression with the given dtype.
271    pub fn new_root(dtype: DType) -> Self {
272        Self::Root { dtype }
273    }
274
275    /// Create a bound scalar node from a scalar function and already-bound children.
276    pub fn try_new(
277        scalar_fn: ScalarFnRef,
278        children: impl IntoIterator<Item = BoundExpression>,
279    ) -> VortexResult<Self> {
280        Self::try_new_vec(scalar_fn, children.into_iter().collect())
281    }
282
283    fn try_new_vec(scalar_fn: ScalarFnRef, children: Vec<BoundExpression>) -> VortexResult<Self> {
284        vortex_ensure!(
285            scalar_fn.signature().arity().matches(children.len()),
286            "Expression arity mismatch: expected {} children but got {}",
287            scalar_fn.signature().arity(),
288            children.len()
289        );
290
291        let arg_dtypes = children
292            .iter()
293            .map(|child| child.dtype().clone())
294            .collect_vec();
295        let scalar_fn = scalar_fn.bind_options(&arg_dtypes)?;
296        let dtype = scalar_fn.return_dtype(&arg_dtypes)?;
297
298        Ok(Self::Scalar {
299            dtype,
300            scalar_fn,
301            children: children.into(),
302        })
303    }
304
305    /// Rebuild this node with new bound children, recomputing its dtype.
306    pub fn with_children(
307        self,
308        children: impl IntoIterator<Item = BoundExpression>,
309    ) -> VortexResult<Self> {
310        let children = Vec::from_iter(children);
311        let BoundExpression::Scalar { scalar_fn, .. } = &self else {
312            vortex_ensure!(
313                children.is_empty(),
314                "Root expression cannot have {} children",
315                children.len()
316            );
317            return Ok(self);
318        };
319
320        Self::try_new_vec(scalar_fn.clone(), children)
321    }
322
323    /// Returns a copy of this node with a fresh top-level children allocation, preserving its
324    /// scalar function, dtype, and child subtrees.
325    ///
326    /// Caches keyed by [`WeakBoundExprKey`] use this when a cached output expression would
327    /// otherwise reuse the key's own children allocation and keep its weak key alive forever.
328    pub fn detach_identity(&self) -> Self {
329        match self {
330            Self::Root { dtype } => Self::Root {
331                dtype: dtype.clone(),
332            },
333            Self::Scalar {
334                dtype,
335                scalar_fn,
336                children,
337            } => Self::Scalar {
338                dtype: dtype.clone(),
339                scalar_fn: scalar_fn.clone(),
340                children: Arc::new((**children).clone()),
341            },
342        }
343    }
344
345    /// The dtype this expression evaluates to.
346    pub fn dtype(&self) -> &DType {
347        match self {
348            Self::Scalar { dtype, .. } | Self::Root { dtype } => dtype,
349        }
350    }
351
352    /// The bound children of this node, in argument order. Empty for [`BoundExpression::Root`].
353    pub fn children(&self) -> &[BoundExpression] {
354        match self {
355            Self::Scalar { children, .. } => children.as_slice(),
356            Self::Root { .. } => &[],
357        }
358    }
359
360    /// Return the child at `index`.
361    pub fn child(&self, index: usize) -> &BoundExpression {
362        &self.children()[index]
363    }
364
365    /// The scalar function for this node, or `None` if it is the scope root.
366    pub fn as_scalar(&self) -> Option<&ScalarFnRef> {
367        match self {
368            Self::Scalar { scalar_fn, .. } => Some(scalar_fn),
369            Self::Root { .. } => None,
370        }
371    }
372
373    /// Return whether this node uses the given scalar-function vtable.
374    pub fn is<V: ScalarFnVTable>(&self) -> bool {
375        self.as_scalar().is_some_and(ScalarFnRef::is::<V>)
376    }
377
378    /// Return whether this expression tree contains a node using the given scalar-function vtable.
379    pub fn contains<V: ScalarFnVTable>(&self) -> VortexResult<bool> {
380        Ok(self.any_node(|node| node.is::<V>()))
381    }
382
383    /// Whether any node of this tree, visited depth-first, satisfies `predicate`.
384    fn any_node(&self, mut predicate: impl FnMut(&BoundExpression) -> bool) -> bool {
385        let mut stack = vec![self];
386        while let Some(node) = stack.pop() {
387            if predicate(node) {
388                return true;
389            }
390            stack.extend(node.children().iter().rev());
391        }
392        false
393    }
394
395    /// Create a bound literal node.
396    pub fn literal(value: Scalar) -> Self {
397        Self::try_new(Literal.bind(value), [])
398            .vortex_expect("literal expressions are always well-typed")
399    }
400
401    /// Return the typed scalar-function options when this node uses the given vtable.
402    pub fn as_opt<V: ScalarFnVTable>(&self) -> Option<&V::Options> {
403        self.as_scalar().and_then(ScalarFnRef::as_opt::<V>)
404    }
405
406    /// Return the typed scalar-function options for this node.
407    ///
408    /// # Panics
409    ///
410    /// Panics when this node is the scope root or uses a different scalar-function vtable.
411    pub fn as_<V: ScalarFnVTable>(&self) -> &V::Options {
412        self.as_opt::<V>()
413            .vortex_expect("Bound expression options type mismatch")
414    }
415
416    /// Whether this node is the scope root.
417    pub fn is_root(&self) -> bool {
418        matches!(self, Self::Root { .. })
419    }
420
421    /// Return whether every scope root in this expression has `dtype`.
422    ///
423    /// Expressions without a scope root, such as literals, match every dtype.
424    pub fn is_root_bound_to(&self, dtype: &DType) -> bool {
425        !self.any_node(|node| node.is_root() && node.dtype() != dtype)
426    }
427
428    /// Returns a new expression representing the validity mask output of this expression.
429    ///
430    /// Returned expression evaluates to a non-nullable boolean array.
431    /// When scalar function's validity is irreducible, returns
432    /// "is_not_null(self)", which requires evaluating "self".
433    pub fn validity(&self) -> VortexResult<BoundExpression> {
434        match self {
435            // The scope is exactly as valid as itself.
436            Self::Root { .. } => Ok(self.clone()),
437            Self::Scalar { .. } => {
438                let node = ExpressionReduceNode::new(self);
439                Ok(match node.validity()? {
440                    ReduceNodeValidity::Reduced(reduced) => reduced.into_expression(),
441                    // IsNotNull(x) -> x.validity() symbolic reduction rule works only
442                    // when node's.validity is Reduced to avoid infinite recursion.
443                    ReduceNodeValidity::Irreducible => {
444                        BoundExpression::try_new(IsNotNull.bind(EmptyOptions), [self.clone()])?
445                    }
446                })
447            }
448        }
449    }
450
451    /// Display the bound expression as a formatted tree structure.
452    pub fn display_tree(&self) -> impl Display {
453        DisplayTreeExpr(self)
454    }
455}
456
457impl Display for BoundExpression {
458    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
459        match self {
460            Self::Scalar { scalar_fn, .. } => scalar_fn.fmt_sql(self, f),
461            Self::Root { .. } => f.write_str("$"),
462        }
463    }
464}
465
466/// Iterative drop to avoid stack overflows on deep trees.
467impl Drop for BoundExpression {
468    fn drop(&mut self) {
469        let Self::Scalar { children, .. } = self else {
470            return;
471        };
472        let Some(children) = Arc::get_mut(children) else {
473            return;
474        };
475
476        let mut to_drop = std::mem::take(children);
477        while let Some(mut child) = to_drop.pop() {
478            if let BoundExpression::Scalar { children, .. } = &mut child
479                && let Some(grandchildren) = Arc::get_mut(children)
480            {
481                to_drop.append(grandchildren);
482            }
483        }
484    }
485}
486
487impl ExprDisplay for BoundExpression {
488    fn display_child(&self, index: usize) -> &dyn ExprDisplay {
489        &self.children()[index]
490    }
491
492    fn display_children_count(&self) -> usize {
493        self.children().len()
494    }
495}