syn/
buffer.rs

1//! A stably addressed token buffer supporting efficient traversal based on a
2//! cheaply copyable cursor.
3//!
4//! *This module is available only if Syn is built with the `"parsing"` feature.*
5
6// This module is heavily commented as it contains most of the unsafe code in
7// Syn, and caution should be used when editing it. The public-facing interface
8// is 100% safe but the implementation is fragile internally.
9
10#[cfg(all(
11    not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
12    feature = "proc-macro"
13))]
14use crate::proc_macro as pm;
15use crate::Lifetime;
16use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};
17use std::hint;
18use std::marker::PhantomData;
19use std::mem;
20use std::ptr;
21use std::slice;
22
23/// Internal type which is used instead of `TokenTree` to represent a token tree
24/// within a `TokenBuffer`.
25enum Entry {
26    // Mimicking types from proc-macro.
27    Group(Group, TokenBuffer),
28    Ident(Ident),
29    Punct(Punct),
30    Literal(Literal),
31    // End entries contain a raw pointer to the entry from the containing
32    // token tree, or null if this is the outermost level.
33    End(*const Entry),
34}
35
36/// A buffer that can be efficiently traversed multiple times, unlike
37/// `TokenStream` which requires a deep copy in order to traverse more than
38/// once.
39///
40/// *This type is available only if Syn is built with the `"parsing"` feature.*
41pub struct TokenBuffer {
42    // NOTE: Do not implement clone on this - there are raw pointers inside
43    // these entries which will be messed up. Moving the `TokenBuffer` itself is
44    // safe as the data pointed to won't be moved.
45    ptr: *const Entry,
46    len: usize,
47}
48
49impl Drop for TokenBuffer {
50    fn drop(&mut self) {
51        unsafe {
52            let slice = slice::from_raw_parts_mut(self.ptr as *mut Entry, self.len);
53            let _ = Box::from_raw(slice);
54        }
55    }
56}
57
58impl TokenBuffer {
59    // NOTE: Do not mutate the Vec returned from this function once it returns;
60    // the address of its backing memory must remain stable.
61    fn inner_new(stream: TokenStream, up: *const Entry) -> TokenBuffer {
62        let iterator = stream.into_iter();
63        let mut entries = Vec::with_capacity(iterator.size_hint().0 + 1);
64        let mut next_index_after_last_group = 0;
65        for tt in iterator {
66            match tt {
67                TokenTree::Ident(ident) => {
68                    entries.push(Entry::Ident(ident));
69                }
70                TokenTree::Punct(punct) => {
71                    entries.push(Entry::Punct(punct));
72                }
73                TokenTree::Literal(literal) => {
74                    entries.push(Entry::Literal(literal));
75                }
76                TokenTree::Group(group) => {
77                    // We cannot fill in a real `End` pointer until `entries` is
78                    // finished growing and getting potentially reallocated.
79                    // Instead, we temporarily coopt the spot where the end
80                    // pointer would go, and use it to string together an
81                    // intrusive linked list of all the Entry::Group entries in
82                    // the vector. Later after `entries` is done growing, we'll
83                    // traverse the linked list and fill in all the end
84                    // pointers with a correct value.
85                    let group_up =
86                        ptr::null::<u8>().wrapping_add(next_index_after_last_group) as *const Entry;
87
88                    let inner = Self::inner_new(group.stream(), group_up);
89                    entries.push(Entry::Group(group, inner));
90                    next_index_after_last_group = entries.len();
91                }
92            }
93        }
94
95        // Add an `End` entry to the end with a reference to the enclosing token
96        // stream which was passed in.
97        entries.push(Entry::End(up));
98
99        // NOTE: This is done to ensure that we don't accidentally modify the
100        // length of the backing buffer. The backing buffer must remain at a
101        // constant address after this point, as we are going to store a raw
102        // pointer into it.
103        let entries = entries.into_boxed_slice();
104        let len = entries.len();
105
106        // Convert boxed slice into a pointer to the first element early, to
107        // avoid invalidating pointers into this slice when we move the Box.
108        // See https://github.com/rust-lang/unsafe-code-guidelines/issues/326
109        let entries = Box::into_raw(entries) as *mut Entry;
110
111        // Traverse intrusive linked list of Entry::Group entries and fill in
112        // correct End pointers.
113        while let Some(idx) = next_index_after_last_group.checked_sub(1) {
114            // We know that idx refers to one of the Entry::Group entries, and
115            // that the very last entry is an Entry::End, so the next index
116            // after any group entry is a valid index.
117            let group_up = unsafe { entries.add(next_index_after_last_group) };
118
119            // Linked list only takes us to entries which are of type Group.
120            let token_buffer = match unsafe { &*entries.add(idx) } {
121                Entry::Group(_group, token_buffer) => token_buffer,
122                _ => unsafe { hint::unreachable_unchecked() },
123            };
124
125            // Last entry in any TokenBuffer is of type End.
126            let buffer_ptr = token_buffer.ptr as *mut Entry;
127            let last_entry = unsafe { &mut *buffer_ptr.add(token_buffer.len - 1) };
128            let end_ptr_slot = match last_entry {
129                Entry::End(end_ptr_slot) => end_ptr_slot,
130                _ => unsafe { hint::unreachable_unchecked() },
131            };
132
133            // Step to next element in linked list.
134            next_index_after_last_group = mem::replace(end_ptr_slot, group_up) as usize;
135        }
136
137        TokenBuffer { ptr: entries, len }
138    }
139
140    /// Creates a `TokenBuffer` containing all the tokens from the input
141    /// `proc_macro::TokenStream`.
142    ///
143    /// *This method is available only if Syn is built with both the `"parsing"` and
144    /// `"proc-macro"` features.*
145    #[cfg(all(
146        not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
147        feature = "proc-macro"
148    ))]
149    pub fn new(stream: pm::TokenStream) -> Self {
150        Self::new2(stream.into())
151    }
152
153    /// Creates a `TokenBuffer` containing all the tokens from the input
154    /// `proc_macro2::TokenStream`.
155    pub fn new2(stream: TokenStream) -> Self {
156        Self::inner_new(stream, ptr::null())
157    }
158
159    /// Creates a cursor referencing the first token in the buffer and able to
160    /// traverse until the end of the buffer.
161    pub fn begin(&self) -> Cursor {
162        unsafe { Cursor::create(self.ptr, self.ptr.add(self.len - 1)) }
163    }
164}
165
166/// A cheaply copyable cursor into a `TokenBuffer`.
167///
168/// This cursor holds a shared reference into the immutable data which is used
169/// internally to represent a `TokenStream`, and can be efficiently manipulated
170/// and copied around.
171///
172/// An empty `Cursor` can be created directly, or one may create a `TokenBuffer`
173/// object and get a cursor to its first token with `begin()`.
174///
175/// Two cursors are equal if they have the same location in the same input
176/// stream, and have the same scope.
177///
178/// *This type is available only if Syn is built with the `"parsing"` feature.*
179pub struct Cursor<'a> {
180    // The current entry which the `Cursor` is pointing at.
181    ptr: *const Entry,
182    // This is the only `Entry::End(..)` object which this cursor is allowed to
183    // point at. All other `End` objects are skipped over in `Cursor::create`.
184    scope: *const Entry,
185    // Cursor is covariant in 'a. This field ensures that our pointers are still
186    // valid.
187    marker: PhantomData<&'a Entry>,
188}
189
190impl<'a> Cursor<'a> {
191    /// Creates a cursor referencing a static empty TokenStream.
192    pub fn empty() -> Self {
193        // It's safe in this situation for us to put an `Entry` object in global
194        // storage, despite it not actually being safe to send across threads
195        // (`Ident` is a reference into a thread-local table). This is because
196        // this entry never includes a `Ident` object.
197        //
198        // This wrapper struct allows us to break the rules and put a `Sync`
199        // object in global storage.
200        struct UnsafeSyncEntry(Entry);
201        unsafe impl Sync for UnsafeSyncEntry {}
202        static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0 as *const Entry));
203
204        Cursor {
205            ptr: &EMPTY_ENTRY.0,
206            scope: &EMPTY_ENTRY.0,
207            marker: PhantomData,
208        }
209    }
210
211    /// This create method intelligently exits non-explicitly-entered
212    /// `None`-delimited scopes when the cursor reaches the end of them,
213    /// allowing for them to be treated transparently.
214    unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self {
215        // NOTE: If we're looking at a `End(..)`, we want to advance the cursor
216        // past it, unless `ptr == scope`, which means that we're at the edge of
217        // our cursor's scope. We should only have `ptr != scope` at the exit
218        // from None-delimited groups entered with `ignore_none`.
219        while let Entry::End(exit) = *ptr {
220            if ptr == scope {
221                break;
222            }
223            ptr = exit;
224        }
225
226        Cursor {
227            ptr,
228            scope,
229            marker: PhantomData,
230        }
231    }
232
233    /// Get the current entry.
234    fn entry(self) -> &'a Entry {
235        unsafe { &*self.ptr }
236    }
237
238    /// Bump the cursor to point at the next token after the current one. This
239    /// is undefined behavior if the cursor is currently looking at an
240    /// `Entry::End`.
241    unsafe fn bump(self) -> Cursor<'a> {
242        Cursor::create(self.ptr.offset(1), self.scope)
243    }
244
245    /// While the cursor is looking at a `None`-delimited group, move it to look
246    /// at the first token inside instead. If the group is empty, this will move
247    /// the cursor past the `None`-delimited group.
248    ///
249    /// WARNING: This mutates its argument.
250    fn ignore_none(&mut self) {
251        while let Entry::Group(group, buf) = self.entry() {
252            if group.delimiter() == Delimiter::None {
253                // NOTE: We call `Cursor::create` here to make sure that
254                // situations where we should immediately exit the span after
255                // entering it are handled correctly.
256                unsafe {
257                    *self = Cursor::create(buf.ptr, self.scope);
258                }
259            } else {
260                break;
261            }
262        }
263    }
264
265    /// Checks whether the cursor is currently pointing at the end of its valid
266    /// scope.
267    pub fn eof(self) -> bool {
268        // We're at eof if we're at the end of our scope.
269        self.ptr == self.scope
270    }
271
272    /// If the cursor is pointing at a `Group` with the given delimiter, returns
273    /// a cursor into that group and one pointing to the next `TokenTree`.
274    pub fn group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, Span, Cursor<'a>)> {
275        // If we're not trying to enter a none-delimited group, we want to
276        // ignore them. We have to make sure to _not_ ignore them when we want
277        // to enter them, of course. For obvious reasons.
278        if delim != Delimiter::None {
279            self.ignore_none();
280        }
281
282        if let Entry::Group(group, buf) = self.entry() {
283            if group.delimiter() == delim {
284                return Some((buf.begin(), group.span(), unsafe { self.bump() }));
285            }
286        }
287
288        None
289    }
290
291    /// If the cursor is pointing at a `Ident`, returns it along with a cursor
292    /// pointing at the next `TokenTree`.
293    pub fn ident(mut self) -> Option<(Ident, Cursor<'a>)> {
294        self.ignore_none();
295        match self.entry() {
296            Entry::Ident(ident) => Some((ident.clone(), unsafe { self.bump() })),
297            _ => None,
298        }
299    }
300
301    /// If the cursor is pointing at a `Punct`, returns it along with a cursor
302    /// pointing at the next `TokenTree`.
303    pub fn punct(mut self) -> Option<(Punct, Cursor<'a>)> {
304        self.ignore_none();
305        match self.entry() {
306            Entry::Punct(punct) if punct.as_char() != '\'' => {
307                Some((punct.clone(), unsafe { self.bump() }))
308            }
309            _ => None,
310        }
311    }
312
313    /// If the cursor is pointing at a `Literal`, return it along with a cursor
314    /// pointing at the next `TokenTree`.
315    pub fn literal(mut self) -> Option<(Literal, Cursor<'a>)> {
316        self.ignore_none();
317        match self.entry() {
318            Entry::Literal(literal) => Some((literal.clone(), unsafe { self.bump() })),
319            _ => None,
320        }
321    }
322
323    /// If the cursor is pointing at a `Lifetime`, returns it along with a
324    /// cursor pointing at the next `TokenTree`.
325    pub fn lifetime(mut self) -> Option<(Lifetime, Cursor<'a>)> {
326        self.ignore_none();
327        match self.entry() {
328            Entry::Punct(punct) if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint => {
329                let next = unsafe { self.bump() };
330                match next.ident() {
331                    Some((ident, rest)) => {
332                        let lifetime = Lifetime {
333                            apostrophe: punct.span(),
334                            ident,
335                        };
336                        Some((lifetime, rest))
337                    }
338                    None => None,
339                }
340            }
341            _ => None,
342        }
343    }
344
345    /// Copies all remaining tokens visible from this cursor into a
346    /// `TokenStream`.
347    pub fn token_stream(self) -> TokenStream {
348        let mut tts = Vec::new();
349        let mut cursor = self;
350        while let Some((tt, rest)) = cursor.token_tree() {
351            tts.push(tt);
352            cursor = rest;
353        }
354        tts.into_iter().collect()
355    }
356
357    /// If the cursor is pointing at a `TokenTree`, returns it along with a
358    /// cursor pointing at the next `TokenTree`.
359    ///
360    /// Returns `None` if the cursor has reached the end of its stream.
361    ///
362    /// This method does not treat `None`-delimited groups as transparent, and
363    /// will return a `Group(None, ..)` if the cursor is looking at one.
364    pub fn token_tree(self) -> Option<(TokenTree, Cursor<'a>)> {
365        let tree = match self.entry() {
366            Entry::Group(group, _) => group.clone().into(),
367            Entry::Literal(literal) => literal.clone().into(),
368            Entry::Ident(ident) => ident.clone().into(),
369            Entry::Punct(punct) => punct.clone().into(),
370            Entry::End(..) => return None,
371        };
372
373        Some((tree, unsafe { self.bump() }))
374    }
375
376    /// Returns the `Span` of the current token, or `Span::call_site()` if this
377    /// cursor points to eof.
378    pub fn span(self) -> Span {
379        match self.entry() {
380            Entry::Group(group, _) => group.span(),
381            Entry::Literal(literal) => literal.span(),
382            Entry::Ident(ident) => ident.span(),
383            Entry::Punct(punct) => punct.span(),
384            Entry::End(..) => Span::call_site(),
385        }
386    }
387
388    /// Skip over the next token without cloning it. Returns `None` if this
389    /// cursor points to eof.
390    ///
391    /// This method treats `'lifetimes` as a single token.
392    pub(crate) fn skip(self) -> Option<Cursor<'a>> {
393        match self.entry() {
394            Entry::End(..) => None,
395
396            // Treat lifetimes as a single tt for the purposes of 'skip'.
397            Entry::Punct(punct) if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint => {
398                let next = unsafe { self.bump() };
399                match next.entry() {
400                    Entry::Ident(_) => Some(unsafe { next.bump() }),
401                    _ => Some(next),
402                }
403            }
404            _ => Some(unsafe { self.bump() }),
405        }
406    }
407}
408
409impl<'a> Copy for Cursor<'a> {}
410
411impl<'a> Clone for Cursor<'a> {
412    fn clone(&self) -> Self {
413        *self
414    }
415}
416
417impl<'a> Eq for Cursor<'a> {}
418
419impl<'a> PartialEq for Cursor<'a> {
420    fn eq(&self, other: &Self) -> bool {
421        let Cursor { ptr, scope, marker } = self;
422        let _ = marker;
423        *ptr == other.ptr && *scope == other.scope
424    }
425}
426
427pub(crate) fn same_scope(a: Cursor, b: Cursor) -> bool {
428    a.scope == b.scope
429}
430
431pub(crate) fn open_span_of_group(cursor: Cursor) -> Span {
432    match cursor.entry() {
433        Entry::Group(group, _) => group.span_open(),
434        _ => cursor.span(),
435    }
436}
437
438pub(crate) fn close_span_of_group(cursor: Cursor) -> Span {
439    match cursor.entry() {
440        Entry::Group(group, _) => group.span_close(),
441        _ => cursor.span(),
442    }
443}