vortex_expr/
expression.rs1use std::cell::Cell;
5use std::fmt;
6use std::fmt::Debug;
7use std::fmt::Display;
8use std::fmt::Formatter;
9use std::hash::Hash;
10use std::sync::Arc;
11
12use itertools::Itertools;
13use vortex_array::dtype::DType;
14use vortex_array::dtype::FieldName;
15use vortex_array::expr::display::DisplayTreeExpr;
16use vortex_array::scalar_fn::ScalarFnRef;
17use vortex_array::scalar_fn::ScalarFnVTable;
18use vortex_error::VortexError;
19use vortex_error::VortexExpect;
20use vortex_error::VortexResult;
21use vortex_error::vortex_ensure;
22use vortex_error::vortex_err;
23
24use crate::traversal::TraversalOrder;
25use crate::traversal::pre_order_visit_down;
26
27const NO_CHILDREN: &[Expression] = &[];
29
30#[derive(Clone, Debug, PartialEq, Eq, Hash)]
39pub enum Expression {
40 Scalar {
42 scalar_fn: ScalarFnRef,
44 children: Arc<Vec<Expression>>,
46 },
47 Root,
49 Variable(FieldName),
54}
55
56impl Expression {
57 pub fn try_new(
59 scalar_fn: ScalarFnRef,
60 children: impl IntoIterator<Item = Expression>,
61 ) -> VortexResult<Self> {
62 let children = Vec::from_iter(children);
63
64 vortex_ensure!(
65 scalar_fn.signature().arity().matches(children.len()),
66 "Expression arity mismatch: expected {} children but got {}",
67 scalar_fn.signature().arity(),
68 children.len()
69 );
70
71 Ok(Self::Scalar {
72 scalar_fn,
73 children: children.into(),
74 })
75 }
76
77 pub fn is_root(&self) -> bool {
79 matches!(self, Self::Root)
80 }
81
82 pub fn as_scalar(&self) -> Option<&ScalarFnRef> {
84 match self {
85 Self::Scalar { scalar_fn, .. } => Some(scalar_fn),
86 Self::Root | Self::Variable(_) => None,
87 }
88 }
89
90 pub fn is<V: ScalarFnVTable>(&self) -> bool {
92 self.as_scalar().is_some_and(|sf| sf.is::<V>())
93 }
94
95 pub fn as_opt<V: ScalarFnVTable>(&self) -> Option<&V::Options> {
97 self.as_scalar().and_then(|sf| sf.as_opt::<V>())
98 }
99
100 pub fn as_<V: ScalarFnVTable>(&self) -> &V::Options {
106 self.as_opt::<V>()
107 .vortex_expect("Expression options type mismatch")
108 }
109
110 pub fn children(&self) -> &[Expression] {
112 match self {
113 Self::Scalar { children, .. } => children.as_slice(),
114 Self::Root | Self::Variable(_) => NO_CHILDREN,
115 }
116 }
117
118 pub fn child(&self, n: usize) -> &Expression {
120 &self.children()[n]
121 }
122
123 pub fn with_children(
125 self,
126 children: impl IntoIterator<Item = Expression>,
127 ) -> VortexResult<Self> {
128 let children = Vec::from_iter(children);
129 match &self {
130 Self::Root => {
131 vortex_ensure!(
132 children.is_empty(),
133 "Expression arity mismatch: root expects 0 children but got {}",
134 children.len()
135 );
136 Ok(Self::Root)
137 }
138 Self::Variable(name) => {
139 vortex_ensure!(
140 children.is_empty(),
141 "Expression arity mismatch: variable expects 0 children but got {}",
142 children.len()
143 );
144 Ok(Self::Variable(name.clone()))
145 }
146 Self::Scalar { scalar_fn, .. } => {
147 vortex_ensure!(
148 scalar_fn.signature().arity().matches(children.len()),
149 "Expression arity mismatch: expected {} children but got {}",
150 scalar_fn.signature().arity(),
151 children.len()
152 );
153 Ok(Self::Scalar {
154 scalar_fn: scalar_fn.clone(),
155 children: children.into(),
156 })
157 }
158 }
159 }
160
161 pub fn return_dtype(&self, scope: &DType) -> VortexResult<DType> {
163 match self {
164 Self::Root => Ok(scope.clone()),
165 Self::Variable(name) => Err(unbound_variable(name)),
166 Self::Scalar {
167 scalar_fn,
168 children,
169 } => {
170 let dtypes: Vec<_> = children
171 .iter()
172 .map(|c| c.return_dtype(scope))
173 .try_collect()?;
174 scalar_fn.return_dtype(&dtypes)
175 }
176 }
177 }
178
179 pub fn fmt_sql(&self, f: &mut Formatter<'_>) -> fmt::Result {
184 match self {
185 Self::Root => write!(f, "$"),
186 Self::Variable(name) => write!(f, "@{name}"),
187 Self::Scalar { scalar_fn, .. } => scalar_fn.fmt_sql(self, f),
188 }
189 }
190
191 pub fn display_tree(&self) -> impl Display {
237 DisplayTreeExpr(self)
238 }
239
240 pub fn contains<E: ScalarFnVTable>(&self) -> VortexResult<bool> {
253 let mut contains = false;
254 pre_order_visit_down(self, |node| {
255 if node.is::<E>() {
256 contains = true;
257 return Ok(TraversalOrder::Stop);
258 }
259 Ok(TraversalOrder::Continue)
260 })?;
261 Ok(contains)
262 }
263}
264
265pub(crate) fn unbound_variable(name: &FieldName) -> VortexError {
267 vortex_err!("variable @{name} is not a parameter of an enclosing lambda")
268}
269
270impl Display for Expression {
272 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
273 self.fmt_sql(f)
274 }
275}
276
277const MAX_DROP_DEPTH: u32 = 32;
279
280thread_local! {
281 static DROP_DEPTH: Cell<u32> = const { Cell::new(0) };
282}
283
284struct DropDepthGuard;
286
287impl DropDepthGuard {
288 fn enter() -> Option<Self> {
289 DROP_DEPTH.with(|depth| {
290 let current = depth.get();
291 (current < MAX_DROP_DEPTH).then(|| {
292 depth.set(current + 1);
293 Self
294 })
295 })
296 }
297}
298
299impl Drop for DropDepthGuard {
300 fn drop(&mut self) {
301 DROP_DEPTH.with(|depth| depth.set(depth.get() - 1));
302 }
303}
304
305impl Drop for Expression {
306 fn drop(&mut self) {
307 let Self::Scalar { children, .. } = self else {
308 return;
309 };
310 let Some(children) = Arc::get_mut(children) else {
311 return;
312 };
313 if children.is_empty() {
314 return;
315 }
316
317 let mut children_to_drop = std::mem::take(children);
318
319 match DropDepthGuard::enter() {
320 Some(_guard) => drop(children_to_drop),
321 None => {
322 while let Some(mut child) = children_to_drop.pop() {
323 if let Self::Scalar { children, .. } = &mut child
324 && let Some(expr_children) = Arc::get_mut(children)
325 {
326 children_to_drop.append(expr_children);
327 }
328 }
329 }
330 }
331 }
332}
333
334#[cfg(test)]
335mod tests {
336 use std::thread;
337
338 use super::*;
339 use crate::lit;
340 use crate::not;
341
342 fn deep_expression(depth: usize) -> Expression {
343 let mut expr = lit(true);
344 for _ in 0..depth {
345 expr = not(expr);
346 }
347 expr
348 }
349
350 #[test]
351 fn deep_expression_drops_within_a_small_stack() -> VortexResult<()> {
352 const DEPTH: usize = 100_000;
353 const STACK_SIZE: usize = 256 * 1024;
354
355 let dropper = thread::Builder::new()
356 .stack_size(STACK_SIZE)
357 .spawn(|| drop(deep_expression(DEPTH)))?;
358
359 assert!(
360 dropper.join().is_ok(),
361 "dropping a tree of depth {DEPTH} exhausted a {STACK_SIZE} byte stack"
362 );
363
364 Ok(())
365 }
366
367 #[test]
368 fn shallow_expression_keeps_shared_children() {
369 let expr = not(lit(true));
370 let shared = expr.clone();
371
372 drop(expr);
373
374 assert_eq!(shared.children(), &[lit(true)]);
375 }
376}