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
use effectful::{
    effective::{Canonical, Effective},
    environment::Environment,
    DynBind,
};

use crate::{
    any::type_name,
    protocol::{DynVisitor, DynWalker},
};

use super::VisitResult;

/// Protocol for requesting a hint from a visitor.
pub trait RequestHint<'src, E: Environment>: DynBind<E> {
    /// Call this to request a hint.
    ///
    /// `walker` is what the visitor (`self`) will call to give a hint using the
    /// [`Hint`][crate::builtins::walker::Hint] protocol.
    fn request_hint<'r>(
        &'r mut self,
        walker: DynWalker<'r, 'src, E>,
    ) -> Canonical<'r, VisitResult, E>;
}

impl<'u, 'src, E> type_name::Lower<'u, 'src, &'u &'src ()> for dyn RequestHint<'static, E>
where
    E: Environment,
{
    type Lowered = dyn RequestHint<'src, E> + 'u;
}

impl<'u, 'src, E> type_name::Raise<'u, 'src, &'u &'src ()> for dyn RequestHint<'src, E> + 'u
where
    E: Environment,
{
    type Raised = dyn RequestHint<'static, E>;
}

/// Visit using the [`RequestHint`] protocol.
///
/// If [`Flow::Continue`] is returned then the visitor wants/needs more information it didn't get
/// from the hints.
/// If [`Flow::Done`] is returned then the visitor doesn't need any more information and the walker
/// should stop walking.
/// If [`Flow::Break`] is returned then there was an error and the walker should stop walking.
pub fn request_hint<'r, 'src, E: Environment>(
    visitor: DynVisitor<'r, 'src, E>,
    walker: DynWalker<'r, 'src, E>,
) -> Canonical<'r, VisitResult<DynWalker<'r, 'src, E>>, E> {
    E::value((visitor, walker))
        .update_map((), |_, (visitor, walker)| {
            if let Some(object) = visitor.upcast_mut::<dyn RequestHint<'src, E> + '_>() {
                // Allow the visitor to give a hint if it wants.
                object
                    .request_hint(walker.cast())
                    .map((), |_, x| x.unit_skipped())
                    .cast()
            } else {
                // If the visitor doesn't support request hint then we continue.
                E::value(VisitResult::Skipped(())).cast()
            }
        })
        .map((), |_, ((_, walker), result)| {
            result.map_skipped(|_| walker)
        })
        .cast()
}