blob: e9428ed95b3f6da55a60fa52b87d62971ad559d1 [file] [log] [blame]
David Tolnay80a914f2018-08-30 23:49:53 -07001// 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 Tolnay18c754c2018-08-21 23:26:58 -04009//! Parsing interface for parsing a token stream into a syntax tree node.
David Tolnay80a914f2018-08-30 23:49:53 -070010//!
David Tolnaye0c51762018-08-31 11:05:22 -070011//! Parsing in Syn is built on parser functions that take in a [`ParseStream`]
12//! and produce a [`Result<T>`] where `T` is some syntax tree node. Underlying
13//! these parser functions is a lower level mechanism built around the
14//! [`Cursor`] type. `Cursor` is a cheaply copyable cursor over a range of
15//! tokens in a token stream.
David Tolnay80a914f2018-08-30 23:49:53 -070016//!
David Tolnaye0c51762018-08-31 11:05:22 -070017//! [`ParseStream`]: type.ParseStream.html
18//! [`Result<T>`]: type.Result.html
David Tolnay80a914f2018-08-30 23:49:53 -070019//! [`Cursor`]: ../buffer/index.html
David Tolnay80a914f2018-08-30 23:49:53 -070020//!
David Tolnay43984452018-09-01 17:43:56 -070021//! # Example
David Tolnay80a914f2018-08-30 23:49:53 -070022//!
David Tolnay43984452018-09-01 17:43:56 -070023//! Here is a snippet of parsing code to get a feel for the style of the
24//! library. We define data structures for a subset of Rust syntax including
25//! enums (not shown) and structs, then provide implementations of the [`Parse`]
26//! trait to parse these syntax tree data structures from a token stream.
27//!
David Tolnay88d9f622018-09-01 17:52:33 -070028//! Once `Parse` impls have been defined, they can be called conveniently from a
David Tolnay8e6096a2018-09-06 02:14:47 -070029//! procedural macro through [`parse_macro_input!`] as shown at the bottom of
30//! the snippet. If the caller provides syntactically invalid input to the
31//! procedural macro, they will receive a helpful compiler error message
32//! pointing out the exact token that triggered the failure to parse.
33//!
34//! [`parse_macro_input!`]: ../macro.parse_macro_input.html
David Tolnay88d9f622018-09-01 17:52:33 -070035//!
David Tolnay43984452018-09-01 17:43:56 -070036//! ```
David Tolnaya1c98072018-09-06 08:58:10 -070037//! #[macro_use]
38//! extern crate syn;
39//!
40//! extern crate proc_macro;
41//!
David Tolnay88d9f622018-09-01 17:52:33 -070042//! use proc_macro::TokenStream;
David Tolnaya1c98072018-09-06 08:58:10 -070043//! use syn::{token, Field, Ident};
David Tolnay43984452018-09-01 17:43:56 -070044//! use syn::parse::{Parse, ParseStream, Result};
45//! use syn::punctuated::Punctuated;
46//!
47//! enum Item {
48//! Struct(ItemStruct),
49//! Enum(ItemEnum),
50//! }
51//!
52//! struct ItemStruct {
53//! struct_token: Token![struct],
54//! ident: Ident,
55//! brace_token: token::Brace,
56//! fields: Punctuated<Field, Token![,]>,
57//! }
58//! #
59//! # enum ItemEnum {}
60//!
61//! impl Parse for Item {
62//! fn parse(input: ParseStream) -> Result<Self> {
63//! let lookahead = input.lookahead1();
64//! if lookahead.peek(Token![struct]) {
65//! input.parse().map(Item::Struct)
66//! } else if lookahead.peek(Token![enum]) {
67//! input.parse().map(Item::Enum)
68//! } else {
69//! Err(lookahead.error())
70//! }
71//! }
72//! }
73//!
74//! impl Parse for ItemStruct {
75//! fn parse(input: ParseStream) -> Result<Self> {
76//! let content;
77//! Ok(ItemStruct {
78//! struct_token: input.parse()?,
79//! ident: input.parse()?,
80//! brace_token: braced!(content in input),
81//! fields: content.parse_terminated(Field::parse_named)?,
82//! })
83//! }
84//! }
85//! #
86//! # impl Parse for ItemEnum {
87//! # fn parse(input: ParseStream) -> Result<Self> {
88//! # unimplemented!()
89//! # }
90//! # }
David Tolnay88d9f622018-09-01 17:52:33 -070091//!
92//! # const IGNORE: &str = stringify! {
93//! #[proc_macro]
94//! # };
95//! pub fn my_macro(tokens: TokenStream) -> TokenStream {
96//! let input = parse_macro_input!(tokens as Item);
97//!
98//! /* ... */
99//! # "".parse().unwrap()
100//! }
101//! #
102//! # fn main() {}
David Tolnay43984452018-09-01 17:43:56 -0700103//! ```
104//!
105//! # The `syn::parse*` functions
David Tolnay80a914f2018-08-30 23:49:53 -0700106//!
107//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
108//! as an entry point for parsing syntax tree nodes that can be parsed in an
109//! obvious default way. These functions can return any syntax tree node that
David Tolnay8aacee12018-08-31 09:15:15 -0700110//! implements the [`Parse`] trait, which includes most types in Syn.
David Tolnay80a914f2018-08-30 23:49:53 -0700111//!
112//! [`syn::parse`]: ../fn.parse.html
113//! [`syn::parse2`]: ../fn.parse2.html
114//! [`syn::parse_str`]: ../fn.parse_str.html
David Tolnay8aacee12018-08-31 09:15:15 -0700115//! [`Parse`]: trait.Parse.html
David Tolnay80a914f2018-08-30 23:49:53 -0700116//!
117//! ```
118//! use syn::Type;
119//!
David Tolnay8aacee12018-08-31 09:15:15 -0700120//! # fn run_parser() -> Result<(), syn::parse::Error> {
David Tolnay80a914f2018-08-30 23:49:53 -0700121//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
122//! # Ok(())
123//! # }
124//! #
125//! # fn main() {
126//! # run_parser().unwrap();
127//! # }
128//! ```
129//!
130//! The [`parse_quote!`] macro also uses this approach.
131//!
132//! [`parse_quote!`]: ../macro.parse_quote.html
133//!
David Tolnay43984452018-09-01 17:43:56 -0700134//! # The `Parser` trait
David Tolnay80a914f2018-08-30 23:49:53 -0700135//!
136//! Some types can be parsed in several ways depending on context. For example
137//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
138//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
139//! may or may not allow trailing punctuation, and parsing it the wrong way
140//! would either reject valid input or accept invalid input.
141//!
142//! [`Attribute`]: ../struct.Attribute.html
143//! [`Punctuated`]: ../punctuated/index.html
144//!
David Tolnaye0c51762018-08-31 11:05:22 -0700145//! The `Parse` trait is not implemented in these cases because there is no good
David Tolnay80a914f2018-08-30 23:49:53 -0700146//! behavior to consider the default.
147//!
148//! ```ignore
149//! // Can't parse `Punctuated` without knowing whether trailing punctuation
150//! // should be allowed in this context.
151//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
152//! ```
153//!
154//! In these cases the types provide a choice of parser functions rather than a
David Tolnaye0c51762018-08-31 11:05:22 -0700155//! single `Parse` implementation, and those parser functions can be invoked
David Tolnay80a914f2018-08-30 23:49:53 -0700156//! through the [`Parser`] trait.
157//!
158//! [`Parser`]: trait.Parser.html
159//!
160//! ```
David Tolnaya1c98072018-09-06 08:58:10 -0700161//! #[macro_use]
162//! extern crate syn;
163//!
164//! extern crate proc_macro2;
165//!
166//! use proc_macro2::TokenStream;
David Tolnay3e3f7752018-08-31 09:33:59 -0700167//! use syn::parse::Parser;
David Tolnay80a914f2018-08-30 23:49:53 -0700168//! use syn::punctuated::Punctuated;
David Tolnaya1c98072018-09-06 08:58:10 -0700169//! use syn::{Attribute, Expr, PathSegment};
David Tolnay80a914f2018-08-30 23:49:53 -0700170//!
David Tolnay3e3f7752018-08-31 09:33:59 -0700171//! # fn run_parsers() -> Result<(), syn::parse::Error> {
David Tolnay80a914f2018-08-30 23:49:53 -0700172//! # let tokens = TokenStream::new().into();
173//! // Parse a nonempty sequence of path segments separated by `::` punctuation
174//! // with no trailing punctuation.
175//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
176//! let path = parser.parse(tokens)?;
177//!
178//! # let tokens = TokenStream::new().into();
179//! // Parse a possibly empty sequence of expressions terminated by commas with
180//! // an optional trailing punctuation.
181//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
182//! let args = parser.parse(tokens)?;
183//!
184//! # let tokens = TokenStream::new().into();
185//! // Parse zero or more outer attributes but not inner attributes.
David Tolnay3e3f7752018-08-31 09:33:59 -0700186//! let parser = Attribute::parse_outer;
187//! let attrs = parser.parse(tokens)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700188//! #
189//! # Ok(())
190//! # }
191//! #
192//! # fn main() {}
193//! ```
194//!
David Tolnaye0c51762018-08-31 11:05:22 -0700195//! ---
David Tolnay80a914f2018-08-30 23:49:53 -0700196//!
197//! *This module is available if Syn is built with the `"parsing"` feature.*
David Tolnay18c754c2018-08-21 23:26:58 -0400198
199use std::cell::Cell;
200use std::fmt::Display;
201use std::marker::PhantomData;
202use std::mem;
203use std::ops::Deref;
David Tolnayeafc8052018-08-25 16:33:53 -0400204use std::rc::Rc;
David Tolnay80a914f2018-08-30 23:49:53 -0700205use std::str::FromStr;
David Tolnayeafc8052018-08-25 16:33:53 -0400206
David Tolnay80a914f2018-08-30 23:49:53 -0700207#[cfg(all(
208 not(all(target_arch = "wasm32", target_os = "unknown")),
209 feature = "proc-macro"
210))]
211use proc_macro;
David Tolnayf07b3342018-09-01 11:58:11 -0700212use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
David Tolnay18c754c2018-08-21 23:26:58 -0400213
David Tolnay80a914f2018-08-30 23:49:53 -0700214use buffer::{Cursor, TokenBuffer};
David Tolnayb6254182018-08-25 08:44:54 -0400215use error;
David Tolnay94f06632018-08-31 10:17:17 -0700216use lookahead;
217use private;
David Tolnay577d0332018-08-25 21:45:24 -0400218use punctuated::Punctuated;
David Tolnay4fb71232018-08-25 23:14:50 -0400219use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -0400220
David Tolnayb6254182018-08-25 08:44:54 -0400221pub use error::{Error, Result};
222pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -0400223
224/// Parsing interface implemented by all types that can be parsed in a default
225/// way from a token stream.
226pub trait Parse: Sized {
227 fn parse(input: ParseStream) -> Result<Self>;
228}
229
230/// Input to a Syn parser function.
David Tolnaya0daa482018-09-01 02:09:40 -0700231///
232/// See the methods of this type under the documentation of [`ParseBuffer`]. For
233/// an overview of parsing in Syn, refer to the [module documentation].
234///
235/// [module documentation]: index.html
David Tolnay18c754c2018-08-21 23:26:58 -0400236pub type ParseStream<'a> = &'a ParseBuffer<'a>;
237
238/// Cursor position within a buffered token stream.
David Tolnay20d29a12018-09-01 15:15:33 -0700239///
240/// This type is more commonly used through the type alias [`ParseStream`] which
241/// is an alias for `&ParseBuffer`.
242///
243/// `ParseStream` is the input type for all parser functions in Syn. They have
244/// the signature `fn(ParseStream) -> Result<T>`.
David Tolnay18c754c2018-08-21 23:26:58 -0400245pub struct ParseBuffer<'a> {
246 scope: Span,
David Tolnay5d7f2252018-09-02 08:21:40 -0700247 // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
248 // The rest of the code in this module needs to be careful that only a
249 // cursor derived from this `cell` is ever assigned to this `cell`.
250 //
251 // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
252 // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
253 // than 'a, and then assign a Cursor<'short> into the Cell.
254 //
255 // By extension, it would not be safe to expose an API that accepts a
256 // Cursor<'a> and trusts that it lives as long as the cursor currently in
257 // the cell.
David Tolnay18c754c2018-08-21 23:26:58 -0400258 cell: Cell<Cursor<'static>>,
259 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400260 unexpected: Rc<Cell<Option<Span>>>,
261}
262
263impl<'a> Drop for ParseBuffer<'a> {
264 fn drop(&mut self) {
265 if !self.is_empty() && self.unexpected.get().is_none() {
266 self.unexpected.set(Some(self.cursor().span()));
267 }
268 }
David Tolnay18c754c2018-08-21 23:26:58 -0400269}
270
David Tolnay642832f2018-09-01 13:08:10 -0700271/// Cursor state associated with speculative parsing.
272///
273/// This type is the input of the closure provided to [`ParseStream::step`].
274///
275/// [`ParseStream::step`]: struct.ParseBuffer.html#method.step
David Tolnay9bd34392018-09-01 13:19:53 -0700276///
277/// # Example
278///
279/// ```
280/// # extern crate proc_macro2;
281/// # extern crate syn;
282/// #
283/// use proc_macro2::TokenTree;
284/// use syn::parse::{ParseStream, Result};
285///
286/// // This function advances the stream past the next occurrence of `@`. If
287/// // no `@` is present in the stream, the stream position is unchanged and
288/// // an error is returned.
289/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
290/// input.step(|cursor| {
291/// let mut rest = *cursor;
Sharad Chande1df40a2018-09-08 15:25:52 +0545292/// while let Some((tt, next)) = rest.token_tree() {
David Tolnay9bd34392018-09-01 13:19:53 -0700293/// match tt {
294/// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
295/// return Ok(((), next));
296/// }
297/// _ => rest = next,
298/// }
299/// }
300/// Err(cursor.error("no `@` was found after this point"))
301/// })
302/// }
303/// #
304/// # fn main() {}
305/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400306#[derive(Copy, Clone)]
307pub struct StepCursor<'c, 'a> {
308 scope: Span,
David Tolnay56924f42018-09-02 08:24:58 -0700309 // This field is covariant in 'c.
David Tolnay18c754c2018-08-21 23:26:58 -0400310 cursor: Cursor<'c>,
David Tolnay56924f42018-09-02 08:24:58 -0700311 // This field is contravariant in 'c. Together these make StepCursor
312 // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
313 // different lifetime but can upcast into a StepCursor with a shorter
314 // lifetime 'a.
315 //
316 // As long as we only ever construct a StepCursor for which 'c outlives 'a,
317 // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
318 // outlives 'a.
David Tolnay18c754c2018-08-21 23:26:58 -0400319 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
320}
321
322impl<'c, 'a> Deref for StepCursor<'c, 'a> {
323 type Target = Cursor<'c>;
324
325 fn deref(&self) -> &Self::Target {
326 &self.cursor
327 }
328}
329
330impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700331 /// Triggers an error at the current position of the parse stream.
332 ///
333 /// The `ParseStream::step` invocation will return this same error without
334 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400335 pub fn error<T: Display>(self, message: T) -> Error {
336 error::new_at(self.scope, self.cursor, message)
337 }
338}
339
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700340impl private {
341 pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
David Tolnay56924f42018-09-02 08:24:58 -0700342 // Refer to the comments within the StepCursor definition. We use the
343 // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
344 // Cursor is covariant in its lifetime parameter so we can cast a
345 // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700346 let _ = proof;
347 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
348 }
349}
350
David Tolnay66cb0c42018-08-31 09:01:30 -0700351fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700352 input
353 .step(|cursor| {
354 if let Some((_lifetime, rest)) = cursor.lifetime() {
355 Ok((true, rest))
356 } else if let Some((_token, rest)) = cursor.token_tree() {
357 Ok((true, rest))
358 } else {
359 Ok((false, *cursor))
360 }
361 }).unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700362}
363
David Tolnay10951d52018-08-31 10:27:39 -0700364impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700365 pub fn new_parse_buffer(
366 scope: Span,
367 cursor: Cursor,
368 unexpected: Rc<Cell<Option<Span>>>,
369 ) -> ParseBuffer {
David Tolnay18c754c2018-08-21 23:26:58 -0400370 ParseBuffer {
371 scope: scope,
David Tolnay5d7f2252018-09-02 08:21:40 -0700372 // See comment on `cell` in the struct definition.
373 cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
David Tolnay18c754c2018-08-21 23:26:58 -0400374 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400375 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400376 }
377 }
378
David Tolnay94f06632018-08-31 10:17:17 -0700379 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
380 buffer.unexpected.clone()
381 }
382}
383
384impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700385 /// Parses a syntax tree node of type `T`, advancing the position of our
386 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400387 pub fn parse<T: Parse>(&self) -> Result<T> {
388 T::parse(self)
389 }
390
David Tolnay725e1c62018-09-01 12:07:25 -0700391 /// Calls the given parser function to parse a syntax tree node of type `T`
392 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700393 ///
394 /// # Example
395 ///
396 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
397 /// zero or more outer attributes.
398 ///
399 /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
400 ///
401 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700402 /// #[macro_use]
403 /// extern crate syn;
404 ///
405 /// use syn::{Attribute, Ident};
David Tolnay21ce84c2018-09-01 15:37:51 -0700406 /// use syn::parse::{Parse, ParseStream, Result};
407 ///
408 /// // Parses a unit struct with attributes.
409 /// //
410 /// // #[path = "s.tmpl"]
411 /// // struct S;
412 /// struct UnitStruct {
413 /// attrs: Vec<Attribute>,
414 /// struct_token: Token![struct],
415 /// name: Ident,
416 /// semi_token: Token![;],
417 /// }
418 ///
419 /// impl Parse for UnitStruct {
420 /// fn parse(input: ParseStream) -> Result<Self> {
421 /// Ok(UnitStruct {
422 /// attrs: input.call(Attribute::parse_outer)?,
423 /// struct_token: input.parse()?,
424 /// name: input.parse()?,
425 /// semi_token: input.parse()?,
426 /// })
427 /// }
428 /// }
429 /// #
430 /// # fn main() {}
431 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400432 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
433 function(self)
434 }
435
David Tolnay725e1c62018-09-01 12:07:25 -0700436 /// Looks at the next token in the parse stream to determine whether it
437 /// matches the requested type of token.
438 ///
439 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700440 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700441 /// # Syntax
442 ///
443 /// Note that this method does not use turbofish syntax. Pass the peek type
444 /// inside of parentheses.
445 ///
446 /// - `input.peek(Token![struct])`
447 /// - `input.peek(Token![==])`
448 /// - `input.peek(Ident)`
449 /// - `input.peek(Lifetime)`
450 /// - `input.peek(token::Brace)`
451 ///
David Tolnayddebc3e2018-09-01 16:29:20 -0700452 /// # Example
453 ///
454 /// In this example we finish parsing the list of supertraits when the next
455 /// token in the input is either `where` or an opening curly brace.
456 ///
457 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700458 /// #[macro_use]
459 /// extern crate syn;
460 ///
461 /// use syn::{token, Generics, Ident, TypeParamBound};
David Tolnayddebc3e2018-09-01 16:29:20 -0700462 /// use syn::parse::{Parse, ParseStream, Result};
463 /// use syn::punctuated::Punctuated;
464 ///
465 /// // Parses a trait definition containing no associated items.
466 /// //
467 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
468 /// struct MarkerTrait {
469 /// trait_token: Token![trait],
470 /// ident: Ident,
471 /// generics: Generics,
472 /// colon_token: Option<Token![:]>,
473 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
474 /// brace_token: token::Brace,
475 /// }
476 ///
477 /// impl Parse for MarkerTrait {
478 /// fn parse(input: ParseStream) -> Result<Self> {
479 /// let trait_token: Token![trait] = input.parse()?;
480 /// let ident: Ident = input.parse()?;
481 /// let mut generics: Generics = input.parse()?;
482 /// let colon_token: Option<Token![:]> = input.parse()?;
483 ///
484 /// let mut supertraits = Punctuated::new();
485 /// if colon_token.is_some() {
486 /// loop {
487 /// supertraits.push_value(input.parse()?);
488 /// if input.peek(Token![where]) || input.peek(token::Brace) {
489 /// break;
490 /// }
491 /// supertraits.push_punct(input.parse()?);
492 /// }
493 /// }
494 ///
495 /// generics.where_clause = input.parse()?;
496 /// let content;
497 /// let empty_brace_token = braced!(content in input);
498 ///
499 /// Ok(MarkerTrait {
500 /// trait_token: trait_token,
501 /// ident: ident,
502 /// generics: generics,
503 /// colon_token: colon_token,
504 /// supertraits: supertraits,
505 /// brace_token: empty_brace_token,
506 /// })
507 /// }
508 /// }
509 /// #
510 /// # fn main() {}
511 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400512 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700513 let _ = token;
514 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400515 }
516
David Tolnay725e1c62018-09-01 12:07:25 -0700517 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700518 ///
519 /// This is commonly useful as a way to implement contextual keywords.
520 ///
521 /// # Example
522 ///
523 /// This example needs to use `peek2` because the symbol `union` is not a
524 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
525 /// the very next token is `union`, because someone is free to write a `mod
526 /// union` and a macro invocation that looks like `union::some_macro! { ...
527 /// }`. In other words `union` is a contextual keyword.
528 ///
529 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700530 /// #[macro_use]
531 /// extern crate syn;
532 ///
533 /// use syn::{Ident, ItemUnion, Macro};
David Tolnaye334b872018-09-01 16:38:10 -0700534 /// use syn::parse::{Parse, ParseStream, Result};
535 ///
536 /// // Parses either a union or a macro invocation.
537 /// enum UnionOrMacro {
538 /// // union MaybeUninit<T> { uninit: (), value: T }
539 /// Union(ItemUnion),
540 /// // lazy_static! { ... }
541 /// Macro(Macro),
542 /// }
543 ///
544 /// impl Parse for UnionOrMacro {
545 /// fn parse(input: ParseStream) -> Result<Self> {
546 /// if input.peek(Token![union]) && input.peek2(Ident) {
547 /// input.parse().map(UnionOrMacro::Union)
548 /// } else {
549 /// input.parse().map(UnionOrMacro::Macro)
550 /// }
551 /// }
552 /// }
553 /// #
554 /// # fn main() {}
555 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400556 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400557 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700558 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400559 }
560
David Tolnay725e1c62018-09-01 12:07:25 -0700561 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400562 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400563 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700564 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400565 }
566
David Tolnay725e1c62018-09-01 12:07:25 -0700567 /// Parses zero or more occurrences of `T` separated by punctuation of type
568 /// `P`, with optional trailing punctuation.
569 ///
570 /// Parsing continues until the end of this parse stream. The entire content
571 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700572 ///
573 /// # Example
574 ///
575 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700576 /// # #[macro_use]
David Tolnay0abe65b2018-09-01 14:31:43 -0700577 /// # extern crate quote;
David Tolnay0abe65b2018-09-01 14:31:43 -0700578 /// #
David Tolnaya1c98072018-09-06 08:58:10 -0700579 /// #[macro_use]
580 /// extern crate syn;
581 ///
582 /// use syn::{token, Ident, Type};
David Tolnay0abe65b2018-09-01 14:31:43 -0700583 /// use syn::parse::{Parse, ParseStream, Result};
584 /// use syn::punctuated::Punctuated;
585 ///
586 /// // Parse a simplified tuple struct syntax like:
587 /// //
588 /// // struct S(A, B);
589 /// struct TupleStruct {
590 /// struct_token: Token![struct],
591 /// ident: Ident,
592 /// paren_token: token::Paren,
593 /// fields: Punctuated<Type, Token![,]>,
594 /// semi_token: Token![;],
595 /// }
596 ///
597 /// impl Parse for TupleStruct {
598 /// fn parse(input: ParseStream) -> Result<Self> {
599 /// let content;
600 /// Ok(TupleStruct {
601 /// struct_token: input.parse()?,
602 /// ident: input.parse()?,
603 /// paren_token: parenthesized!(content in input),
604 /// fields: content.parse_terminated(Type::parse)?,
605 /// semi_token: input.parse()?,
606 /// })
607 /// }
608 /// }
609 /// #
610 /// # fn main() {
611 /// # let input = quote! {
612 /// # struct S(A, B);
613 /// # };
614 /// # syn::parse2::<TupleStruct>(input).unwrap();
615 /// # }
616 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400617 pub fn parse_terminated<T, P: Parse>(
618 &self,
619 parser: fn(ParseStream) -> Result<T>,
620 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700621 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400622 }
623
David Tolnay725e1c62018-09-01 12:07:25 -0700624 /// Returns whether there are tokens remaining in this stream.
625 ///
626 /// This method returns true at the end of the content of a set of
627 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700628 ///
629 /// # Example
630 ///
631 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700632 /// #[macro_use]
633 /// extern crate syn;
634 ///
635 /// use syn::{token, Ident, Item};
David Tolnaycce6b5f2018-09-01 14:24:46 -0700636 /// use syn::parse::{Parse, ParseStream, Result};
637 ///
638 /// // Parses a Rust `mod m { ... }` containing zero or more items.
639 /// struct Mod {
640 /// mod_token: Token![mod],
641 /// name: Ident,
642 /// brace_token: token::Brace,
643 /// items: Vec<Item>,
644 /// }
645 ///
646 /// impl Parse for Mod {
647 /// fn parse(input: ParseStream) -> Result<Self> {
648 /// let content;
649 /// Ok(Mod {
650 /// mod_token: input.parse()?,
651 /// name: input.parse()?,
652 /// brace_token: braced!(content in input),
653 /// items: {
654 /// let mut items = Vec::new();
655 /// while !content.is_empty() {
656 /// items.push(content.parse()?);
657 /// }
658 /// items
659 /// },
660 /// })
661 /// }
662 /// }
663 /// #
664 /// # fn main() {}
David Tolnayf5d30452018-09-01 02:29:04 -0700665 pub fn is_empty(&self) -> bool {
666 self.cursor().eof()
667 }
668
David Tolnay725e1c62018-09-01 12:07:25 -0700669 /// Constructs a helper for peeking at the next token in this stream and
670 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700671 ///
672 /// # Example
673 ///
674 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700675 /// #[macro_use]
676 /// extern crate syn;
677 ///
678 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, TypeParam};
David Tolnay2c77e772018-09-01 14:18:46 -0700679 /// use syn::parse::{Parse, ParseStream, Result};
680 ///
681 /// // A generic parameter, a single one of the comma-separated elements inside
682 /// // angle brackets in:
683 /// //
684 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
685 /// //
686 /// // On invalid input, lookahead gives us a reasonable error message.
687 /// //
688 /// // error: expected one of: identifier, lifetime, `const`
689 /// // |
690 /// // 5 | fn f<!Sized>() {}
691 /// // | ^
692 /// enum GenericParam {
693 /// Type(TypeParam),
694 /// Lifetime(LifetimeDef),
695 /// Const(ConstParam),
696 /// }
697 ///
698 /// impl Parse for GenericParam {
699 /// fn parse(input: ParseStream) -> Result<Self> {
700 /// let lookahead = input.lookahead1();
701 /// if lookahead.peek(Ident) {
702 /// input.parse().map(GenericParam::Type)
703 /// } else if lookahead.peek(Lifetime) {
704 /// input.parse().map(GenericParam::Lifetime)
705 /// } else if lookahead.peek(Token![const]) {
706 /// input.parse().map(GenericParam::Const)
707 /// } else {
708 /// Err(lookahead.error())
709 /// }
710 /// }
711 /// }
712 /// #
713 /// # fn main() {}
714 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700715 pub fn lookahead1(&self) -> Lookahead1<'a> {
716 lookahead::new(self.scope, self.cursor())
717 }
718
David Tolnay725e1c62018-09-01 12:07:25 -0700719 /// Forks a parse stream so that parsing tokens out of either the original
720 /// or the fork does not advance the position of the other.
721 ///
722 /// # Performance
723 ///
724 /// Forking a parse stream is a cheap fixed amount of work and does not
725 /// involve copying token buffers. Where you might hit performance problems
726 /// is if your macro ends up parsing a large amount of content more than
727 /// once.
728 ///
729 /// ```
730 /// # use syn::Expr;
731 /// # use syn::parse::{ParseStream, Result};
732 /// #
733 /// # fn bad(input: ParseStream) -> Result<Expr> {
734 /// // Do not do this.
735 /// if input.fork().parse::<Expr>().is_ok() {
736 /// return input.parse::<Expr>();
737 /// }
738 /// # unimplemented!()
739 /// # }
740 /// ```
741 ///
742 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
743 /// parse stream. Only use a fork when the amount of work performed against
744 /// the fork is small and bounded.
745 ///
David Tolnayec149b02018-09-01 14:17:28 -0700746 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700747 /// speculative parsing, consider using [`ParseStream::step`] instead.
748 ///
749 /// [`ParseStream::step`]: #method.step
David Tolnayec149b02018-09-01 14:17:28 -0700750 ///
751 /// # Example
752 ///
753 /// The parse implementation shown here parses possibly restricted `pub`
754 /// visibilities.
755 ///
756 /// - `pub`
757 /// - `pub(crate)`
758 /// - `pub(self)`
759 /// - `pub(super)`
760 /// - `pub(in some::path)`
761 ///
762 /// To handle the case of visibilities inside of tuple structs, the parser
763 /// needs to distinguish parentheses that specify visibility restrictions
764 /// from parentheses that form part of a tuple type.
765 ///
766 /// ```
767 /// # struct A;
768 /// # struct B;
769 /// # struct C;
770 /// #
771 /// struct S(pub(crate) A, pub (B, C));
772 /// ```
773 ///
774 /// In this example input the first tuple struct element of `S` has
775 /// `pub(crate)` visibility while the second tuple struct element has `pub`
776 /// visibility; the parentheses around `(B, C)` are part of the type rather
777 /// than part of a visibility restriction.
778 ///
779 /// The parser uses a forked parse stream to check the first token inside of
780 /// parentheses after the `pub` keyword. This is a small bounded amount of
781 /// work performed against the forked parse stream.
782 ///
783 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700784 /// #[macro_use]
785 /// extern crate syn;
786 ///
787 /// use syn::{token, Ident, Path};
David Tolnayec149b02018-09-01 14:17:28 -0700788 /// use syn::ext::IdentExt;
789 /// use syn::parse::{Parse, ParseStream, Result};
790 ///
791 /// struct PubVisibility {
792 /// pub_token: Token![pub],
793 /// restricted: Option<Restricted>,
794 /// }
795 ///
796 /// struct Restricted {
797 /// paren_token: token::Paren,
798 /// in_token: Option<Token![in]>,
799 /// path: Path,
800 /// }
801 ///
802 /// impl Parse for PubVisibility {
803 /// fn parse(input: ParseStream) -> Result<Self> {
804 /// let pub_token: Token![pub] = input.parse()?;
805 ///
806 /// if input.peek(token::Paren) {
807 /// let ahead = input.fork();
808 /// let mut content;
809 /// parenthesized!(content in ahead);
810 ///
811 /// if content.peek(Token![crate])
812 /// || content.peek(Token![self])
813 /// || content.peek(Token![super])
814 /// {
815 /// return Ok(PubVisibility {
816 /// pub_token: pub_token,
817 /// restricted: Some(Restricted {
818 /// paren_token: parenthesized!(content in input),
819 /// in_token: None,
820 /// path: Path::from(content.call(Ident::parse_any)?),
821 /// }),
822 /// });
823 /// } else if content.peek(Token![in]) {
824 /// return Ok(PubVisibility {
825 /// pub_token: pub_token,
826 /// restricted: Some(Restricted {
827 /// paren_token: parenthesized!(content in input),
828 /// in_token: Some(content.parse()?),
829 /// path: content.call(Path::parse_mod_style)?,
830 /// }),
831 /// });
832 /// }
833 /// }
834 ///
835 /// Ok(PubVisibility {
836 /// pub_token: pub_token,
837 /// restricted: None,
838 /// })
839 /// }
840 /// }
841 /// #
842 /// # fn main() {}
843 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400844 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400845 ParseBuffer {
846 scope: self.scope,
847 cell: self.cell.clone(),
848 marker: PhantomData,
849 // Not the parent's unexpected. Nothing cares whether the clone
850 // parses all the way.
851 unexpected: Rc::new(Cell::new(None)),
852 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400853 }
854
David Tolnay725e1c62018-09-01 12:07:25 -0700855 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700856 ///
857 /// # Example
858 ///
859 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700860 /// #[macro_use]
861 /// extern crate syn;
862 ///
863 /// use syn::Expr;
David Tolnay23fce0b2018-09-01 13:50:31 -0700864 /// use syn::parse::{Parse, ParseStream, Result};
865 ///
866 /// // Some kind of loop: `while` or `for` or `loop`.
867 /// struct Loop {
868 /// expr: Expr,
869 /// }
870 ///
871 /// impl Parse for Loop {
872 /// fn parse(input: ParseStream) -> Result<Self> {
873 /// if input.peek(Token![while])
874 /// || input.peek(Token![for])
875 /// || input.peek(Token![loop])
876 /// {
877 /// Ok(Loop {
878 /// expr: input.parse()?,
879 /// })
880 /// } else {
881 /// Err(input.error("expected some kind of loop"))
882 /// }
883 /// }
884 /// }
David Tolnaya1c98072018-09-06 08:58:10 -0700885 /// #
886 /// # fn main() {}
David Tolnay23fce0b2018-09-01 13:50:31 -0700887 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400888 pub fn error<T: Display>(&self, message: T) -> Error {
889 error::new_at(self.scope, self.cursor(), message)
890 }
891
David Tolnay725e1c62018-09-01 12:07:25 -0700892 /// Speculatively parses tokens from this parse stream, advancing the
893 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700894 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700895 /// This is a powerful low-level API used for defining the `Parse` impls of
896 /// the basic built-in token types. It is not something that will be used
897 /// widely outside of the Syn codebase.
898 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700899 /// # Example
900 ///
901 /// ```
902 /// # extern crate proc_macro2;
903 /// # extern crate syn;
904 /// #
905 /// use proc_macro2::TokenTree;
906 /// use syn::parse::{ParseStream, Result};
907 ///
908 /// // This function advances the stream past the next occurrence of `@`. If
909 /// // no `@` is present in the stream, the stream position is unchanged and
910 /// // an error is returned.
911 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
912 /// input.step(|cursor| {
913 /// let mut rest = *cursor;
914 /// while let Some((tt, next)) = cursor.token_tree() {
915 /// match tt {
916 /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
917 /// return Ok(((), next));
918 /// }
919 /// _ => rest = next,
920 /// }
921 /// }
922 /// Err(cursor.error("no `@` was found after this point"))
923 /// })
924 /// }
925 /// #
926 /// # fn main() {}
927 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700928 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400929 where
930 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
931 {
David Tolnayc142b092018-09-02 08:52:52 -0700932 // Since the user's function is required to work for any 'c, we know
933 // that the Cursor<'c> they return is either derived from the input
934 // StepCursor<'c, 'a> or from a Cursor<'static>.
935 //
936 // It would not be legal to write this function without the invariant
937 // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
938 // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
939 // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
940 // `step` on their ParseBuffer<'short> with a closure that returns
941 // Cursor<'short>, and we would wrongly write that Cursor<'short> into
942 // the Cell intended to hold Cursor<'a>.
943 //
944 // In some cases it may be necessary for R to contain a Cursor<'a>.
945 // Within Syn we solve this using `private::advance_step_cursor` which
946 // uses the existence of a StepCursor<'c, 'a> as proof that it is safe
947 // to cast from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it
948 // would be safe to expose that API as a method on StepCursor.
David Tolnay6b65f852018-09-01 11:56:25 -0700949 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -0400950 scope: self.scope,
951 cursor: self.cell.get(),
952 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700953 })?;
954 self.cell.set(rest);
955 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -0400956 }
David Tolnayeafc8052018-08-25 16:33:53 -0400957
David Tolnay725e1c62018-09-01 12:07:25 -0700958 /// Provides low-level access to the token representation underlying this
959 /// parse stream.
960 ///
961 /// Cursors are immutable so no operations you perform against the cursor
962 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -0700963 pub fn cursor(&self) -> Cursor<'a> {
964 self.cell.get()
965 }
966
David Tolnay94f06632018-08-31 10:17:17 -0700967 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -0400968 match self.unexpected.get() {
969 Some(span) => Err(Error::new(span, "unexpected token")),
970 None => Ok(()),
971 }
972 }
David Tolnay18c754c2018-08-21 23:26:58 -0400973}
974
David Tolnaya7d69fc2018-08-26 13:30:24 -0400975impl<T: Parse> Parse for Box<T> {
976 fn parse(input: ParseStream) -> Result<Self> {
977 input.parse().map(Box::new)
978 }
979}
980
David Tolnay4fb71232018-08-25 23:14:50 -0400981impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400982 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -0700983 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -0400984 Ok(Some(input.parse()?))
985 } else {
986 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400987 }
David Tolnay18c754c2018-08-21 23:26:58 -0400988 }
989}
David Tolnay4ac232d2018-08-31 10:18:03 -0700990
David Tolnay80a914f2018-08-30 23:49:53 -0700991impl Parse for TokenStream {
992 fn parse(input: ParseStream) -> Result<Self> {
993 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
994 }
995}
996
997impl Parse for TokenTree {
998 fn parse(input: ParseStream) -> Result<Self> {
999 input.step(|cursor| match cursor.token_tree() {
1000 Some((tt, rest)) => Ok((tt, rest)),
1001 None => Err(cursor.error("expected token tree")),
1002 })
1003 }
1004}
1005
1006impl Parse for Group {
1007 fn parse(input: ParseStream) -> Result<Self> {
1008 input.step(|cursor| {
1009 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
1010 if let Some((inside, span, rest)) = cursor.group(*delim) {
1011 let mut group = Group::new(*delim, inside.token_stream());
1012 group.set_span(span);
1013 return Ok((group, rest));
1014 }
1015 }
1016 Err(cursor.error("expected group token"))
1017 })
1018 }
1019}
1020
1021impl Parse for Punct {
1022 fn parse(input: ParseStream) -> Result<Self> {
1023 input.step(|cursor| match cursor.punct() {
1024 Some((punct, rest)) => Ok((punct, rest)),
1025 None => Err(cursor.error("expected punctuation token")),
1026 })
1027 }
1028}
1029
1030impl Parse for Literal {
1031 fn parse(input: ParseStream) -> Result<Self> {
1032 input.step(|cursor| match cursor.literal() {
1033 Some((literal, rest)) => Ok((literal, rest)),
1034 None => Err(cursor.error("expected literal token")),
1035 })
1036 }
1037}
1038
1039/// Parser that can parse Rust tokens into a particular syntax tree node.
1040///
1041/// Refer to the [module documentation] for details about parsing in Syn.
1042///
1043/// [module documentation]: index.html
1044///
1045/// *This trait is available if Syn is built with the `"parsing"` feature.*
1046pub trait Parser: Sized {
1047 type Output;
1048
1049 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
1050 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1051
1052 /// Parse tokens of source code into the chosen syntax tree node.
1053 ///
1054 /// *This method is available if Syn is built with both the `"parsing"` and
1055 /// `"proc-macro"` features.*
1056 #[cfg(all(
1057 not(all(target_arch = "wasm32", target_os = "unknown")),
1058 feature = "proc-macro"
1059 ))]
1060 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1061 self.parse2(proc_macro2::TokenStream::from(tokens))
1062 }
1063
1064 /// Parse a string of Rust code into the chosen syntax tree node.
1065 ///
1066 /// # Hygiene
1067 ///
1068 /// Every span in the resulting syntax tree will be set to resolve at the
1069 /// macro call site.
1070 fn parse_str(self, s: &str) -> Result<Self::Output> {
1071 self.parse2(proc_macro2::TokenStream::from_str(s)?)
1072 }
1073}
1074
David Tolnay7b07aa12018-09-01 11:41:12 -07001075fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1076 let scope = Span::call_site();
1077 let cursor = tokens.begin();
1078 let unexpected = Rc::new(Cell::new(None));
1079 private::new_parse_buffer(scope, cursor, unexpected)
1080}
1081
David Tolnay80a914f2018-08-30 23:49:53 -07001082impl<F, T> Parser for F
1083where
1084 F: FnOnce(ParseStream) -> Result<T>,
1085{
1086 type Output = T;
1087
1088 fn parse2(self, tokens: TokenStream) -> Result<T> {
1089 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -07001090 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -07001091 let node = self(&state)?;
1092 state.check_unexpected()?;
1093 if state.is_empty() {
1094 Ok(node)
1095 } else {
1096 Err(state.error("unexpected token"))
1097 }
1098 }
1099}