blob: 8ca7d2ef89eb80f94cb1c887579bae1783f0e7e7 [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 }
David Tolnayfb84fc02018-10-02 21:01:30 -0700361 })
362 .unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700363}
364
David Tolnay10951d52018-08-31 10:27:39 -0700365impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700366 pub fn new_parse_buffer(
367 scope: Span,
368 cursor: Cursor,
369 unexpected: Rc<Cell<Option<Span>>>,
370 ) -> ParseBuffer {
David Tolnay18c754c2018-08-21 23:26:58 -0400371 ParseBuffer {
372 scope: scope,
David Tolnay5d7f2252018-09-02 08:21:40 -0700373 // See comment on `cell` in the struct definition.
374 cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
David Tolnay18c754c2018-08-21 23:26:58 -0400375 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400376 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400377 }
378 }
379
David Tolnay94f06632018-08-31 10:17:17 -0700380 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
381 buffer.unexpected.clone()
382 }
383}
384
385impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700386 /// Parses a syntax tree node of type `T`, advancing the position of our
387 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400388 pub fn parse<T: Parse>(&self) -> Result<T> {
389 T::parse(self)
390 }
391
David Tolnay725e1c62018-09-01 12:07:25 -0700392 /// Calls the given parser function to parse a syntax tree node of type `T`
393 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700394 ///
395 /// # Example
396 ///
397 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
398 /// zero or more outer attributes.
399 ///
400 /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
401 ///
402 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700403 /// #[macro_use]
404 /// extern crate syn;
405 ///
406 /// use syn::{Attribute, Ident};
David Tolnay21ce84c2018-09-01 15:37:51 -0700407 /// use syn::parse::{Parse, ParseStream, Result};
408 ///
409 /// // Parses a unit struct with attributes.
410 /// //
411 /// // #[path = "s.tmpl"]
412 /// // struct S;
413 /// struct UnitStruct {
414 /// attrs: Vec<Attribute>,
415 /// struct_token: Token![struct],
416 /// name: Ident,
417 /// semi_token: Token![;],
418 /// }
419 ///
420 /// impl Parse for UnitStruct {
421 /// fn parse(input: ParseStream) -> Result<Self> {
422 /// Ok(UnitStruct {
423 /// attrs: input.call(Attribute::parse_outer)?,
424 /// struct_token: input.parse()?,
425 /// name: input.parse()?,
426 /// semi_token: input.parse()?,
427 /// })
428 /// }
429 /// }
430 /// #
431 /// # fn main() {}
432 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400433 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
434 function(self)
435 }
436
David Tolnay725e1c62018-09-01 12:07:25 -0700437 /// Looks at the next token in the parse stream to determine whether it
438 /// matches the requested type of token.
439 ///
440 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700441 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700442 /// # Syntax
443 ///
444 /// Note that this method does not use turbofish syntax. Pass the peek type
445 /// inside of parentheses.
446 ///
447 /// - `input.peek(Token![struct])`
448 /// - `input.peek(Token![==])`
449 /// - `input.peek(Ident)`
450 /// - `input.peek(Lifetime)`
451 /// - `input.peek(token::Brace)`
452 ///
David Tolnayddebc3e2018-09-01 16:29:20 -0700453 /// # Example
454 ///
455 /// In this example we finish parsing the list of supertraits when the next
456 /// token in the input is either `where` or an opening curly brace.
457 ///
458 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700459 /// #[macro_use]
460 /// extern crate syn;
461 ///
462 /// use syn::{token, Generics, Ident, TypeParamBound};
David Tolnayddebc3e2018-09-01 16:29:20 -0700463 /// use syn::parse::{Parse, ParseStream, Result};
464 /// use syn::punctuated::Punctuated;
465 ///
466 /// // Parses a trait definition containing no associated items.
467 /// //
468 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
469 /// struct MarkerTrait {
470 /// trait_token: Token![trait],
471 /// ident: Ident,
472 /// generics: Generics,
473 /// colon_token: Option<Token![:]>,
474 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
475 /// brace_token: token::Brace,
476 /// }
477 ///
478 /// impl Parse for MarkerTrait {
479 /// fn parse(input: ParseStream) -> Result<Self> {
480 /// let trait_token: Token![trait] = input.parse()?;
481 /// let ident: Ident = input.parse()?;
482 /// let mut generics: Generics = input.parse()?;
483 /// let colon_token: Option<Token![:]> = input.parse()?;
484 ///
485 /// let mut supertraits = Punctuated::new();
486 /// if colon_token.is_some() {
487 /// loop {
488 /// supertraits.push_value(input.parse()?);
489 /// if input.peek(Token![where]) || input.peek(token::Brace) {
490 /// break;
491 /// }
492 /// supertraits.push_punct(input.parse()?);
493 /// }
494 /// }
495 ///
496 /// generics.where_clause = input.parse()?;
497 /// let content;
498 /// let empty_brace_token = braced!(content in input);
499 ///
500 /// Ok(MarkerTrait {
501 /// trait_token: trait_token,
502 /// ident: ident,
503 /// generics: generics,
504 /// colon_token: colon_token,
505 /// supertraits: supertraits,
506 /// brace_token: empty_brace_token,
507 /// })
508 /// }
509 /// }
510 /// #
511 /// # fn main() {}
512 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400513 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700514 let _ = token;
515 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400516 }
517
David Tolnay725e1c62018-09-01 12:07:25 -0700518 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700519 ///
520 /// This is commonly useful as a way to implement contextual keywords.
521 ///
522 /// # Example
523 ///
524 /// This example needs to use `peek2` because the symbol `union` is not a
525 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
526 /// the very next token is `union`, because someone is free to write a `mod
527 /// union` and a macro invocation that looks like `union::some_macro! { ...
528 /// }`. In other words `union` is a contextual keyword.
529 ///
530 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700531 /// #[macro_use]
532 /// extern crate syn;
533 ///
534 /// use syn::{Ident, ItemUnion, Macro};
David Tolnaye334b872018-09-01 16:38:10 -0700535 /// use syn::parse::{Parse, ParseStream, Result};
536 ///
537 /// // Parses either a union or a macro invocation.
538 /// enum UnionOrMacro {
539 /// // union MaybeUninit<T> { uninit: (), value: T }
540 /// Union(ItemUnion),
541 /// // lazy_static! { ... }
542 /// Macro(Macro),
543 /// }
544 ///
545 /// impl Parse for UnionOrMacro {
546 /// fn parse(input: ParseStream) -> Result<Self> {
547 /// if input.peek(Token![union]) && input.peek2(Ident) {
548 /// input.parse().map(UnionOrMacro::Union)
549 /// } else {
550 /// input.parse().map(UnionOrMacro::Macro)
551 /// }
552 /// }
553 /// }
554 /// #
555 /// # fn main() {}
556 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400557 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400558 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700559 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400560 }
561
David Tolnay725e1c62018-09-01 12:07:25 -0700562 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400563 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400564 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700565 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400566 }
567
David Tolnay725e1c62018-09-01 12:07:25 -0700568 /// Parses zero or more occurrences of `T` separated by punctuation of type
569 /// `P`, with optional trailing punctuation.
570 ///
571 /// Parsing continues until the end of this parse stream. The entire content
572 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700573 ///
574 /// # Example
575 ///
576 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700577 /// # #[macro_use]
David Tolnay0abe65b2018-09-01 14:31:43 -0700578 /// # extern crate quote;
David Tolnay0abe65b2018-09-01 14:31:43 -0700579 /// #
David Tolnaya1c98072018-09-06 08:58:10 -0700580 /// #[macro_use]
581 /// extern crate syn;
582 ///
583 /// use syn::{token, Ident, Type};
David Tolnay0abe65b2018-09-01 14:31:43 -0700584 /// use syn::parse::{Parse, ParseStream, Result};
585 /// use syn::punctuated::Punctuated;
586 ///
587 /// // Parse a simplified tuple struct syntax like:
588 /// //
589 /// // struct S(A, B);
590 /// struct TupleStruct {
591 /// struct_token: Token![struct],
592 /// ident: Ident,
593 /// paren_token: token::Paren,
594 /// fields: Punctuated<Type, Token![,]>,
595 /// semi_token: Token![;],
596 /// }
597 ///
598 /// impl Parse for TupleStruct {
599 /// fn parse(input: ParseStream) -> Result<Self> {
600 /// let content;
601 /// Ok(TupleStruct {
602 /// struct_token: input.parse()?,
603 /// ident: input.parse()?,
604 /// paren_token: parenthesized!(content in input),
605 /// fields: content.parse_terminated(Type::parse)?,
606 /// semi_token: input.parse()?,
607 /// })
608 /// }
609 /// }
610 /// #
611 /// # fn main() {
612 /// # let input = quote! {
613 /// # struct S(A, B);
614 /// # };
615 /// # syn::parse2::<TupleStruct>(input).unwrap();
616 /// # }
617 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400618 pub fn parse_terminated<T, P: Parse>(
619 &self,
620 parser: fn(ParseStream) -> Result<T>,
621 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700622 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400623 }
624
David Tolnay725e1c62018-09-01 12:07:25 -0700625 /// Returns whether there are tokens remaining in this stream.
626 ///
627 /// This method returns true at the end of the content of a set of
628 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700629 ///
630 /// # Example
631 ///
632 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700633 /// #[macro_use]
634 /// extern crate syn;
635 ///
636 /// use syn::{token, Ident, Item};
David Tolnaycce6b5f2018-09-01 14:24:46 -0700637 /// use syn::parse::{Parse, ParseStream, Result};
638 ///
639 /// // Parses a Rust `mod m { ... }` containing zero or more items.
640 /// struct Mod {
641 /// mod_token: Token![mod],
642 /// name: Ident,
643 /// brace_token: token::Brace,
644 /// items: Vec<Item>,
645 /// }
646 ///
647 /// impl Parse for Mod {
648 /// fn parse(input: ParseStream) -> Result<Self> {
649 /// let content;
650 /// Ok(Mod {
651 /// mod_token: input.parse()?,
652 /// name: input.parse()?,
653 /// brace_token: braced!(content in input),
654 /// items: {
655 /// let mut items = Vec::new();
656 /// while !content.is_empty() {
657 /// items.push(content.parse()?);
658 /// }
659 /// items
660 /// },
661 /// })
662 /// }
663 /// }
664 /// #
665 /// # fn main() {}
David Tolnayf5d30452018-09-01 02:29:04 -0700666 pub fn is_empty(&self) -> bool {
667 self.cursor().eof()
668 }
669
David Tolnay725e1c62018-09-01 12:07:25 -0700670 /// Constructs a helper for peeking at the next token in this stream and
671 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700672 ///
673 /// # Example
674 ///
675 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700676 /// #[macro_use]
677 /// extern crate syn;
678 ///
679 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, TypeParam};
David Tolnay2c77e772018-09-01 14:18:46 -0700680 /// use syn::parse::{Parse, ParseStream, Result};
681 ///
682 /// // A generic parameter, a single one of the comma-separated elements inside
683 /// // angle brackets in:
684 /// //
685 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
686 /// //
687 /// // On invalid input, lookahead gives us a reasonable error message.
688 /// //
689 /// // error: expected one of: identifier, lifetime, `const`
690 /// // |
691 /// // 5 | fn f<!Sized>() {}
692 /// // | ^
693 /// enum GenericParam {
694 /// Type(TypeParam),
695 /// Lifetime(LifetimeDef),
696 /// Const(ConstParam),
697 /// }
698 ///
699 /// impl Parse for GenericParam {
700 /// fn parse(input: ParseStream) -> Result<Self> {
701 /// let lookahead = input.lookahead1();
702 /// if lookahead.peek(Ident) {
703 /// input.parse().map(GenericParam::Type)
704 /// } else if lookahead.peek(Lifetime) {
705 /// input.parse().map(GenericParam::Lifetime)
706 /// } else if lookahead.peek(Token![const]) {
707 /// input.parse().map(GenericParam::Const)
708 /// } else {
709 /// Err(lookahead.error())
710 /// }
711 /// }
712 /// }
713 /// #
714 /// # fn main() {}
715 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700716 pub fn lookahead1(&self) -> Lookahead1<'a> {
717 lookahead::new(self.scope, self.cursor())
718 }
719
David Tolnay725e1c62018-09-01 12:07:25 -0700720 /// Forks a parse stream so that parsing tokens out of either the original
721 /// or the fork does not advance the position of the other.
722 ///
723 /// # Performance
724 ///
725 /// Forking a parse stream is a cheap fixed amount of work and does not
726 /// involve copying token buffers. Where you might hit performance problems
727 /// is if your macro ends up parsing a large amount of content more than
728 /// once.
729 ///
730 /// ```
731 /// # use syn::Expr;
732 /// # use syn::parse::{ParseStream, Result};
733 /// #
734 /// # fn bad(input: ParseStream) -> Result<Expr> {
735 /// // Do not do this.
736 /// if input.fork().parse::<Expr>().is_ok() {
737 /// return input.parse::<Expr>();
738 /// }
739 /// # unimplemented!()
740 /// # }
741 /// ```
742 ///
743 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
744 /// parse stream. Only use a fork when the amount of work performed against
745 /// the fork is small and bounded.
746 ///
David Tolnayec149b02018-09-01 14:17:28 -0700747 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700748 /// speculative parsing, consider using [`ParseStream::step`] instead.
749 ///
750 /// [`ParseStream::step`]: #method.step
David Tolnayec149b02018-09-01 14:17:28 -0700751 ///
752 /// # Example
753 ///
754 /// The parse implementation shown here parses possibly restricted `pub`
755 /// visibilities.
756 ///
757 /// - `pub`
758 /// - `pub(crate)`
759 /// - `pub(self)`
760 /// - `pub(super)`
761 /// - `pub(in some::path)`
762 ///
763 /// To handle the case of visibilities inside of tuple structs, the parser
764 /// needs to distinguish parentheses that specify visibility restrictions
765 /// from parentheses that form part of a tuple type.
766 ///
767 /// ```
768 /// # struct A;
769 /// # struct B;
770 /// # struct C;
771 /// #
772 /// struct S(pub(crate) A, pub (B, C));
773 /// ```
774 ///
775 /// In this example input the first tuple struct element of `S` has
776 /// `pub(crate)` visibility while the second tuple struct element has `pub`
777 /// visibility; the parentheses around `(B, C)` are part of the type rather
778 /// than part of a visibility restriction.
779 ///
780 /// The parser uses a forked parse stream to check the first token inside of
781 /// parentheses after the `pub` keyword. This is a small bounded amount of
782 /// work performed against the forked parse stream.
783 ///
784 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700785 /// #[macro_use]
786 /// extern crate syn;
787 ///
788 /// use syn::{token, Ident, Path};
David Tolnayec149b02018-09-01 14:17:28 -0700789 /// use syn::ext::IdentExt;
790 /// use syn::parse::{Parse, ParseStream, Result};
791 ///
792 /// struct PubVisibility {
793 /// pub_token: Token![pub],
794 /// restricted: Option<Restricted>,
795 /// }
796 ///
797 /// struct Restricted {
798 /// paren_token: token::Paren,
799 /// in_token: Option<Token![in]>,
800 /// path: Path,
801 /// }
802 ///
803 /// impl Parse for PubVisibility {
804 /// fn parse(input: ParseStream) -> Result<Self> {
805 /// let pub_token: Token![pub] = input.parse()?;
806 ///
807 /// if input.peek(token::Paren) {
808 /// let ahead = input.fork();
809 /// let mut content;
810 /// parenthesized!(content in ahead);
811 ///
812 /// if content.peek(Token![crate])
813 /// || content.peek(Token![self])
814 /// || content.peek(Token![super])
815 /// {
816 /// return Ok(PubVisibility {
817 /// pub_token: pub_token,
818 /// restricted: Some(Restricted {
819 /// paren_token: parenthesized!(content in input),
820 /// in_token: None,
821 /// path: Path::from(content.call(Ident::parse_any)?),
822 /// }),
823 /// });
824 /// } else if content.peek(Token![in]) {
825 /// return Ok(PubVisibility {
826 /// pub_token: pub_token,
827 /// restricted: Some(Restricted {
828 /// paren_token: parenthesized!(content in input),
829 /// in_token: Some(content.parse()?),
830 /// path: content.call(Path::parse_mod_style)?,
831 /// }),
832 /// });
833 /// }
834 /// }
835 ///
836 /// Ok(PubVisibility {
837 /// pub_token: pub_token,
838 /// restricted: None,
839 /// })
840 /// }
841 /// }
842 /// #
843 /// # fn main() {}
844 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400845 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400846 ParseBuffer {
847 scope: self.scope,
848 cell: self.cell.clone(),
849 marker: PhantomData,
850 // Not the parent's unexpected. Nothing cares whether the clone
851 // parses all the way.
852 unexpected: Rc::new(Cell::new(None)),
853 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400854 }
855
David Tolnay725e1c62018-09-01 12:07:25 -0700856 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700857 ///
858 /// # Example
859 ///
860 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700861 /// #[macro_use]
862 /// extern crate syn;
863 ///
864 /// use syn::Expr;
David Tolnay23fce0b2018-09-01 13:50:31 -0700865 /// use syn::parse::{Parse, ParseStream, Result};
866 ///
867 /// // Some kind of loop: `while` or `for` or `loop`.
868 /// struct Loop {
869 /// expr: Expr,
870 /// }
871 ///
872 /// impl Parse for Loop {
873 /// fn parse(input: ParseStream) -> Result<Self> {
874 /// if input.peek(Token![while])
875 /// || input.peek(Token![for])
876 /// || input.peek(Token![loop])
877 /// {
878 /// Ok(Loop {
879 /// expr: input.parse()?,
880 /// })
881 /// } else {
882 /// Err(input.error("expected some kind of loop"))
883 /// }
884 /// }
885 /// }
David Tolnaya1c98072018-09-06 08:58:10 -0700886 /// #
887 /// # fn main() {}
David Tolnay23fce0b2018-09-01 13:50:31 -0700888 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400889 pub fn error<T: Display>(&self, message: T) -> Error {
890 error::new_at(self.scope, self.cursor(), message)
891 }
892
David Tolnay725e1c62018-09-01 12:07:25 -0700893 /// Speculatively parses tokens from this parse stream, advancing the
894 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700895 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700896 /// This is a powerful low-level API used for defining the `Parse` impls of
897 /// the basic built-in token types. It is not something that will be used
898 /// widely outside of the Syn codebase.
899 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700900 /// # Example
901 ///
902 /// ```
903 /// # extern crate proc_macro2;
904 /// # extern crate syn;
905 /// #
906 /// use proc_macro2::TokenTree;
907 /// use syn::parse::{ParseStream, Result};
908 ///
909 /// // This function advances the stream past the next occurrence of `@`. If
910 /// // no `@` is present in the stream, the stream position is unchanged and
911 /// // an error is returned.
912 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
913 /// input.step(|cursor| {
914 /// let mut rest = *cursor;
915 /// while let Some((tt, next)) = cursor.token_tree() {
916 /// match tt {
917 /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
918 /// return Ok(((), next));
919 /// }
920 /// _ => rest = next,
921 /// }
922 /// }
923 /// Err(cursor.error("no `@` was found after this point"))
924 /// })
925 /// }
926 /// #
927 /// # fn main() {}
928 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700929 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400930 where
931 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
932 {
David Tolnayc142b092018-09-02 08:52:52 -0700933 // Since the user's function is required to work for any 'c, we know
934 // that the Cursor<'c> they return is either derived from the input
935 // StepCursor<'c, 'a> or from a Cursor<'static>.
936 //
937 // It would not be legal to write this function without the invariant
938 // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
939 // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
940 // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
941 // `step` on their ParseBuffer<'short> with a closure that returns
942 // Cursor<'short>, and we would wrongly write that Cursor<'short> into
943 // the Cell intended to hold Cursor<'a>.
944 //
945 // In some cases it may be necessary for R to contain a Cursor<'a>.
946 // Within Syn we solve this using `private::advance_step_cursor` which
947 // uses the existence of a StepCursor<'c, 'a> as proof that it is safe
948 // to cast from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it
949 // would be safe to expose that API as a method on StepCursor.
David Tolnay6b65f852018-09-01 11:56:25 -0700950 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -0400951 scope: self.scope,
952 cursor: self.cell.get(),
953 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700954 })?;
955 self.cell.set(rest);
956 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -0400957 }
David Tolnayeafc8052018-08-25 16:33:53 -0400958
David Tolnay725e1c62018-09-01 12:07:25 -0700959 /// Provides low-level access to the token representation underlying this
960 /// parse stream.
961 ///
962 /// Cursors are immutable so no operations you perform against the cursor
963 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -0700964 pub fn cursor(&self) -> Cursor<'a> {
965 self.cell.get()
966 }
967
David Tolnay94f06632018-08-31 10:17:17 -0700968 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -0400969 match self.unexpected.get() {
970 Some(span) => Err(Error::new(span, "unexpected token")),
971 None => Ok(()),
972 }
973 }
David Tolnay18c754c2018-08-21 23:26:58 -0400974}
975
David Tolnaya7d69fc2018-08-26 13:30:24 -0400976impl<T: Parse> Parse for Box<T> {
977 fn parse(input: ParseStream) -> Result<Self> {
978 input.parse().map(Box::new)
979 }
980}
981
David Tolnay4fb71232018-08-25 23:14:50 -0400982impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400983 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -0700984 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -0400985 Ok(Some(input.parse()?))
986 } else {
987 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400988 }
David Tolnay18c754c2018-08-21 23:26:58 -0400989 }
990}
David Tolnay4ac232d2018-08-31 10:18:03 -0700991
David Tolnay80a914f2018-08-30 23:49:53 -0700992impl Parse for TokenStream {
993 fn parse(input: ParseStream) -> Result<Self> {
994 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
995 }
996}
997
998impl Parse for TokenTree {
999 fn parse(input: ParseStream) -> Result<Self> {
1000 input.step(|cursor| match cursor.token_tree() {
1001 Some((tt, rest)) => Ok((tt, rest)),
1002 None => Err(cursor.error("expected token tree")),
1003 })
1004 }
1005}
1006
1007impl Parse for Group {
1008 fn parse(input: ParseStream) -> Result<Self> {
1009 input.step(|cursor| {
1010 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
1011 if let Some((inside, span, rest)) = cursor.group(*delim) {
1012 let mut group = Group::new(*delim, inside.token_stream());
1013 group.set_span(span);
1014 return Ok((group, rest));
1015 }
1016 }
1017 Err(cursor.error("expected group token"))
1018 })
1019 }
1020}
1021
1022impl Parse for Punct {
1023 fn parse(input: ParseStream) -> Result<Self> {
1024 input.step(|cursor| match cursor.punct() {
1025 Some((punct, rest)) => Ok((punct, rest)),
1026 None => Err(cursor.error("expected punctuation token")),
1027 })
1028 }
1029}
1030
1031impl Parse for Literal {
1032 fn parse(input: ParseStream) -> Result<Self> {
1033 input.step(|cursor| match cursor.literal() {
1034 Some((literal, rest)) => Ok((literal, rest)),
1035 None => Err(cursor.error("expected literal token")),
1036 })
1037 }
1038}
1039
1040/// Parser that can parse Rust tokens into a particular syntax tree node.
1041///
1042/// Refer to the [module documentation] for details about parsing in Syn.
1043///
1044/// [module documentation]: index.html
1045///
1046/// *This trait is available if Syn is built with the `"parsing"` feature.*
1047pub trait Parser: Sized {
1048 type Output;
1049
1050 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
1051 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1052
1053 /// Parse tokens of source code into the chosen syntax tree node.
1054 ///
1055 /// *This method is available if Syn is built with both the `"parsing"` and
1056 /// `"proc-macro"` features.*
1057 #[cfg(all(
1058 not(all(target_arch = "wasm32", target_os = "unknown")),
1059 feature = "proc-macro"
1060 ))]
1061 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1062 self.parse2(proc_macro2::TokenStream::from(tokens))
1063 }
1064
1065 /// Parse a string of Rust code into the chosen syntax tree node.
1066 ///
1067 /// # Hygiene
1068 ///
1069 /// Every span in the resulting syntax tree will be set to resolve at the
1070 /// macro call site.
1071 fn parse_str(self, s: &str) -> Result<Self::Output> {
1072 self.parse2(proc_macro2::TokenStream::from_str(s)?)
1073 }
1074}
1075
David Tolnay7b07aa12018-09-01 11:41:12 -07001076fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1077 let scope = Span::call_site();
1078 let cursor = tokens.begin();
1079 let unexpected = Rc::new(Cell::new(None));
1080 private::new_parse_buffer(scope, cursor, unexpected)
1081}
1082
David Tolnay80a914f2018-08-30 23:49:53 -07001083impl<F, T> Parser for F
1084where
1085 F: FnOnce(ParseStream) -> Result<T>,
1086{
1087 type Output = T;
1088
1089 fn parse2(self, tokens: TokenStream) -> Result<T> {
1090 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -07001091 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -07001092 let node = self(&state)?;
1093 state.check_unexpected()?;
1094 if state.is_empty() {
1095 Ok(node)
1096 } else {
1097 Err(state.error("unexpected token"))
1098 }
1099 }
1100}