blob: 9c5738fc588985d5c2a6c739aaa63dff7b6dbbf7 [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
David Tolnay7c3e77d2018-01-06 17:42:53 -08009//! A stably addressed token buffer supporting efficient traversal based on a
10//! cheaply copyable cursor.
Michael Layzell2a60e252017-05-31 21:36:47 -040011//!
David Tolnay461d98e2018-01-07 11:07:19 -080012//! *This module is available if Syn is built with the `"parsing"` feature.*
Michael Layzell2a60e252017-05-31 21:36:47 -040013
David Tolnay7c3e77d2018-01-06 17:42:53 -080014// This module is heavily commented as it contains the only unsafe code in Syn,
15// and caution should be used when editing it. The public-facing interface is
16// 100% safe but the implementation is fragile internally.
17
David Tolnay278f9e32018-08-14 22:41:11 -070018#[cfg(all(
19 not(all(target_arch = "wasm32", target_os = "unknown")),
20 feature = "proc-macro"
21))]
David Tolnay7c3e77d2018-01-06 17:42:53 -080022use proc_macro as pm;
David Tolnay65fb5662018-05-20 20:02:28 -070023use proc_macro2::{Delimiter, Ident, Literal, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -070024use proc_macro2::{Group, Punct, TokenTree};
Michael Layzell2a60e252017-05-31 21:36:47 -040025
Michael Layzell2a60e252017-05-31 21:36:47 -040026use std::marker::PhantomData;
David Tolnay94d2b792018-04-29 12:26:10 -070027use std::ptr;
Michael Layzell2a60e252017-05-31 21:36:47 -040028
David Tolnay7c3e77d2018-01-06 17:42:53 -080029/// Internal type which is used instead of `TokenTree` to represent a token tree
30/// within a `TokenBuffer`.
Michael Layzell2a60e252017-05-31 21:36:47 -040031enum Entry {
David Tolnay7c3e77d2018-01-06 17:42:53 -080032 // Mimicking types from proc-macro.
David Tolnaydfc886b2018-01-06 08:03:09 -080033 Group(Span, Delimiter, TokenBuffer),
Alex Crichtona74a1c82018-05-16 10:20:44 -070034 Ident(Ident),
35 Punct(Punct),
Alex Crichton9a4dca22018-03-28 06:32:19 -070036 Literal(Literal),
David Tolnay7c3e77d2018-01-06 17:42:53 -080037 // End entries contain a raw pointer to the entry from the containing
38 // token tree, or null if this is the outermost level.
Michael Layzell2a60e252017-05-31 21:36:47 -040039 End(*const Entry),
40}
41
David Tolnay7c3e77d2018-01-06 17:42:53 -080042/// A buffer that can be efficiently traversed multiple times, unlike
43/// `TokenStream` which requires a deep copy in order to traverse more than
44/// once.
45///
David Tolnay461d98e2018-01-07 11:07:19 -080046/// *This type is available if Syn is built with the `"parsing"` feature.*
David Tolnaydfc886b2018-01-06 08:03:09 -080047pub struct TokenBuffer {
Michael Layzell2a60e252017-05-31 21:36:47 -040048 // NOTE: Do not derive clone on this - there are raw pointers inside which
David Tolnaydfc886b2018-01-06 08:03:09 -080049 // will be messed up. Moving the `TokenBuffer` itself is safe as the actual
Michael Layzell2a60e252017-05-31 21:36:47 -040050 // backing slices won't be moved.
51 data: Box<[Entry]>,
52}
53
David Tolnaydfc886b2018-01-06 08:03:09 -080054impl TokenBuffer {
Michael Layzell2a60e252017-05-31 21:36:47 -040055 // NOTE: DO NOT MUTATE THE `Vec` RETURNED FROM THIS FUNCTION ONCE IT
56 // RETURNS, THE ADDRESS OF ITS BACKING MEMORY MUST REMAIN STABLE.
David Tolnaydfc886b2018-01-06 08:03:09 -080057 fn inner_new(stream: TokenStream, up: *const Entry) -> TokenBuffer {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070058 // Build up the entries list, recording the locations of any Groups
Michael Layzell2a60e252017-05-31 21:36:47 -040059 // in the list to be processed later.
60 let mut entries = Vec::new();
61 let mut seqs = Vec::new();
David Tolnay50fa4682017-12-26 23:17:22 -050062 for tt in stream {
Alex Crichton9a4dca22018-03-28 06:32:19 -070063 match tt {
Alex Crichtona74a1c82018-05-16 10:20:44 -070064 TokenTree::Ident(sym) => {
65 entries.push(Entry::Ident(sym));
Michael Layzell2a60e252017-05-31 21:36:47 -040066 }
Alex Crichtona74a1c82018-05-16 10:20:44 -070067 TokenTree::Punct(op) => {
68 entries.push(Entry::Punct(op));
Michael Layzell2a60e252017-05-31 21:36:47 -040069 }
Alex Crichton9a4dca22018-03-28 06:32:19 -070070 TokenTree::Literal(l) => {
71 entries.push(Entry::Literal(l));
Michael Layzell2a60e252017-05-31 21:36:47 -040072 }
Alex Crichton9a4dca22018-03-28 06:32:19 -070073 TokenTree::Group(g) => {
Michael Layzell2a60e252017-05-31 21:36:47 -040074 // Record the index of the interesting entry, and store an
75 // `End(null)` there temporarially.
Alex Crichton9a4dca22018-03-28 06:32:19 -070076 seqs.push((entries.len(), g.span(), g.delimiter(), g.stream().clone()));
Michael Layzell2a60e252017-05-31 21:36:47 -040077 entries.push(Entry::End(ptr::null()));
78 }
79 }
80 }
81 // Add an `End` entry to the end with a reference to the enclosing token
82 // stream which was passed in.
83 entries.push(Entry::End(up));
84
85 // NOTE: This is done to ensure that we don't accidentally modify the
86 // length of the backing buffer. The backing buffer must remain at a
87 // constant address after this point, as we are going to store a raw
88 // pointer into it.
89 let mut entries = entries.into_boxed_slice();
90 for (idx, span, delim, seq_stream) in seqs {
91 // We know that this index refers to one of the temporary
92 // `End(null)` entries, and we know that the last entry is
93 // `End(up)`, so the next index is also valid.
94 let seq_up = &entries[idx + 1] as *const Entry;
95
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070096 // The end entry stored at the end of this Entry::Group should
97 // point to the Entry which follows the Group in the list.
Michael Layzell2a60e252017-05-31 21:36:47 -040098 let inner = Self::inner_new(seq_stream, seq_up);
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070099 entries[idx] = Entry::Group(span, delim, inner);
Michael Layzell2a60e252017-05-31 21:36:47 -0400100 }
101
David Tolnaydfc886b2018-01-06 08:03:09 -0800102 TokenBuffer { data: entries }
Michael Layzell2a60e252017-05-31 21:36:47 -0400103 }
104
David Tolnay7c3e77d2018-01-06 17:42:53 -0800105 /// Creates a `TokenBuffer` containing all the tokens from the input
106 /// `TokenStream`.
hcpl4b72a382018-04-04 14:50:24 +0300107 ///
108 /// *This method is available if Syn is built with both the `"parsing"` and
109 /// `"proc-macro"` features.*
David Tolnay278f9e32018-08-14 22:41:11 -0700110 #[cfg(all(
111 not(all(target_arch = "wasm32", target_os = "unknown")),
112 feature = "proc-macro"
113 ))]
David Tolnay7c3e77d2018-01-06 17:42:53 -0800114 pub fn new(stream: pm::TokenStream) -> TokenBuffer {
115 Self::new2(stream.into())
116 }
117
118 /// Creates a `TokenBuffer` containing all the tokens from the input
119 /// `TokenStream`.
120 pub fn new2(stream: TokenStream) -> TokenBuffer {
Michael Layzell2a60e252017-05-31 21:36:47 -0400121 Self::inner_new(stream, ptr::null())
122 }
123
David Tolnay7c3e77d2018-01-06 17:42:53 -0800124 /// Creates a cursor referencing the first token in the buffer and able to
125 /// traverse until the end of the buffer.
Michael Layzell2a60e252017-05-31 21:36:47 -0400126 pub fn begin(&self) -> Cursor {
David Tolnay51382052017-12-27 13:46:21 -0500127 unsafe { Cursor::create(&self.data[0], &self.data[self.data.len() - 1]) }
Michael Layzell2a60e252017-05-31 21:36:47 -0400128 }
129}
130
David Tolnay7c3e77d2018-01-06 17:42:53 -0800131/// A cheaply copyable cursor into a `TokenBuffer`.
132///
133/// This cursor holds a shared reference into the immutable data which is used
134/// internally to represent a `TokenStream`, and can be efficiently manipulated
135/// and copied around.
Michael Layzell2a60e252017-05-31 21:36:47 -0400136///
David Tolnaydfc886b2018-01-06 08:03:09 -0800137/// An empty `Cursor` can be created directly, or one may create a `TokenBuffer`
Michael Layzell2a60e252017-05-31 21:36:47 -0400138/// object and get a cursor to its first token with `begin()`.
139///
140/// Two cursors are equal if they have the same location in the same input
141/// stream, and have the same scope.
David Tolnay7c3e77d2018-01-06 17:42:53 -0800142///
David Tolnay461d98e2018-01-07 11:07:19 -0800143/// *This type is available if Syn is built with the `"parsing"` feature.*
Michael Layzell2a60e252017-05-31 21:36:47 -0400144#[derive(Copy, Clone, Eq, PartialEq)]
145pub struct Cursor<'a> {
146 /// The current entry which the `Cursor` is pointing at.
147 ptr: *const Entry,
148 /// This is the only `Entry::End(..)` object which this cursor is allowed to
149 /// point at. All other `End` objects are skipped over in `Cursor::create`.
150 scope: *const Entry,
151 /// This uses the &'a reference which guarantees that these pointers are
152 /// still valid.
153 marker: PhantomData<&'a Entry>,
154}
155
Michael Layzell2a60e252017-05-31 21:36:47 -0400156impl<'a> Cursor<'a> {
David Tolnay7c3e77d2018-01-06 17:42:53 -0800157 /// Creates a cursor referencing a static empty TokenStream.
Michael Layzell2a60e252017-05-31 21:36:47 -0400158 pub fn empty() -> Self {
Michael Layzell69cf9082017-06-03 12:15:58 -0400159 // It's safe in this situation for us to put an `Entry` object in global
160 // storage, despite it not actually being safe to send across threads
Alex Crichtona74a1c82018-05-16 10:20:44 -0700161 // (`Ident` is a reference into a thread-local table). This is because
162 // this entry never includes a `Ident` object.
Michael Layzell69cf9082017-06-03 12:15:58 -0400163 //
164 // This wrapper struct allows us to break the rules and put a `Sync`
165 // object in global storage.
166 struct UnsafeSyncEntry(Entry);
167 unsafe impl Sync for UnsafeSyncEntry {}
David Tolnay51382052017-12-27 13:46:21 -0500168 static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0 as *const Entry));
Michael Layzell69cf9082017-06-03 12:15:58 -0400169
Michael Layzell2a60e252017-05-31 21:36:47 -0400170 Cursor {
Michael Layzell69cf9082017-06-03 12:15:58 -0400171 ptr: &EMPTY_ENTRY.0,
172 scope: &EMPTY_ENTRY.0,
Michael Layzell2a60e252017-05-31 21:36:47 -0400173 marker: PhantomData,
174 }
175 }
176
177 /// This create method intelligently exits non-explicitly-entered
178 /// `None`-delimited scopes when the cursor reaches the end of them,
179 /// allowing for them to be treated transparently.
180 unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self {
181 // NOTE: If we're looking at a `End(..)`, we want to advance the cursor
182 // past it, unless `ptr == scope`, which means that we're at the edge of
183 // our cursor's scope. We should only have `ptr != scope` at the exit
David Tolnayc10676a2017-12-27 23:42:36 -0500184 // from None-delimited groups entered with `ignore_none`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400185 while let Entry::End(exit) = *ptr {
186 if ptr == scope {
187 break;
188 }
189 ptr = exit;
190 }
191
192 Cursor {
193 ptr: ptr,
194 scope: scope,
195 marker: PhantomData,
196 }
197 }
198
199 /// Get the current entry.
200 fn entry(self) -> &'a Entry {
201 unsafe { &*self.ptr }
202 }
203
204 /// Bump the cursor to point at the next token after the current one. This
205 /// is undefined behavior if the cursor is currently looking at an
206 /// `Entry::End`.
207 unsafe fn bump(self) -> Cursor<'a> {
208 Cursor::create(self.ptr.offset(1), self.scope)
209 }
210
David Tolnayc10676a2017-12-27 23:42:36 -0500211 /// If the cursor is looking at a `None`-delimited group, move it to look at
212 /// the first token inside instead. If the group is empty, this will move
213 /// the cursor past the `None`-delimited group.
Michael Layzell2a60e252017-05-31 21:36:47 -0400214 ///
215 /// WARNING: This mutates its argument.
216 fn ignore_none(&mut self) {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700217 if let Entry::Group(_, Delimiter::None, ref buf) = *self.entry() {
Michael Layzell2a60e252017-05-31 21:36:47 -0400218 // NOTE: We call `Cursor::create` here to make sure that situations
219 // where we should immediately exit the span after entering it are
220 // handled correctly.
221 unsafe {
222 *self = Cursor::create(&buf.data[0], self.scope);
223 }
224 }
225 }
226
David Tolnay7c3e77d2018-01-06 17:42:53 -0800227 /// Checks whether the cursor is currently pointing at the end of its valid
228 /// scope.
Michael Layzell2a60e252017-05-31 21:36:47 -0400229 #[inline]
230 pub fn eof(self) -> bool {
231 // We're at eof if we're at the end of our scope.
232 self.ptr == self.scope
233 }
234
David Tolnay7c3e77d2018-01-06 17:42:53 -0800235 /// If the cursor is pointing at a `Group` with the given delimiter, returns
236 /// a cursor into that group and one pointing to the next `TokenTree`.
David Tolnay65729482017-12-31 16:14:50 -0500237 pub fn group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, Span, Cursor<'a>)> {
David Tolnayc10676a2017-12-27 23:42:36 -0500238 // If we're not trying to enter a none-delimited group, we want to
Michael Layzell2a60e252017-05-31 21:36:47 -0400239 // ignore them. We have to make sure to _not_ ignore them when we want
240 // to enter them, of course. For obvious reasons.
David Tolnayc10676a2017-12-27 23:42:36 -0500241 if delim != Delimiter::None {
Michael Layzell2a60e252017-05-31 21:36:47 -0400242 self.ignore_none();
243 }
244
David Tolnayc10676a2017-12-27 23:42:36 -0500245 if let Entry::Group(span, group_delim, ref buf) = *self.entry() {
246 if group_delim == delim {
David Tolnay65729482017-12-31 16:14:50 -0500247 return Some((buf.begin(), span, unsafe { self.bump() }));
Michael Layzell2a60e252017-05-31 21:36:47 -0400248 }
Michael Layzell2a60e252017-05-31 21:36:47 -0400249 }
David Tolnayc10676a2017-12-27 23:42:36 -0500250
251 None
Michael Layzell2a60e252017-05-31 21:36:47 -0400252 }
253
Alex Crichtona74a1c82018-05-16 10:20:44 -0700254 /// If the cursor is pointing at a `Ident`, returns it along with a cursor
David Tolnay7c3e77d2018-01-06 17:42:53 -0800255 /// pointing at the next `TokenTree`.
David Tolnay55a5f3a2018-05-20 18:00:51 -0700256 pub fn ident(mut self) -> Option<(Ident, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400257 self.ignore_none();
258 match *self.entry() {
David Tolnaya4319b72018-06-02 00:49:15 -0700259 Entry::Ident(ref ident) => Some((ident.clone(), unsafe { self.bump() })),
David Tolnay51382052017-12-27 13:46:21 -0500260 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400261 }
262 }
263
Alex Crichtona74a1c82018-05-16 10:20:44 -0700264 /// If the cursor is pointing at an `Punct`, returns it along with a cursor
David Tolnay7c3e77d2018-01-06 17:42:53 -0800265 /// pointing at the next `TokenTree`.
David Tolnay55a5f3a2018-05-20 18:00:51 -0700266 pub fn punct(mut self) -> Option<(Punct, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400267 self.ignore_none();
268 match *self.entry() {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700269 Entry::Punct(ref op) => Some((op.clone(), unsafe { self.bump() })),
David Tolnay51382052017-12-27 13:46:21 -0500270 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400271 }
272 }
273
David Tolnay7c3e77d2018-01-06 17:42:53 -0800274 /// If the cursor is pointing at a `Literal`, return it along with a cursor
275 /// pointing at the next `TokenTree`.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700276 pub fn literal(mut self) -> Option<(Literal, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400277 self.ignore_none();
278 match *self.entry() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700279 Entry::Literal(ref lit) => Some((lit.clone(), unsafe { self.bump() })),
David Tolnay51382052017-12-27 13:46:21 -0500280 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400281 }
282 }
283
David Tolnay7c3e77d2018-01-06 17:42:53 -0800284 /// Copies all remaining tokens visible from this cursor into a
285 /// `TokenStream`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400286 pub fn token_stream(self) -> TokenStream {
287 let mut tts = Vec::new();
288 let mut cursor = self;
David Tolnay65729482017-12-31 16:14:50 -0500289 while let Some((tt, rest)) = cursor.token_tree() {
Michael Layzell2a60e252017-05-31 21:36:47 -0400290 tts.push(tt);
David Tolnay65729482017-12-31 16:14:50 -0500291 cursor = rest;
Michael Layzell2a60e252017-05-31 21:36:47 -0400292 }
293 tts.into_iter().collect()
294 }
295
David Tolnay7c3e77d2018-01-06 17:42:53 -0800296 /// If the cursor is pointing at a `TokenTree`, returns it along with a
297 /// cursor pointing at the next `TokenTree`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400298 ///
David Tolnay7c3e77d2018-01-06 17:42:53 -0800299 /// Returns `None` if the cursor has reached the end of its stream.
300 ///
301 /// This method does not treat `None`-delimited groups as transparent, and
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700302 /// will return a `Group(None, ..)` if the cursor is looking at one.
David Tolnay65729482017-12-31 16:14:50 -0500303 pub fn token_tree(self) -> Option<(TokenTree, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400304 let tree = match *self.entry() {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700305 Entry::Group(span, delim, ref buf) => {
Michael Layzell2a60e252017-05-31 21:36:47 -0400306 let stream = buf.begin().token_stream();
Alex Crichton9a4dca22018-03-28 06:32:19 -0700307 let mut g = Group::new(delim, stream);
308 g.set_span(span);
309 TokenTree::from(g)
Michael Layzell2a60e252017-05-31 21:36:47 -0400310 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700311 Entry::Literal(ref lit) => lit.clone().into(),
David Tolnaya4319b72018-06-02 00:49:15 -0700312 Entry::Ident(ref ident) => ident.clone().into(),
Alex Crichtona74a1c82018-05-16 10:20:44 -0700313 Entry::Punct(ref op) => op.clone().into(),
Michael Layzell2a60e252017-05-31 21:36:47 -0400314 Entry::End(..) => {
315 return None;
316 }
317 };
318
David Tolnay65729482017-12-31 16:14:50 -0500319 Some((tree, unsafe { self.bump() }))
Michael Layzell2a60e252017-05-31 21:36:47 -0400320 }
David Tolnay225efa22017-12-31 16:51:29 -0500321
322 /// Returns the `Span` of the current token, or `Span::call_site()` if this
323 /// cursor points to eof.
324 pub fn span(self) -> Span {
325 match *self.entry() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700326 Entry::Group(span, ..) => span,
327 Entry::Literal(ref l) => l.span(),
Alex Crichtona74a1c82018-05-16 10:20:44 -0700328 Entry::Ident(ref t) => t.span(),
329 Entry::Punct(ref o) => o.span(),
David Tolnay225efa22017-12-31 16:51:29 -0500330 Entry::End(..) => Span::call_site(),
331 }
332 }
Michael Layzell2a60e252017-05-31 21:36:47 -0400333}