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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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()
    }
}