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