use core::{any::TypeId, marker::PhantomData, ops::ControlFlow};
use crate::{
any::{static_wrapper::OwnedStatic, LtTypeId},
any_trait,
effect::{Effect, Future},
protocol::{visitor::{
tag::{Dyn, Tag},
value::Value, request_hint::RequestHint,
}, self},
DynWalker,
};
pub struct Walker<E>(usize, PhantomData<fn() -> E>);
any_trait! {
impl['a, 'ctx, E] Walker<E> = [
dyn RequestHint<'ctx, Effect = E> + 'a,
dyn Tag<'ctx, Dyn, Effect = E> + 'a,
dyn Value<'a, 'ctx, OwnedStatic<&'static str>, Effect = E> + 'a,
dyn Value<'a, 'ctx, OwnedStatic<TypeId>, Effect = E> + 'a,
] else fallback where E: Effect<'ctx>
}
fn fallback(id: LtTypeId<'_>) {
println!("Unknown trait: {}", id);
}
impl<'ctx, E: Effect<'ctx>> Walker<E> {
pub fn new() -> Self {
Self(0, PhantomData)
}
fn tab(&self) {
for _ in 0..self.0 {
print!(" ");
}
}
}
impl<'ctx, E: Effect<'ctx>> RequestHint<'ctx> for Walker<E> {
type Effect = E;
fn request_hint<'a>(
&'a mut self,
_walker: crate::protocol::Walker<'a, 'ctx>,
) -> Future<'a, 'ctx, ControlFlow<(), ()>, Self::Effect>
where
Self: 'a
{
self.tab();
println!("Visit request hint (no hint given)");
E::wrap(async { ControlFlow::Continue(()) })
}
}
impl<'ctx, E: Effect<'ctx>> Tag<'ctx, Dyn> for Walker<E> {
type Effect = E;
fn visit<'a>(
&'a mut self,
kind: Dyn,
walker: &'a mut dyn DynWalker<'ctx, Effect = Self::Effect>,
) -> Future<'a, 'ctx, ControlFlow<(), protocol::visitor::tag::Status>, Self::Effect>
where
Self: 'a,
{
self.tab();
println!("Visit tag: {}", kind.0);
E::wrap(async {
self.0 += 1;
let result = walker.walk(self).await;
self.0 -= 1;
match result {
ControlFlow::Continue(()) => ControlFlow::Continue(protocol::visitor::tag::Status::Walked),
ControlFlow::Break(()) => ControlFlow::Break(()),
}
})
}
}
impl<'a, 'ctx: 'a, E: Effect<'ctx>> Value<'a, 'ctx, OwnedStatic<&'static str>> for Walker<E> {
type Effect = E;
fn visit(&'a mut self, OwnedStatic(value): OwnedStatic<&'static str>) -> Future<'a, 'ctx, ControlFlow<(), ()>, Self::Effect> where Self: 'a {
self.tab();
println!("Visit static str: {:?}", value);
E::wrap(async { ControlFlow::Continue(()) })
}
}
impl<'a, 'ctx: 'a, E: Effect<'ctx>> Value<'a, 'ctx, OwnedStatic<TypeId>> for Walker<E> {
type Effect = E;
fn visit(&'a mut self, OwnedStatic(value): OwnedStatic<TypeId>) -> Future<'a, 'ctx, ControlFlow<(), ()>, Self::Effect> where Self: 'a {
self.tab();
println!("Visit type ID: {:?}", value);
E::wrap(async { ControlFlow::Continue(()) })
}
}