1use crate::Lifetime;
9use proc_macro2::extra::DelimSpan;
10use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};
11use std::cmp::Ordering;
12use std::marker::PhantomData;
13use std::ptr;
14
15enum Entry {
18    Group(Group, usize),
21    Ident(Ident),
22    Punct(Punct),
23    Literal(Literal),
24    End(isize, isize),
27}
28
29pub struct TokenBuffer {
33    entries: Box<[Entry]>,
36}
37
38impl TokenBuffer {
39    fn recursive_new(entries: &mut Vec<Entry>, stream: TokenStream) {
40        for tt in stream {
41            match tt {
42                TokenTree::Ident(ident) => entries.push(Entry::Ident(ident)),
43                TokenTree::Punct(punct) => entries.push(Entry::Punct(punct)),
44                TokenTree::Literal(literal) => entries.push(Entry::Literal(literal)),
45                TokenTree::Group(group) => {
46                    let group_start_index = entries.len();
47                    entries.push(Entry::End(0, 0)); Self::recursive_new(entries, group.stream());
49                    let group_end_index = entries.len();
50                    let group_offset = group_end_index - group_start_index;
51                    entries.push(Entry::End(
52                        -(group_end_index as isize),
53                        -(group_offset as isize),
54                    ));
55                    entries[group_start_index] = Entry::Group(group, group_offset);
56                }
57            }
58        }
59    }
60
61    #[cfg(feature = "proc-macro")]
64    #[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]
65    pub fn new(stream: proc_macro::TokenStream) -> Self {
66        Self::new2(stream.into())
67    }
68
69    pub fn new2(stream: TokenStream) -> Self {
72        let mut entries = Vec::new();
73        Self::recursive_new(&mut entries, stream);
74        entries.push(Entry::End(-(entries.len() as isize), 0));
75        Self {
76            entries: entries.into_boxed_slice(),
77        }
78    }
79
80    pub fn begin(&self) -> Cursor {
83        let ptr = self.entries.as_ptr();
84        unsafe { Cursor::create(ptr, ptr.add(self.entries.len() - 1)) }
85    }
86}
87
88pub struct Cursor<'a> {
97    ptr: *const Entry,
99    scope: *const Entry,
102    marker: PhantomData<&'a Entry>,
105}
106
107impl<'a> Cursor<'a> {
108    pub fn empty() -> Self {
110        struct UnsafeSyncEntry(Entry);
118        unsafe impl Sync for UnsafeSyncEntry {}
119        static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0, 0));
120
121        Cursor {
122            ptr: &EMPTY_ENTRY.0,
123            scope: &EMPTY_ENTRY.0,
124            marker: PhantomData,
125        }
126    }
127
128    unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self {
132        while let Entry::End(..) = unsafe { &*ptr } {
137            if ptr::eq(ptr, scope) {
138                break;
139            }
140            ptr = unsafe { ptr.add(1) };
141        }
142
143        Cursor {
144            ptr,
145            scope,
146            marker: PhantomData,
147        }
148    }
149
150    fn entry(self) -> &'a Entry {
152        unsafe { &*self.ptr }
153    }
154
155    unsafe fn bump_ignore_group(self) -> Cursor<'a> {
162        unsafe { Cursor::create(self.ptr.offset(1), self.scope) }
163    }
164
165    fn ignore_none(&mut self) {
171        while let Entry::Group(group, _) = self.entry() {
172            if group.delimiter() == Delimiter::None {
173                unsafe { *self = self.bump_ignore_group() };
174            } else {
175                break;
176            }
177        }
178    }
179
180    pub fn eof(self) -> bool {
183        ptr::eq(self.ptr, self.scope)
185    }
186
187    pub fn ident(mut self) -> Option<(Ident, Cursor<'a>)> {
190        self.ignore_none();
191        match self.entry() {
192            Entry::Ident(ident) => Some((ident.clone(), unsafe { self.bump_ignore_group() })),
193            _ => None,
194        }
195    }
196
197    pub fn punct(mut self) -> Option<(Punct, Cursor<'a>)> {
200        self.ignore_none();
201        match self.entry() {
202            Entry::Punct(punct) if punct.as_char() != '\'' => {
203                Some((punct.clone(), unsafe { self.bump_ignore_group() }))
204            }
205            _ => None,
206        }
207    }
208
209    pub fn literal(mut self) -> Option<(Literal, Cursor<'a>)> {
212        self.ignore_none();
213        match self.entry() {
214            Entry::Literal(literal) => Some((literal.clone(), unsafe { self.bump_ignore_group() })),
215            _ => None,
216        }
217    }
218
219    pub fn lifetime(mut self) -> Option<(Lifetime, Cursor<'a>)> {
222        self.ignore_none();
223        match self.entry() {
224            Entry::Punct(punct) if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint => {
225                let next = unsafe { self.bump_ignore_group() };
226                let (ident, rest) = next.ident()?;
227                let lifetime = Lifetime {
228                    apostrophe: punct.span(),
229                    ident,
230                };
231                Some((lifetime, rest))
232            }
233            _ => None,
234        }
235    }
236
237    pub fn group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, DelimSpan, Cursor<'a>)> {
240        if delim != Delimiter::None {
244            self.ignore_none();
245        }
246
247        if let Entry::Group(group, end_offset) = self.entry() {
248            if group.delimiter() == delim {
249                let span = group.delim_span();
250                let end_of_group = unsafe { self.ptr.add(*end_offset) };
251                let inside_of_group = unsafe { Cursor::create(self.ptr.add(1), end_of_group) };
252                let after_group = unsafe { Cursor::create(end_of_group, self.scope) };
253                return Some((inside_of_group, span, after_group));
254            }
255        }
256
257        None
258    }
259
260    pub fn any_group(self) -> Option<(Cursor<'a>, Delimiter, DelimSpan, Cursor<'a>)> {
263        if let Entry::Group(group, end_offset) = self.entry() {
264            let delimiter = group.delimiter();
265            let span = group.delim_span();
266            let end_of_group = unsafe { self.ptr.add(*end_offset) };
267            let inside_of_group = unsafe { Cursor::create(self.ptr.add(1), end_of_group) };
268            let after_group = unsafe { Cursor::create(end_of_group, self.scope) };
269            return Some((inside_of_group, delimiter, span, after_group));
270        }
271
272        None
273    }
274
275    pub(crate) fn any_group_token(self) -> Option<(Group, Cursor<'a>)> {
276        if let Entry::Group(group, end_offset) = self.entry() {
277            let end_of_group = unsafe { self.ptr.add(*end_offset) };
278            let after_group = unsafe { Cursor::create(end_of_group, self.scope) };
279            return Some((group.clone(), after_group));
280        }
281
282        None
283    }
284
285    pub fn token_stream(self) -> TokenStream {
288        let mut tts = Vec::new();
289        let mut cursor = self;
290        while let Some((tt, rest)) = cursor.token_tree() {
291            tts.push(tt);
292            cursor = rest;
293        }
294        tts.into_iter().collect()
295    }
296
297    pub fn token_tree(self) -> Option<(TokenTree, Cursor<'a>)> {
305        let (tree, len) = match self.entry() {
306            Entry::Group(group, end_offset) => (group.clone().into(), *end_offset),
307            Entry::Literal(literal) => (literal.clone().into(), 1),
308            Entry::Ident(ident) => (ident.clone().into(), 1),
309            Entry::Punct(punct) => (punct.clone().into(), 1),
310            Entry::End(..) => return None,
311        };
312
313        let rest = unsafe { Cursor::create(self.ptr.add(len), self.scope) };
314        Some((tree, rest))
315    }
316
317    pub fn span(mut self) -> Span {
320        match self.entry() {
321            Entry::Group(group, _) => group.span(),
322            Entry::Literal(literal) => literal.span(),
323            Entry::Ident(ident) => ident.span(),
324            Entry::Punct(punct) => punct.span(),
325            Entry::End(_, offset) => {
326                self.ptr = unsafe { self.ptr.offset(*offset) };
327                if let Entry::Group(group, _) = self.entry() {
328                    group.span_close()
329                } else {
330                    Span::call_site()
331                }
332            }
333        }
334    }
335
336    #[cfg(any(feature = "full", feature = "derive"))]
339    pub(crate) fn prev_span(mut self) -> Span {
340        if start_of_buffer(self) < self.ptr {
341            self.ptr = unsafe { self.ptr.offset(-1) };
342        }
343        self.span()
344    }
345
346    pub(crate) fn skip(mut self) -> Option<Cursor<'a>> {
351        self.ignore_none();
352
353        let len = match self.entry() {
354            Entry::End(..) => return None,
355
356            Entry::Punct(punct) if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint => {
358                match unsafe { &*self.ptr.add(1) } {
359                    Entry::Ident(_) => 2,
360                    _ => 1,
361                }
362            }
363
364            Entry::Group(_, end_offset) => *end_offset,
365            _ => 1,
366        };
367
368        Some(unsafe { Cursor::create(self.ptr.add(len), self.scope) })
369    }
370
371    pub(crate) fn scope_delimiter(self) -> Delimiter {
372        match unsafe { &*self.scope } {
373            Entry::End(_, offset) => match unsafe { &*self.scope.offset(*offset) } {
374                Entry::Group(group, _) => group.delimiter(),
375                _ => Delimiter::None,
376            },
377            _ => unreachable!(),
378        }
379    }
380}
381
382impl<'a> Copy for Cursor<'a> {}
383
384impl<'a> Clone for Cursor<'a> {
385    fn clone(&self) -> Self {
386        *self
387    }
388}
389
390impl<'a> Eq for Cursor<'a> {}
391
392impl<'a> PartialEq for Cursor<'a> {
393    fn eq(&self, other: &Self) -> bool {
394        ptr::eq(self.ptr, other.ptr)
395    }
396}
397
398impl<'a> PartialOrd for Cursor<'a> {
399    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
400        if same_buffer(*self, *other) {
401            Some(cmp_assuming_same_buffer(*self, *other))
402        } else {
403            None
404        }
405    }
406}
407
408pub(crate) fn same_scope(a: Cursor, b: Cursor) -> bool {
409    ptr::eq(a.scope, b.scope)
410}
411
412pub(crate) fn same_buffer(a: Cursor, b: Cursor) -> bool {
413    ptr::eq(start_of_buffer(a), start_of_buffer(b))
414}
415
416fn start_of_buffer(cursor: Cursor) -> *const Entry {
417    unsafe {
418        match &*cursor.scope {
419            Entry::End(offset, _) => cursor.scope.offset(*offset),
420            _ => unreachable!(),
421        }
422    }
423}
424
425pub(crate) fn cmp_assuming_same_buffer(a: Cursor, b: Cursor) -> Ordering {
426    a.ptr.cmp(&b.ptr)
427}
428
429pub(crate) fn open_span_of_group(cursor: Cursor) -> Span {
430    match cursor.entry() {
431        Entry::Group(group, _) => group.span_open(),
432        _ => cursor.span(),
433    }
434}