blob: 2b816d93b8bcd52fbf0091721221f63deabfaff7 [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;
Diggory Hardy1c522e12018-11-02 10:10:02 +0000200use std::fmt::{self, Debug, Display};
David Tolnay18c754c2018-08-21 23:26:58 -0400201use 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
Diggory Hardy1c522e12018-11-02 10:10:02 +0000271impl<'a> Display for ParseBuffer<'a> {
272 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
273 Display::fmt(&self.cursor().token_stream(), f)
274 }
275}
276
277impl<'a> Debug for ParseBuffer<'a> {
278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
279 Debug::fmt(&self.cursor().token_stream(), f)
280 }
281}
282
David Tolnay642832f2018-09-01 13:08:10 -0700283/// Cursor state associated with speculative parsing.
284///
285/// This type is the input of the closure provided to [`ParseStream::step`].
286///
287/// [`ParseStream::step`]: struct.ParseBuffer.html#method.step
David Tolnay9bd34392018-09-01 13:19:53 -0700288///
289/// # Example
290///
291/// ```
292/// # extern crate proc_macro2;
293/// # extern crate syn;
294/// #
295/// use proc_macro2::TokenTree;
296/// use syn::parse::{ParseStream, Result};
297///
298/// // This function advances the stream past the next occurrence of `@`. If
299/// // no `@` is present in the stream, the stream position is unchanged and
300/// // an error is returned.
301/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
302/// input.step(|cursor| {
303/// let mut rest = *cursor;
Sharad Chande1df40a2018-09-08 15:25:52 +0545304/// while let Some((tt, next)) = rest.token_tree() {
David Tolnay9bd34392018-09-01 13:19:53 -0700305/// match tt {
306/// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
307/// return Ok(((), next));
308/// }
309/// _ => rest = next,
310/// }
311/// }
312/// Err(cursor.error("no `@` was found after this point"))
313/// })
314/// }
315/// #
316/// # fn main() {}
317/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400318#[derive(Copy, Clone)]
319pub struct StepCursor<'c, 'a> {
320 scope: Span,
David Tolnay56924f42018-09-02 08:24:58 -0700321 // This field is covariant in 'c.
David Tolnay18c754c2018-08-21 23:26:58 -0400322 cursor: Cursor<'c>,
David Tolnay56924f42018-09-02 08:24:58 -0700323 // This field is contravariant in 'c. Together these make StepCursor
324 // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
325 // different lifetime but can upcast into a StepCursor with a shorter
326 // lifetime 'a.
327 //
328 // As long as we only ever construct a StepCursor for which 'c outlives 'a,
329 // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
330 // outlives 'a.
David Tolnay18c754c2018-08-21 23:26:58 -0400331 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
332}
333
334impl<'c, 'a> Deref for StepCursor<'c, 'a> {
335 type Target = Cursor<'c>;
336
337 fn deref(&self) -> &Self::Target {
338 &self.cursor
339 }
340}
341
342impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700343 /// Triggers an error at the current position of the parse stream.
344 ///
345 /// The `ParseStream::step` invocation will return this same error without
346 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400347 pub fn error<T: Display>(self, message: T) -> Error {
348 error::new_at(self.scope, self.cursor, message)
349 }
350}
351
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700352impl private {
353 pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
David Tolnay56924f42018-09-02 08:24:58 -0700354 // Refer to the comments within the StepCursor definition. We use the
355 // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
356 // Cursor is covariant in its lifetime parameter so we can cast a
357 // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700358 let _ = proof;
359 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
360 }
361}
362
David Tolnay66cb0c42018-08-31 09:01:30 -0700363fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700364 input
365 .step(|cursor| {
366 if let Some((_lifetime, rest)) = cursor.lifetime() {
367 Ok((true, rest))
368 } else if let Some((_token, rest)) = cursor.token_tree() {
369 Ok((true, rest))
370 } else {
371 Ok((false, *cursor))
372 }
David Tolnayfb84fc02018-10-02 21:01:30 -0700373 })
374 .unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700375}
376
David Tolnay10951d52018-08-31 10:27:39 -0700377impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700378 pub fn new_parse_buffer(
379 scope: Span,
380 cursor: Cursor,
381 unexpected: Rc<Cell<Option<Span>>>,
382 ) -> ParseBuffer {
David Tolnay18c754c2018-08-21 23:26:58 -0400383 ParseBuffer {
384 scope: scope,
David Tolnay5d7f2252018-09-02 08:21:40 -0700385 // See comment on `cell` in the struct definition.
386 cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
David Tolnay18c754c2018-08-21 23:26:58 -0400387 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400388 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400389 }
390 }
391
David Tolnay94f06632018-08-31 10:17:17 -0700392 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
393 buffer.unexpected.clone()
394 }
395}
396
397impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700398 /// Parses a syntax tree node of type `T`, advancing the position of our
399 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400400 pub fn parse<T: Parse>(&self) -> Result<T> {
401 T::parse(self)
402 }
403
David Tolnay725e1c62018-09-01 12:07:25 -0700404 /// Calls the given parser function to parse a syntax tree node of type `T`
405 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700406 ///
407 /// # Example
408 ///
409 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
410 /// zero or more outer attributes.
411 ///
412 /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
413 ///
414 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700415 /// #[macro_use]
416 /// extern crate syn;
417 ///
418 /// use syn::{Attribute, Ident};
David Tolnay21ce84c2018-09-01 15:37:51 -0700419 /// use syn::parse::{Parse, ParseStream, Result};
420 ///
421 /// // Parses a unit struct with attributes.
422 /// //
423 /// // #[path = "s.tmpl"]
424 /// // struct S;
425 /// struct UnitStruct {
426 /// attrs: Vec<Attribute>,
427 /// struct_token: Token![struct],
428 /// name: Ident,
429 /// semi_token: Token![;],
430 /// }
431 ///
432 /// impl Parse for UnitStruct {
433 /// fn parse(input: ParseStream) -> Result<Self> {
434 /// Ok(UnitStruct {
435 /// attrs: input.call(Attribute::parse_outer)?,
436 /// struct_token: input.parse()?,
437 /// name: input.parse()?,
438 /// semi_token: input.parse()?,
439 /// })
440 /// }
441 /// }
442 /// #
443 /// # fn main() {}
444 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400445 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
446 function(self)
447 }
448
David Tolnay725e1c62018-09-01 12:07:25 -0700449 /// Looks at the next token in the parse stream to determine whether it
450 /// matches the requested type of token.
451 ///
452 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700453 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700454 /// # Syntax
455 ///
456 /// Note that this method does not use turbofish syntax. Pass the peek type
457 /// inside of parentheses.
458 ///
459 /// - `input.peek(Token![struct])`
460 /// - `input.peek(Token![==])`
461 /// - `input.peek(Ident)`
462 /// - `input.peek(Lifetime)`
463 /// - `input.peek(token::Brace)`
464 ///
David Tolnayddebc3e2018-09-01 16:29:20 -0700465 /// # Example
466 ///
467 /// In this example we finish parsing the list of supertraits when the next
468 /// token in the input is either `where` or an opening curly brace.
469 ///
470 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700471 /// #[macro_use]
472 /// extern crate syn;
473 ///
474 /// use syn::{token, Generics, Ident, TypeParamBound};
David Tolnayddebc3e2018-09-01 16:29:20 -0700475 /// use syn::parse::{Parse, ParseStream, Result};
476 /// use syn::punctuated::Punctuated;
477 ///
478 /// // Parses a trait definition containing no associated items.
479 /// //
480 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
481 /// struct MarkerTrait {
482 /// trait_token: Token![trait],
483 /// ident: Ident,
484 /// generics: Generics,
485 /// colon_token: Option<Token![:]>,
486 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
487 /// brace_token: token::Brace,
488 /// }
489 ///
490 /// impl Parse for MarkerTrait {
491 /// fn parse(input: ParseStream) -> Result<Self> {
492 /// let trait_token: Token![trait] = input.parse()?;
493 /// let ident: Ident = input.parse()?;
494 /// let mut generics: Generics = input.parse()?;
495 /// let colon_token: Option<Token![:]> = input.parse()?;
496 ///
497 /// let mut supertraits = Punctuated::new();
498 /// if colon_token.is_some() {
499 /// loop {
500 /// supertraits.push_value(input.parse()?);
501 /// if input.peek(Token![where]) || input.peek(token::Brace) {
502 /// break;
503 /// }
504 /// supertraits.push_punct(input.parse()?);
505 /// }
506 /// }
507 ///
508 /// generics.where_clause = input.parse()?;
509 /// let content;
510 /// let empty_brace_token = braced!(content in input);
511 ///
512 /// Ok(MarkerTrait {
513 /// trait_token: trait_token,
514 /// ident: ident,
515 /// generics: generics,
516 /// colon_token: colon_token,
517 /// supertraits: supertraits,
518 /// brace_token: empty_brace_token,
519 /// })
520 /// }
521 /// }
522 /// #
523 /// # fn main() {}
524 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400525 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700526 let _ = token;
527 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400528 }
529
David Tolnay725e1c62018-09-01 12:07:25 -0700530 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700531 ///
532 /// This is commonly useful as a way to implement contextual keywords.
533 ///
534 /// # Example
535 ///
536 /// This example needs to use `peek2` because the symbol `union` is not a
537 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
538 /// the very next token is `union`, because someone is free to write a `mod
539 /// union` and a macro invocation that looks like `union::some_macro! { ...
540 /// }`. In other words `union` is a contextual keyword.
541 ///
542 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700543 /// #[macro_use]
544 /// extern crate syn;
545 ///
546 /// use syn::{Ident, ItemUnion, Macro};
David Tolnaye334b872018-09-01 16:38:10 -0700547 /// use syn::parse::{Parse, ParseStream, Result};
548 ///
549 /// // Parses either a union or a macro invocation.
550 /// enum UnionOrMacro {
551 /// // union MaybeUninit<T> { uninit: (), value: T }
552 /// Union(ItemUnion),
553 /// // lazy_static! { ... }
554 /// Macro(Macro),
555 /// }
556 ///
557 /// impl Parse for UnionOrMacro {
558 /// fn parse(input: ParseStream) -> Result<Self> {
559 /// if input.peek(Token![union]) && input.peek2(Ident) {
560 /// input.parse().map(UnionOrMacro::Union)
561 /// } else {
562 /// input.parse().map(UnionOrMacro::Macro)
563 /// }
564 /// }
565 /// }
566 /// #
567 /// # fn main() {}
568 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400569 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400570 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700571 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400572 }
573
David Tolnay725e1c62018-09-01 12:07:25 -0700574 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400575 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400576 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700577 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400578 }
579
David Tolnay725e1c62018-09-01 12:07:25 -0700580 /// Parses zero or more occurrences of `T` separated by punctuation of type
581 /// `P`, with optional trailing punctuation.
582 ///
583 /// Parsing continues until the end of this parse stream. The entire content
584 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700585 ///
586 /// # Example
587 ///
588 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700589 /// # #[macro_use]
David Tolnay0abe65b2018-09-01 14:31:43 -0700590 /// # extern crate quote;
David Tolnay0abe65b2018-09-01 14:31:43 -0700591 /// #
David Tolnaya1c98072018-09-06 08:58:10 -0700592 /// #[macro_use]
593 /// extern crate syn;
594 ///
595 /// use syn::{token, Ident, Type};
David Tolnay0abe65b2018-09-01 14:31:43 -0700596 /// use syn::parse::{Parse, ParseStream, Result};
597 /// use syn::punctuated::Punctuated;
598 ///
599 /// // Parse a simplified tuple struct syntax like:
600 /// //
601 /// // struct S(A, B);
602 /// struct TupleStruct {
603 /// struct_token: Token![struct],
604 /// ident: Ident,
605 /// paren_token: token::Paren,
606 /// fields: Punctuated<Type, Token![,]>,
607 /// semi_token: Token![;],
608 /// }
609 ///
610 /// impl Parse for TupleStruct {
611 /// fn parse(input: ParseStream) -> Result<Self> {
612 /// let content;
613 /// Ok(TupleStruct {
614 /// struct_token: input.parse()?,
615 /// ident: input.parse()?,
616 /// paren_token: parenthesized!(content in input),
617 /// fields: content.parse_terminated(Type::parse)?,
618 /// semi_token: input.parse()?,
619 /// })
620 /// }
621 /// }
622 /// #
623 /// # fn main() {
624 /// # let input = quote! {
625 /// # struct S(A, B);
626 /// # };
627 /// # syn::parse2::<TupleStruct>(input).unwrap();
628 /// # }
629 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400630 pub fn parse_terminated<T, P: Parse>(
631 &self,
632 parser: fn(ParseStream) -> Result<T>,
633 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700634 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400635 }
636
David Tolnay725e1c62018-09-01 12:07:25 -0700637 /// Returns whether there are tokens remaining in this stream.
638 ///
639 /// This method returns true at the end of the content of a set of
640 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700641 ///
642 /// # Example
643 ///
644 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700645 /// #[macro_use]
646 /// extern crate syn;
647 ///
648 /// use syn::{token, Ident, Item};
David Tolnaycce6b5f2018-09-01 14:24:46 -0700649 /// use syn::parse::{Parse, ParseStream, Result};
650 ///
651 /// // Parses a Rust `mod m { ... }` containing zero or more items.
652 /// struct Mod {
653 /// mod_token: Token![mod],
654 /// name: Ident,
655 /// brace_token: token::Brace,
656 /// items: Vec<Item>,
657 /// }
658 ///
659 /// impl Parse for Mod {
660 /// fn parse(input: ParseStream) -> Result<Self> {
661 /// let content;
662 /// Ok(Mod {
663 /// mod_token: input.parse()?,
664 /// name: input.parse()?,
665 /// brace_token: braced!(content in input),
666 /// items: {
667 /// let mut items = Vec::new();
668 /// while !content.is_empty() {
669 /// items.push(content.parse()?);
670 /// }
671 /// items
672 /// },
673 /// })
674 /// }
675 /// }
676 /// #
677 /// # fn main() {}
David Tolnayf5d30452018-09-01 02:29:04 -0700678 pub fn is_empty(&self) -> bool {
679 self.cursor().eof()
680 }
681
David Tolnay725e1c62018-09-01 12:07:25 -0700682 /// Constructs a helper for peeking at the next token in this stream and
683 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700684 ///
685 /// # Example
686 ///
687 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700688 /// #[macro_use]
689 /// extern crate syn;
690 ///
691 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, TypeParam};
David Tolnay2c77e772018-09-01 14:18:46 -0700692 /// use syn::parse::{Parse, ParseStream, Result};
693 ///
694 /// // A generic parameter, a single one of the comma-separated elements inside
695 /// // angle brackets in:
696 /// //
697 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
698 /// //
699 /// // On invalid input, lookahead gives us a reasonable error message.
700 /// //
701 /// // error: expected one of: identifier, lifetime, `const`
702 /// // |
703 /// // 5 | fn f<!Sized>() {}
704 /// // | ^
705 /// enum GenericParam {
706 /// Type(TypeParam),
707 /// Lifetime(LifetimeDef),
708 /// Const(ConstParam),
709 /// }
710 ///
711 /// impl Parse for GenericParam {
712 /// fn parse(input: ParseStream) -> Result<Self> {
713 /// let lookahead = input.lookahead1();
714 /// if lookahead.peek(Ident) {
715 /// input.parse().map(GenericParam::Type)
716 /// } else if lookahead.peek(Lifetime) {
717 /// input.parse().map(GenericParam::Lifetime)
718 /// } else if lookahead.peek(Token![const]) {
719 /// input.parse().map(GenericParam::Const)
720 /// } else {
721 /// Err(lookahead.error())
722 /// }
723 /// }
724 /// }
725 /// #
726 /// # fn main() {}
727 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700728 pub fn lookahead1(&self) -> Lookahead1<'a> {
729 lookahead::new(self.scope, self.cursor())
730 }
731
David Tolnay725e1c62018-09-01 12:07:25 -0700732 /// Forks a parse stream so that parsing tokens out of either the original
733 /// or the fork does not advance the position of the other.
734 ///
735 /// # Performance
736 ///
737 /// Forking a parse stream is a cheap fixed amount of work and does not
738 /// involve copying token buffers. Where you might hit performance problems
739 /// is if your macro ends up parsing a large amount of content more than
740 /// once.
741 ///
742 /// ```
743 /// # use syn::Expr;
744 /// # use syn::parse::{ParseStream, Result};
745 /// #
746 /// # fn bad(input: ParseStream) -> Result<Expr> {
747 /// // Do not do this.
748 /// if input.fork().parse::<Expr>().is_ok() {
749 /// return input.parse::<Expr>();
750 /// }
751 /// # unimplemented!()
752 /// # }
753 /// ```
754 ///
755 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
756 /// parse stream. Only use a fork when the amount of work performed against
757 /// the fork is small and bounded.
758 ///
David Tolnayec149b02018-09-01 14:17:28 -0700759 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700760 /// speculative parsing, consider using [`ParseStream::step`] instead.
761 ///
762 /// [`ParseStream::step`]: #method.step
David Tolnayec149b02018-09-01 14:17:28 -0700763 ///
764 /// # Example
765 ///
766 /// The parse implementation shown here parses possibly restricted `pub`
767 /// visibilities.
768 ///
769 /// - `pub`
770 /// - `pub(crate)`
771 /// - `pub(self)`
772 /// - `pub(super)`
773 /// - `pub(in some::path)`
774 ///
775 /// To handle the case of visibilities inside of tuple structs, the parser
776 /// needs to distinguish parentheses that specify visibility restrictions
777 /// from parentheses that form part of a tuple type.
778 ///
779 /// ```
780 /// # struct A;
781 /// # struct B;
782 /// # struct C;
783 /// #
784 /// struct S(pub(crate) A, pub (B, C));
785 /// ```
786 ///
787 /// In this example input the first tuple struct element of `S` has
788 /// `pub(crate)` visibility while the second tuple struct element has `pub`
789 /// visibility; the parentheses around `(B, C)` are part of the type rather
790 /// than part of a visibility restriction.
791 ///
792 /// The parser uses a forked parse stream to check the first token inside of
793 /// parentheses after the `pub` keyword. This is a small bounded amount of
794 /// work performed against the forked parse stream.
795 ///
796 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700797 /// #[macro_use]
798 /// extern crate syn;
799 ///
800 /// use syn::{token, Ident, Path};
David Tolnayec149b02018-09-01 14:17:28 -0700801 /// use syn::ext::IdentExt;
802 /// use syn::parse::{Parse, ParseStream, Result};
803 ///
804 /// struct PubVisibility {
805 /// pub_token: Token![pub],
806 /// restricted: Option<Restricted>,
807 /// }
808 ///
809 /// struct Restricted {
810 /// paren_token: token::Paren,
811 /// in_token: Option<Token![in]>,
812 /// path: Path,
813 /// }
814 ///
815 /// impl Parse for PubVisibility {
816 /// fn parse(input: ParseStream) -> Result<Self> {
817 /// let pub_token: Token![pub] = input.parse()?;
818 ///
819 /// if input.peek(token::Paren) {
820 /// let ahead = input.fork();
821 /// let mut content;
822 /// parenthesized!(content in ahead);
823 ///
824 /// if content.peek(Token![crate])
825 /// || content.peek(Token![self])
826 /// || content.peek(Token![super])
827 /// {
828 /// return Ok(PubVisibility {
829 /// pub_token: pub_token,
830 /// restricted: Some(Restricted {
831 /// paren_token: parenthesized!(content in input),
832 /// in_token: None,
833 /// path: Path::from(content.call(Ident::parse_any)?),
834 /// }),
835 /// });
836 /// } else if content.peek(Token![in]) {
837 /// return Ok(PubVisibility {
838 /// pub_token: pub_token,
839 /// restricted: Some(Restricted {
840 /// paren_token: parenthesized!(content in input),
841 /// in_token: Some(content.parse()?),
842 /// path: content.call(Path::parse_mod_style)?,
843 /// }),
844 /// });
845 /// }
846 /// }
847 ///
848 /// Ok(PubVisibility {
849 /// pub_token: pub_token,
850 /// restricted: None,
851 /// })
852 /// }
853 /// }
854 /// #
855 /// # fn main() {}
856 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400857 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400858 ParseBuffer {
859 scope: self.scope,
860 cell: self.cell.clone(),
861 marker: PhantomData,
862 // Not the parent's unexpected. Nothing cares whether the clone
863 // parses all the way.
864 unexpected: Rc::new(Cell::new(None)),
865 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400866 }
867
David Tolnay725e1c62018-09-01 12:07:25 -0700868 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700869 ///
870 /// # Example
871 ///
872 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700873 /// #[macro_use]
874 /// extern crate syn;
875 ///
876 /// use syn::Expr;
David Tolnay23fce0b2018-09-01 13:50:31 -0700877 /// use syn::parse::{Parse, ParseStream, Result};
878 ///
879 /// // Some kind of loop: `while` or `for` or `loop`.
880 /// struct Loop {
881 /// expr: Expr,
882 /// }
883 ///
884 /// impl Parse for Loop {
885 /// fn parse(input: ParseStream) -> Result<Self> {
886 /// if input.peek(Token![while])
887 /// || input.peek(Token![for])
888 /// || input.peek(Token![loop])
889 /// {
890 /// Ok(Loop {
891 /// expr: input.parse()?,
892 /// })
893 /// } else {
894 /// Err(input.error("expected some kind of loop"))
895 /// }
896 /// }
897 /// }
David Tolnaya1c98072018-09-06 08:58:10 -0700898 /// #
899 /// # fn main() {}
David Tolnay23fce0b2018-09-01 13:50:31 -0700900 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400901 pub fn error<T: Display>(&self, message: T) -> Error {
902 error::new_at(self.scope, self.cursor(), message)
903 }
904
David Tolnay725e1c62018-09-01 12:07:25 -0700905 /// Speculatively parses tokens from this parse stream, advancing the
906 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700907 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700908 /// This is a powerful low-level API used for defining the `Parse` impls of
909 /// the basic built-in token types. It is not something that will be used
910 /// widely outside of the Syn codebase.
911 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700912 /// # Example
913 ///
914 /// ```
915 /// # extern crate proc_macro2;
916 /// # extern crate syn;
917 /// #
918 /// use proc_macro2::TokenTree;
919 /// use syn::parse::{ParseStream, Result};
920 ///
921 /// // This function advances the stream past the next occurrence of `@`. If
922 /// // no `@` is present in the stream, the stream position is unchanged and
923 /// // an error is returned.
924 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
925 /// input.step(|cursor| {
926 /// let mut rest = *cursor;
927 /// while let Some((tt, next)) = cursor.token_tree() {
928 /// match tt {
929 /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
930 /// return Ok(((), next));
931 /// }
932 /// _ => rest = next,
933 /// }
934 /// }
935 /// Err(cursor.error("no `@` was found after this point"))
936 /// })
937 /// }
938 /// #
939 /// # fn main() {}
940 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700941 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400942 where
943 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
944 {
David Tolnayc142b092018-09-02 08:52:52 -0700945 // Since the user's function is required to work for any 'c, we know
946 // that the Cursor<'c> they return is either derived from the input
947 // StepCursor<'c, 'a> or from a Cursor<'static>.
948 //
949 // It would not be legal to write this function without the invariant
950 // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
951 // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
952 // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
953 // `step` on their ParseBuffer<'short> with a closure that returns
954 // Cursor<'short>, and we would wrongly write that Cursor<'short> into
955 // the Cell intended to hold Cursor<'a>.
956 //
957 // In some cases it may be necessary for R to contain a Cursor<'a>.
958 // Within Syn we solve this using `private::advance_step_cursor` which
959 // uses the existence of a StepCursor<'c, 'a> as proof that it is safe
960 // to cast from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it
961 // would be safe to expose that API as a method on StepCursor.
David Tolnay6b65f852018-09-01 11:56:25 -0700962 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -0400963 scope: self.scope,
964 cursor: self.cell.get(),
965 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700966 })?;
967 self.cell.set(rest);
968 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -0400969 }
David Tolnayeafc8052018-08-25 16:33:53 -0400970
David Tolnay725e1c62018-09-01 12:07:25 -0700971 /// Provides low-level access to the token representation underlying this
972 /// parse stream.
973 ///
974 /// Cursors are immutable so no operations you perform against the cursor
975 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -0700976 pub fn cursor(&self) -> Cursor<'a> {
977 self.cell.get()
978 }
979
David Tolnay94f06632018-08-31 10:17:17 -0700980 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -0400981 match self.unexpected.get() {
982 Some(span) => Err(Error::new(span, "unexpected token")),
983 None => Ok(()),
984 }
985 }
David Tolnay18c754c2018-08-21 23:26:58 -0400986}
987
David Tolnaya7d69fc2018-08-26 13:30:24 -0400988impl<T: Parse> Parse for Box<T> {
989 fn parse(input: ParseStream) -> Result<Self> {
990 input.parse().map(Box::new)
991 }
992}
993
David Tolnay4fb71232018-08-25 23:14:50 -0400994impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400995 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -0700996 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -0400997 Ok(Some(input.parse()?))
998 } else {
999 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -04001000 }
David Tolnay18c754c2018-08-21 23:26:58 -04001001 }
1002}
David Tolnay4ac232d2018-08-31 10:18:03 -07001003
David Tolnay80a914f2018-08-30 23:49:53 -07001004impl Parse for TokenStream {
1005 fn parse(input: ParseStream) -> Result<Self> {
1006 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
1007 }
1008}
1009
1010impl Parse for TokenTree {
1011 fn parse(input: ParseStream) -> Result<Self> {
1012 input.step(|cursor| match cursor.token_tree() {
1013 Some((tt, rest)) => Ok((tt, rest)),
1014 None => Err(cursor.error("expected token tree")),
1015 })
1016 }
1017}
1018
1019impl Parse for Group {
1020 fn parse(input: ParseStream) -> Result<Self> {
1021 input.step(|cursor| {
1022 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
1023 if let Some((inside, span, rest)) = cursor.group(*delim) {
1024 let mut group = Group::new(*delim, inside.token_stream());
1025 group.set_span(span);
1026 return Ok((group, rest));
1027 }
1028 }
1029 Err(cursor.error("expected group token"))
1030 })
1031 }
1032}
1033
1034impl Parse for Punct {
1035 fn parse(input: ParseStream) -> Result<Self> {
1036 input.step(|cursor| match cursor.punct() {
1037 Some((punct, rest)) => Ok((punct, rest)),
1038 None => Err(cursor.error("expected punctuation token")),
1039 })
1040 }
1041}
1042
1043impl Parse for Literal {
1044 fn parse(input: ParseStream) -> Result<Self> {
1045 input.step(|cursor| match cursor.literal() {
1046 Some((literal, rest)) => Ok((literal, rest)),
1047 None => Err(cursor.error("expected literal token")),
1048 })
1049 }
1050}
1051
1052/// Parser that can parse Rust tokens into a particular syntax tree node.
1053///
1054/// Refer to the [module documentation] for details about parsing in Syn.
1055///
1056/// [module documentation]: index.html
1057///
1058/// *This trait is available if Syn is built with the `"parsing"` feature.*
1059pub trait Parser: Sized {
1060 type Output;
1061
1062 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
1063 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1064
1065 /// Parse tokens of source code into the chosen syntax tree node.
1066 ///
1067 /// *This method is available if Syn is built with both the `"parsing"` and
1068 /// `"proc-macro"` features.*
1069 #[cfg(all(
1070 not(all(target_arch = "wasm32", target_os = "unknown")),
1071 feature = "proc-macro"
1072 ))]
1073 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1074 self.parse2(proc_macro2::TokenStream::from(tokens))
1075 }
1076
1077 /// Parse a string of Rust code into the chosen syntax tree node.
1078 ///
1079 /// # Hygiene
1080 ///
1081 /// Every span in the resulting syntax tree will be set to resolve at the
1082 /// macro call site.
1083 fn parse_str(self, s: &str) -> Result<Self::Output> {
1084 self.parse2(proc_macro2::TokenStream::from_str(s)?)
1085 }
1086}
1087
David Tolnay7b07aa12018-09-01 11:41:12 -07001088fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1089 let scope = Span::call_site();
1090 let cursor = tokens.begin();
1091 let unexpected = Rc::new(Cell::new(None));
1092 private::new_parse_buffer(scope, cursor, unexpected)
1093}
1094
David Tolnay80a914f2018-08-30 23:49:53 -07001095impl<F, T> Parser for F
1096where
1097 F: FnOnce(ParseStream) -> Result<T>,
1098{
1099 type Output = T;
1100
1101 fn parse2(self, tokens: TokenStream) -> Result<T> {
1102 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -07001103 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -07001104 let node = self(&state)?;
1105 state.check_unexpected()?;
1106 if state.is_empty() {
1107 Ok(node)
1108 } else {
1109 Err(state.error("unexpected token"))
1110 }
1111 }
1112}