blob: d92a7a66013e58cf64c630138e6d38acc6b3b536 [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//! ```
25//! #![feature(proc_macro)]
26//!
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
Kartikaya Gupta6434beb2018-02-22 17:07:00 -0500130#[cfg(feature = "proc-macro")]
David Tolnay7c3e77d2018-01-06 17:42:53 -0800131use proc_macro as pm;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700132use proc_macro2::{Delimiter, Literal, Span, Term, TokenStream};
133use proc_macro2::{Group, TokenTree, Op};
Michael Layzell2a60e252017-05-31 21:36:47 -0400134
135use std::ptr;
Michael Layzell2a60e252017-05-31 21:36:47 -0400136use std::marker::PhantomData;
137
David Tolnayd1ec6ec2018-01-03 00:23:45 -0800138#[cfg(synom_verbose_trace)]
David Tolnayf9e1de12017-12-31 00:47:01 -0500139use std::fmt::{self, Debug};
140
David Tolnay7c3e77d2018-01-06 17:42:53 -0800141/// Internal type which is used instead of `TokenTree` to represent a token tree
142/// within a `TokenBuffer`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400143enum Entry {
David Tolnay7c3e77d2018-01-06 17:42:53 -0800144 // Mimicking types from proc-macro.
David Tolnaydfc886b2018-01-06 08:03:09 -0800145 Group(Span, Delimiter, TokenBuffer),
Alex Crichton9a4dca22018-03-28 06:32:19 -0700146 Term(Term),
147 Op(Op),
148 Literal(Literal),
David Tolnay7c3e77d2018-01-06 17:42:53 -0800149 // End entries contain a raw pointer to the entry from the containing
150 // token tree, or null if this is the outermost level.
Michael Layzell2a60e252017-05-31 21:36:47 -0400151 End(*const Entry),
152}
153
David Tolnay7c3e77d2018-01-06 17:42:53 -0800154/// A buffer that can be efficiently traversed multiple times, unlike
155/// `TokenStream` which requires a deep copy in order to traverse more than
156/// once.
157///
158/// See the [module documentation] for an example of `TokenBuffer` in action.
159///
160/// [module documentation]: index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800161///
162/// *This type is available if Syn is built with the `"parsing"` feature.*
David Tolnaydfc886b2018-01-06 08:03:09 -0800163pub struct TokenBuffer {
Michael Layzell2a60e252017-05-31 21:36:47 -0400164 // NOTE: Do not derive clone on this - there are raw pointers inside which
David Tolnaydfc886b2018-01-06 08:03:09 -0800165 // will be messed up. Moving the `TokenBuffer` itself is safe as the actual
Michael Layzell2a60e252017-05-31 21:36:47 -0400166 // backing slices won't be moved.
167 data: Box<[Entry]>,
168}
169
David Tolnaydfc886b2018-01-06 08:03:09 -0800170impl TokenBuffer {
Michael Layzell2a60e252017-05-31 21:36:47 -0400171 // NOTE: DO NOT MUTATE THE `Vec` RETURNED FROM THIS FUNCTION ONCE IT
172 // RETURNS, THE ADDRESS OF ITS BACKING MEMORY MUST REMAIN STABLE.
David Tolnaydfc886b2018-01-06 08:03:09 -0800173 fn inner_new(stream: TokenStream, up: *const Entry) -> TokenBuffer {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700174 // Build up the entries list, recording the locations of any Groups
Michael Layzell2a60e252017-05-31 21:36:47 -0400175 // in the list to be processed later.
176 let mut entries = Vec::new();
177 let mut seqs = Vec::new();
David Tolnay50fa4682017-12-26 23:17:22 -0500178 for tt in stream {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700179 match tt {
180 TokenTree::Term(sym) => {
181 entries.push(Entry::Term(sym));
Michael Layzell2a60e252017-05-31 21:36:47 -0400182 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700183 TokenTree::Op(op) => {
184 entries.push(Entry::Op(op));
Michael Layzell2a60e252017-05-31 21:36:47 -0400185 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700186 TokenTree::Literal(l) => {
187 entries.push(Entry::Literal(l));
Michael Layzell2a60e252017-05-31 21:36:47 -0400188 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700189 TokenTree::Group(g) => {
Michael Layzell2a60e252017-05-31 21:36:47 -0400190 // Record the index of the interesting entry, and store an
191 // `End(null)` there temporarially.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700192 seqs.push((entries.len(), g.span(), g.delimiter(), g.stream().clone()));
Michael Layzell2a60e252017-05-31 21:36:47 -0400193 entries.push(Entry::End(ptr::null()));
194 }
195 }
196 }
197 // Add an `End` entry to the end with a reference to the enclosing token
198 // stream which was passed in.
199 entries.push(Entry::End(up));
200
201 // NOTE: This is done to ensure that we don't accidentally modify the
202 // length of the backing buffer. The backing buffer must remain at a
203 // constant address after this point, as we are going to store a raw
204 // pointer into it.
205 let mut entries = entries.into_boxed_slice();
206 for (idx, span, delim, seq_stream) in seqs {
207 // We know that this index refers to one of the temporary
208 // `End(null)` entries, and we know that the last entry is
209 // `End(up)`, so the next index is also valid.
210 let seq_up = &entries[idx + 1] as *const Entry;
211
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700212 // The end entry stored at the end of this Entry::Group should
213 // point to the Entry which follows the Group in the list.
Michael Layzell2a60e252017-05-31 21:36:47 -0400214 let inner = Self::inner_new(seq_stream, seq_up);
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700215 entries[idx] = Entry::Group(span, delim, inner);
Michael Layzell2a60e252017-05-31 21:36:47 -0400216 }
217
David Tolnaydfc886b2018-01-06 08:03:09 -0800218 TokenBuffer { data: entries }
Michael Layzell2a60e252017-05-31 21:36:47 -0400219 }
220
David Tolnay7c3e77d2018-01-06 17:42:53 -0800221 /// Creates a `TokenBuffer` containing all the tokens from the input
222 /// `TokenStream`.
Kartikaya Gupta6434beb2018-02-22 17:07:00 -0500223 #[cfg(feature = "proc-macro")]
David Tolnay7c3e77d2018-01-06 17:42:53 -0800224 pub fn new(stream: pm::TokenStream) -> TokenBuffer {
225 Self::new2(stream.into())
226 }
227
228 /// Creates a `TokenBuffer` containing all the tokens from the input
229 /// `TokenStream`.
230 pub fn new2(stream: TokenStream) -> TokenBuffer {
Michael Layzell2a60e252017-05-31 21:36:47 -0400231 Self::inner_new(stream, ptr::null())
232 }
233
David Tolnay7c3e77d2018-01-06 17:42:53 -0800234 /// Creates a cursor referencing the first token in the buffer and able to
235 /// traverse until the end of the buffer.
Michael Layzell2a60e252017-05-31 21:36:47 -0400236 pub fn begin(&self) -> Cursor {
David Tolnay51382052017-12-27 13:46:21 -0500237 unsafe { Cursor::create(&self.data[0], &self.data[self.data.len() - 1]) }
Michael Layzell2a60e252017-05-31 21:36:47 -0400238 }
239}
240
David Tolnay7c3e77d2018-01-06 17:42:53 -0800241/// A cheaply copyable cursor into a `TokenBuffer`.
242///
243/// This cursor holds a shared reference into the immutable data which is used
244/// internally to represent a `TokenStream`, and can be efficiently manipulated
245/// and copied around.
Michael Layzell2a60e252017-05-31 21:36:47 -0400246///
David Tolnaydfc886b2018-01-06 08:03:09 -0800247/// An empty `Cursor` can be created directly, or one may create a `TokenBuffer`
Michael Layzell2a60e252017-05-31 21:36:47 -0400248/// object and get a cursor to its first token with `begin()`.
249///
250/// Two cursors are equal if they have the same location in the same input
251/// stream, and have the same scope.
David Tolnay7c3e77d2018-01-06 17:42:53 -0800252///
253/// See the [module documentation] for an example of a `Cursor` in action.
254///
255/// [module documentation]: index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800256///
257/// *This type is available if Syn is built with the `"parsing"` feature.*
Michael Layzell2a60e252017-05-31 21:36:47 -0400258#[derive(Copy, Clone, Eq, PartialEq)]
259pub struct Cursor<'a> {
260 /// The current entry which the `Cursor` is pointing at.
261 ptr: *const Entry,
262 /// This is the only `Entry::End(..)` object which this cursor is allowed to
263 /// point at. All other `End` objects are skipped over in `Cursor::create`.
264 scope: *const Entry,
265 /// This uses the &'a reference which guarantees that these pointers are
266 /// still valid.
267 marker: PhantomData<&'a Entry>,
268}
269
Michael Layzell2a60e252017-05-31 21:36:47 -0400270impl<'a> Cursor<'a> {
David Tolnay7c3e77d2018-01-06 17:42:53 -0800271 /// Creates a cursor referencing a static empty TokenStream.
Michael Layzell2a60e252017-05-31 21:36:47 -0400272 pub fn empty() -> Self {
Michael Layzell69cf9082017-06-03 12:15:58 -0400273 // It's safe in this situation for us to put an `Entry` object in global
274 // storage, despite it not actually being safe to send across threads
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700275 // (`Term` is a reference into a thread-local table). This is because
276 // this entry never includes a `Term` object.
Michael Layzell69cf9082017-06-03 12:15:58 -0400277 //
278 // This wrapper struct allows us to break the rules and put a `Sync`
279 // object in global storage.
280 struct UnsafeSyncEntry(Entry);
281 unsafe impl Sync for UnsafeSyncEntry {}
David Tolnay51382052017-12-27 13:46:21 -0500282 static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0 as *const Entry));
Michael Layzell69cf9082017-06-03 12:15:58 -0400283
Michael Layzell2a60e252017-05-31 21:36:47 -0400284 Cursor {
Michael Layzell69cf9082017-06-03 12:15:58 -0400285 ptr: &EMPTY_ENTRY.0,
286 scope: &EMPTY_ENTRY.0,
Michael Layzell2a60e252017-05-31 21:36:47 -0400287 marker: PhantomData,
288 }
289 }
290
291 /// This create method intelligently exits non-explicitly-entered
292 /// `None`-delimited scopes when the cursor reaches the end of them,
293 /// allowing for them to be treated transparently.
294 unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self {
295 // NOTE: If we're looking at a `End(..)`, we want to advance the cursor
296 // past it, unless `ptr == scope`, which means that we're at the edge of
297 // our cursor's scope. We should only have `ptr != scope` at the exit
David Tolnayc10676a2017-12-27 23:42:36 -0500298 // from None-delimited groups entered with `ignore_none`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400299 while let Entry::End(exit) = *ptr {
300 if ptr == scope {
301 break;
302 }
303 ptr = exit;
304 }
305
306 Cursor {
307 ptr: ptr,
308 scope: scope,
309 marker: PhantomData,
310 }
311 }
312
313 /// Get the current entry.
314 fn entry(self) -> &'a Entry {
315 unsafe { &*self.ptr }
316 }
317
318 /// Bump the cursor to point at the next token after the current one. This
319 /// is undefined behavior if the cursor is currently looking at an
320 /// `Entry::End`.
321 unsafe fn bump(self) -> Cursor<'a> {
322 Cursor::create(self.ptr.offset(1), self.scope)
323 }
324
David Tolnayc10676a2017-12-27 23:42:36 -0500325 /// If the cursor is looking at a `None`-delimited group, move it to look at
326 /// the first token inside instead. If the group is empty, this will move
327 /// the cursor past the `None`-delimited group.
Michael Layzell2a60e252017-05-31 21:36:47 -0400328 ///
329 /// WARNING: This mutates its argument.
330 fn ignore_none(&mut self) {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700331 if let Entry::Group(_, Delimiter::None, ref buf) = *self.entry() {
Michael Layzell2a60e252017-05-31 21:36:47 -0400332 // NOTE: We call `Cursor::create` here to make sure that situations
333 // where we should immediately exit the span after entering it are
334 // handled correctly.
335 unsafe {
336 *self = Cursor::create(&buf.data[0], self.scope);
337 }
338 }
339 }
340
David Tolnay7c3e77d2018-01-06 17:42:53 -0800341 /// Checks whether the cursor is currently pointing at the end of its valid
342 /// scope.
Michael Layzell2a60e252017-05-31 21:36:47 -0400343 #[inline]
344 pub fn eof(self) -> bool {
345 // We're at eof if we're at the end of our scope.
346 self.ptr == self.scope
347 }
348
David Tolnay7c3e77d2018-01-06 17:42:53 -0800349 /// If the cursor is pointing at a `Group` with the given delimiter, returns
350 /// a cursor into that group and one pointing to the next `TokenTree`.
David Tolnay65729482017-12-31 16:14:50 -0500351 pub fn group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, Span, Cursor<'a>)> {
David Tolnayc10676a2017-12-27 23:42:36 -0500352 // If we're not trying to enter a none-delimited group, we want to
Michael Layzell2a60e252017-05-31 21:36:47 -0400353 // ignore them. We have to make sure to _not_ ignore them when we want
354 // to enter them, of course. For obvious reasons.
David Tolnayc10676a2017-12-27 23:42:36 -0500355 if delim != Delimiter::None {
Michael Layzell2a60e252017-05-31 21:36:47 -0400356 self.ignore_none();
357 }
358
David Tolnayc10676a2017-12-27 23:42:36 -0500359 if let Entry::Group(span, group_delim, ref buf) = *self.entry() {
360 if group_delim == delim {
David Tolnay65729482017-12-31 16:14:50 -0500361 return Some((buf.begin(), span, unsafe { self.bump() }));
Michael Layzell2a60e252017-05-31 21:36:47 -0400362 }
Michael Layzell2a60e252017-05-31 21:36:47 -0400363 }
David Tolnayc10676a2017-12-27 23:42:36 -0500364
365 None
Michael Layzell2a60e252017-05-31 21:36:47 -0400366 }
367
David Tolnay7c3e77d2018-01-06 17:42:53 -0800368 /// If the cursor is pointing at a `Term`, returns it along with a cursor
369 /// pointing at the next `TokenTree`.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700370 pub fn term(mut self) -> Option<(Term, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400371 self.ignore_none();
372 match *self.entry() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700373 Entry::Term(term) => Some((term, unsafe { self.bump() })),
David Tolnay51382052017-12-27 13:46:21 -0500374 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400375 }
376 }
377
David Tolnay7c3e77d2018-01-06 17:42:53 -0800378 /// If the cursor is pointing at an `Op`, returns it along with a cursor
379 /// pointing at the next `TokenTree`.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700380 pub fn op(mut self) -> Option<(Op, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400381 self.ignore_none();
382 match *self.entry() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700383 Entry::Op(op) => Some((op, unsafe { self.bump() })),
David Tolnay51382052017-12-27 13:46:21 -0500384 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400385 }
386 }
387
David Tolnay7c3e77d2018-01-06 17:42:53 -0800388 /// If the cursor is pointing at a `Literal`, return it along with a cursor
389 /// pointing at the next `TokenTree`.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700390 pub fn literal(mut self) -> Option<(Literal, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400391 self.ignore_none();
392 match *self.entry() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700393 Entry::Literal(ref lit) => Some((lit.clone(), unsafe { self.bump() })),
David Tolnay51382052017-12-27 13:46:21 -0500394 _ => None,
Michael Layzell2a60e252017-05-31 21:36:47 -0400395 }
396 }
397
David Tolnay7c3e77d2018-01-06 17:42:53 -0800398 /// Copies all remaining tokens visible from this cursor into a
399 /// `TokenStream`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400400 pub fn token_stream(self) -> TokenStream {
401 let mut tts = Vec::new();
402 let mut cursor = self;
David Tolnay65729482017-12-31 16:14:50 -0500403 while let Some((tt, rest)) = cursor.token_tree() {
Michael Layzell2a60e252017-05-31 21:36:47 -0400404 tts.push(tt);
David Tolnay65729482017-12-31 16:14:50 -0500405 cursor = rest;
Michael Layzell2a60e252017-05-31 21:36:47 -0400406 }
407 tts.into_iter().collect()
408 }
409
David Tolnay7c3e77d2018-01-06 17:42:53 -0800410 /// If the cursor is pointing at a `TokenTree`, returns it along with a
411 /// cursor pointing at the next `TokenTree`.
Michael Layzell2a60e252017-05-31 21:36:47 -0400412 ///
David Tolnay7c3e77d2018-01-06 17:42:53 -0800413 /// Returns `None` if the cursor has reached the end of its stream.
414 ///
415 /// This method does not treat `None`-delimited groups as transparent, and
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700416 /// will return a `Group(None, ..)` if the cursor is looking at one.
David Tolnay65729482017-12-31 16:14:50 -0500417 pub fn token_tree(self) -> Option<(TokenTree, Cursor<'a>)> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400418 let tree = match *self.entry() {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700419 Entry::Group(span, delim, ref buf) => {
Michael Layzell2a60e252017-05-31 21:36:47 -0400420 let stream = buf.begin().token_stream();
Alex Crichton9a4dca22018-03-28 06:32:19 -0700421 let mut g = Group::new(delim, stream);
422 g.set_span(span);
423 TokenTree::from(g)
Michael Layzell2a60e252017-05-31 21:36:47 -0400424 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700425 Entry::Literal(ref lit) => lit.clone().into(),
426 Entry::Term(term) => term.into(),
427 Entry::Op(op) => op.into(),
Michael Layzell2a60e252017-05-31 21:36:47 -0400428 Entry::End(..) => {
429 return None;
430 }
431 };
432
David Tolnay65729482017-12-31 16:14:50 -0500433 Some((tree, unsafe { self.bump() }))
Michael Layzell2a60e252017-05-31 21:36:47 -0400434 }
David Tolnay225efa22017-12-31 16:51:29 -0500435
436 /// Returns the `Span` of the current token, or `Span::call_site()` if this
437 /// cursor points to eof.
438 pub fn span(self) -> Span {
439 match *self.entry() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700440 Entry::Group(span, ..) => span,
441 Entry::Literal(ref l) => l.span(),
442 Entry::Term(t) => t.span(),
443 Entry::Op(o) => o.span(),
David Tolnay225efa22017-12-31 16:51:29 -0500444 Entry::End(..) => Span::call_site(),
445 }
446 }
Michael Layzell2a60e252017-05-31 21:36:47 -0400447}
448
449// We do a custom implementation for `Debug` as the default implementation is
450// pretty useless.
David Tolnayd1ec6ec2018-01-03 00:23:45 -0800451#[cfg(synom_verbose_trace)]
David Tolnayf9e1de12017-12-31 00:47:01 -0500452impl<'a> Debug for Cursor<'a> {
Michael Layzell2a60e252017-05-31 21:36:47 -0400453 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Nika Layzellae81b372017-12-05 14:12:33 -0500454 // Print what the cursor is currently looking at.
455 // This will look like Cursor("some remaining tokens here")
456 f.debug_tuple("Cursor")
457 .field(&self.token_stream().to_string())
Michael Layzell2a60e252017-05-31 21:36:47 -0400458 .finish()
459 }
460}