use std::fmt::Formatter;
use prost::Message;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_session::VortexSession;
use vortex_session::registry::CachedId;
use crate::AnyColumnar;
use crate::ArrayRef;
use crate::ExecutionCtx;
use crate::arrays::Constant;
use crate::arrays::ScalarFnArray;
use crate::dtype::DType;
use crate::dtype::Nullability;
use crate::matcher::Matcher;
use crate::proto::expr as pb;
use crate::require_input;
use crate::scalar::Scalar;
use crate::scalar_fn::Arity;
use crate::scalar_fn::ChildName;
use crate::scalar_fn::ExecutionArgs;
use crate::scalar_fn::ReduceNode;
use crate::scalar_fn::ScalarFnExecutionResult;
use crate::scalar_fn::ScalarFnId;
use crate::scalar_fn::ScalarFnVTable;
use crate::scalar_fn::ScalarFnVTableExt;
use crate::scalar_fn::builtin::binary::binary_child_name;
use crate::scalar_fn::builtin::binary::fmt_infix;
use crate::scalar_fn::builtin::cast::Cast;
use crate::scalar_fn::builtin::operators::BooleanOperator;
use crate::scalar_fn::display::ExprDisplay;
mod kernel;
pub use kernel::BooleanExecuteAdaptor;
pub use kernel::BooleanKernel;
#[expect(deprecated)]
pub use kernel::and_kleene;
pub use kernel::kleene_boolean_buffer_scalar;
pub use kernel::kleene_boolean_buffers;
#[expect(deprecated)]
pub use kernel::or_kleene;
#[derive(Clone)]
pub struct Boolean;
impl Boolean {
pub fn try_new(
lhs: ArrayRef,
rhs: ArrayRef,
operator: BooleanOperator,
) -> VortexResult<ScalarFnArray> {
ScalarFnArray::try_new(Boolean.bind(operator), [lhs, rhs])
}
}
const KLEENE_LUT: [[[bool; 2]; 2]; 2] = [
[[false, true], [true, true]], [[false, false], [false, true]], ];
impl ScalarFnVTable for Boolean {
type Options = BooleanOperator;
fn id(&self) -> ScalarFnId {
static ID: CachedId = CachedId::new("vortex.boolean");
*ID
}
fn serialize(&self, operator: &BooleanOperator) -> VortexResult<Option<Vec<u8>>> {
Ok(Some(
pb::BooleanOpts {
op: pb::boolean_opts::BooleanOp::from(*operator).into(),
}
.encode_to_vec(),
))
}
fn deserialize(
&self,
metadata: &[u8],
_session: &VortexSession,
) -> VortexResult<BooleanOperator> {
let opts = pb::BooleanOpts::decode(metadata)?;
Ok(pb::boolean_opts::BooleanOp::try_from(opts.op)?.into())
}
fn arity(&self, _operator: &BooleanOperator) -> Arity {
Arity::Exact(2)
}
fn child_name(&self, _operator: &BooleanOperator, child_idx: usize) -> ChildName {
binary_child_name(child_idx)
}
fn fmt_sql(
&self,
operator: &BooleanOperator,
expr: &dyn ExprDisplay,
f: &mut Formatter<'_>,
) -> std::fmt::Result {
fmt_infix(operator, expr, f)
}
fn return_dtype(
&self,
operator: &BooleanOperator,
arg_dtypes: &[DType],
) -> VortexResult<DType> {
let lhs = &arg_dtypes[0];
let rhs = &arg_dtypes[1];
if !(lhs.is_boolean() && rhs.is_boolean()) {
vortex_bail!("'{operator}' requires bool operands, got {lhs} and {rhs}",);
}
Ok(DType::Bool((lhs.is_nullable() || rhs.is_nullable()).into()))
}
fn execute(
&self,
operator: &BooleanOperator,
args: &dyn ExecutionArgs,
ctx: &mut ExecutionCtx,
) -> VortexResult<ArrayRef> {
let lhs = args.get(0)?;
let rhs = args.get(1)?;
kernel::execute_boolean(lhs, rhs, *operator, ctx)
}
fn simplify<T: ReduceNode>(
&self,
operator: &BooleanOperator,
node: &T,
) -> VortexResult<Option<T>> {
let lhs = node.child(0);
let rhs = node.child(1);
let bool_constant = |node: &T| node.as_constant()?.as_bool_opt().map(|value| value.value());
let result_nullable = lhs.node_dtype()?.is_nullable() || rhs.node_dtype()?.is_nullable();
let nullability = Nullability::from(result_nullable);
let bool_constant_node = |value: bool| node.new_constant(Scalar::bool(value, nullability));
let widen = |child: T| -> VortexResult<T> {
if child.node_dtype()?.is_nullable() == result_nullable {
Ok(child)
} else {
child.new_node(
Cast.bind(DType::Bool(nullability)),
std::slice::from_ref(&child),
)
}
};
Ok(match operator {
BooleanOperator::And => match (bool_constant(&lhs), bool_constant(&rhs)) {
(Some(Some(false)), _) | (_, Some(Some(false))) => Some(bool_constant_node(false)),
(Some(Some(true)), _) => Some(widen(rhs)?),
(_, Some(Some(true))) => Some(widen(lhs)?),
(Some(None), Some(None)) => Some(widen(lhs)?),
_ => None,
},
BooleanOperator::Or => match (bool_constant(&lhs), bool_constant(&rhs)) {
(Some(Some(true)), _) | (_, Some(Some(true))) => Some(bool_constant_node(true)),
(Some(Some(false)), _) => Some(widen(rhs)?),
(_, Some(Some(false))) => Some(widen(lhs)?),
(Some(None), Some(None)) => Some(widen(lhs)?),
_ => None,
},
})
}
fn reduce<T: ReduceNode>(
&self,
operator: &BooleanOperator,
node: &T,
) -> VortexResult<Option<T>> {
let left = node.child(0);
let right = node.child(1);
let left_const = left.as_constant();
let right_const = right.as_constant();
let left_const = left_const
.and_then(|s| s.value().cloned())
.map(|v| v.as_bool());
let right_const = right_const
.and_then(|s| s.value().cloned())
.map(|v| v.as_bool());
let is_and = *operator == BooleanOperator::And;
let nullability = node.node_dtype()?.nullability();
let (constant, other) = match (left_const, right_const) {
(None, None) => return Ok(None),
(Some(left_const), Some(right_const)) => {
return Ok(Some(left.new_constant(Scalar::bool(
KLEENE_LUT[is_and as usize][left_const as usize][right_const as usize],
nullability,
))));
}
(Some(constant), None) => (constant, right),
(None, Some(constant)) => (constant, left),
};
if constant == is_and {
return Ok((other.node_dtype()?.nullability() == nullability).then_some(other));
}
Ok(Some(
other.new_constant(Scalar::bool(constant, nullability)),
))
}
fn execute_step(
&self,
operator: &BooleanOperator,
args: &dyn ExecutionArgs,
ctx: &mut ExecutionCtx,
) -> VortexResult<ScalarFnExecutionResult> {
let columnar = |idx| args.input_matches(idx, AnyColumnar::matches);
let constant = |idx| args.input_matches(idx, |array| array.is::<Constant>());
let ready = (columnar(0)? && columnar(1)?) || constant(0)? || constant(1)?;
if !ready {
require_input!(args, 0 => AnyColumnar);
require_input!(args, 1 => AnyColumnar);
}
self.execute(operator, args, ctx)
.map(ScalarFnExecutionResult::done)
}
fn is_strict(&self, _operator: &BooleanOperator) -> bool {
false
}
fn is_infallible(&self, _operator: &BooleanOperator) -> bool {
true
}
}