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 ))]
14 use crate::proc_macro as pm;
15 use crate::Lifetime;
16 use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};
17 use std::marker::PhantomData;
18 use std::ptr;
19 
20 /// Internal type which is used instead of `TokenTree` to represent a token tree
21 /// within a `TokenBuffer`.
22 enum Entry {
23     // Mimicking types from proc-macro.
24     Group(Group, TokenBuffer),
25     Ident(Ident),
26     Punct(Punct),
27     Literal(Literal),
28     // End entries contain a raw pointer to the entry from the containing
29     // token tree, or null if this is the outermost level.
30     End(*const Entry),
31 }
32 
33 /// A buffer that can be efficiently traversed multiple times, unlike
34 /// `TokenStream` which requires a deep copy in order to traverse more than
35 /// once.
36 ///
37 /// *This type is available only if Syn is built with the `"parsing"` feature.*
38 pub struct TokenBuffer {
39     // NOTE: Do not derive clone on this - there are raw pointers inside which
40     // will be messed up. Moving the `TokenBuffer` itself is safe as the actual
41     // backing slices won't be moved.
42     data: Box<[Entry]>,
43 }
44 
45 impl TokenBuffer {
46     // NOTE: DO NOT MUTATE THE `Vec` RETURNED FROM THIS FUNCTION ONCE IT
47     // RETURNS, THE ADDRESS OF ITS BACKING MEMORY MUST REMAIN STABLE.
inner_new(stream: TokenStream, up: *const Entry) -> TokenBuffer48     fn inner_new(stream: TokenStream, up: *const Entry) -> TokenBuffer {
49         // Build up the entries list, recording the locations of any Groups
50         // in the list to be processed later.
51         let mut entries = Vec::new();
52         let mut seqs = Vec::new();
53         for tt in stream {
54             match tt {
55                 TokenTree::Ident(sym) => {
56                     entries.push(Entry::Ident(sym));
57                 }
58                 TokenTree::Punct(op) => {
59                     entries.push(Entry::Punct(op));
60                 }
61                 TokenTree::Literal(l) => {
62                     entries.push(Entry::Literal(l));
63                 }
64                 TokenTree::Group(g) => {
65                     // Record the index of the interesting entry, and store an
66                     // `End(null)` there temporarially.
67                     seqs.push((entries.len(), g));
68                     entries.push(Entry::End(ptr::null()));
69                 }
70             }
71         }
72         // Add an `End` entry to the end with a reference to the enclosing token
73         // stream which was passed in.
74         entries.push(Entry::End(up));
75 
76         // NOTE: This is done to ensure that we don't accidentally modify the
77         // length of the backing buffer. The backing buffer must remain at a
78         // constant address after this point, as we are going to store a raw
79         // pointer into it.
80         let mut entries = entries.into_boxed_slice();
81         for (idx, group) in seqs {
82             // We know that this index refers to one of the temporary
83             // `End(null)` entries, and we know that the last entry is
84             // `End(up)`, so the next index is also valid.
85             let seq_up = &entries[idx + 1] as *const Entry;
86 
87             // The end entry stored at the end of this Entry::Group should
88             // point to the Entry which follows the Group in the list.
89             let inner = Self::inner_new(group.stream(), seq_up);
90             entries[idx] = Entry::Group(group, inner);
91         }
92 
93         TokenBuffer { data: entries }
94     }
95 
96     /// Creates a `TokenBuffer` containing all the tokens from the input
97     /// `TokenStream`.
98     ///
99     /// *This method is available only if Syn is built with both the `"parsing"` and
100     /// `"proc-macro"` features.*
101     #[cfg(all(
102         not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
103         feature = "proc-macro"
104     ))]
new(stream: pm::TokenStream) -> TokenBuffer105     pub fn new(stream: pm::TokenStream) -> TokenBuffer {
106         Self::new2(stream.into())
107     }
108 
109     /// Creates a `TokenBuffer` containing all the tokens from the input
110     /// `TokenStream`.
new2(stream: TokenStream) -> TokenBuffer111     pub fn new2(stream: TokenStream) -> TokenBuffer {
112         Self::inner_new(stream, ptr::null())
113     }
114 
115     /// Creates a cursor referencing the first token in the buffer and able to
116     /// traverse until the end of the buffer.
begin(&self) -> Cursor117     pub fn begin(&self) -> Cursor {
118         unsafe { Cursor::create(&self.data[0], &self.data[self.data.len() - 1]) }
119     }
120 }
121 
122 /// A cheaply copyable cursor into a `TokenBuffer`.
123 ///
124 /// This cursor holds a shared reference into the immutable data which is used
125 /// internally to represent a `TokenStream`, and can be efficiently manipulated
126 /// and copied around.
127 ///
128 /// An empty `Cursor` can be created directly, or one may create a `TokenBuffer`
129 /// object and get a cursor to its first token with `begin()`.
130 ///
131 /// Two cursors are equal if they have the same location in the same input
132 /// stream, and have the same scope.
133 ///
134 /// *This type is available only if Syn is built with the `"parsing"` feature.*
135 pub struct Cursor<'a> {
136     // The current entry which the `Cursor` is pointing at.
137     ptr: *const Entry,
138     // This is the only `Entry::End(..)` object which this cursor is allowed to
139     // point at. All other `End` objects are skipped over in `Cursor::create`.
140     scope: *const Entry,
141     // Cursor is covariant in 'a. This field ensures that our pointers are still
142     // valid.
143     marker: PhantomData<&'a Entry>,
144 }
145 
146 impl<'a> Cursor<'a> {
147     /// Creates a cursor referencing a static empty TokenStream.
empty() -> Self148     pub fn empty() -> Self {
149         // It's safe in this situation for us to put an `Entry` object in global
150         // storage, despite it not actually being safe to send across threads
151         // (`Ident` is a reference into a thread-local table). This is because
152         // this entry never includes a `Ident` object.
153         //
154         // This wrapper struct allows us to break the rules and put a `Sync`
155         // object in global storage.
156         struct UnsafeSyncEntry(Entry);
157         unsafe impl Sync for UnsafeSyncEntry {}
158         static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0 as *const Entry));
159 
160         Cursor {
161             ptr: &EMPTY_ENTRY.0,
162             scope: &EMPTY_ENTRY.0,
163             marker: PhantomData,
164         }
165     }
166 
167     /// This create method intelligently exits non-explicitly-entered
168     /// `None`-delimited scopes when the cursor reaches the end of them,
169     /// allowing for them to be treated transparently.
create(mut ptr: *const Entry, scope: *const Entry) -> Self170     unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self {
171         // NOTE: If we're looking at a `End(..)`, we want to advance the cursor
172         // past it, unless `ptr == scope`, which means that we're at the edge of
173         // our cursor's scope. We should only have `ptr != scope` at the exit
174         // from None-delimited groups entered with `ignore_none`.
175         while let Entry::End(exit) = *ptr {
176             if ptr == scope {
177                 break;
178             }
179             ptr = exit;
180         }
181 
182         Cursor {
183             ptr,
184             scope,
185             marker: PhantomData,
186         }
187     }
188 
189     /// Get the current entry.
entry(self) -> &'a Entry190     fn entry(self) -> &'a Entry {
191         unsafe { &*self.ptr }
192     }
193 
194     /// Bump the cursor to point at the next token after the current one. This
195     /// is undefined behavior if the cursor is currently looking at an
196     /// `Entry::End`.
bump(self) -> Cursor<'a>197     unsafe fn bump(self) -> Cursor<'a> {
198         Cursor::create(self.ptr.offset(1), self.scope)
199     }
200 
201     /// While the cursor is looking at a `None`-delimited group, move it to look
202     /// at the first token inside instead. If the group is empty, this will move
203     /// the cursor past the `None`-delimited group.
204     ///
205     /// WARNING: This mutates its argument.
ignore_none(&mut self)206     fn ignore_none(&mut self) {
207         while let Entry::Group(group, buf) = self.entry() {
208             if group.delimiter() == Delimiter::None {
209                 // NOTE: We call `Cursor::create` here to make sure that
210                 // situations where we should immediately exit the span after
211                 // entering it are handled correctly.
212                 unsafe {
213                     *self = Cursor::create(&buf.data[0], self.scope);
214                 }
215             } else {
216                 break;
217             }
218         }
219     }
220 
221     /// Checks whether the cursor is currently pointing at the end of its valid
222     /// scope.
eof(self) -> bool223     pub fn eof(self) -> bool {
224         // We're at eof if we're at the end of our scope.
225         self.ptr == self.scope
226     }
227 
228     /// If the cursor is pointing at a `Group` with the given delimiter, returns
229     /// a cursor into that group and one pointing to the next `TokenTree`.
group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, Span, Cursor<'a>)>230     pub fn group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, Span, Cursor<'a>)> {
231         // If we're not trying to enter a none-delimited group, we want to
232         // ignore them. We have to make sure to _not_ ignore them when we want
233         // to enter them, of course. For obvious reasons.
234         if delim != Delimiter::None {
235             self.ignore_none();
236         }
237 
238         if let Entry::Group(group, buf) = self.entry() {
239             if group.delimiter() == delim {
240                 return Some((buf.begin(), group.span(), unsafe { self.bump() }));
241             }
242         }
243 
244         None
245     }
246 
247     /// If the cursor is pointing at a `Ident`, returns it along with a cursor
248     /// pointing at the next `TokenTree`.
ident(mut self) -> Option<(Ident, Cursor<'a>)>249     pub fn ident(mut self) -> Option<(Ident, Cursor<'a>)> {
250         self.ignore_none();
251         match self.entry() {
252             Entry::Ident(ident) => Some((ident.clone(), unsafe { self.bump() })),
253             _ => None,
254         }
255     }
256 
257     /// If the cursor is pointing at an `Punct`, returns it along with a cursor
258     /// pointing at the next `TokenTree`.
punct(mut self) -> Option<(Punct, Cursor<'a>)>259     pub fn punct(mut self) -> Option<(Punct, Cursor<'a>)> {
260         self.ignore_none();
261         match self.entry() {
262             Entry::Punct(op) if op.as_char() != '\'' => Some((op.clone(), unsafe { self.bump() })),
263             _ => None,
264         }
265     }
266 
267     /// If the cursor is pointing at a `Literal`, return it along with a cursor
268     /// pointing at the next `TokenTree`.
literal(mut self) -> Option<(Literal, Cursor<'a>)>269     pub fn literal(mut self) -> Option<(Literal, Cursor<'a>)> {
270         self.ignore_none();
271         match self.entry() {
272             Entry::Literal(lit) => Some((lit.clone(), unsafe { self.bump() })),
273             _ => None,
274         }
275     }
276 
277     /// If the cursor is pointing at a `Lifetime`, returns it along with a
278     /// cursor pointing at the next `TokenTree`.
lifetime(mut self) -> Option<(Lifetime, Cursor<'a>)>279     pub fn lifetime(mut self) -> Option<(Lifetime, Cursor<'a>)> {
280         self.ignore_none();
281         match self.entry() {
282             Entry::Punct(op) if op.as_char() == '\'' && op.spacing() == Spacing::Joint => {
283                 let next = unsafe { self.bump() };
284                 match next.ident() {
285                     Some((ident, rest)) => {
286                         let lifetime = Lifetime {
287                             apostrophe: op.span(),
288                             ident,
289                         };
290                         Some((lifetime, rest))
291                     }
292                     None => None,
293                 }
294             }
295             _ => None,
296         }
297     }
298 
299     /// Copies all remaining tokens visible from this cursor into a
300     /// `TokenStream`.
token_stream(self) -> TokenStream301     pub fn token_stream(self) -> TokenStream {
302         let mut tts = Vec::new();
303         let mut cursor = self;
304         while let Some((tt, rest)) = cursor.token_tree() {
305             tts.push(tt);
306             cursor = rest;
307         }
308         tts.into_iter().collect()
309     }
310 
311     /// If the cursor is pointing at a `TokenTree`, returns it along with a
312     /// cursor pointing at the next `TokenTree`.
313     ///
314     /// Returns `None` if the cursor has reached the end of its stream.
315     ///
316     /// This method does not treat `None`-delimited groups as transparent, and
317     /// will return a `Group(None, ..)` if the cursor is looking at one.
token_tree(self) -> Option<(TokenTree, Cursor<'a>)>318     pub fn token_tree(self) -> Option<(TokenTree, Cursor<'a>)> {
319         let tree = match self.entry() {
320             Entry::Group(group, _) => group.clone().into(),
321             Entry::Literal(lit) => lit.clone().into(),
322             Entry::Ident(ident) => ident.clone().into(),
323             Entry::Punct(op) => op.clone().into(),
324             Entry::End(..) => {
325                 return None;
326             }
327         };
328 
329         Some((tree, unsafe { self.bump() }))
330     }
331 
332     /// Returns the `Span` of the current token, or `Span::call_site()` if this
333     /// cursor points to eof.
span(self) -> Span334     pub fn span(self) -> Span {
335         match self.entry() {
336             Entry::Group(group, _) => group.span(),
337             Entry::Literal(l) => l.span(),
338             Entry::Ident(t) => t.span(),
339             Entry::Punct(o) => o.span(),
340             Entry::End(..) => Span::call_site(),
341         }
342     }
343 
344     /// Skip over the next token without cloning it. Returns `None` if this
345     /// cursor points to eof.
346     ///
347     /// This method treats `'lifetimes` as a single token.
skip(self) -> Option<Cursor<'a>>348     pub(crate) fn skip(self) -> Option<Cursor<'a>> {
349         match self.entry() {
350             Entry::End(..) => None,
351 
352             // Treat lifetimes as a single tt for the purposes of 'skip'.
353             Entry::Punct(op) if op.as_char() == '\'' && op.spacing() == Spacing::Joint => {
354                 let next = unsafe { self.bump() };
355                 match next.entry() {
356                     Entry::Ident(_) => Some(unsafe { next.bump() }),
357                     _ => Some(next),
358                 }
359             }
360             _ => Some(unsafe { self.bump() }),
361         }
362     }
363 }
364 
365 impl<'a> Copy for Cursor<'a> {}
366 
367 impl<'a> Clone for Cursor<'a> {
clone(&self) -> Self368     fn clone(&self) -> Self {
369         *self
370     }
371 }
372 
373 impl<'a> Eq for Cursor<'a> {}
374 
375 impl<'a> PartialEq for Cursor<'a> {
eq(&self, other: &Self) -> bool376     fn eq(&self, other: &Self) -> bool {
377         let Cursor { ptr, scope, marker } = self;
378         let _ = marker;
379         *ptr == other.ptr && *scope == other.scope
380     }
381 }
382 
same_scope(a: Cursor, b: Cursor) -> bool383 pub(crate) fn same_scope(a: Cursor, b: Cursor) -> bool {
384     a.scope == b.scope
385 }
386 
open_span_of_group(cursor: Cursor) -> Span387 pub(crate) fn open_span_of_group(cursor: Cursor) -> Span {
388     match cursor.entry() {
389         Entry::Group(group, _) => group.span_open(),
390         _ => cursor.span(),
391     }
392 }
393 
close_span_of_group(cursor: Cursor) -> Span394 pub(crate) fn close_span_of_group(cursor: Cursor) -> Span {
395     match cursor.entry() {
396         Entry::Group(group, _) => group.span_close(),
397         _ => cursor.span(),
398     }
399 }
400