1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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},
    Status,
};

use super::VisitResult;

pub trait Recoverable<'ctx, E: Environment>: DynBind<E> {
    fn visit<'a>(
        &'a mut self,
        scope: DynRecoverableScope<'a, 'ctx, E>,
    ) -> NativeForm<'a, VisitResult, E>;
}

const _: () = {
    pub struct RecoverableProto<E>(Marker<E>);

    impl<'a, 'ctx, E: 'static> type_name::Lower<'a, 'ctx, &'a &'ctx ()> for RecoverableProto<E> {
        type Lowered = dyn Recoverable<'ctx, E> + 'a;
    }

    impl<'a, 'ctx, E: 'static> type_name::Raise<'a, 'ctx, &'a &'ctx ()>
        for dyn Recoverable<'ctx, E> + 'a
    {
        type Raised = RecoverableProto<E>;
    }

    impl<E: Environment> HintMeta for RecoverableProto<E> {
        type Known = Rank1<()>;

        type Hint = Rank1<()>;
    }

    impl<E: Environment> InEnvironment for RecoverableProto<E> {
        type Env = E;
    }
};

pub trait RecoverableScope<'ctx, E: Environment>: DynBind<E> {
    fn new_walk<'this: 'effect, 'visitor: 'effect, 'effect>(
        &'this mut self,
        visitor: DynVisitor<'visitor, 'ctx, E>,
    ) -> NativeForm<'effect, Status, E>;
}

pub type DynRecoverableScope<'a, 'ctx, E> = &'a mut (dyn RecoverableScope<'ctx, E> + 'a);

pub fn visit_recoverable<'a, 'ctx, E: Environment>(
    visitor: DynVisitor<'a, 'ctx, E>,
    scope: DynRecoverableScope<'a, 'ctx, E>,
) -> NativeForm<'a, VisitResult, E> {
    if let Some(object) = visitor
        .0
        .cast_mut()
        .upcast_mut::<dyn Recoverable<'ctx, E> + 'a>()
    {
        // Allow the visitor to give a hint if it wants.
        object.visit(scope)
    } else {
        // If the visitor doesn't support request hint then we continue.
        E::value(VisitResult::Skipped(())).cast()
    }
}