use std::any::Any;
use std::borrow::Cow;
use std::fmt;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::hash::Hash;
use std::hash::Hasher;
use std::marker::PhantomData;
use std::ops::Deref;
use std::ops::Range;
use std::sync::Arc;
use vortex_array::SerializeMetadata;
use vortex_array::dtype::DType;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_ensure;
use vortex_mask::Mask;
use vortex_session::VortexSession;
use crate::execution::pipeline::Chain;
use crate::execution::pipeline::Compiler;
use crate::plan::PlanId;
use crate::plan::PlanSlots;
use crate::plan::PlanVTable;
use crate::plan::display::PlanTreeDisplay;
struct PlanInner<D: ?Sized> {
id: PlanId,
dtype: DType,
row_count: u64,
slots: PlanSlots,
data: D, }
#[derive(Clone)]
pub struct PlanRef(Arc<PlanInner<dyn DynPlan>>);
impl PlanRef {
fn from_inner<V: PlanVTable>(inner: Arc<PlanInner<PlanData<V>>>) -> Self {
let inner: Arc<PlanInner<dyn DynPlan>> = inner;
Self(inner)
}
fn dyn_plan(&self) -> &dyn DynPlan {
&self.0.data
}
pub(crate) fn is_data_source(&self) -> bool {
self.dyn_plan().dyn_is_data_source(self)
}
pub(crate) fn reduce(&self, session: &VortexSession) -> VortexResult<Option<PlanRef>> {
self.dyn_plan().dyn_reduce(self, session)
}
pub(crate) fn reduce_parent(
&self,
parent: &PlanRef,
slot: usize,
session: &VortexSession,
) -> VortexResult<Option<PlanRef>> {
self.dyn_plan()
.dyn_reduce_parent(self, parent, slot, session)
}
pub fn ptr_eq(lhs: &Self, rhs: &Self) -> bool {
Arc::ptr_eq(&lhs.0, &rhs.0)
}
pub fn id(&self) -> PlanId {
self.0.id
}
pub fn dtype(&self) -> &DType {
&self.0.dtype
}
pub fn row_count(&self) -> u64 {
self.0.row_count
}
pub fn slots(&self) -> &PlanSlots {
&self.0.slots
}
pub fn nslots(&self) -> usize {
self.0.slots.len()
}
pub fn slot(&self, slot: usize) -> VortexResult<Option<PlanRef>> {
Ok(self.0.slots.get(slot)?.cloned())
}
pub fn slot_required(&self, slot: usize) -> VortexResult<PlanRef> {
self.0.slots.required(slot).cloned()
}
pub fn children(&self) -> impl Iterator<Item = VortexResult<&PlanRef>> + '_ {
self.0.slots.children()
}
pub fn with_slots(&self, slots: impl Into<PlanSlots>) -> VortexResult<PlanRef> {
self.dyn_plan().dyn_with_slots(self, slots.into())
}
pub fn slot_name(&self, slot: usize) -> Cow<'_, str> {
self.dyn_plan().dyn_slot_name(self, slot)
}
pub fn metadata(&self) -> Option<Vec<u8>> {
self.dyn_plan().dyn_metadata(self)
}
pub fn is<V: PlanVTable>(&self) -> bool {
self.dyn_plan().as_any().is::<PlanData<V>>()
}
pub fn as_<V: PlanVTable>(&self) -> &Plan<V> {
self.as_opt::<V>().vortex_expect("Failed to downcast")
}
pub fn as_opt<V: PlanVTable>(&self) -> Option<&Plan<V>> {
if !self.is::<V>() {
return None;
}
Some(unsafe { &*(std::ptr::from_ref(self).cast::<Plan<V>>()) })
}
pub fn compile(
&self,
rows: Range<u64>,
mask: &Mask,
compiler: &mut Compiler<'_>,
) -> VortexResult<Option<Chain>> {
vortex_ensure!(
rows.start <= rows.end && rows.end <= self.row_count(),
"Compile rows {rows:?} exceed plan row count {}",
self.row_count()
);
vortex_ensure!(
mask.len() as u64 == rows.end - rows.start,
"Compile mask length {} does not match rows {rows:?}",
mask.len()
);
self.dyn_plan().dyn_compile(self, rows, mask, compiler)
}
pub fn display_tree(&self) -> PlanTreeDisplay<'_> {
PlanTreeDisplay::default_display(self)
}
pub fn tree_display_builder(&self) -> PlanTreeDisplay<'_> {
PlanTreeDisplay::new(self)
}
}
impl Display for PlanRef {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(
formatter,
"{}({}, rows={})",
self.id(),
self.dtype(),
self.row_count()
)?;
self.dyn_plan().dyn_fmt(self, formatter)
}
}
impl Debug for PlanRef {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Plan")
.field("id", &self.0.id)
.field("dtype", &self.0.dtype)
.field("row_count", &self.0.row_count)
.field("slots", &self.0.slots)
.field("data", &&self.0.data)
.finish()
}
}
pub struct PlanParts<V: PlanVTable> {
pub vtable: V,
pub dtype: DType,
pub row_count: u64,
pub slots: PlanSlots,
pub data: V::PlanData,
}
impl<V: PlanVTable> PlanParts<V> {
pub fn into_typed(self) -> Plan<V> {
Plan::from_parts(self)
}
pub fn into_plan(self) -> PlanRef {
self.into_typed().into_plan()
}
}
#[derive(Clone, Debug)]
pub(crate) struct PlanByPtr(pub(crate) PlanRef);
impl PartialEq for PlanByPtr {
fn eq(&self, other: &Self) -> bool {
PlanRef::ptr_eq(&self.0, &other.0)
}
}
impl Eq for PlanByPtr {}
impl Hash for PlanByPtr {
fn hash<H: Hasher>(&self, state: &mut H) {
Arc::as_ptr(&self.0.0).cast::<()>().hash(state);
}
}
#[repr(transparent)]
pub struct Plan<V: PlanVTable> {
inner: PlanRef,
_vtable: PhantomData<V>,
}
impl<V: PlanVTable> Plan<V> {
pub fn from_parts(parts: PlanParts<V>) -> Self {
let inner = Arc::new(PlanInner {
id: parts.vtable.id(),
dtype: parts.dtype,
row_count: parts.row_count,
slots: parts.slots,
data: PlanData {
vtable: parts.vtable,
data: parts.data,
},
});
Self {
inner: PlanRef::from_inner(inner),
_vtable: PhantomData,
}
}
fn typed_data(&self) -> &PlanData<V> {
self.inner
.dyn_plan()
.as_any()
.downcast_ref::<PlanData<V>>()
.vortex_expect("Typed plan contains the wrong vtable")
}
pub fn vtable(&self) -> &V {
&self.typed_data().vtable
}
pub fn data(&self) -> &V::PlanData {
&self.typed_data().data
}
pub fn dtype(&self) -> &DType {
self.inner.dtype()
}
pub fn row_count(&self) -> u64 {
self.inner.row_count()
}
pub fn slots(&self) -> &PlanSlots {
self.inner.slots()
}
pub fn nslots(&self) -> usize {
self.inner.nslots()
}
pub fn slot(&self, slot: usize) -> VortexResult<Option<PlanRef>> {
self.inner.slot(slot)
}
pub fn slot_required(&self, slot: usize) -> VortexResult<PlanRef> {
self.inner.slot_required(slot)
}
pub fn children(&self) -> impl Iterator<Item = VortexResult<&PlanRef>> + '_ {
self.inner.children()
}
pub fn to_plan(&self) -> PlanRef {
self.inner.clone()
}
pub fn into_plan(self) -> PlanRef {
self.inner
}
}
impl<V: PlanVTable> Clone for Plan<V> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
_vtable: PhantomData,
}
}
}
impl<V: PlanVTable> Debug for Plan<V> {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
Debug::fmt(&self.inner, formatter)
}
}
impl<V: PlanVTable> Display for Plan<V> {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
Display::fmt(&self.inner, formatter)
}
}
impl<V: PlanVTable> Deref for Plan<V> {
type Target = V::PlanData;
fn deref(&self) -> &Self::Target {
self.data()
}
}
impl<V: PlanVTable> From<Plan<V>> for PlanRef {
fn from(value: Plan<V>) -> Self {
value.into_plan()
}
}
struct PlanData<V: PlanVTable> {
vtable: V,
data: V::PlanData,
}
impl<V: PlanVTable> Debug for PlanData<V> {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PlanData")
.field("vtable", &self.vtable)
.field("data", &self.data)
.finish()
}
}
#[doc(hidden)]
pub trait DynPlan: 'static + Send + Sync + Debug {
fn as_any(&self) -> &dyn Any;
fn dyn_is_data_source(&self, plan: &PlanRef) -> bool;
fn dyn_reduce(&self, plan: &PlanRef, session: &VortexSession) -> VortexResult<Option<PlanRef>>;
fn dyn_reduce_parent(
&self,
plan: &PlanRef,
parent: &PlanRef,
slot: usize,
session: &VortexSession,
) -> VortexResult<Option<PlanRef>>;
fn dyn_fmt(&self, plan: &PlanRef, formatter: &mut Formatter<'_>) -> fmt::Result;
fn dyn_with_slots(&self, plan: &PlanRef, slots: PlanSlots) -> VortexResult<PlanRef>;
fn dyn_slot_name<'a>(&'a self, plan: &'a PlanRef, slot: usize) -> Cow<'a, str>;
fn dyn_metadata(&self, plan: &PlanRef) -> Option<Vec<u8>>;
fn dyn_compile(
&self,
plan: &PlanRef,
rows: Range<u64>,
mask: &Mask,
compiler: &mut Compiler<'_>,
) -> VortexResult<Option<Chain>>;
}
impl<V: PlanVTable> DynPlan for PlanData<V> {
fn as_any(&self) -> &dyn Any {
self
}
fn dyn_is_data_source(&self, plan: &PlanRef) -> bool {
V::is_data_source(plan.as_::<V>())
}
fn dyn_reduce(&self, plan: &PlanRef, session: &VortexSession) -> VortexResult<Option<PlanRef>> {
V::reduce(plan.as_::<V>(), session)
}
fn dyn_reduce_parent(
&self,
plan: &PlanRef,
parent: &PlanRef,
slot: usize,
session: &VortexSession,
) -> VortexResult<Option<PlanRef>> {
V::reduce_parent(plan.as_::<V>(), parent, slot, session)
}
fn dyn_fmt(&self, plan: &PlanRef, formatter: &mut Formatter<'_>) -> fmt::Result {
<V as PlanVTable>::fmt(plan.as_::<V>(), formatter)
}
fn dyn_with_slots(&self, plan: &PlanRef, slots: PlanSlots) -> VortexResult<PlanRef> {
let mut data = self.data.clone();
V::with_slots(plan.as_::<V>(), &slots, &mut data)?;
Ok(PlanParts {
vtable: self.vtable.clone(),
dtype: plan.dtype().clone(),
row_count: plan.row_count(),
slots,
data,
}
.into_plan())
}
fn dyn_slot_name<'a>(&'a self, plan: &'a PlanRef, slot: usize) -> Cow<'a, str> {
V::slot_name(plan.as_::<V>(), slot)
}
fn dyn_metadata(&self, plan: &PlanRef) -> Option<Vec<u8>> {
V::metadata(plan.as_::<V>()).map(SerializeMetadata::serialize)
}
fn dyn_compile(
&self,
plan: &PlanRef,
rows: Range<u64>,
mask: &Mask,
compiler: &mut Compiler<'_>,
) -> VortexResult<Option<Chain>> {
V::compile(plan.as_::<V>(), rows, mask, compiler)
}
}