Skip to main content

vortex_expr/
bind.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Binding expressions against a scope.
5
6use itertools::Itertools;
7use vortex_array::dtype::DType;
8use vortex_error::VortexExpect;
9use vortex_error::VortexResult;
10
11use crate::BoundExpression;
12use crate::Expression;
13use crate::expression::unbound_variable;
14use crate::scope::Scope;
15
16impl Expression {
17    /// Bind this expression against a root dtype, type-checking every node in a single walk.
18    ///
19    /// The returned tree carries a dtype on each node, so callers needing types at more than one
20    /// node should bind once and read fields rather than calling
21    /// [`return_dtype`](Expression::return_dtype) repeatedly.
22    pub fn bind(&self, dtype: &DType) -> VortexResult<BoundExpression> {
23        self.bind_scope(&Scope::new(dtype.clone()))
24    }
25
26    /// Bind this expression against an explicit [`Scope`].
27    pub fn bind_scope(&self, scope: &Scope) -> VortexResult<BoundExpression> {
28        if self.is_root() {
29            return Ok(BoundExpression::new_root(scope.root().clone()));
30        }
31        if let Expression::Variable(name) = self {
32            return Err(unbound_variable(name));
33        }
34
35        let children: Vec<_> = self
36            .children()
37            .iter()
38            .map(|child| child.bind_scope(scope))
39            .try_collect()?;
40        let scalar_fn = self
41            .as_scalar()
42            .vortex_expect("leaves were handled above, so this is a scalar node");
43        BoundExpression::try_new(scalar_fn.clone(), children)
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use std::sync::Arc;
50
51    use vortex_array::dtype::Nullability;
52    use vortex_array::dtype::PType;
53    use vortex_array::scalar_fn::builtin::literal::Literal;
54    use vortex_error::VortexResult;
55
56    use super::*;
57    use crate::ExactBoundExpr;
58    use crate::ExactKey;
59    use crate::WeakBoundExprKey;
60    use crate::col;
61    use crate::eq;
62    use crate::lit;
63    use crate::root;
64    use crate::test_harness::struct_dtype;
65
66    fn scope() -> Scope {
67        Scope::new(struct_dtype())
68    }
69
70    #[test]
71    fn root_binds_to_the_scope() -> VortexResult<()> {
72        let bound = root().bind_scope(&scope())?;
73        assert!(bound.is_root());
74        assert_eq!(bound.dtype(), &struct_dtype());
75        assert_eq!(bound, BoundExpression::new_root(struct_dtype()));
76        Ok(())
77    }
78
79    #[test]
80    fn every_node_carries_its_dtype() -> VortexResult<()> {
81        let expr = eq(col("a"), lit(1_i32));
82        let bound = expr.bind_scope(&scope())?;
83
84        assert_eq!(bound.dtype(), &DType::Bool(Nullability::NonNullable));
85
86        let lhs = &bound.children()[0];
87        assert_eq!(
88            lhs.dtype(),
89            &DType::Primitive(PType::I32, Nullability::NonNullable)
90        );
91        assert_eq!(lhs.children()[0].dtype(), &struct_dtype());
92        Ok(())
93    }
94
95    #[test]
96    fn bind_agrees_with_return_dtype() -> VortexResult<()> {
97        for (expr, expected) in [
98            (root(), struct_dtype()),
99            (
100                col("a"),
101                DType::Primitive(PType::I32, Nullability::NonNullable),
102            ),
103            (
104                eq(col("a"), lit(1_i32)),
105                DType::Bool(Nullability::NonNullable),
106            ),
107            (lit(true), DType::Bool(Nullability::NonNullable)),
108        ] {
109            assert_eq!(
110                expr.bind(&struct_dtype())?.dtype(),
111                &expected,
112                "binding {expr}"
113            );
114            assert_eq!(
115                expr.return_dtype(&struct_dtype())?,
116                expected,
117                "return dtype of {expr}"
118            );
119        }
120        Ok(())
121    }
122
123    #[test]
124    fn contains_scalar_function() -> VortexResult<()> {
125        let bound = eq(col("a"), lit(1_i32)).bind_scope(&scope())?;
126        assert!(bound.contains::<Literal>()?);
127        assert!(!root().bind_scope(&scope())?.contains::<Literal>()?);
128        Ok(())
129    }
130
131    #[test]
132    fn bound_to_checks_every_root() -> VortexResult<()> {
133        let dtype = struct_dtype();
134        let bound = eq(col("a"), col("a")).bind(&dtype)?;
135        assert!(bound.is_root_bound_to(&dtype));
136        assert!(!bound.is_root_bound_to(&DType::Bool(Nullability::NonNullable)));
137        assert!(
138            lit(true)
139                .bind(&dtype)?
140                .is_root_bound_to(&DType::Bool(Nullability::NonNullable))
141        );
142        Ok(())
143    }
144
145    #[test]
146    fn bound_display_matches_unbound() -> VortexResult<()> {
147        for expr in [root(), col("a"), eq(col("a"), lit(1_i32)), lit(true)] {
148            let bound = expr.bind_scope(&scope())?;
149            assert_eq!(bound.to_string(), expr.to_string());
150            assert_eq!(
151                bound.display_tree().to_string(),
152                expr.display_tree().to_string()
153            );
154        }
155        Ok(())
156    }
157
158    #[test]
159    fn clone_shares_children() -> VortexResult<()> {
160        let bound = eq(col("a"), lit(1_i32)).bind_scope(&scope())?;
161        let cloned = bound.clone();
162
163        let (
164            BoundExpression::Scalar { children: a, .. },
165            BoundExpression::Scalar { children: b, .. },
166        ) = (&bound, &cloned)
167        else {
168            unreachable!("eq is a scalar node")
169        };
170        assert!(Arc::ptr_eq(a, b));
171        Ok(())
172    }
173
174    #[test]
175    fn repeated_subtree_is_bound_per_occurrence() -> VortexResult<()> {
176        let shared = col("a");
177        let bound = eq(shared.clone(), shared).bind_scope(&scope())?;
178        let children = bound.children();
179        assert_eq!(children.len(), 2);
180        for child in children {
181            assert_eq!(
182                child.dtype(),
183                &DType::Primitive(PType::I32, Nullability::NonNullable)
184            );
185        }
186        Ok(())
187    }
188
189    #[test]
190    fn structural_and_exact_equality_are_distinct() -> VortexResult<()> {
191        let expr = eq(col("a"), lit(1_i32));
192        let bound = expr.bind_scope(&scope())?;
193        let independently_bound = expr.bind_scope(&scope())?;
194
195        assert_eq!(bound, independently_bound);
196        assert_eq!(ExactBoundExpr(bound.clone()), ExactBoundExpr(bound.clone()));
197        assert_ne!(ExactBoundExpr(bound), ExactBoundExpr(independently_bound));
198        Ok(())
199    }
200
201    #[test]
202    fn weak_keys_match_only_their_live_expression() -> VortexResult<()> {
203        let expr = eq(col("a"), lit(1_i32));
204        let bound = expr.bind_scope(&scope())?;
205        let independently_bound = expr.bind_scope(&scope())?;
206        let key = WeakBoundExprKey::new(&bound);
207
208        assert!(key.is_live());
209        assert!((&key as &dyn ExactKey) == (&bound as &dyn ExactKey));
210        assert!((&key as &dyn ExactKey) != (&independently_bound as &dyn ExactKey));
211        // A clone shares the children, so it is the same expression to the key.
212        let clone = bound.clone();
213        assert_eq!(key, WeakBoundExprKey::new(&clone));
214
215        drop(bound);
216        assert!(key.is_live());
217        drop(clone);
218        assert!(!key.is_live());
219        Ok(())
220    }
221
222    #[test]
223    fn binding_reports_a_type_error() {
224        let expr = eq(col("a"), lit("nope"));
225        assert!(expr.bind_scope(&scope()).is_err());
226    }
227}