//! [`Protocol`] for giving a visitor an owned value.
//!
//! In some sense, this is the most basic protocol.
use crate::{
any::TypeName,
effect::{Effect, Future},
higher_ranked_type,
hkt::Marker,
protocol::{
walker::hint::{HintMeta, Meta},
DynVisitor,
},
};
use super::VisitResult;
/// Trait object for the [`Value`] protocol.
///
/// Types implementing the [`Value`] protocol will implement this trait.
pub trait Value<'ctx, T: ?Sized + TypeName::MemberType, E: Effect> {
/// Visit a value of type `T`.
///
/// Use this to give a value to a visitor. Its expected that a walker
/// only calls this once per usage of the trait object, but that is not
/// forced.
///
/// If a [`ControlFlow::Break`] is returned then the walker
/// should stop walking as soon as possible as there has likely been
/// and error.
fn visit<'a>(
&'a mut self,
value: TypeName::T<'a, 'ctx, T>,
) -> Future<'a, VisitResult<TypeName::T<'a, 'ctx, T>>, E>
where
TypeName::T<'a, 'ctx, T>: Send + Sized,
'ctx: 'a;
}
pub struct ValueProto<T: ?Sized + TypeName::MemberType, E: Effect>(Marker<(*const T, E)>);
higher_ranked_type! {
impl TypeName {
impl['a, 'ctx, T, E] type T['a, 'ctx] for ValueProto<T, E> =
dyn Value<'ctx, T, E> + Send + Sync + 'a
where {
T: ?Sized + TypeName::MemberType,
E: Effect
};
impl['a, 'ctx, T, E] type HigherRanked['a, 'ctx] for dyn Value<'ctx, T, E> + Send + Sync + 'a =
ValueProto<T, E>
where {
T: ?Sized + TypeName::MemberType,
E: Effect
};
}
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct ValueKnown<'a, T: ?Sized> {
/// A preview of the value.
///
/// This can be used to inspect the value before committing to a visit.
pub preview: Option<&'a T>,
}
#[derive(Copy, Clone, Debug)]
pub struct ValueKnownHrt<T: ?Sized>(Marker<T>);
higher_ranked_type! {
impl Meta {
impl['a, 'ctx, T] type T['a, 'ctx] for ValueKnownHrt<T> =
ValueKnown<'a, TypeName::T<'a, 'ctx, T>>
where {
T: ?Sized + TypeName::LowerForLt<'a, 'ctx, TypeName::Bound<'a, 'ctx>>,
};
impl['a, 'ctx, T] type HigherRanked['a, 'ctx] for ValueKnown<'a, T> =
ValueKnownHrt<<T as TypeName::RaiseForLt<'a, 'ctx, TypeName::Bound<'a, 'ctx>>>::HigherRanked>
where {
T: ?Sized + TypeName::LowerType<'a, 'ctx>,
};
}
}
// This enrolls the Value protocol into the walker hint system.
impl<T: TypeName::MemberType, E: Effect> HintMeta for ValueProto<T, E> {
type Known = ValueKnownHrt<T>;
type Hint = ();
type Effect = E;
}
pub fn visit_value<'a, 'ctx, T: Send + TypeName::LowerType<'a, 'ctx>, E: Effect>(
visitor: DynVisitor<'a, 'ctx>,
value: T,
) -> Future<'a, VisitResult<T>, E>
where
TypeName::HigherRanked<'a, 'ctx, T>: TypeName::MemberType,
{
if let Some(object) = visitor
.0
.upcast_mut::<ValueProto<TypeName::HigherRanked<'a, 'ctx, T>, E>>()
{
// Allow the visitor to give a hint if it wants.
object.visit(value)
} else {
// If the visitor doesn't support request hint then we continue.
E::ready(VisitResult::Skipped(value))
}
}