blob: bdd08740ca670888bc80a655f1a27188e2aa65db [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;
14use std::fmt;
15use std::marker::PhantomData;
16
17/// Internal type which is used instead of `TokenTree` to represent a single
18/// `TokenTree` within a `SynomBuffer`.
19#[derive(Debug)]
20enum Entry {
21 /// Mimicing types from proc-macro.
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070022 Group(Span, Delimiter, SynomBuffer),
23 Term(Span, Term),
24 Op(Span, char, Spacing),
Michael Layzell2a60e252017-05-31 21:36:47 -040025 Literal(Span, Literal),
26 /// End entries contain a raw pointer to the entry from the containing
27 /// TokenTree.
28 End(*const Entry),
29}
30
Michael Layzell2a60e252017-05-31 21:36:47 -040031/// A buffer of data which contains a structured representation of the input
32/// `TokenStream` object.
33#[derive(Debug)]
34pub 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
104#[derive(Copy, Clone, Debug)]
David Tolnayc10676a2017-12-27 23:42:36 -0500105pub struct Group<'a> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400106 pub span: Span,
107 pub inside: Cursor<'a>,
108 pub outside: Cursor<'a>,
109}
110
111/// A cursor into an input `TokenStream`'s data. This cursor holds a reference
112/// into the immutable data which is used internally to represent a
113/// `TokenStream`, and can be efficiently manipulated and copied around.
114///
115/// An empty `Cursor` can be created directly, or one may create a `SynomBuffer`
116/// object and get a cursor to its first token with `begin()`.
117///
118/// Two cursors are equal if they have the same location in the same input
119/// stream, and have the same scope.
120#[derive(Copy, Clone, Eq, PartialEq)]
121pub struct Cursor<'a> {
122 /// The current entry which the `Cursor` is pointing at.
123 ptr: *const Entry,
124 /// This is the only `Entry::End(..)` object which this cursor is allowed to
125 /// point at. All other `End` objects are skipped over in `Cursor::create`.
126 scope: *const Entry,
127 /// This uses the &'a reference which guarantees that these pointers are
128 /// still valid.
129 marker: PhantomData<&'a Entry>,
130}
131
Michael Layzell2a60e252017-05-31 21:36:47 -0400132impl<'a> Cursor<'a> {
133 /// Create a cursor referencing a static empty TokenStream.
134 pub fn empty() -> Self {
Michael Layzell69cf9082017-06-03 12:15:58 -0400135 // It's safe in this situation for us to put an `Entry` object in global
136 // storage, despite it not actually being safe to send across threads
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700137 // (`Term` is a reference into a thread-local table). This is because
138 // this entry never includes a `Term` object.
Michael Layzell69cf9082017-06-03 12:15:58 -0400139 //
140 // This wrapper struct allows us to break the rules and put a `Sync`
141 // object in global storage.
142 struct UnsafeSyncEntry(Entry);
143 unsafe impl Sync for UnsafeSyncEntry {}
David Tolnay51382052017-12-27 13:46:21 -0500144 static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0 as *const Entry));
Michael Layzell69cf9082017-06-03 12:15:58 -0400145
Michael Layzell2a60e252017-05-31 21:36:47 -0400146 Cursor {
Michael Layzell69cf9082017-06-03 12:15:58 -0400147 ptr: &EMPTY_ENTRY.0,
148 scope: &EMPTY_ENTRY.0,
Michael Layzell2a60e252017-05-31 21:36:47 -0400149 marker: PhantomData,
150 }
151 }
152
153 /// This create method intelligently exits non-explicitly-entered
154 /// `None`-delimited scopes when the cursor reaches the end of them,
155 /// allowing for them to be treated transparently.
156 unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self {
157 // NOTE: If we're looking at a `End(..)`, we want to advance the cursor
158 // past it, unless `ptr == scope`, which means that we're at the edge of
159 // our cursor's scope. We should only have `ptr != scope` at the exit
David Tolnayc10676a2017-12-27 23:42:36 -0500160 // from None-delimited groups entered with `ignore_none`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400161 while let Entry::End(exit) = *ptr {
162 if ptr == scope {
163 break;
164 }
165 ptr = exit;
166 }
167
168 Cursor {
169 ptr: ptr,
170 scope: scope,
171 marker: PhantomData,
172 }
173 }
174
175 /// Get the current entry.
176 fn entry(self) -> &'a Entry {
177 unsafe { &*self.ptr }
178 }
179
180 /// Bump the cursor to point at the next token after the current one. This
181 /// is undefined behavior if the cursor is currently looking at an
182 /// `Entry::End`.
183 unsafe fn bump(self) -> Cursor<'a> {
184 Cursor::create(self.ptr.offset(1), self.scope)
185 }
186
David Tolnayc10676a2017-12-27 23:42:36 -0500187 /// If the cursor is looking at a `None`-delimited group, move it to look at
188 /// the first token inside instead. If the group is empty, this will move
189 /// the cursor past the `None`-delimited group.
Michael Layzell2a60e252017-05-31 21:36:47 -0400190 ///
191 /// WARNING: This mutates its argument.
192 fn ignore_none(&mut self) {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700193 if let Entry::Group(_, Delimiter::None, ref buf) = *self.entry() {
Michael Layzell2a60e252017-05-31 21:36:47 -0400194 // NOTE: We call `Cursor::create` here to make sure that situations
195 // where we should immediately exit the span after entering it are
196 // handled correctly.
197 unsafe {
198 *self = Cursor::create(&buf.data[0], self.scope);
199 }
200 }
201 }
202
203 /// Check if the cursor is currently pointing at the end of its valid scope.
204 #[inline]
205 pub fn eof(self) -> bool {
206 // We're at eof if we're at the end of our scope.
207 self.ptr == self.scope
208 }
209
David Tolnayc10676a2017-12-27 23:42:36 -0500210 /// If the cursor is pointing at a Group with the given `Delimiter`, return
211 /// a cursor into that group, and one pointing to the next `TokenTree`.
212 pub fn group(mut self, delim: Delimiter) -> Option<Group<'a>> {
213 // If we're not trying to enter a none-delimited group, we want to
Michael Layzell2a60e252017-05-31 21:36:47 -0400214 // ignore them. We have to make sure to _not_ ignore them when we want
215 // to enter them, of course. For obvious reasons.
David Tolnayc10676a2017-12-27 23:42:36 -0500216 if delim != Delimiter::None {
Michael Layzell2a60e252017-05-31 21:36:47 -0400217 self.ignore_none();
218 }
219
David Tolnayc10676a2017-12-27 23:42:36 -0500220 if let Entry::Group(span, group_delim, ref buf) = *self.entry() {
221 if group_delim == delim {
222 return Some(Group {
Michael Layzell2a60e252017-05-31 21:36:47 -0400223 span: span,
224 inside: buf.begin(),
225 outside: unsafe { self.bump() },
David Tolnayc10676a2017-12-27 23:42:36 -0500226 });
Michael Layzell2a60e252017-05-31 21:36:47 -0400227 }
Michael Layzell2a60e252017-05-31 21:36:47 -0400228 }
David Tolnayc10676a2017-12-27 23:42:36 -0500229
230 None
Michael Layzell2a60e252017-05-31 21:36:47 -0400231 }
232
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700233 /// If the cursor is pointing at a Term, return it and a cursor pointing at
Michael Layzell2a60e252017-05-31 21:36:47 -0400234 /// the next `TokenTree`.
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700235 pub fn word(mut self) -> Option<(Cursor<'a>, Span, Term)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400236 self.ignore_none();
237 match *self.entry() {
David Tolnay51382052017-12-27 13:46:21 -0500238 Entry::Term(span, sym) => Some((unsafe { self.bump() }, span, sym)),
239 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400240 }
241 }
242
243 /// If the cursor is pointing at an Op, return it and a cursor pointing
244 /// at the next `TokenTree`.
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700245 pub fn op(mut self) -> Option<(Cursor<'a>, Span, char, Spacing)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400246 self.ignore_none();
247 match *self.entry() {
David Tolnay51382052017-12-27 13:46:21 -0500248 Entry::Op(span, chr, kind) => Some((unsafe { self.bump() }, span, chr, kind)),
249 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400250 }
251 }
252
253 /// If the cursor is pointing at a Literal, return it and a cursor pointing
254 /// at the next `TokenTree`.
255 pub fn literal(mut self) -> Option<(Cursor<'a>, Span, Literal)> {
256 self.ignore_none();
257 match *self.entry() {
David Tolnay51382052017-12-27 13:46:21 -0500258 Entry::Literal(span, ref lit) => Some((unsafe { self.bump() }, span, lit.clone())),
259 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400260 }
261 }
262
263 /// Copy all remaining tokens visible from this cursor into a `TokenStream`.
264 pub fn token_stream(self) -> TokenStream {
265 let mut tts = Vec::new();
266 let mut cursor = self;
267 while let Some((next, tt)) = cursor.token_tree() {
268 tts.push(tt);
269 cursor = next;
270 }
271 tts.into_iter().collect()
272 }
273
274 /// If the cursor is looking at a `TokenTree`, returns it along with a
David Tolnayc10676a2017-12-27 23:42:36 -0500275 /// cursor pointing to the next token in the group, otherwise returns
Michael Layzell2a60e252017-05-31 21:36:47 -0400276 /// `None`.
277 ///
David Tolnayc10676a2017-12-27 23:42:36 -0500278 /// This method does not treat `None`-delimited groups as invisible, and
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700279 /// will return a `Group(None, ..)` if the cursor is looking at one.
Michael Layzell2a60e252017-05-31 21:36:47 -0400280 pub fn token_tree(self) -> Option<(Cursor<'a>, TokenTree)> {
281 let tree = match *self.entry() {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700282 Entry::Group(span, delim, ref buf) => {
Michael Layzell2a60e252017-05-31 21:36:47 -0400283 let stream = buf.begin().token_stream();
284 TokenTree {
285 span: span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700286 kind: TokenNode::Group(delim, stream),
Michael Layzell2a60e252017-05-31 21:36:47 -0400287 }
288 }
David Tolnay51382052017-12-27 13:46:21 -0500289 Entry::Literal(span, ref lit) => TokenTree {
290 span: span,
291 kind: TokenNode::Literal(lit.clone()),
292 },
293 Entry::Term(span, sym) => TokenTree {
294 span: span,
295 kind: TokenNode::Term(sym),
296 },
297 Entry::Op(span, chr, kind) => TokenTree {
298 span: span,
299 kind: TokenNode::Op(chr, kind),
300 },
Michael Layzell2a60e252017-05-31 21:36:47 -0400301 Entry::End(..) => {
302 return None;
303 }
304 };
305
David Tolnay51382052017-12-27 13:46:21 -0500306 Some((unsafe { self.bump() }, tree))
Michael Layzell2a60e252017-05-31 21:36:47 -0400307 }
308}
309
310// We do a custom implementation for `Debug` as the default implementation is
311// pretty useless.
312impl<'a> fmt::Debug for Cursor<'a> {
313 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}