use effectful::{
effective::Effective,
environment::{DynBind, EnvConfig, Environment, InEnvironment, NativeForm},
higher_ranked::Rank1,
SendSync,
};
use crate::{
any::type_name,
hkt::Marker,
protocol::{walker::hint::HintMeta, DynVisitor},
Flow,
};
use super::VisitResult;
/// Protocol for visiting a sequence.
///
/// This protocol uses a scope to give temporary control to the visitor.
/// The visitor will drive the walker for each item.
pub trait Sequence<'ctx, E: Environment>: DynBind<E> {
fn visit<'a: 'c, 'b: 'c, 'c>(
&'a mut self,
scope: DynSequenceScope<'b, 'ctx, E>,
) -> NativeForm<'c, VisitResult, E>
where
'ctx: 'a;
}
const _: () = {
pub struct SequenceProto<E: Environment>(Marker<E>);
impl<'a, 'ctx, E> type_name::Lower<'a, 'ctx, &'a &'ctx ()> for SequenceProto<E>
where
E: Environment,
{
type Lowered = dyn Sequence<'ctx, E> + 'a;
}
impl<'a, 'ctx, E> type_name::Raise<'a, 'ctx, &'a &'ctx ()> for dyn Sequence<'ctx, E> + 'a
where
E: Environment,
{
type Raised = SequenceProto<E>;
}
impl<'a, 'ctx, E: Environment> HintMeta for SequenceProto<E> {
type Known = Rank1<SequenceKnown>;
type Hint = Rank1<SequenceHint>;
}
impl<'a, 'ctx, E: Environment> InEnvironment for SequenceProto<E> {
type Env = E;
}
};
pub trait SequenceScope<'ctx, E: Environment>: DynBind<E> {
fn size_hint(&mut self) -> NativeForm<'_, (usize, Option<usize>), E>;
fn next<'a: 'c, 'b: 'c, 'c>(
&'a mut self,
visitor: DynVisitor<'b, 'ctx, E>,
) -> NativeForm<'c, Flow, E>
where
'ctx: 'c + 'a + 'b;
}
pub type DynSequenceScope<'a, 'ctx, E> = &'a mut (dyn SequenceScope<'ctx, E> + 'a);
#[derive(Default, SendSync)]
pub struct SequenceKnown {
pub len: (usize, Option<usize>),
}
#[derive(SendSync)]
pub struct SequenceHint {
pub len: (usize, Option<usize>),
}
#[inline(always)]
pub fn visit_sequence<'a, 'ctx, E: Environment>(
visitor: DynVisitor<'a, 'ctx, E>,
scope: DynSequenceScope<'a, 'ctx, E>,
) -> NativeForm<'a, VisitResult, E> {
if let Some(object) = visitor
.0
.cast_mut()
.upcast_mut::<dyn Sequence<'ctx, E> + 'a>()
{
// Allow the visitor to walk the sequence scope.
object.visit(scope)
} else {
// If the visitor doesn't support sequence then we continue.
E::value(VisitResult::Skipped(())).cast()
}
}