blob: 499c4f1dd6a13ea63833d5232e87cfc3c8f5a298 [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 Tolnay7c3e77d2018-01-06 17:42:53 -080012//! The [`Synom`] trait is implemented for syntax tree types that can be parsed
13//! from one of these token cursors.
Michael Layzell2a60e252017-05-31 21:36:47 -040014//!
David Tolnay7c3e77d2018-01-06 17:42:53 -080015//! [`Synom`]: ../synom/trait.Synom.html
16//!
David Tolnay461d98e2018-01-07 11:07:19 -080017//! *This module is available if Syn is built with the `"parsing"` feature.*
18//!
David Tolnay7c3e77d2018-01-06 17:42:53 -080019//! # Example
20//!
21//! This example shows a basic token parser for parsing a token stream without
22//! using Syn's parser combinator macros.
23//!
24//! ```
David Tolnay28bb2e02018-07-21 13:06:04 -070025//! #![feature(proc_macro_diagnostic)]
David Tolnay7c3e77d2018-01-06 17:42:53 -080026//!
27//! extern crate syn;
28//! extern crate proc_macro;
29//!
30//! #[macro_use]
31//! extern crate quote;
32//!
33//! use syn::{token, ExprTuple};
34//! use syn::buffer::{Cursor, TokenBuffer};
35//! use syn::spanned::Spanned;
36//! use syn::synom::Synom;
37//! use proc_macro::{Diagnostic, Span, TokenStream};
38//!
39//! /// A basic token parser for parsing a token stream without using Syn's
40//! /// parser combinator macros.
41//! pub struct Parser<'a> {
42//! cursor: Cursor<'a>,
43//! }
44//!
45//! impl<'a> Parser<'a> {
46//! pub fn new(cursor: Cursor<'a>) -> Self {
47//! Parser { cursor }
48//! }
49//!
50//! pub fn current_span(&self) -> Span {
51//! self.cursor.span().unstable()
52//! }
53//!
54//! pub fn parse<T: Synom>(&mut self) -> Result<T, Diagnostic> {
55//! let (val, rest) = T::parse(self.cursor)
56//! .map_err(|e| match T::description() {
57//! Some(desc) => {
58//! self.current_span().error(format!("{}: expected {}", e, desc))
59//! }
60//! None => {
61//! self.current_span().error(e.to_string())
62//! }
63//! })?;
64//!
65//! self.cursor = rest;
66//! Ok(val)
67//! }
68//!
69//! pub fn expect_eof(&mut self) -> Result<(), Diagnostic> {
70//! if !self.cursor.eof() {
71//! return Err(self.current_span().error("trailing characters; expected eof"));
72//! }
73//!
74//! Ok(())
75//! }
76//! }
77//!
78//! fn eval(input: TokenStream) -> Result<TokenStream, Diagnostic> {
79//! let buffer = TokenBuffer::new(input);
80//! let mut parser = Parser::new(buffer.begin());
81//!
82//! // Parse some syntax tree types out of the input tokens. In this case we
83//! // expect something like:
84//! //
85//! // (a, b, c) = (1, 2, 3)
86//! let a = parser.parse::<ExprTuple>()?;
87//! parser.parse::<token::Eq>()?;
88//! let b = parser.parse::<ExprTuple>()?;
89//! parser.expect_eof()?;
90//!
91//! // Perform some validation and report errors.
92//! let (a_len, b_len) = (a.elems.len(), b.elems.len());
93//! if a_len != b_len {
94//! let diag = b.span().unstable()
95//! .error(format!("expected {} element(s), got {}", a_len, b_len))
96//! .span_note(a.span().unstable(), "because of this");
97//!
98//! return Err(diag);
99//! }
100//!
101//! // Build the output tokens.
102//! let out = quote! {
103//! println!("All good! Received two tuples of size {}", #a_len);
104//! };
105//!
106//! Ok(out.into())
107//! }
108//! #
109//! # extern crate proc_macro2;
110//! #
111//! # // This method exists on proc_macro2::Span but is behind the "nightly"
112//! # // feature.
113//! # trait ToUnstableSpan {
114//! # fn unstable(&self) -> Span;
115//! # }
116//! #
117//! # impl ToUnstableSpan for proc_macro2::Span {
118//! # fn unstable(&self) -> Span {
119//! # unimplemented!()
120//! # }
121//! # }
122//! #
123//! # fn main() {}
124//! ```
Michael Layzell2a60e252017-05-31 21:36:47 -0400125
David Tolnay7c3e77d2018-01-06 17:42:53 -0800126// This module is heavily commented as it contains the only unsafe code in Syn,
127// and caution should be used when editing it. The public-facing interface is
128// 100% safe but the implementation is fragile internally.
129
David Tolnay278f9e32018-08-14 22:41:11 -0700130#[cfg(all(
131 not(all(target_arch = "wasm32", target_os = "unknown")),
132 feature = "proc-macro"
133))]
David Tolnay7c3e77d2018-01-06 17:42:53 -0800134use proc_macro as pm;
David Tolnay65fb5662018-05-20 20:02:28 -0700135use proc_macro2::{Delimiter, Ident, Literal, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700136use proc_macro2::{Group, Punct, TokenTree};
Michael Layzell2a60e252017-05-31 21:36:47 -0400137
Michael Layzell2a60e252017-05-31 21:36:47 -0400138use std::marker::PhantomData;
David Tolnay94d2b792018-04-29 12:26:10 -0700139use std::ptr;
Michael Layzell2a60e252017-05-31 21:36:47 -0400140
David Tolnayd1ec6ec2018-01-03 00:23:45 -0800141#[cfg(synom_verbose_trace)]
David Tolnayf9e1de12017-12-31 00:47:01 -0500142use std::fmt::{self, Debug};
143
David Tolnay7c3e77d2018-01-06 17:42:53 -0800144/// Internal type which is used instead of `TokenTree` to represent a token tree
145/// within a `TokenBuffer`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400146enum Entry {
David Tolnay7c3e77d2018-01-06 17:42:53 -0800147 // Mimicking types from proc-macro.
David Tolnaydfc886b2018-01-06 08:03:09 -0800148 Group(Span, Delimiter, TokenBuffer),
Alex Crichtona74a1c82018-05-16 10:20:44 -0700149 Ident(Ident),
150 Punct(Punct),
Alex Crichton9a4dca22018-03-28 06:32:19 -0700151 Literal(Literal),
David Tolnay7c3e77d2018-01-06 17:42:53 -0800152 // End entries contain a raw pointer to the entry from the containing
153 // token tree, or null if this is the outermost level.
Michael Layzell2a60e252017-05-31 21:36:47 -0400154 End(*const Entry),
155}
156
David Tolnay7c3e77d2018-01-06 17:42:53 -0800157/// A buffer that can be efficiently traversed multiple times, unlike
158/// `TokenStream` which requires a deep copy in order to traverse more than
159/// once.
160///
161/// See the [module documentation] for an example of `TokenBuffer` in action.
162///
163/// [module documentation]: index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800164///
165/// *This type is available if Syn is built with the `"parsing"` feature.*
David Tolnaydfc886b2018-01-06 08:03:09 -0800166pub struct TokenBuffer {
Michael Layzell2a60e252017-05-31 21:36:47 -0400167 // NOTE: Do not derive clone on this - there are raw pointers inside which
David Tolnaydfc886b2018-01-06 08:03:09 -0800168 // will be messed up. Moving the `TokenBuffer` itself is safe as the actual
Michael Layzell2a60e252017-05-31 21:36:47 -0400169 // backing slices won't be moved.
170 data: Box<[Entry]>,
171}
172
David Tolnaydfc886b2018-01-06 08:03:09 -0800173impl TokenBuffer {
Michael Layzell2a60e252017-05-31 21:36:47 -0400174 // NOTE: DO NOT MUTATE THE `Vec` RETURNED FROM THIS FUNCTION ONCE IT
175 // RETURNS, THE ADDRESS OF ITS BACKING MEMORY MUST REMAIN STABLE.
David Tolnaydfc886b2018-01-06 08:03:09 -0800176 fn inner_new(stream: TokenStream, up: *const Entry) -> TokenBuffer {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700177 // Build up the entries list, recording the locations of any Groups
Michael Layzell2a60e252017-05-31 21:36:47 -0400178 // in the list to be processed later.
179 let mut entries = Vec::new();
180 let mut seqs = Vec::new();
David Tolnay50fa4682017-12-26 23:17:22 -0500181 for tt in stream {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700182 match tt {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700183 TokenTree::Ident(sym) => {
184 entries.push(Entry::Ident(sym));
Michael Layzell2a60e252017-05-31 21:36:47 -0400185 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700186 TokenTree::Punct(op) => {
187 entries.push(Entry::Punct(op));
Michael Layzell2a60e252017-05-31 21:36:47 -0400188 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700189 TokenTree::Literal(l) => {
190 entries.push(Entry::Literal(l));
Michael Layzell2a60e252017-05-31 21:36:47 -0400191 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700192 TokenTree::Group(g) => {
Michael Layzell2a60e252017-05-31 21:36:47 -0400193 // Record the index of the interesting entry, and store an
194 // `End(null)` there temporarially.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700195 seqs.push((entries.len(), g.span(), g.delimiter(), g.stream().clone()));
Michael Layzell2a60e252017-05-31 21:36:47 -0400196 entries.push(Entry::End(ptr::null()));
197 }
198 }
199 }
200 // Add an `End` entry to the end with a reference to the enclosing token
201 // stream which was passed in.
202 entries.push(Entry::End(up));
203
204 // NOTE: This is done to ensure that we don't accidentally modify the
205 // length of the backing buffer. The backing buffer must remain at a
206 // constant address after this point, as we are going to store a raw
207 // pointer into it.
208 let mut entries = entries.into_boxed_slice();
209 for (idx, span, delim, seq_stream) in seqs {
210 // We know that this index refers to one of the temporary
211 // `End(null)` entries, and we know that the last entry is
212 // `End(up)`, so the next index is also valid.
213 let seq_up = &entries[idx + 1] as *const Entry;
214
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700215 // The end entry stored at the end of this Entry::Group should
216 // point to the Entry which follows the Group in the list.
Michael Layzell2a60e252017-05-31 21:36:47 -0400217 let inner = Self::inner_new(seq_stream, seq_up);
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700218 entries[idx] = Entry::Group(span, delim, inner);
Michael Layzell2a60e252017-05-31 21:36:47 -0400219 }
220
David Tolnaydfc886b2018-01-06 08:03:09 -0800221 TokenBuffer { data: entries }
Michael Layzell2a60e252017-05-31 21:36:47 -0400222 }
223
David Tolnay7c3e77d2018-01-06 17:42:53 -0800224 /// Creates a `TokenBuffer` containing all the tokens from the input
225 /// `TokenStream`.
hcpl4b72a382018-04-04 14:50:24 +0300226 ///
227 /// *This method is available if Syn is built with both the `"parsing"` and
228 /// `"proc-macro"` features.*
David Tolnay278f9e32018-08-14 22:41:11 -0700229 #[cfg(all(
230 not(all(target_arch = "wasm32", target_os = "unknown")),
231 feature = "proc-macro"
232 ))]
David Tolnay7c3e77d2018-01-06 17:42:53 -0800233 pub fn new(stream: pm::TokenStream) -> TokenBuffer {
234 Self::new2(stream.into())
235 }
236
237 /// Creates a `TokenBuffer` containing all the tokens from the input
238 /// `TokenStream`.
239 pub fn new2(stream: TokenStream) -> TokenBuffer {
Michael Layzell2a60e252017-05-31 21:36:47 -0400240 Self::inner_new(stream, ptr::null())
241 }
242
David Tolnay7c3e77d2018-01-06 17:42:53 -0800243 /// Creates a cursor referencing the first token in the buffer and able to
244 /// traverse until the end of the buffer.
Michael Layzell2a60e252017-05-31 21:36:47 -0400245 pub fn begin(&self) -> Cursor {
David Tolnay51382052017-12-27 13:46:21 -0500246 unsafe { Cursor::create(&self.data[0], &self.data[self.data.len() - 1]) }
Michael Layzell2a60e252017-05-31 21:36:47 -0400247 }
248}
249
David Tolnay7c3e77d2018-01-06 17:42:53 -0800250/// A cheaply copyable cursor into a `TokenBuffer`.
251///
252/// This cursor holds a shared reference into the immutable data which is used
253/// internally to represent a `TokenStream`, and can be efficiently manipulated
254/// and copied around.
Michael Layzell2a60e252017-05-31 21:36:47 -0400255///
David Tolnaydfc886b2018-01-06 08:03:09 -0800256/// An empty `Cursor` can be created directly, or one may create a `TokenBuffer`
Michael Layzell2a60e252017-05-31 21:36:47 -0400257/// object and get a cursor to its first token with `begin()`.
258///
259/// Two cursors are equal if they have the same location in the same input
260/// stream, and have the same scope.
David Tolnay7c3e77d2018-01-06 17:42:53 -0800261///
262/// See the [module documentation] for an example of a `Cursor` in action.
263///
264/// [module documentation]: index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800265///
266/// *This type is available if Syn is built with the `"parsing"` feature.*
Michael Layzell2a60e252017-05-31 21:36:47 -0400267#[derive(Copy, Clone, Eq, PartialEq)]
268pub struct Cursor<'a> {
269 /// The current entry which the `Cursor` is pointing at.
270 ptr: *const Entry,
271 /// This is the only `Entry::End(..)` object which this cursor is allowed to
272 /// point at. All other `End` objects are skipped over in `Cursor::create`.
273 scope: *const Entry,
274 /// This uses the &'a reference which guarantees that these pointers are
275 /// still valid.
276 marker: PhantomData<&'a Entry>,
277}
278
Michael Layzell2a60e252017-05-31 21:36:47 -0400279impl<'a> Cursor<'a> {
David Tolnay7c3e77d2018-01-06 17:42:53 -0800280 /// Creates a cursor referencing a static empty TokenStream.
Michael Layzell2a60e252017-05-31 21:36:47 -0400281 pub fn empty() -> Self {
Michael Layzell69cf9082017-06-03 12:15:58 -0400282 // It's safe in this situation for us to put an `Entry` object in global
283 // storage, despite it not actually being safe to send across threads
Alex Crichtona74a1c82018-05-16 10:20:44 -0700284 // (`Ident` is a reference into a thread-local table). This is because
285 // this entry never includes a `Ident` object.
Michael Layzell69cf9082017-06-03 12:15:58 -0400286 //
287 // This wrapper struct allows us to break the rules and put a `Sync`
288 // object in global storage.
289 struct UnsafeSyncEntry(Entry);
290 unsafe impl Sync for UnsafeSyncEntry {}
David Tolnay51382052017-12-27 13:46:21 -0500291 static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0 as *const Entry));
Michael Layzell69cf9082017-06-03 12:15:58 -0400292
Michael Layzell2a60e252017-05-31 21:36:47 -0400293 Cursor {
Michael Layzell69cf9082017-06-03 12:15:58 -0400294 ptr: &EMPTY_ENTRY.0,
295 scope: &EMPTY_ENTRY.0,
Michael Layzell2a60e252017-05-31 21:36:47 -0400296 marker: PhantomData,
297 }
298 }
299
300 /// This create method intelligently exits non-explicitly-entered
301 /// `None`-delimited scopes when the cursor reaches the end of them,
302 /// allowing for them to be treated transparently.
303 unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self {
304 // NOTE: If we're looking at a `End(..)`, we want to advance the cursor
305 // past it, unless `ptr == scope`, which means that we're at the edge of
306 // our cursor's scope. We should only have `ptr != scope` at the exit
David Tolnayc10676a2017-12-27 23:42:36 -0500307 // from None-delimited groups entered with `ignore_none`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400308 while let Entry::End(exit) = *ptr {
309 if ptr == scope {
310 break;
311 }
312 ptr = exit;
313 }
314
315 Cursor {
316 ptr: ptr,
317 scope: scope,
318 marker: PhantomData,
319 }
320 }
321
322 /// Get the current entry.
323 fn entry(self) -> &'a Entry {
324 unsafe { &*self.ptr }
325 }
326
327 /// Bump the cursor to point at the next token after the current one. This
328 /// is undefined behavior if the cursor is currently looking at an
329 /// `Entry::End`.
330 unsafe fn bump(self) -> Cursor<'a> {
331 Cursor::create(self.ptr.offset(1), self.scope)
332 }
333
David Tolnayc10676a2017-12-27 23:42:36 -0500334 /// If the cursor is looking at a `None`-delimited group, move it to look at
335 /// the first token inside instead. If the group is empty, this will move
336 /// the cursor past the `None`-delimited group.
Michael Layzell2a60e252017-05-31 21:36:47 -0400337 ///
338 /// WARNING: This mutates its argument.
339 fn ignore_none(&mut self) {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700340 if let Entry::Group(_, Delimiter::None, ref buf) = *self.entry() {
Michael Layzell2a60e252017-05-31 21:36:47 -0400341 // NOTE: We call `Cursor::create` here to make sure that situations
342 // where we should immediately exit the span after entering it are
343 // handled correctly.
344 unsafe {
345 *self = Cursor::create(&buf.data[0], self.scope);
346 }
347 }
348 }
349
David Tolnay7c3e77d2018-01-06 17:42:53 -0800350 /// Checks whether the cursor is currently pointing at the end of its valid
351 /// scope.
Michael Layzell2a60e252017-05-31 21:36:47 -0400352 #[inline]
353 pub fn eof(self) -> bool {
354 // We're at eof if we're at the end of our scope.
355 self.ptr == self.scope
356 }
357
David Tolnay7c3e77d2018-01-06 17:42:53 -0800358 /// If the cursor is pointing at a `Group` with the given delimiter, returns
359 /// a cursor into that group and one pointing to the next `TokenTree`.
David Tolnay65729482017-12-31 16:14:50 -0500360 pub fn group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, Span, Cursor<'a>)> {
David Tolnayc10676a2017-12-27 23:42:36 -0500361 // If we're not trying to enter a none-delimited group, we want to
Michael Layzell2a60e252017-05-31 21:36:47 -0400362 // ignore them. We have to make sure to _not_ ignore them when we want
363 // to enter them, of course. For obvious reasons.
David Tolnayc10676a2017-12-27 23:42:36 -0500364 if delim != Delimiter::None {
Michael Layzell2a60e252017-05-31 21:36:47 -0400365 self.ignore_none();
366 }
367
David Tolnayc10676a2017-12-27 23:42:36 -0500368 if let Entry::Group(span, group_delim, ref buf) = *self.entry() {
369 if group_delim == delim {
David Tolnay65729482017-12-31 16:14:50 -0500370 return Some((buf.begin(), span, unsafe { self.bump() }));
Michael Layzell2a60e252017-05-31 21:36:47 -0400371 }
Michael Layzell2a60e252017-05-31 21:36:47 -0400372 }
David Tolnayc10676a2017-12-27 23:42:36 -0500373
374 None
Michael Layzell2a60e252017-05-31 21:36:47 -0400375 }
376
Alex Crichtona74a1c82018-05-16 10:20:44 -0700377 /// If the cursor is pointing at a `Ident`, returns it along with a cursor
David Tolnay7c3e77d2018-01-06 17:42:53 -0800378 /// pointing at the next `TokenTree`.
David Tolnay55a5f3a2018-05-20 18:00:51 -0700379 pub fn ident(mut self) -> Option<(Ident, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400380 self.ignore_none();
381 match *self.entry() {
David Tolnaya4319b72018-06-02 00:49:15 -0700382 Entry::Ident(ref ident) => Some((ident.clone(), unsafe { self.bump() })),
David Tolnay51382052017-12-27 13:46:21 -0500383 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400384 }
385 }
386
Alex Crichtona74a1c82018-05-16 10:20:44 -0700387 /// If the cursor is pointing at an `Punct`, returns it along with a cursor
David Tolnay7c3e77d2018-01-06 17:42:53 -0800388 /// pointing at the next `TokenTree`.
David Tolnay55a5f3a2018-05-20 18:00:51 -0700389 pub fn punct(mut self) -> Option<(Punct, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400390 self.ignore_none();
391 match *self.entry() {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700392 Entry::Punct(ref op) => Some((op.clone(), unsafe { self.bump() })),
David Tolnay51382052017-12-27 13:46:21 -0500393 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400394 }
395 }
396
David Tolnay7c3e77d2018-01-06 17:42:53 -0800397 /// If the cursor is pointing at a `Literal`, return it along with a cursor
398 /// pointing at the next `TokenTree`.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700399 pub fn literal(mut self) -> Option<(Literal, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400400 self.ignore_none();
401 match *self.entry() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700402 Entry::Literal(ref lit) => Some((lit.clone(), unsafe { self.bump() })),
David Tolnay51382052017-12-27 13:46:21 -0500403 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400404 }
405 }
406
David Tolnay7c3e77d2018-01-06 17:42:53 -0800407 /// Copies all remaining tokens visible from this cursor into a
408 /// `TokenStream`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400409 pub fn token_stream(self) -> TokenStream {
410 let mut tts = Vec::new();
411 let mut cursor = self;
David Tolnay65729482017-12-31 16:14:50 -0500412 while let Some((tt, rest)) = cursor.token_tree() {
Michael Layzell2a60e252017-05-31 21:36:47 -0400413 tts.push(tt);
David Tolnay65729482017-12-31 16:14:50 -0500414 cursor = rest;
Michael Layzell2a60e252017-05-31 21:36:47 -0400415 }
416 tts.into_iter().collect()
417 }
418
David Tolnay7c3e77d2018-01-06 17:42:53 -0800419 /// If the cursor is pointing at a `TokenTree`, returns it along with a
420 /// cursor pointing at the next `TokenTree`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400421 ///
David Tolnay7c3e77d2018-01-06 17:42:53 -0800422 /// Returns `None` if the cursor has reached the end of its stream.
423 ///
424 /// This method does not treat `None`-delimited groups as transparent, and
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700425 /// will return a `Group(None, ..)` if the cursor is looking at one.
David Tolnay65729482017-12-31 16:14:50 -0500426 pub fn token_tree(self) -> Option<(TokenTree, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400427 let tree = match *self.entry() {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700428 Entry::Group(span, delim, ref buf) => {
Michael Layzell2a60e252017-05-31 21:36:47 -0400429 let stream = buf.begin().token_stream();
Alex Crichton9a4dca22018-03-28 06:32:19 -0700430 let mut g = Group::new(delim, stream);
431 g.set_span(span);
432 TokenTree::from(g)
Michael Layzell2a60e252017-05-31 21:36:47 -0400433 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700434 Entry::Literal(ref lit) => lit.clone().into(),
David Tolnaya4319b72018-06-02 00:49:15 -0700435 Entry::Ident(ref ident) => ident.clone().into(),
Alex Crichtona74a1c82018-05-16 10:20:44 -0700436 Entry::Punct(ref op) => op.clone().into(),
Michael Layzell2a60e252017-05-31 21:36:47 -0400437 Entry::End(..) => {
438 return None;
439 }
440 };
441
David Tolnay65729482017-12-31 16:14:50 -0500442 Some((tree, unsafe { self.bump() }))
Michael Layzell2a60e252017-05-31 21:36:47 -0400443 }
David Tolnay225efa22017-12-31 16:51:29 -0500444
445 /// Returns the `Span` of the current token, or `Span::call_site()` if this
446 /// cursor points to eof.
447 pub fn span(self) -> Span {
448 match *self.entry() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700449 Entry::Group(span, ..) => span,
450 Entry::Literal(ref l) => l.span(),
Alex Crichtona74a1c82018-05-16 10:20:44 -0700451 Entry::Ident(ref t) => t.span(),
452 Entry::Punct(ref o) => o.span(),
David Tolnay225efa22017-12-31 16:51:29 -0500453 Entry::End(..) => Span::call_site(),
454 }
455 }
Michael Layzell2a60e252017-05-31 21:36:47 -0400456}
457
458// We do a custom implementation for `Debug` as the default implementation is
459// pretty useless.
David Tolnayd1ec6ec2018-01-03 00:23:45 -0800460#[cfg(synom_verbose_trace)]
David Tolnayf9e1de12017-12-31 00:47:01 -0500461impl<'a> Debug for Cursor<'a> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400462 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Nika Layzellae81b372017-12-05 14:12:33 -0500463 // Print what the cursor is currently looking at.
464 // This will look like Cursor("some remaining tokens here")
465 f.debug_tuple("Cursor")
466 .field(&self.token_stream().to_string())
Michael Layzell2a60e252017-05-31 21:36:47 -0400467 .finish()
468 }
469}