musli_common/context/
system_context.rs

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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
use core::cell::{Cell, UnsafeCell};
use core::fmt;
use core::marker::PhantomData;
use core::ops::Range;

use alloc::string::{String, ToString};
use alloc::vec::Vec;

use musli::{Allocator, Context};

use super::access::{self, Access};
use super::rich_error::{RichError, Step};
use super::ErrorMarker;
use crate::buf::{self, BufString};

type BufTriplet<E> = (Vec<Step<String>>, Range<usize>, E);

/// A rich context dynamically allocating space using the system allocator.
pub struct SystemContext<A, M> {
    access: Access,
    mark: Cell<usize>,
    alloc: A,
    errors: UnsafeCell<Vec<BufTriplet<String>>>,
    path: UnsafeCell<Vec<Step<String>>>,
    include_type: bool,
    _marker: PhantomData<M>,
}

impl<A, M> SystemContext<A, M> {
    /// Construct a new context which uses allocations to store arbitrary
    /// amounts of diagnostics about decoding.
    ///
    /// Or at least until we run out of memory.
    pub fn new(alloc: A) -> Self {
        Self {
            access: Access::new(),
            mark: Cell::new(0),
            alloc,
            errors: UnsafeCell::new(Vec::new()),
            path: UnsafeCell::new(Vec::new()),
            include_type: false,
            _marker: PhantomData,
        }
    }

    /// Configure the context to visualize type information, and not just
    /// variant and fields.
    pub fn include_type(&mut self) -> &mut Self {
        self.include_type = true;
        self
    }

    /// Iterate over all collected errors.
    pub fn errors(&self) -> Errors<'_, String> {
        let access = self.access.shared();

        // SAFETY: We've checked above that we have shared access.
        Errors {
            errors: unsafe { &*self.errors.get() },
            index: 0,
            _access: access,
        }
    }
}

impl<A, M> SystemContext<A, M>
where
    A: Allocator,
{
    fn push_error(&self, range: Range<usize>, message: String) {
        let _access = self.access.exclusive();

        // SAFETY: We've restricted access to the context, so this is safe.
        let path = unsafe { (*self.path.get()).clone() };
        let errors = unsafe { &mut (*self.errors.get()) };

        errors.push((path, range, message));
    }

    fn push_path(&self, step: Step<String>) {
        let _access = self.access.exclusive();

        // SAFETY: We've checked that we have exclusive access just above.
        let path = unsafe { &mut (*self.path.get()) };

        path.push(step);
    }

    fn pop_path(&self) {
        let _access = self.access.exclusive();

        // SAFETY: We've checked that we have exclusive access just above.
        let path = unsafe { &mut (*self.path.get()) };

        path.pop();
    }
}

impl<A, M> Context for SystemContext<A, M>
where
    A: Allocator,
{
    type Mode = M;
    type Error = ErrorMarker;
    type Mark = usize;
    type Buf<'this> = A::Buf<'this> where Self: 'this;
    type BufString<'this> = BufString<A::Buf<'this>> where Self: 'this;

    #[inline]
    fn alloc(&self) -> Option<Self::Buf<'_>> {
        self.alloc.alloc()
    }

    #[inline]
    fn collect_string<T>(&self, value: &T) -> Result<Self::BufString<'_>, Self::Error>
    where
        T: ?Sized + fmt::Display,
    {
        buf::collect_string(self, value)
    }

    #[inline]
    fn custom<T>(&self, message: T) -> Self::Error
    where
        T: 'static + Send + Sync + fmt::Display + fmt::Debug,
    {
        self.push_error(self.mark.get()..self.mark.get(), message.to_string());
        ErrorMarker
    }

    #[inline]
    fn message<T>(&self, message: T) -> Self::Error
    where
        T: fmt::Display,
    {
        self.push_error(self.mark.get()..self.mark.get(), message.to_string());
        ErrorMarker
    }

    #[inline]
    fn marked_message<T>(&self, mark: Self::Mark, message: T) -> Self::Error
    where
        T: fmt::Display,
    {
        self.push_error(mark..self.mark.get(), message.to_string());
        ErrorMarker
    }

    #[inline]
    fn marked_custom<T>(&self, mark: Self::Mark, message: T) -> Self::Error
    where
        T: 'static + Send + Sync + fmt::Display + fmt::Debug,
    {
        self.push_error(mark..self.mark.get(), message.to_string());
        ErrorMarker
    }

    #[inline]
    fn mark(&self) -> Self::Mark {
        self.mark.get()
    }

    #[inline]
    fn advance(&self, n: usize) {
        self.mark.set(self.mark.get().wrapping_add(n));
    }

    #[inline]
    fn enter_named_field<T>(&self, name: &'static str, _: &T)
    where
        T: ?Sized + fmt::Display,
    {
        self.push_path(Step::Named(name));
    }

    #[inline]
    fn enter_unnamed_field<T>(&self, index: u32, _: &T)
    where
        T: ?Sized + fmt::Display,
    {
        self.push_path(Step::Unnamed(index));
    }

    #[inline]
    fn leave_field(&self) {
        self.pop_path();
    }

    #[inline]
    fn enter_struct(&self, name: &'static str) {
        if self.include_type {
            self.push_path(Step::Struct(name));
        }
    }

    #[inline]
    fn leave_struct(&self) {
        if self.include_type {
            self.pop_path();
        }
    }

    #[inline]
    fn enter_enum(&self, name: &'static str) {
        if self.include_type {
            self.push_path(Step::Enum(name));
        }
    }

    #[inline]
    fn leave_enum(&self) {
        if self.include_type {
            self.pop_path();
        }
    }

    #[inline]
    fn enter_variant<T>(&self, name: &'static str, _: T) {
        self.push_path(Step::Variant(name));
    }

    #[inline]
    fn leave_variant(&self) {
        self.pop_path();
    }

    #[inline]
    fn enter_sequence_index(&self, index: usize) {
        self.push_path(Step::Index(index));
    }

    #[inline]
    fn leave_sequence_index(&self) {
        self.pop_path();
    }

    #[inline]
    fn enter_map_key<T>(&self, field: T)
    where
        T: fmt::Display,
    {
        self.push_path(Step::Key(field.to_string()));
    }

    #[inline]
    fn leave_map_key(&self) {
        self.pop_path();
    }
}

/// An iterator over collected errors.
pub struct Errors<'a, E> {
    errors: &'a [BufTriplet<E>],
    index: usize,
    // NB: Drop order is significant, drop the shared access last.
    _access: access::Shared<'a>,
}

impl<'a, E> Iterator for Errors<'a, E> {
    type Item = RichError<'a, String, E>;

    fn next(&mut self) -> Option<Self::Item> {
        let (path, range, error) = self.errors.get(self.index)?;
        self.index += 1;
        Some(RichError::new(path, 0, range.clone(), error))
    }
}