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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
use core::any::Any;

use crate::{
    build::{Build, Builder},
    protocol::{
        lookup_hint, lookup_visit, AnyVisit, ProtocolId, Visit, VisitorMissingProtocol,
        WalkerMissingProtocol,
    },
    protocols::reference,
    walk::{Walk, WalkMut, WalkOnce},
    ControlFlow, Visitor, Walker,
};

impl<'borrow, 'ctx, T> WalkOnce<'ctx> for &'borrow mut T
where
    T: WalkMut<'borrow, 'ctx>,
{
    type Error = T::Error;

    type Value = T::Value;

    fn walk_once(self, visitor: &mut dyn Visitor<'ctx>) -> Result<Self::Value, Self::Error> {
        T::walk_mut(self, visitor)
    }
}

impl<'borrow, 'ctx, T> WalkMut<'borrow, 'ctx> for &'borrow mut T
where
    T: WalkMut<'borrow, 'ctx>,
{
    fn walk_mut(
        &'borrow mut self,
        visitor: &mut dyn Visitor<'ctx>,
    ) -> Result<Self::Value, Self::Error> {
        T::walk_mut(self, visitor)
    }
}

impl<'borrow, 'ctx, T> Walk<'borrow, 'ctx> for &'borrow mut T
where
    T: Walk<'borrow, 'ctx>,
{
    fn walk(&'borrow self, visitor: &mut dyn Visitor<'ctx>) -> Result<Self::Value, Self::Error> {
        T::walk(self, visitor)
    }
}

impl<'ctx, T: ?Sized + Any> Build<'ctx> for &'ctx mut T {
    type Builder = MutBuilder<'ctx, T>;
}

pub struct MutWalker<'ctx, T: ?Sized> {
    value: Option<&'ctx mut T>,
}

impl<'ctx, T: ?Sized> MutWalker<'ctx, T> {
    pub fn new(value: &'ctx mut T) -> Self {
        Self {
            value: Some(value),
        }
    }
}

impl<'ctx, T: ?Sized + Any> WalkOnce<'ctx> for MutWalker<'ctx, T> {
    type Error = VisitorMissingProtocol;

    type Value = ();

    fn walk_once(mut self, visitor: &mut dyn Visitor<'ctx>) -> Result<Self::Value, Self::Error> {
        if let Some(value) = self.value.take() {
            let visit = lookup_visit::<reference::ReferenceMut<T>, _>(visitor)?;
            visit.visit(reference::Mut::Context(value));
        }
        Ok(())
    }
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("Missing value after walk.")]
    MissingValue,

    #[error("A value with a lifetime to short was given.")]
    ShortLifetime,

    #[error(transparent)]
    MissingProtocol(#[from] WalkerMissingProtocol),
}

pub struct MutBuilder<'ctx, T: ?Sized> {
    value: Option<Result<&'ctx mut T, Error>>,
}

impl<'ctx, T: ?Sized> Default for MutBuilder<'ctx, T> {
    fn default() -> Self {
        Self { value: None }
    }
}

impl<'ctx, T: ?Sized + Any> Builder<'ctx> for MutBuilder<'ctx, T> {
    type Error = Error;

    type Value = &'ctx mut T;

    fn as_visitor(&mut self) -> &mut dyn Visitor<'ctx> {
        self
    }

    fn build(self) -> Result<Self::Value, Self::Error> {
        match self.value {
            Some(Ok(value)) => Ok(value),
            Some(Err(err)) => Err(err.into()),
            None => Err(Error::MissingValue),
        }
    }
}

impl<'ctx, T: ?Sized + Any> Visitor<'ctx> for MutBuilder<'ctx, T> {
    fn request_hint(
        &mut self,
        hints: &mut dyn crate::Walker<'ctx>,
        _need_hint: bool,
    ) -> ControlFlow {
        match lookup_hint::<reference::Reference<T>, _>(hints) {
            Ok(hint) => hint.hint(
                self,
                reference::Hint {
                    kind: Some(reference::Kind::Context),
                    min_len: None,
                    max_len: None,
                },
            ),
            Err(err) => {
                self.value = Some(Err(err.into()));
                ControlFlow::Error
            }
        }
    }

    fn protocol(&mut self, id: crate::protocol::ProtocolId) -> Option<AnyVisit<'_, 'ctx>> {
        if id == ProtocolId::of::<reference::ReferenceMut<T>>() {
            Some(AnyVisit::new(self))
        } else {
            None
        }
    }
}

impl<'ctx, T: ?Sized + Any> Visit<'ctx, reference::ReferenceMut<T>> for MutBuilder<'ctx, T> {
    fn visit(&mut self, accessor: reference::Mut<'_, 'ctx, T>) -> ControlFlow {
        match accessor {
            reference::Mut::Walking(_) => {
                self.value = Some(Err(Error::ShortLifetime));
                ControlFlow::Continue
            }
            reference::Mut::Context(value) | reference::Mut::Static(value) => {
                self.value = Some(Ok(value));
                ControlFlow::Done
            }
        }
    }
}