blob: a13d683a75815abb3e8a2cc9aca357ba56e0ed97 [file] [log] [blame]
David Tolnay7c3e77d2018-01-06 17:42:53 -08001//! A stably addressed token buffer supporting efficient traversal based on a
2//! cheaply copyable cursor.
Michael Layzell2a60e252017-05-31 21:36:47 -04003//!
David Tolnay461d98e2018-01-07 11:07:19 -08004//! *This module is available if Syn is built with the `"parsing"` feature.*
Michael Layzell2a60e252017-05-31 21:36:47 -04005
David Tolnay57cf7522018-12-31 17:10:45 -05006// 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.
David Tolnay7c3e77d2018-01-06 17:42:53 -08009
David Tolnay278f9e32018-08-14 22:41:11 -070010#[cfg(all(
11 not(all(target_arch = "wasm32", target_os = "unknown")),
12 feature = "proc-macro"
13))]
David Tolnay7c3e77d2018-01-06 17:42:53 -080014use proc_macro as pm;
David Tolnay66cb0c42018-08-31 09:01:30 -070015use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};
Michael Layzell2a60e252017-05-31 21:36:47 -040016
Michael Layzell2a60e252017-05-31 21:36:47 -040017use std::marker::PhantomData;
David Tolnay94d2b792018-04-29 12:26:10 -070018use std::ptr;
Michael Layzell2a60e252017-05-31 21:36:47 -040019
David Tolnayfe89fcc2018-09-08 17:56:31 -070020use private;
David Tolnay66cb0c42018-08-31 09:01:30 -070021use Lifetime;
22
David Tolnay7c3e77d2018-01-06 17:42:53 -080023/// Internal type which is used instead of `TokenTree` to represent a token tree
24/// within a `TokenBuffer`.
Michael Layzell2a60e252017-05-31 21:36:47 -040025enum Entry {
David Tolnay7c3e77d2018-01-06 17:42:53 -080026 // Mimicking types from proc-macro.
David Tolnay582a45e2018-09-08 17:56:31 -070027 Group(Group, TokenBuffer),
Alex Crichtona74a1c82018-05-16 10:20:44 -070028 Ident(Ident),
29 Punct(Punct),
Alex Crichton9a4dca22018-03-28 06:32:19 -070030 Literal(Literal),
David Tolnay7c3e77d2018-01-06 17:42:53 -080031 // End entries contain a raw pointer to the entry from the containing
32 // token tree, or null if this is the outermost level.
Michael Layzell2a60e252017-05-31 21:36:47 -040033 End(*const Entry),
34}
35
David Tolnay7c3e77d2018-01-06 17:42:53 -080036/// 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///
David Tolnay461d98e2018-01-07 11:07:19 -080040/// *This type is available if Syn is built with the `"parsing"` feature.*
David Tolnaydfc886b2018-01-06 08:03:09 -080041pub struct TokenBuffer {
Michael Layzell2a60e252017-05-31 21:36:47 -040042 // NOTE: Do not derive clone on this - there are raw pointers inside which
David Tolnaydfc886b2018-01-06 08:03:09 -080043 // will be messed up. Moving the `TokenBuffer` itself is safe as the actual
Michael Layzell2a60e252017-05-31 21:36:47 -040044 // backing slices won't be moved.
45 data: Box<[Entry]>,
46}
47
David Tolnaydfc886b2018-01-06 08:03:09 -080048impl TokenBuffer {
Michael Layzell2a60e252017-05-31 21:36:47 -040049 // NOTE: DO NOT MUTATE THE `Vec` RETURNED FROM THIS FUNCTION ONCE IT
50 // RETURNS, THE ADDRESS OF ITS BACKING MEMORY MUST REMAIN STABLE.
David Tolnaydfc886b2018-01-06 08:03:09 -080051 fn inner_new(stream: TokenStream, up: *const Entry) -> TokenBuffer {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070052 // Build up the entries list, recording the locations of any Groups
Michael Layzell2a60e252017-05-31 21:36:47 -040053 // in the list to be processed later.
54 let mut entries = Vec::new();
55 let mut seqs = Vec::new();
David Tolnay50fa4682017-12-26 23:17:22 -050056 for tt in stream {
Alex Crichton9a4dca22018-03-28 06:32:19 -070057 match tt {
Alex Crichtona74a1c82018-05-16 10:20:44 -070058 TokenTree::Ident(sym) => {
59 entries.push(Entry::Ident(sym));
Michael Layzell2a60e252017-05-31 21:36:47 -040060 }
Alex Crichtona74a1c82018-05-16 10:20:44 -070061 TokenTree::Punct(op) => {
62 entries.push(Entry::Punct(op));
Michael Layzell2a60e252017-05-31 21:36:47 -040063 }
Alex Crichton9a4dca22018-03-28 06:32:19 -070064 TokenTree::Literal(l) => {
65 entries.push(Entry::Literal(l));
Michael Layzell2a60e252017-05-31 21:36:47 -040066 }
Alex Crichton9a4dca22018-03-28 06:32:19 -070067 TokenTree::Group(g) => {
Michael Layzell2a60e252017-05-31 21:36:47 -040068 // Record the index of the interesting entry, and store an
69 // `End(null)` there temporarially.
David Tolnay582a45e2018-09-08 17:56:31 -070070 seqs.push((entries.len(), g));
Michael Layzell2a60e252017-05-31 21:36:47 -040071 entries.push(Entry::End(ptr::null()));
72 }
73 }
74 }
75 // Add an `End` entry to the end with a reference to the enclosing token
76 // stream which was passed in.
77 entries.push(Entry::End(up));
78
79 // NOTE: This is done to ensure that we don't accidentally modify the
80 // length of the backing buffer. The backing buffer must remain at a
81 // constant address after this point, as we are going to store a raw
82 // pointer into it.
83 let mut entries = entries.into_boxed_slice();
David Tolnay582a45e2018-09-08 17:56:31 -070084 for (idx, group) in seqs {
Michael Layzell2a60e252017-05-31 21:36:47 -040085 // We know that this index refers to one of the temporary
86 // `End(null)` entries, and we know that the last entry is
87 // `End(up)`, so the next index is also valid.
88 let seq_up = &entries[idx + 1] as *const Entry;
89
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070090 // The end entry stored at the end of this Entry::Group should
91 // point to the Entry which follows the Group in the list.
David Tolnay582a45e2018-09-08 17:56:31 -070092 let inner = Self::inner_new(group.stream(), seq_up);
93 entries[idx] = Entry::Group(group, inner);
Michael Layzell2a60e252017-05-31 21:36:47 -040094 }
95
David Tolnaydfc886b2018-01-06 08:03:09 -080096 TokenBuffer { data: entries }
Michael Layzell2a60e252017-05-31 21:36:47 -040097 }
98
David Tolnay7c3e77d2018-01-06 17:42:53 -080099 /// Creates a `TokenBuffer` containing all the tokens from the input
100 /// `TokenStream`.
hcpl4b72a382018-04-04 14:50:24 +0300101 ///
102 /// *This method is available if Syn is built with both the `"parsing"` and
103 /// `"proc-macro"` features.*
David Tolnay278f9e32018-08-14 22:41:11 -0700104 #[cfg(all(
105 not(all(target_arch = "wasm32", target_os = "unknown")),
106 feature = "proc-macro"
107 ))]
David Tolnay7c3e77d2018-01-06 17:42:53 -0800108 pub fn new(stream: pm::TokenStream) -> TokenBuffer {
109 Self::new2(stream.into())
110 }
111
112 /// Creates a `TokenBuffer` containing all the tokens from the input
113 /// `TokenStream`.
114 pub fn new2(stream: TokenStream) -> TokenBuffer {
Michael Layzell2a60e252017-05-31 21:36:47 -0400115 Self::inner_new(stream, ptr::null())
116 }
117
David Tolnay7c3e77d2018-01-06 17:42:53 -0800118 /// Creates a cursor referencing the first token in the buffer and able to
119 /// traverse until the end of the buffer.
Michael Layzell2a60e252017-05-31 21:36:47 -0400120 pub fn begin(&self) -> Cursor {
David Tolnay51382052017-12-27 13:46:21 -0500121 unsafe { Cursor::create(&self.data[0], &self.data[self.data.len() - 1]) }
Michael Layzell2a60e252017-05-31 21:36:47 -0400122 }
123}
124
David Tolnay7c3e77d2018-01-06 17:42:53 -0800125/// A cheaply copyable cursor into a `TokenBuffer`.
126///
127/// This cursor holds a shared reference into the immutable data which is used
128/// internally to represent a `TokenStream`, and can be efficiently manipulated
129/// and copied around.
Michael Layzell2a60e252017-05-31 21:36:47 -0400130///
David Tolnaydfc886b2018-01-06 08:03:09 -0800131/// An empty `Cursor` can be created directly, or one may create a `TokenBuffer`
Michael Layzell2a60e252017-05-31 21:36:47 -0400132/// object and get a cursor to its first token with `begin()`.
133///
134/// Two cursors are equal if they have the same location in the same input
135/// stream, and have the same scope.
David Tolnay7c3e77d2018-01-06 17:42:53 -0800136///
David Tolnay461d98e2018-01-07 11:07:19 -0800137/// *This type is available if Syn is built with the `"parsing"` feature.*
Michael Layzell2a60e252017-05-31 21:36:47 -0400138#[derive(Copy, Clone, Eq, PartialEq)]
139pub struct Cursor<'a> {
David Tolnay56924f42018-09-02 08:24:58 -0700140 // The current entry which the `Cursor` is pointing at.
Michael Layzell2a60e252017-05-31 21:36:47 -0400141 ptr: *const Entry,
David Tolnay56924f42018-09-02 08:24:58 -0700142 // This is the only `Entry::End(..)` object which this cursor is allowed to
143 // point at. All other `End` objects are skipped over in `Cursor::create`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400144 scope: *const Entry,
David Tolnay56924f42018-09-02 08:24:58 -0700145 // Cursor is covariant in 'a. This field ensures that our pointers are still
146 // valid.
Michael Layzell2a60e252017-05-31 21:36:47 -0400147 marker: PhantomData<&'a Entry>,
148}
149
Michael Layzell2a60e252017-05-31 21:36:47 -0400150impl<'a> Cursor<'a> {
David Tolnay7c3e77d2018-01-06 17:42:53 -0800151 /// Creates a cursor referencing a static empty TokenStream.
Michael Layzell2a60e252017-05-31 21:36:47 -0400152 pub fn empty() -> Self {
Michael Layzell69cf9082017-06-03 12:15:58 -0400153 // It's safe in this situation for us to put an `Entry` object in global
154 // storage, despite it not actually being safe to send across threads
Alex Crichtona74a1c82018-05-16 10:20:44 -0700155 // (`Ident` is a reference into a thread-local table). This is because
156 // this entry never includes a `Ident` object.
Michael Layzell69cf9082017-06-03 12:15:58 -0400157 //
158 // This wrapper struct allows us to break the rules and put a `Sync`
159 // object in global storage.
160 struct UnsafeSyncEntry(Entry);
161 unsafe impl Sync for UnsafeSyncEntry {}
David Tolnay51382052017-12-27 13:46:21 -0500162 static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0 as *const Entry));
Michael Layzell69cf9082017-06-03 12:15:58 -0400163
Michael Layzell2a60e252017-05-31 21:36:47 -0400164 Cursor {
Michael Layzell69cf9082017-06-03 12:15:58 -0400165 ptr: &EMPTY_ENTRY.0,
166 scope: &EMPTY_ENTRY.0,
Michael Layzell2a60e252017-05-31 21:36:47 -0400167 marker: PhantomData,
168 }
169 }
170
171 /// This create method intelligently exits non-explicitly-entered
172 /// `None`-delimited scopes when the cursor reaches the end of them,
173 /// allowing for them to be treated transparently.
174 unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self {
175 // NOTE: If we're looking at a `End(..)`, we want to advance the cursor
176 // past it, unless `ptr == scope`, which means that we're at the edge of
177 // our cursor's scope. We should only have `ptr != scope` at the exit
David Tolnayc10676a2017-12-27 23:42:36 -0500178 // from None-delimited groups entered with `ignore_none`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400179 while let Entry::End(exit) = *ptr {
180 if ptr == scope {
181 break;
182 }
183 ptr = exit;
184 }
185
186 Cursor {
187 ptr: ptr,
188 scope: scope,
189 marker: PhantomData,
190 }
191 }
192
193 /// Get the current entry.
194 fn entry(self) -> &'a Entry {
195 unsafe { &*self.ptr }
196 }
197
198 /// Bump the cursor to point at the next token after the current one. This
199 /// is undefined behavior if the cursor is currently looking at an
200 /// `Entry::End`.
201 unsafe fn bump(self) -> Cursor<'a> {
202 Cursor::create(self.ptr.offset(1), self.scope)
203 }
204
David Tolnayc10676a2017-12-27 23:42:36 -0500205 /// If the cursor is looking at a `None`-delimited group, move it to look at
206 /// the first token inside instead. If the group is empty, this will move
207 /// the cursor past the `None`-delimited group.
Michael Layzell2a60e252017-05-31 21:36:47 -0400208 ///
209 /// WARNING: This mutates its argument.
210 fn ignore_none(&mut self) {
David Tolnay582a45e2018-09-08 17:56:31 -0700211 if let Entry::Group(ref group, ref buf) = *self.entry() {
212 if group.delimiter() == Delimiter::None {
213 // NOTE: We call `Cursor::create` here to make sure that
214 // situations where we should immediately exit the span after
215 // entering it are handled correctly.
216 unsafe {
217 *self = Cursor::create(&buf.data[0], self.scope);
218 }
Michael Layzell2a60e252017-05-31 21:36:47 -0400219 }
220 }
221 }
222
David Tolnay7c3e77d2018-01-06 17:42:53 -0800223 /// Checks whether the cursor is currently pointing at the end of its valid
224 /// scope.
Michael Layzell2a60e252017-05-31 21:36:47 -0400225 #[inline]
226 pub fn eof(self) -> bool {
227 // We're at eof if we're at the end of our scope.
228 self.ptr == self.scope
229 }
230
David Tolnay7c3e77d2018-01-06 17:42:53 -0800231 /// If the cursor is pointing at a `Group` with the given delimiter, returns
232 /// a cursor into that group and one pointing to the next `TokenTree`.
David Tolnay65729482017-12-31 16:14:50 -0500233 pub fn group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, Span, Cursor<'a>)> {
David Tolnayc10676a2017-12-27 23:42:36 -0500234 // If we're not trying to enter a none-delimited group, we want to
Michael Layzell2a60e252017-05-31 21:36:47 -0400235 // ignore them. We have to make sure to _not_ ignore them when we want
236 // to enter them, of course. For obvious reasons.
David Tolnayc10676a2017-12-27 23:42:36 -0500237 if delim != Delimiter::None {
Michael Layzell2a60e252017-05-31 21:36:47 -0400238 self.ignore_none();
239 }
240
David Tolnay582a45e2018-09-08 17:56:31 -0700241 if let Entry::Group(ref group, ref buf) = *self.entry() {
242 if group.delimiter() == delim {
243 return Some((buf.begin(), group.span(), unsafe { self.bump() }));
Michael Layzell2a60e252017-05-31 21:36:47 -0400244 }
Michael Layzell2a60e252017-05-31 21:36:47 -0400245 }
David Tolnayc10676a2017-12-27 23:42:36 -0500246
247 None
Michael Layzell2a60e252017-05-31 21:36:47 -0400248 }
249
Alex Crichtona74a1c82018-05-16 10:20:44 -0700250 /// If the cursor is pointing at a `Ident`, returns it along with a cursor
David Tolnay7c3e77d2018-01-06 17:42:53 -0800251 /// pointing at the next `TokenTree`.
David Tolnay55a5f3a2018-05-20 18:00:51 -0700252 pub fn ident(mut self) -> Option<(Ident, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400253 self.ignore_none();
254 match *self.entry() {
David Tolnaya4319b72018-06-02 00:49:15 -0700255 Entry::Ident(ref ident) => Some((ident.clone(), unsafe { self.bump() })),
David Tolnay51382052017-12-27 13:46:21 -0500256 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400257 }
258 }
259
Alex Crichtona74a1c82018-05-16 10:20:44 -0700260 /// If the cursor is pointing at an `Punct`, returns it along with a cursor
David Tolnay7c3e77d2018-01-06 17:42:53 -0800261 /// pointing at the next `TokenTree`.
David Tolnay55a5f3a2018-05-20 18:00:51 -0700262 pub fn punct(mut self) -> Option<(Punct, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400263 self.ignore_none();
264 match *self.entry() {
David Tolnay66cb0c42018-08-31 09:01:30 -0700265 Entry::Punct(ref op) if op.as_char() != '\'' => {
266 Some((op.clone(), unsafe { self.bump() }))
267 }
David Tolnay51382052017-12-27 13:46:21 -0500268 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400269 }
270 }
271
David Tolnay7c3e77d2018-01-06 17:42:53 -0800272 /// If the cursor is pointing at a `Literal`, return it along with a cursor
273 /// pointing at the next `TokenTree`.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700274 pub fn literal(mut self) -> Option<(Literal, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400275 self.ignore_none();
276 match *self.entry() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700277 Entry::Literal(ref lit) => Some((lit.clone(), unsafe { self.bump() })),
David Tolnay51382052017-12-27 13:46:21 -0500278 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400279 }
280 }
281
David Tolnay66cb0c42018-08-31 09:01:30 -0700282 /// If the cursor is pointing at a `Lifetime`, returns it along with a
283 /// cursor pointing at the next `TokenTree`.
284 pub fn lifetime(mut self) -> Option<(Lifetime, Cursor<'a>)> {
285 self.ignore_none();
286 match *self.entry() {
287 Entry::Punct(ref op) if op.as_char() == '\'' && op.spacing() == Spacing::Joint => {
288 let next = unsafe { self.bump() };
289 match next.ident() {
290 Some((ident, rest)) => {
291 let lifetime = Lifetime {
292 apostrophe: op.span(),
293 ident: ident,
294 };
295 Some((lifetime, rest))
296 }
297 None => None,
298 }
299 }
300 _ => None,
301 }
302 }
303
David Tolnay7c3e77d2018-01-06 17:42:53 -0800304 /// Copies all remaining tokens visible from this cursor into a
305 /// `TokenStream`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400306 pub fn token_stream(self) -> TokenStream {
307 let mut tts = Vec::new();
308 let mut cursor = self;
David Tolnay65729482017-12-31 16:14:50 -0500309 while let Some((tt, rest)) = cursor.token_tree() {
Michael Layzell2a60e252017-05-31 21:36:47 -0400310 tts.push(tt);
David Tolnay65729482017-12-31 16:14:50 -0500311 cursor = rest;
Michael Layzell2a60e252017-05-31 21:36:47 -0400312 }
313 tts.into_iter().collect()
314 }
315
David Tolnay7c3e77d2018-01-06 17:42:53 -0800316 /// If the cursor is pointing at a `TokenTree`, returns it along with a
317 /// cursor pointing at the next `TokenTree`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400318 ///
David Tolnay7c3e77d2018-01-06 17:42:53 -0800319 /// Returns `None` if the cursor has reached the end of its stream.
320 ///
321 /// This method does not treat `None`-delimited groups as transparent, and
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700322 /// will return a `Group(None, ..)` if the cursor is looking at one.
David Tolnay65729482017-12-31 16:14:50 -0500323 pub fn token_tree(self) -> Option<(TokenTree, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400324 let tree = match *self.entry() {
David Tolnay582a45e2018-09-08 17:56:31 -0700325 Entry::Group(ref group, _) => group.clone().into(),
Alex Crichton9a4dca22018-03-28 06:32:19 -0700326 Entry::Literal(ref lit) => lit.clone().into(),
David Tolnaya4319b72018-06-02 00:49:15 -0700327 Entry::Ident(ref ident) => ident.clone().into(),
Alex Crichtona74a1c82018-05-16 10:20:44 -0700328 Entry::Punct(ref op) => op.clone().into(),
Michael Layzell2a60e252017-05-31 21:36:47 -0400329 Entry::End(..) => {
330 return None;
331 }
332 };
333
David Tolnay65729482017-12-31 16:14:50 -0500334 Some((tree, unsafe { self.bump() }))
Michael Layzell2a60e252017-05-31 21:36:47 -0400335 }
David Tolnay225efa22017-12-31 16:51:29 -0500336
337 /// Returns the `Span` of the current token, or `Span::call_site()` if this
338 /// cursor points to eof.
339 pub fn span(self) -> Span {
340 match *self.entry() {
David Tolnay582a45e2018-09-08 17:56:31 -0700341 Entry::Group(ref group, _) => group.span(),
Alex Crichton9a4dca22018-03-28 06:32:19 -0700342 Entry::Literal(ref l) => l.span(),
Alex Crichtona74a1c82018-05-16 10:20:44 -0700343 Entry::Ident(ref t) => t.span(),
344 Entry::Punct(ref o) => o.span(),
David Tolnay225efa22017-12-31 16:51:29 -0500345 Entry::End(..) => Span::call_site(),
346 }
347 }
Michael Layzell2a60e252017-05-31 21:36:47 -0400348}
David Tolnayfe89fcc2018-09-08 17:56:31 -0700349
350impl private {
David Tolnay6db0f2a2019-06-23 13:37:39 -0700351 pub fn same_scope(a: Cursor, b: Cursor) -> bool {
352 a.scope == b.scope
353 }
354
David Tolnayfe89fcc2018-09-08 17:56:31 -0700355 #[cfg(procmacro2_semver_exempt)]
356 pub fn open_span_of_group(cursor: Cursor) -> Span {
357 match *cursor.entry() {
358 Entry::Group(ref group, _) => group.span_open(),
359 _ => cursor.span(),
360 }
361 }
362
363 #[cfg(procmacro2_semver_exempt)]
364 pub fn close_span_of_group(cursor: Cursor) -> Span {
365 match *cursor.entry() {
366 Entry::Group(ref group, _) => group.span_close(),
367 _ => cursor.span(),
368 }
369 }
370}