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