use std::borrow::Borrow;
use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;
use std::hash::Hash;
use std::hash::Hasher;
use std::sync::Arc;
use std::sync::Weak;
use itertools::Itertools;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_ensure;
use crate::dtype::DType;
use crate::expr::display::DisplayTreeExpr;
use crate::scalar::Scalar;
use crate::scalar_fn::EmptyOptions;
use crate::scalar_fn::ExpressionReduceNode;
use crate::scalar_fn::ReduceNode;
use crate::scalar_fn::ReduceNodeValidity;
use crate::scalar_fn::ScalarFnRef;
use crate::scalar_fn::ScalarFnVTable;
use crate::scalar_fn::ScalarFnVTableExt;
use crate::scalar_fn::builtin::is_not_null::IsNotNull;
use crate::scalar_fn::builtin::literal::Literal;
use crate::scalar_fn::display::ExprDisplay;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum BoundExpression {
Scalar {
dtype: DType,
scalar_fn: ScalarFnRef,
children: Arc<Vec<BoundExpression>>,
},
Root {
dtype: DType,
},
}
#[derive(Clone, Debug)]
pub struct ExactBoundExpr(pub BoundExpression);
pub trait ExactKey {
fn identity(&self) -> ExactIdentity<'_>;
}
pub enum ExactIdentity<'a> {
Root(&'a DType),
Scalar {
children: *const Vec<BoundExpression>,
scalar_fn: &'a ScalarFnRef,
dtype: &'a DType,
},
}
impl BoundExpression {
fn exact_identity(&self) -> ExactIdentity<'_> {
match self {
BoundExpression::Root { dtype } => ExactIdentity::Root(dtype),
BoundExpression::Scalar {
dtype,
scalar_fn,
children,
} => ExactIdentity::Scalar {
children: Arc::as_ptr(children),
scalar_fn,
dtype,
},
}
}
}
impl ExactKey for ExactBoundExpr {
fn identity(&self) -> ExactIdentity<'_> {
self.0.exact_identity()
}
}
impl ExactKey for BoundExpression {
fn identity(&self) -> ExactIdentity<'_> {
self.exact_identity()
}
}
impl<'a> Borrow<dyn ExactKey + 'a> for ExactBoundExpr {
fn borrow(&self) -> &(dyn ExactKey + 'a) {
self
}
}
impl PartialEq for dyn ExactKey + '_ {
fn eq(&self, other: &Self) -> bool {
match (self.identity(), other.identity()) {
(ExactIdentity::Root(lhs_dtype), ExactIdentity::Root(rhs_dtype)) => {
lhs_dtype == rhs_dtype
}
(
ExactIdentity::Scalar {
children: lhs_children,
scalar_fn: lhs_fn,
dtype: lhs_dtype,
},
ExactIdentity::Scalar {
children: rhs_children,
scalar_fn: rhs_fn,
dtype: rhs_dtype,
},
) => {
std::ptr::eq(lhs_children, rhs_children)
&& lhs_fn == rhs_fn
&& lhs_dtype == rhs_dtype
}
_ => false,
}
}
}
impl Eq for dyn ExactKey + '_ {}
impl Hash for dyn ExactKey + '_ {
fn hash<H: Hasher>(&self, state: &mut H) {
match self.identity() {
ExactIdentity::Root(_) => state.write_u8(0),
ExactIdentity::Scalar { children, .. } => {
state.write_u8(1);
children.hash(state);
}
}
}
}
#[derive(Clone, Debug)]
pub enum WeakBoundExprKey {
Root(DType),
Scalar {
children: Weak<Vec<BoundExpression>>,
scalar_fn: ScalarFnRef,
dtype: DType,
},
}
impl WeakBoundExprKey {
pub fn new(expr: &BoundExpression) -> Self {
match expr {
BoundExpression::Root { dtype } => Self::Root(dtype.clone()),
BoundExpression::Scalar {
dtype,
scalar_fn,
children,
} => Self::Scalar {
children: Arc::downgrade(children),
scalar_fn: scalar_fn.clone(),
dtype: dtype.clone(),
},
}
}
pub fn is_live(&self) -> bool {
match self {
Self::Root(_) => true,
Self::Scalar { children, .. } => children.strong_count() > 0,
}
}
}
impl ExactKey for WeakBoundExprKey {
fn identity(&self) -> ExactIdentity<'_> {
match self {
Self::Root(dtype) => ExactIdentity::Root(dtype),
Self::Scalar {
children,
scalar_fn,
dtype,
} => ExactIdentity::Scalar {
children: children.as_ptr(),
scalar_fn,
dtype,
},
}
}
}
impl<'a> Borrow<dyn ExactKey + 'a> for WeakBoundExprKey {
fn borrow(&self) -> &(dyn ExactKey + 'a) {
self
}
}
impl PartialEq for WeakBoundExprKey {
fn eq(&self, other: &Self) -> bool {
(self as &dyn ExactKey) == (other as &dyn ExactKey)
}
}
impl Eq for WeakBoundExprKey {}
impl Hash for WeakBoundExprKey {
fn hash<H: Hasher>(&self, state: &mut H) {
(self as &dyn ExactKey).hash(state);
}
}
impl PartialEq for ExactBoundExpr {
fn eq(&self, other: &Self) -> bool {
(self as &dyn ExactKey) == (other as &dyn ExactKey)
}
}
impl Eq for ExactBoundExpr {}
impl Hash for ExactBoundExpr {
fn hash<H: Hasher>(&self, state: &mut H) {
(self as &dyn ExactKey).hash(state);
}
}
impl BoundExpression {
pub fn new_root(dtype: DType) -> Self {
Self::Root { dtype }
}
pub fn try_new(
scalar_fn: ScalarFnRef,
children: impl IntoIterator<Item = BoundExpression>,
) -> VortexResult<Self> {
Self::try_new_vec(scalar_fn, children.into_iter().collect())
}
fn try_new_vec(scalar_fn: ScalarFnRef, children: Vec<BoundExpression>) -> VortexResult<Self> {
vortex_ensure!(
scalar_fn.signature().arity().matches(children.len()),
"Expression arity mismatch: expected {} children but got {}",
scalar_fn.signature().arity(),
children.len()
);
let arg_dtypes = children
.iter()
.map(|child| child.dtype().clone())
.collect_vec();
let scalar_fn = scalar_fn.bind_options(&arg_dtypes)?;
let dtype = scalar_fn.return_dtype(&arg_dtypes)?;
Ok(Self::Scalar {
dtype,
scalar_fn,
children: children.into(),
})
}
pub fn with_children(
self,
children: impl IntoIterator<Item = BoundExpression>,
) -> VortexResult<Self> {
let children = Vec::from_iter(children);
let BoundExpression::Scalar { scalar_fn, .. } = &self else {
vortex_ensure!(
children.is_empty(),
"Root expression cannot have {} children",
children.len()
);
return Ok(self);
};
Self::try_new_vec(scalar_fn.clone(), children)
}
pub fn detach_identity(&self) -> Self {
match self {
Self::Root { dtype } => Self::Root {
dtype: dtype.clone(),
},
Self::Scalar {
dtype,
scalar_fn,
children,
} => Self::Scalar {
dtype: dtype.clone(),
scalar_fn: scalar_fn.clone(),
children: Arc::new((**children).clone()),
},
}
}
pub fn dtype(&self) -> &DType {
match self {
Self::Scalar { dtype, .. } | Self::Root { dtype } => dtype,
}
}
pub fn children(&self) -> &[BoundExpression] {
match self {
Self::Scalar { children, .. } => children.as_slice(),
Self::Root { .. } => &[],
}
}
pub fn child(&self, index: usize) -> &BoundExpression {
&self.children()[index]
}
pub fn as_scalar(&self) -> Option<&ScalarFnRef> {
match self {
Self::Scalar { scalar_fn, .. } => Some(scalar_fn),
Self::Root { .. } => None,
}
}
pub fn is<V: ScalarFnVTable>(&self) -> bool {
self.as_scalar().is_some_and(ScalarFnRef::is::<V>)
}
pub fn contains<V: ScalarFnVTable>(&self) -> VortexResult<bool> {
Ok(self.any_node(|node| node.is::<V>()))
}
fn any_node(&self, mut predicate: impl FnMut(&BoundExpression) -> bool) -> bool {
let mut stack = vec![self];
while let Some(node) = stack.pop() {
if predicate(node) {
return true;
}
stack.extend(node.children().iter().rev());
}
false
}
pub fn literal(value: Scalar) -> Self {
Self::try_new(Literal.bind(value), [])
.vortex_expect("literal expressions are always well-typed")
}
pub fn as_opt<V: ScalarFnVTable>(&self) -> Option<&V::Options> {
self.as_scalar().and_then(ScalarFnRef::as_opt::<V>)
}
pub fn as_<V: ScalarFnVTable>(&self) -> &V::Options {
self.as_opt::<V>()
.vortex_expect("Bound expression options type mismatch")
}
pub fn is_root(&self) -> bool {
matches!(self, Self::Root { .. })
}
pub fn is_root_bound_to(&self, dtype: &DType) -> bool {
!self.any_node(|node| node.is_root() && node.dtype() != dtype)
}
pub fn validity(&self) -> VortexResult<BoundExpression> {
match self {
Self::Root { .. } => Ok(self.clone()),
Self::Scalar { .. } => {
let node = ExpressionReduceNode::new(self);
Ok(match node.validity()? {
ReduceNodeValidity::Reduced(reduced) => reduced.into_expression(),
ReduceNodeValidity::Irreducible => {
BoundExpression::try_new(IsNotNull.bind(EmptyOptions), [self.clone()])?
}
})
}
}
}
pub fn display_tree(&self) -> impl Display {
DisplayTreeExpr(self)
}
}
impl Display for BoundExpression {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Scalar { scalar_fn, .. } => scalar_fn.fmt_sql(self, f),
Self::Root { .. } => f.write_str("$"),
}
}
}
impl Drop for BoundExpression {
fn drop(&mut self) {
let Self::Scalar { children, .. } = self else {
return;
};
let Some(children) = Arc::get_mut(children) else {
return;
};
let mut to_drop = std::mem::take(children);
while let Some(mut child) = to_drop.pop() {
if let BoundExpression::Scalar { children, .. } = &mut child
&& let Some(grandchildren) = Arc::get_mut(children)
{
to_drop.append(grandchildren);
}
}
}
}
impl ExprDisplay for BoundExpression {
fn display_child(&self, index: usize) -> &dyn ExprDisplay {
&self.children()[index]
}
fn display_children_count(&self) -> usize {
self.children().len()
}
}