1use 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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
40pub enum BoundExpression {
41 Scalar {
43 dtype: DType,
45 scalar_fn: ScalarFnRef,
47 children: Arc<Vec<BoundExpression>>,
52 },
53 Root {
55 dtype: DType,
57 },
58}
59
60#[derive(Clone, Debug)]
62pub struct ExactBoundExpr(pub BoundExpression);
63
64pub trait ExactKey {
70 fn identity(&self) -> ExactIdentity<'_>;
72}
73
74pub enum ExactIdentity<'a> {
77 Root(&'a DType),
79 Scalar {
81 children: *const Vec<BoundExpression>,
83 scalar_fn: &'a ScalarFnRef,
85 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 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#[derive(Clone, Debug)]
178pub enum WeakBoundExprKey {
179 Root(DType),
181 Scalar {
183 children: Weak<Vec<BoundExpression>>,
185 scalar_fn: ScalarFnRef,
187 dtype: DType,
189 },
190}
191
192impl WeakBoundExprKey {
193 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 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 pub fn new_root(dtype: DType) -> Self {
272 Self::Root { dtype }
273 }
274
275 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 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 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 pub fn dtype(&self) -> &DType {
347 match self {
348 Self::Scalar { dtype, .. } | Self::Root { dtype } => dtype,
349 }
350 }
351
352 pub fn children(&self) -> &[BoundExpression] {
354 match self {
355 Self::Scalar { children, .. } => children.as_slice(),
356 Self::Root { .. } => &[],
357 }
358 }
359
360 pub fn child(&self, index: usize) -> &BoundExpression {
362 &self.children()[index]
363 }
364
365 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 pub fn is<V: ScalarFnVTable>(&self) -> bool {
375 self.as_scalar().is_some_and(ScalarFnRef::is::<V>)
376 }
377
378 pub fn contains<V: ScalarFnVTable>(&self) -> VortexResult<bool> {
380 Ok(self.any_node(|node| node.is::<V>()))
381 }
382
383 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 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 pub fn as_opt<V: ScalarFnVTable>(&self) -> Option<&V::Options> {
403 self.as_scalar().and_then(ScalarFnRef::as_opt::<V>)
404 }
405
406 pub fn as_<V: ScalarFnVTable>(&self) -> &V::Options {
412 self.as_opt::<V>()
413 .vortex_expect("Bound expression options type mismatch")
414 }
415
416 pub fn is_root(&self) -> bool {
418 matches!(self, Self::Root { .. })
419 }
420
421 pub fn is_root_bound_to(&self, dtype: &DType) -> bool {
425 !self.any_node(|node| node.is_root() && node.dtype() != dtype)
426 }
427
428 pub fn validity(&self) -> VortexResult<BoundExpression> {
434 match self {
435 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 ReduceNodeValidity::Irreducible => {
444 BoundExpression::try_new(IsNotNull.bind(EmptyOptions), [self.clone()])?
445 }
446 })
447 }
448 }
449 }
450
451 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
466impl 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}