Debian Codegraph @

third_party/rust/winnow/src/stream/token.rs

raw
1 use crate::error::Needed;
2 use crate::lib::std::iter::Enumerate;
3 use crate::lib::std::slice::Iter;
4 use crate::stream::Checkpoint;
5 use crate::stream::Compare;
6 use crate::stream::CompareResult;
7 use crate::stream::Location;
8 use crate::stream::Offset;
9 #[cfg(feature = "unstable-recover")]
10 #[cfg(feature = "std")]
11 use crate::stream::Recover;
12 use crate::stream::SliceLen;
13 use crate::stream::Stream;
14 use crate::stream::StreamIsPartial;
15 use crate::stream::UpdateSlice;
16
17 /// Specialized input for parsing lexed tokens
18 ///
19 /// Helpful impls
20 /// - Any `PartialEq` type (e.g. a `TokenKind` or `&str`) can be used with
21 /// [`literal`][crate::token::literal]
22 /// - A `PartialEq` for `&str` allows for using `&str` as a parser for tokens
23 /// - [`ContainsToken`][crate::stream::ContainsToken] for `T` to for parsing with token sets
24 /// - [`Location`] for `T` to extract spans from tokens
25 ///
26 /// See also [Lexing and Parsing][crate::_topic::lexing].
27 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
28 pub struct TokenSlice<'t, T> {
29 initial: &'t [T],
30 input: &'t [T],
31 }
32
33 impl<'t, T> TokenSlice<'t, T>
34 where
35 T: crate::lib::std::fmt::Debug + Clone,
36 {
37 /// Make a stream to parse tokens
38 #[inline]
39 pub fn new(input: &'t [T]) -> Self {
40 Self {
41 initial: input,
42 input,
43 }
44 }
45
46 /// Reset the stream to the start
47 ///
48 /// This is useful for formats that encode a graph with addresses relative to the start of the
49 /// input.
50 #[doc(alias = "fseek")]
51 #[inline]
52 pub fn reset_to_start(&mut self) {
53 let start = self.initial.checkpoint();
54 self.input.reset(&start);
55 }
56
57 /// Iterate over consumed tokens starting with the last emitted
58 ///
59 /// This is intended to help build up appropriate context when reporting errors.
60 #[inline]
61 pub fn previous_tokens(&self) -> impl Iterator<Item = &'t T> {
62 let offset = self.input.offset_from(&self.initial);
63 self.initial[0..offset].iter().rev()
64 }
65 }
66
67 /// Track locations by implementing [`Location`] on the Token.
68 impl<T> TokenSlice<'_, T>
69 where
70 T: Location,
71 {
72 #[inline(always)]
73 fn previous_token_end(&self) -> Option<usize> {
74 let index = self.input.offset_from(&self.initial);
75 index
76 .checked_sub(1)
77 .map(|i| self.initial[i].previous_token_end())
78 }
79
80 #[inline(always)]
81 fn current_token_start(&self) -> Option<usize> {
82 self.input.first().map(|t| t.current_token_start())
83 }
84 }
85
86 impl<T> Default for TokenSlice<'_, T>
87 where
88 T: crate::lib::std::fmt::Debug + Clone,
89 {
90 fn default() -> Self {
91 Self::new(&[])
92 }
93 }
94
95 impl<T> crate::lib::std::ops::Deref for TokenSlice<'_, T> {
96 type Target = [T];
97
98 fn deref(&self) -> &Self::Target {
99 self.input
100 }
101 }
102
103 impl<T> SliceLen for TokenSlice<'_, T> {
104 #[inline(always)]
105 fn slice_len(&self) -> usize {
106 self.input.slice_len()
107 }
108 }
109
110 impl<'t, T> Stream for TokenSlice<'t, T>
111 where
112 T: crate::lib::std::fmt::Debug + Clone,
113 {
114 type Token = &'t T;
115 type Slice = &'t [T];
116
117 type IterOffsets = Enumerate<Iter<'t, T>>;
118
119 type Checkpoint = Checkpoint<&'t [T], Self>;
120
121 #[inline(always)]
122 fn iter_offsets(&self) -> Self::IterOffsets {
123 self.input.iter().enumerate()
124 }
125 #[inline(always)]
126 fn eof_offset(&self) -> usize {
127 self.input.eof_offset()
128 }
129
130 #[inline(always)]
131 fn next_token(&mut self) -> Option<Self::Token> {
132 let (token, next) = self.input.split_first()?;
133 self.input = next;
134 Some(token)
135 }
136
137 #[inline(always)]
138 fn peek_token(&self) -> Option<Self::Token> {
139 self.input.first()
140 }
141
142 #[inline(always)]
143 fn offset_for<P>(&self, predicate: P) -> Option<usize>
144 where
145 P: Fn(Self::Token) -> bool,
146 {
147 self.input.iter().position(predicate)
148 }
149 #[inline(always)]
150 fn offset_at(&self, tokens: usize) -> Result<usize, Needed> {
151 self.input.offset_at(tokens)
152 }
153 #[inline(always)]
154 fn next_slice(&mut self, offset: usize) -> Self::Slice {
155 self.input.next_slice(offset)
156 }
157 #[inline(always)]
158 unsafe fn next_slice_unchecked(&mut self, offset: usize) -> Self::Slice {
159 // SAFETY: Passing up invariants
160 unsafe { self.input.next_slice_unchecked(offset) }
161 }
162 #[inline(always)]
163 fn peek_slice(&self, offset: usize) -> Self::Slice {
164 self.input.peek_slice(offset)
165 }
166 #[inline(always)]
167 unsafe fn peek_slice_unchecked(&self, offset: usize) -> Self::Slice {
168 // SAFETY: Passing up invariants
169 unsafe { self.input.peek_slice_unchecked(offset) }
170 }
171
172 #[inline(always)]
173 fn checkpoint(&self) -> Self::Checkpoint {
174 Checkpoint::<_, Self>::new(self.input)
175 }
176 #[inline(always)]
177 fn reset(&mut self, checkpoint: &Self::Checkpoint) {
178 self.input = checkpoint.inner;
179 }
180
181 #[inline(always)]
182 fn raw(&self) -> &dyn crate::lib::std::fmt::Debug {
183 &self.input
184 }
185 }
186
187 impl<T> Location for TokenSlice<'_, T>
188 where
189 T: Location,
190 {
191 #[inline(always)]
192 fn previous_token_end(&self) -> usize {
193 self.previous_token_end()
194 .or_else(|| self.current_token_start())
195 .unwrap_or(0)
196 }
197 #[inline(always)]
198 fn current_token_start(&self) -> usize {
199 self.current_token_start()
200 .or_else(|| self.previous_token_end())
201 .unwrap_or(0)
202 }
203 }
204
205 #[cfg(feature = "unstable-recover")]
206 #[cfg(feature = "std")]
207 impl<T, E> Recover<E> for TokenSlice<'_, T>
208 where
209 T: crate::lib::std::fmt::Debug + Clone,
210 {
211 #[inline(always)]
212 fn record_err(
213 &mut self,
214 _token_start: &Self::Checkpoint,
215 _err_start: &Self::Checkpoint,
216 err: E,
217 ) -> Result<(), E> {
218 Err(err)
219 }
220
221 /// Report whether the [`Stream`] can save off errors for recovery
222 #[inline(always)]
223 fn is_recovery_supported() -> bool {
224 false
225 }
226 }
227
228 impl<'t, T> StreamIsPartial for TokenSlice<'t, T>
229 where
230 T: crate::lib::std::fmt::Debug + Clone,
231 {
232 type PartialState = <&'t [T] as StreamIsPartial>::PartialState;
233
234 #[inline]
235 fn complete(&mut self) -> Self::PartialState {
236 #![allow(clippy::semicolon_if_nothing_returned)]
237 self.input.complete()
238 }
239
240 #[inline]
241 fn restore_partial(&mut self, state: Self::PartialState) {
242 self.input.restore_partial(state);
243 }
244
245 #[inline(always)]
246 fn is_partial_supported() -> bool {
247 <&[T] as StreamIsPartial>::is_partial_supported()
248 }
249
250 #[inline(always)]
251 fn is_partial(&self) -> bool {
252 self.input.is_partial()
253 }
254 }
255
256 impl<T> Offset for TokenSlice<'_, T>
257 where
258 T: crate::lib::std::fmt::Debug + Clone,
259 {
260 #[inline(always)]
261 fn offset_from(&self, other: &Self) -> usize {
262 self.offset_from(&other.checkpoint())
263 }
264 }
265
266 impl<T> Offset<<TokenSlice<'_, T> as Stream>::Checkpoint> for TokenSlice<'_, T>
267 where
268 T: crate::lib::std::fmt::Debug + Clone,
269 {
270 #[inline(always)]
271 fn offset_from(&self, other: &<TokenSlice<'_, T> as Stream>::Checkpoint) -> usize {
272 self.checkpoint().offset_from(other)
273 }
274 }
275
276 impl<T, O> Compare<O> for TokenSlice<'_, T>
277 where
278 T: PartialEq<O> + Eq,
279 {
280 #[inline]
281 fn compare(&self, t: O) -> CompareResult {
282 if let Some(token) = self.first() {
283 if *token == t {
284 CompareResult::Ok(1)
285 } else {
286 CompareResult::Error
287 }
288 } else {
289 CompareResult::Incomplete
290 }
291 }
292 }
293
294 impl<T> UpdateSlice for TokenSlice<'_, T>
295 where
296 T: crate::lib::std::fmt::Debug + Clone,
297 {
298 #[inline(always)]
299 fn update_slice(mut self, inner: Self::Slice) -> Self {
300 self.input = <&[T] as UpdateSlice>::update_slice(self.input, inner);
301 self
302 }
303 }