blob: ce8934db2819841cb2ac7cdaab5f6619da7c04ea [file] [log] [blame]
Michael Layzell2a60e252017-05-31 21:36:47 -04001//! This module defines a cheaply-copyable cursor into a TokenStream's data.
2//!
3//! It does this by copying the data into a stably-addressed structured buffer,
4//! and holding raw pointers into that buffer to allow walking through delimited
David Tolnayc10676a2017-12-27 23:42:36 -05005//! groups cheaply.
Michael Layzell2a60e252017-05-31 21:36:47 -04006//!
7//! This module is heavily commented as it contains the only unsafe code in
8//! `syn`, and caution should be made when editing it. It provides a safe
9//! interface, but is fragile internally.
10
11use proc_macro2::*;
12
13use std::ptr;
Michael Layzell2a60e252017-05-31 21:36:47 -040014use std::marker::PhantomData;
15
David Tolnayf9e1de12017-12-31 00:47:01 -050016#[cfg(all(feature = "verbose-trace", not(feature = "all-features")))]
17use std::fmt::{self, Debug};
18
Michael Layzell2a60e252017-05-31 21:36:47 -040019/// Internal type which is used instead of `TokenTree` to represent a single
20/// `TokenTree` within a `SynomBuffer`.
Michael Layzell2a60e252017-05-31 21:36:47 -040021enum Entry {
22 /// Mimicing types from proc-macro.
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070023 Group(Span, Delimiter, SynomBuffer),
24 Term(Span, Term),
25 Op(Span, char, Spacing),
Michael Layzell2a60e252017-05-31 21:36:47 -040026 Literal(Span, Literal),
27 /// End entries contain a raw pointer to the entry from the containing
28 /// TokenTree.
29 End(*const Entry),
30}
31
Michael Layzell2a60e252017-05-31 21:36:47 -040032/// A buffer of data which contains a structured representation of the input
33/// `TokenStream` object.
Michael Layzell2a60e252017-05-31 21:36:47 -040034pub struct SynomBuffer {
35 // NOTE: Do not derive clone on this - there are raw pointers inside which
36 // will be messed up. Moving the `SynomBuffer` itself is safe as the actual
37 // backing slices won't be moved.
38 data: Box<[Entry]>,
39}
40
41impl SynomBuffer {
42 // NOTE: DO NOT MUTATE THE `Vec` RETURNED FROM THIS FUNCTION ONCE IT
43 // RETURNS, THE ADDRESS OF ITS BACKING MEMORY MUST REMAIN STABLE.
44 fn inner_new(stream: TokenStream, up: *const Entry) -> SynomBuffer {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070045 // Build up the entries list, recording the locations of any Groups
Michael Layzell2a60e252017-05-31 21:36:47 -040046 // in the list to be processed later.
47 let mut entries = Vec::new();
48 let mut seqs = Vec::new();
David Tolnay50fa4682017-12-26 23:17:22 -050049 for tt in stream {
Michael Layzell2a60e252017-05-31 21:36:47 -040050 match tt.kind {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070051 TokenNode::Term(sym) => {
52 entries.push(Entry::Term(tt.span, sym));
Michael Layzell2a60e252017-05-31 21:36:47 -040053 }
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070054 TokenNode::Op(chr, ok) => {
Michael Layzell2a60e252017-05-31 21:36:47 -040055 entries.push(Entry::Op(tt.span, chr, ok));
56 }
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070057 TokenNode::Literal(lit) => {
Michael Layzell2a60e252017-05-31 21:36:47 -040058 entries.push(Entry::Literal(tt.span, lit));
59 }
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070060 TokenNode::Group(delim, seq_stream) => {
Michael Layzell2a60e252017-05-31 21:36:47 -040061 // Record the index of the interesting entry, and store an
62 // `End(null)` there temporarially.
63 seqs.push((entries.len(), tt.span, delim, seq_stream));
64 entries.push(Entry::End(ptr::null()));
65 }
66 }
67 }
68 // Add an `End` entry to the end with a reference to the enclosing token
69 // stream which was passed in.
70 entries.push(Entry::End(up));
71
72 // NOTE: This is done to ensure that we don't accidentally modify the
73 // length of the backing buffer. The backing buffer must remain at a
74 // constant address after this point, as we are going to store a raw
75 // pointer into it.
76 let mut entries = entries.into_boxed_slice();
77 for (idx, span, delim, seq_stream) in seqs {
78 // We know that this index refers to one of the temporary
79 // `End(null)` entries, and we know that the last entry is
80 // `End(up)`, so the next index is also valid.
81 let seq_up = &entries[idx + 1] as *const Entry;
82
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070083 // The end entry stored at the end of this Entry::Group should
84 // point to the Entry which follows the Group in the list.
Michael Layzell2a60e252017-05-31 21:36:47 -040085 let inner = Self::inner_new(seq_stream, seq_up);
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070086 entries[idx] = Entry::Group(span, delim, inner);
Michael Layzell2a60e252017-05-31 21:36:47 -040087 }
88
David Tolnay51382052017-12-27 13:46:21 -050089 SynomBuffer { data: entries }
Michael Layzell2a60e252017-05-31 21:36:47 -040090 }
91
92 /// Create a new SynomBuffer, which contains the data from the given
93 /// TokenStream.
94 pub fn new(stream: TokenStream) -> SynomBuffer {
95 Self::inner_new(stream, ptr::null())
96 }
97
98 /// Create a cursor referencing the first token in the input.
99 pub fn begin(&self) -> Cursor {
David Tolnay51382052017-12-27 13:46:21 -0500100 unsafe { Cursor::create(&self.data[0], &self.data[self.data.len() - 1]) }
Michael Layzell2a60e252017-05-31 21:36:47 -0400101 }
102}
103
David Tolnayc10676a2017-12-27 23:42:36 -0500104pub struct Group<'a> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400105 pub span: Span,
106 pub inside: Cursor<'a>,
107 pub outside: Cursor<'a>,
108}
109
110/// A cursor into an input `TokenStream`'s data. This cursor holds a reference
111/// into the immutable data which is used internally to represent a
112/// `TokenStream`, and can be efficiently manipulated and copied around.
113///
114/// An empty `Cursor` can be created directly, or one may create a `SynomBuffer`
115/// object and get a cursor to its first token with `begin()`.
116///
117/// Two cursors are equal if they have the same location in the same input
118/// stream, and have the same scope.
119#[derive(Copy, Clone, Eq, PartialEq)]
120pub struct Cursor<'a> {
121 /// The current entry which the `Cursor` is pointing at.
122 ptr: *const Entry,
123 /// This is the only `Entry::End(..)` object which this cursor is allowed to
124 /// point at. All other `End` objects are skipped over in `Cursor::create`.
125 scope: *const Entry,
126 /// This uses the &'a reference which guarantees that these pointers are
127 /// still valid.
128 marker: PhantomData<&'a Entry>,
129}
130
Michael Layzell2a60e252017-05-31 21:36:47 -0400131impl<'a> Cursor<'a> {
132 /// Create a cursor referencing a static empty TokenStream.
133 pub fn empty() -> Self {
Michael Layzell69cf9082017-06-03 12:15:58 -0400134 // It's safe in this situation for us to put an `Entry` object in global
135 // storage, despite it not actually being safe to send across threads
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700136 // (`Term` is a reference into a thread-local table). This is because
137 // this entry never includes a `Term` object.
Michael Layzell69cf9082017-06-03 12:15:58 -0400138 //
139 // This wrapper struct allows us to break the rules and put a `Sync`
140 // object in global storage.
141 struct UnsafeSyncEntry(Entry);
142 unsafe impl Sync for UnsafeSyncEntry {}
David Tolnay51382052017-12-27 13:46:21 -0500143 static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0 as *const Entry));
Michael Layzell69cf9082017-06-03 12:15:58 -0400144
Michael Layzell2a60e252017-05-31 21:36:47 -0400145 Cursor {
Michael Layzell69cf9082017-06-03 12:15:58 -0400146 ptr: &EMPTY_ENTRY.0,
147 scope: &EMPTY_ENTRY.0,
Michael Layzell2a60e252017-05-31 21:36:47 -0400148 marker: PhantomData,
149 }
150 }
151
152 /// This create method intelligently exits non-explicitly-entered
153 /// `None`-delimited scopes when the cursor reaches the end of them,
154 /// allowing for them to be treated transparently.
155 unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self {
156 // NOTE: If we're looking at a `End(..)`, we want to advance the cursor
157 // past it, unless `ptr == scope`, which means that we're at the edge of
158 // our cursor's scope. We should only have `ptr != scope` at the exit
David Tolnayc10676a2017-12-27 23:42:36 -0500159 // from None-delimited groups entered with `ignore_none`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400160 while let Entry::End(exit) = *ptr {
161 if ptr == scope {
162 break;
163 }
164 ptr = exit;
165 }
166
167 Cursor {
168 ptr: ptr,
169 scope: scope,
170 marker: PhantomData,
171 }
172 }
173
174 /// Get the current entry.
175 fn entry(self) -> &'a Entry {
176 unsafe { &*self.ptr }
177 }
178
179 /// Bump the cursor to point at the next token after the current one. This
180 /// is undefined behavior if the cursor is currently looking at an
181 /// `Entry::End`.
182 unsafe fn bump(self) -> Cursor<'a> {
183 Cursor::create(self.ptr.offset(1), self.scope)
184 }
185
David Tolnayc10676a2017-12-27 23:42:36 -0500186 /// If the cursor is looking at a `None`-delimited group, move it to look at
187 /// the first token inside instead. If the group is empty, this will move
188 /// the cursor past the `None`-delimited group.
Michael Layzell2a60e252017-05-31 21:36:47 -0400189 ///
190 /// WARNING: This mutates its argument.
191 fn ignore_none(&mut self) {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700192 if let Entry::Group(_, Delimiter::None, ref buf) = *self.entry() {
Michael Layzell2a60e252017-05-31 21:36:47 -0400193 // NOTE: We call `Cursor::create` here to make sure that situations
194 // where we should immediately exit the span after entering it are
195 // handled correctly.
196 unsafe {
197 *self = Cursor::create(&buf.data[0], self.scope);
198 }
199 }
200 }
201
202 /// Check if the cursor is currently pointing at the end of its valid scope.
203 #[inline]
204 pub fn eof(self) -> bool {
205 // We're at eof if we're at the end of our scope.
206 self.ptr == self.scope
207 }
208
David Tolnayc10676a2017-12-27 23:42:36 -0500209 /// If the cursor is pointing at a Group with the given `Delimiter`, return
210 /// a cursor into that group, and one pointing to the next `TokenTree`.
211 pub fn group(mut self, delim: Delimiter) -> Option<Group<'a>> {
212 // If we're not trying to enter a none-delimited group, we want to
Michael Layzell2a60e252017-05-31 21:36:47 -0400213 // ignore them. We have to make sure to _not_ ignore them when we want
214 // to enter them, of course. For obvious reasons.
David Tolnayc10676a2017-12-27 23:42:36 -0500215 if delim != Delimiter::None {
Michael Layzell2a60e252017-05-31 21:36:47 -0400216 self.ignore_none();
217 }
218
David Tolnayc10676a2017-12-27 23:42:36 -0500219 if let Entry::Group(span, group_delim, ref buf) = *self.entry() {
220 if group_delim == delim {
221 return Some(Group {
Michael Layzell2a60e252017-05-31 21:36:47 -0400222 span: span,
223 inside: buf.begin(),
224 outside: unsafe { self.bump() },
David Tolnayc10676a2017-12-27 23:42:36 -0500225 });
Michael Layzell2a60e252017-05-31 21:36:47 -0400226 }
Michael Layzell2a60e252017-05-31 21:36:47 -0400227 }
David Tolnayc10676a2017-12-27 23:42:36 -0500228
229 None
Michael Layzell2a60e252017-05-31 21:36:47 -0400230 }
231
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700232 /// If the cursor is pointing at a Term, return it and a cursor pointing at
Michael Layzell2a60e252017-05-31 21:36:47 -0400233 /// the next `TokenTree`.
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700234 pub fn word(mut self) -> Option<(Cursor<'a>, Span, Term)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400235 self.ignore_none();
236 match *self.entry() {
David Tolnay51382052017-12-27 13:46:21 -0500237 Entry::Term(span, sym) => Some((unsafe { self.bump() }, span, sym)),
238 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400239 }
240 }
241
242 /// If the cursor is pointing at an Op, return it and a cursor pointing
243 /// at the next `TokenTree`.
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700244 pub fn op(mut self) -> Option<(Cursor<'a>, Span, char, Spacing)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400245 self.ignore_none();
246 match *self.entry() {
David Tolnay51382052017-12-27 13:46:21 -0500247 Entry::Op(span, chr, kind) => Some((unsafe { self.bump() }, span, chr, kind)),
248 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400249 }
250 }
251
252 /// If the cursor is pointing at a Literal, return it and a cursor pointing
253 /// at the next `TokenTree`.
254 pub fn literal(mut self) -> Option<(Cursor<'a>, Span, Literal)> {
255 self.ignore_none();
256 match *self.entry() {
David Tolnay51382052017-12-27 13:46:21 -0500257 Entry::Literal(span, ref lit) => Some((unsafe { self.bump() }, span, lit.clone())),
258 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400259 }
260 }
261
262 /// Copy all remaining tokens visible from this cursor into a `TokenStream`.
263 pub fn token_stream(self) -> TokenStream {
264 let mut tts = Vec::new();
265 let mut cursor = self;
266 while let Some((next, tt)) = cursor.token_tree() {
267 tts.push(tt);
268 cursor = next;
269 }
270 tts.into_iter().collect()
271 }
272
273 /// If the cursor is looking at a `TokenTree`, returns it along with a
David Tolnayc10676a2017-12-27 23:42:36 -0500274 /// cursor pointing to the next token in the group, otherwise returns
Michael Layzell2a60e252017-05-31 21:36:47 -0400275 /// `None`.
276 ///
David Tolnayc10676a2017-12-27 23:42:36 -0500277 /// This method does not treat `None`-delimited groups as invisible, and
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700278 /// will return a `Group(None, ..)` if the cursor is looking at one.
Michael Layzell2a60e252017-05-31 21:36:47 -0400279 pub fn token_tree(self) -> Option<(Cursor<'a>, TokenTree)> {
280 let tree = match *self.entry() {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700281 Entry::Group(span, delim, ref buf) => {
Michael Layzell2a60e252017-05-31 21:36:47 -0400282 let stream = buf.begin().token_stream();
283 TokenTree {
284 span: span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700285 kind: TokenNode::Group(delim, stream),
Michael Layzell2a60e252017-05-31 21:36:47 -0400286 }
287 }
David Tolnay51382052017-12-27 13:46:21 -0500288 Entry::Literal(span, ref lit) => TokenTree {
289 span: span,
290 kind: TokenNode::Literal(lit.clone()),
291 },
292 Entry::Term(span, sym) => TokenTree {
293 span: span,
294 kind: TokenNode::Term(sym),
295 },
296 Entry::Op(span, chr, kind) => TokenTree {
297 span: span,
298 kind: TokenNode::Op(chr, kind),
299 },
Michael Layzell2a60e252017-05-31 21:36:47 -0400300 Entry::End(..) => {
301 return None;
302 }
303 };
304
David Tolnay51382052017-12-27 13:46:21 -0500305 Some((unsafe { self.bump() }, tree))
Michael Layzell2a60e252017-05-31 21:36:47 -0400306 }
307}
308
309// We do a custom implementation for `Debug` as the default implementation is
310// pretty useless.
David Tolnayf9e1de12017-12-31 00:47:01 -0500311#[cfg(all(feature = "verbose-trace", not(feature = "all-features")))]
312impl<'a> Debug for Cursor<'a> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400313 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Nika Layzellae81b372017-12-05 14:12:33 -0500314 // Print what the cursor is currently looking at.
315 // This will look like Cursor("some remaining tokens here")
316 f.debug_tuple("Cursor")
317 .field(&self.token_stream().to_string())
Michael Layzell2a60e252017-05-31 21:36:47 -0400318 .finish()
319 }
320}