blob: 6c36009daa28568aca78b1750597d801198d01e2 [file] [log] [blame]
David Tolnay18c754c2018-08-21 23:26:58 -04001//! Parsing interface for parsing a token stream into a syntax tree node.
David Tolnay80a914f2018-08-30 23:49:53 -07002//!
David Tolnaye0c51762018-08-31 11:05:22 -07003//! Parsing in Syn is built on parser functions that take in a [`ParseStream`]
4//! and produce a [`Result<T>`] where `T` is some syntax tree node. Underlying
5//! these parser functions is a lower level mechanism built around the
6//! [`Cursor`] type. `Cursor` is a cheaply copyable cursor over a range of
7//! tokens in a token stream.
David Tolnay80a914f2018-08-30 23:49:53 -07008//!
David Tolnaye0c51762018-08-31 11:05:22 -07009//! [`ParseStream`]: type.ParseStream.html
10//! [`Result<T>`]: type.Result.html
David Tolnay80a914f2018-08-30 23:49:53 -070011//! [`Cursor`]: ../buffer/index.html
David Tolnay80a914f2018-08-30 23:49:53 -070012//!
David Tolnay43984452018-09-01 17:43:56 -070013//! # Example
David Tolnay80a914f2018-08-30 23:49:53 -070014//!
David Tolnay43984452018-09-01 17:43:56 -070015//! Here is a snippet of parsing code to get a feel for the style of the
16//! library. We define data structures for a subset of Rust syntax including
17//! enums (not shown) and structs, then provide implementations of the [`Parse`]
18//! trait to parse these syntax tree data structures from a token stream.
19//!
David Tolnay88d9f622018-09-01 17:52:33 -070020//! Once `Parse` impls have been defined, they can be called conveniently from a
David Tolnay8e6096a2018-09-06 02:14:47 -070021//! procedural macro through [`parse_macro_input!`] as shown at the bottom of
22//! the snippet. If the caller provides syntactically invalid input to the
23//! procedural macro, they will receive a helpful compiler error message
24//! pointing out the exact token that triggered the failure to parse.
25//!
26//! [`parse_macro_input!`]: ../macro.parse_macro_input.html
David Tolnay88d9f622018-09-01 17:52:33 -070027//!
David Tolnay95989db2019-01-01 15:05:57 -050028//! ```edition2018
David Tolnaya1c98072018-09-06 08:58:10 -070029//! extern crate proc_macro;
30//!
David Tolnay88d9f622018-09-01 17:52:33 -070031//! use proc_macro::TokenStream;
David Tolnayfd5b1172018-12-31 17:54:36 -050032//! use syn::{braced, parse_macro_input, token, Field, Ident, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -080033//! use syn::parse::{Parse, ParseStream};
David Tolnay43984452018-09-01 17:43:56 -070034//! use syn::punctuated::Punctuated;
35//!
36//! enum Item {
37//! Struct(ItemStruct),
38//! Enum(ItemEnum),
39//! }
40//!
41//! struct ItemStruct {
42//! struct_token: Token![struct],
43//! ident: Ident,
44//! brace_token: token::Brace,
45//! fields: Punctuated<Field, Token![,]>,
46//! }
47//! #
48//! # enum ItemEnum {}
49//!
50//! impl Parse for Item {
51//! fn parse(input: ParseStream) -> Result<Self> {
52//! let lookahead = input.lookahead1();
53//! if lookahead.peek(Token![struct]) {
54//! input.parse().map(Item::Struct)
55//! } else if lookahead.peek(Token![enum]) {
56//! input.parse().map(Item::Enum)
57//! } else {
58//! Err(lookahead.error())
59//! }
60//! }
61//! }
62//!
63//! impl Parse for ItemStruct {
64//! fn parse(input: ParseStream) -> Result<Self> {
65//! let content;
66//! Ok(ItemStruct {
67//! struct_token: input.parse()?,
68//! ident: input.parse()?,
69//! brace_token: braced!(content in input),
70//! fields: content.parse_terminated(Field::parse_named)?,
71//! })
72//! }
73//! }
74//! #
75//! # impl Parse for ItemEnum {
76//! # fn parse(input: ParseStream) -> Result<Self> {
77//! # unimplemented!()
78//! # }
79//! # }
David Tolnay88d9f622018-09-01 17:52:33 -070080//!
81//! # const IGNORE: &str = stringify! {
82//! #[proc_macro]
83//! # };
84//! pub fn my_macro(tokens: TokenStream) -> TokenStream {
85//! let input = parse_macro_input!(tokens as Item);
86//!
87//! /* ... */
88//! # "".parse().unwrap()
89//! }
David Tolnay43984452018-09-01 17:43:56 -070090//! ```
91//!
92//! # The `syn::parse*` functions
David Tolnay80a914f2018-08-30 23:49:53 -070093//!
94//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
95//! as an entry point for parsing syntax tree nodes that can be parsed in an
96//! obvious default way. These functions can return any syntax tree node that
David Tolnay8aacee12018-08-31 09:15:15 -070097//! implements the [`Parse`] trait, which includes most types in Syn.
David Tolnay80a914f2018-08-30 23:49:53 -070098//!
99//! [`syn::parse`]: ../fn.parse.html
100//! [`syn::parse2`]: ../fn.parse2.html
101//! [`syn::parse_str`]: ../fn.parse_str.html
David Tolnay8aacee12018-08-31 09:15:15 -0700102//! [`Parse`]: trait.Parse.html
David Tolnay80a914f2018-08-30 23:49:53 -0700103//!
David Tolnay95989db2019-01-01 15:05:57 -0500104//! ```edition2018
David Tolnay80a914f2018-08-30 23:49:53 -0700105//! use syn::Type;
106//!
David Tolnay67fea042018-11-24 14:50:20 -0800107//! # fn run_parser() -> syn::Result<()> {
David Tolnay80a914f2018-08-30 23:49:53 -0700108//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
109//! # Ok(())
110//! # }
111//! #
112//! # fn main() {
113//! # run_parser().unwrap();
114//! # }
115//! ```
116//!
117//! The [`parse_quote!`] macro also uses this approach.
118//!
119//! [`parse_quote!`]: ../macro.parse_quote.html
120//!
David Tolnay43984452018-09-01 17:43:56 -0700121//! # The `Parser` trait
David Tolnay80a914f2018-08-30 23:49:53 -0700122//!
123//! Some types can be parsed in several ways depending on context. For example
124//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
125//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
126//! may or may not allow trailing punctuation, and parsing it the wrong way
127//! would either reject valid input or accept invalid input.
128//!
129//! [`Attribute`]: ../struct.Attribute.html
130//! [`Punctuated`]: ../punctuated/index.html
131//!
David Tolnaye0c51762018-08-31 11:05:22 -0700132//! The `Parse` trait is not implemented in these cases because there is no good
David Tolnay80a914f2018-08-30 23:49:53 -0700133//! behavior to consider the default.
134//!
David Tolnay95989db2019-01-01 15:05:57 -0500135//! ```edition2018,compile_fail
David Tolnay2b45fd42018-11-06 21:16:55 -0800136//! # extern crate proc_macro;
David Tolnay2b45fd42018-11-06 21:16:55 -0800137//! #
David Tolnay2b45fd42018-11-06 21:16:55 -0800138//! # use syn::punctuated::Punctuated;
David Tolnay67fea042018-11-24 14:50:20 -0800139//! # use syn::{PathSegment, Result, Token};
David Tolnay2b45fd42018-11-06 21:16:55 -0800140//! #
141//! # fn f(tokens: proc_macro::TokenStream) -> Result<()> {
142//! #
David Tolnay80a914f2018-08-30 23:49:53 -0700143//! // Can't parse `Punctuated` without knowing whether trailing punctuation
144//! // should be allowed in this context.
145//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
David Tolnay2b45fd42018-11-06 21:16:55 -0800146//! #
147//! # Ok(())
148//! # }
David Tolnay80a914f2018-08-30 23:49:53 -0700149//! ```
150//!
151//! In these cases the types provide a choice of parser functions rather than a
David Tolnaye0c51762018-08-31 11:05:22 -0700152//! single `Parse` implementation, and those parser functions can be invoked
David Tolnay80a914f2018-08-30 23:49:53 -0700153//! through the [`Parser`] trait.
154//!
155//! [`Parser`]: trait.Parser.html
156//!
David Tolnay95989db2019-01-01 15:05:57 -0500157//! ```edition2018
David Tolnay66a23602018-12-31 17:59:21 -0500158//! extern crate proc_macro;
159//!
160//! use proc_macro::TokenStream;
David Tolnay3e3f7752018-08-31 09:33:59 -0700161//! use syn::parse::Parser;
David Tolnay80a914f2018-08-30 23:49:53 -0700162//! use syn::punctuated::Punctuated;
David Tolnay66a23602018-12-31 17:59:21 -0500163//! use syn::{Attribute, Expr, PathSegment, Result, Token};
David Tolnay80a914f2018-08-30 23:49:53 -0700164//!
David Tolnay66a23602018-12-31 17:59:21 -0500165//! fn call_some_parser_methods(input: TokenStream) -> Result<()> {
166//! // Parse a nonempty sequence of path segments separated by `::` punctuation
167//! // with no trailing punctuation.
168//! let tokens = input.clone();
169//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
170//! let _path = parser.parse(tokens)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700171//!
David Tolnay66a23602018-12-31 17:59:21 -0500172//! // Parse a possibly empty sequence of expressions terminated by commas with
173//! // an optional trailing punctuation.
174//! let tokens = input.clone();
175//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
176//! let _args = parser.parse(tokens)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700177//!
David Tolnay66a23602018-12-31 17:59:21 -0500178//! // Parse zero or more outer attributes but not inner attributes.
179//! let tokens = input.clone();
180//! let parser = Attribute::parse_outer;
181//! let _attrs = parser.parse(tokens)?;
182//!
183//! Ok(())
184//! }
David Tolnay80a914f2018-08-30 23:49:53 -0700185//! ```
186//!
David Tolnaye0c51762018-08-31 11:05:22 -0700187//! ---
David Tolnay80a914f2018-08-30 23:49:53 -0700188//!
189//! *This module is available if Syn is built with the `"parsing"` feature.*
David Tolnay18c754c2018-08-21 23:26:58 -0400190
David Tolnayb9e23032019-01-23 21:43:36 -0800191#[path = "discouraged.rs"]
cad9789bb9452019-01-20 18:33:48 -0500192pub mod discouraged;
193
David Tolnay18c754c2018-08-21 23:26:58 -0400194use std::cell::Cell;
Diggory Hardy1c522e12018-11-02 10:10:02 +0000195use std::fmt::{self, Debug, Display};
David Tolnay18c754c2018-08-21 23:26:58 -0400196use std::marker::PhantomData;
197use std::mem;
198use std::ops::Deref;
David Tolnayeafc8052018-08-25 16:33:53 -0400199use std::rc::Rc;
David Tolnay80a914f2018-08-30 23:49:53 -0700200use std::str::FromStr;
David Tolnayeafc8052018-08-25 16:33:53 -0400201
David Tolnay80a914f2018-08-30 23:49:53 -0700202#[cfg(all(
203 not(all(target_arch = "wasm32", target_os = "unknown")),
204 feature = "proc-macro"
205))]
206use proc_macro;
David Tolnayf07b3342018-09-01 11:58:11 -0700207use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
David Tolnay18c754c2018-08-21 23:26:58 -0400208
David Tolnay80a914f2018-08-30 23:49:53 -0700209use buffer::{Cursor, TokenBuffer};
David Tolnayb6254182018-08-25 08:44:54 -0400210use error;
David Tolnay94f06632018-08-31 10:17:17 -0700211use lookahead;
212use private;
David Tolnay577d0332018-08-25 21:45:24 -0400213use punctuated::Punctuated;
David Tolnay4fb71232018-08-25 23:14:50 -0400214use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -0400215
David Tolnayb6254182018-08-25 08:44:54 -0400216pub use error::{Error, Result};
217pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -0400218
219/// Parsing interface implemented by all types that can be parsed in a default
220/// way from a token stream.
221pub trait Parse: Sized {
222 fn parse(input: ParseStream) -> Result<Self>;
223}
224
225/// Input to a Syn parser function.
David Tolnaya0daa482018-09-01 02:09:40 -0700226///
227/// See the methods of this type under the documentation of [`ParseBuffer`]. For
228/// an overview of parsing in Syn, refer to the [module documentation].
229///
230/// [module documentation]: index.html
David Tolnay18c754c2018-08-21 23:26:58 -0400231pub type ParseStream<'a> = &'a ParseBuffer<'a>;
232
233/// Cursor position within a buffered token stream.
David Tolnay20d29a12018-09-01 15:15:33 -0700234///
235/// This type is more commonly used through the type alias [`ParseStream`] which
236/// is an alias for `&ParseBuffer`.
237///
238/// `ParseStream` is the input type for all parser functions in Syn. They have
239/// the signature `fn(ParseStream) -> Result<T>`.
David Tolnay028a7d72018-12-31 17:11:02 -0500240///
241/// ## Calling a parser function
242///
243/// There is no public way to construct a `ParseBuffer`. Instead, if you are
244/// looking to invoke a parser function that requires `ParseStream` as input,
245/// you will need to go through one of the public parsing entry points.
246///
247/// - The [`parse_macro_input!`] macro if parsing input of a procedural macro;
248/// - One of [the `syn::parse*` functions][syn-parse]; or
249/// - A method of the [`Parser`] trait.
250///
251/// [`parse_macro_input!`]: ../macro.parse_macro_input.html
252/// [syn-parse]: index.html#the-synparse-functions
David Tolnay18c754c2018-08-21 23:26:58 -0400253pub struct ParseBuffer<'a> {
cad9789bb9452019-01-20 18:33:48 -0500254 // The identity of this Rc tracks the origin of forks.
255 // That is, any Rc which is Rc::ptr_eq are derived from the same cursor,
256 // and thus the cursor may be copied between them safely.
257 // Thus a new Rc must be created for a new buffer, and only be cloned on fork.
258 scope: Rc<Span>,
David Tolnay5d7f2252018-09-02 08:21:40 -0700259 // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
260 // The rest of the code in this module needs to be careful that only a
261 // cursor derived from this `cell` is ever assigned to this `cell`.
262 //
263 // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
264 // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
265 // than 'a, and then assign a Cursor<'short> into the Cell.
266 //
267 // By extension, it would not be safe to expose an API that accepts a
268 // Cursor<'a> and trusts that it lives as long as the cursor currently in
269 // the cell.
David Tolnay18c754c2018-08-21 23:26:58 -0400270 cell: Cell<Cursor<'static>>,
271 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400272 unexpected: Rc<Cell<Option<Span>>>,
273}
274
275impl<'a> Drop for ParseBuffer<'a> {
276 fn drop(&mut self) {
277 if !self.is_empty() && self.unexpected.get().is_none() {
278 self.unexpected.set(Some(self.cursor().span()));
279 }
280 }
David Tolnay18c754c2018-08-21 23:26:58 -0400281}
282
Diggory Hardy1c522e12018-11-02 10:10:02 +0000283impl<'a> Display for ParseBuffer<'a> {
284 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
285 Display::fmt(&self.cursor().token_stream(), f)
286 }
287}
288
289impl<'a> Debug for ParseBuffer<'a> {
290 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
291 Debug::fmt(&self.cursor().token_stream(), f)
292 }
293}
294
David Tolnay642832f2018-09-01 13:08:10 -0700295/// Cursor state associated with speculative parsing.
296///
297/// This type is the input of the closure provided to [`ParseStream::step`].
298///
299/// [`ParseStream::step`]: struct.ParseBuffer.html#method.step
David Tolnay9bd34392018-09-01 13:19:53 -0700300///
301/// # Example
302///
David Tolnay95989db2019-01-01 15:05:57 -0500303/// ```edition2018
David Tolnay9bd34392018-09-01 13:19:53 -0700304/// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800305/// use syn::Result;
306/// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700307///
308/// // This function advances the stream past the next occurrence of `@`. If
309/// // no `@` is present in the stream, the stream position is unchanged and
310/// // an error is returned.
311/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
312/// input.step(|cursor| {
313/// let mut rest = *cursor;
Sharad Chande1df40a2018-09-08 15:25:52 +0545314/// while let Some((tt, next)) = rest.token_tree() {
David Tolnay65336072019-04-22 23:10:52 -0700315/// match &tt {
316/// TokenTree::Punct(punct) if punct.as_char() == '@' => {
David Tolnay9bd34392018-09-01 13:19:53 -0700317/// return Ok(((), next));
318/// }
319/// _ => rest = next,
320/// }
321/// }
322/// Err(cursor.error("no `@` was found after this point"))
323/// })
324/// }
325/// #
David Tolnaydb312582018-11-06 20:42:05 -0800326/// # fn remainder_after_skipping_past_next_at(
327/// # input: ParseStream,
328/// # ) -> Result<proc_macro2::TokenStream> {
329/// # skip_past_next_at(input)?;
330/// # input.parse()
331/// # }
332/// #
333/// # fn main() {
334/// # use syn::parse::Parser;
335/// # let remainder = remainder_after_skipping_past_next_at
336/// # .parse_str("a @ b c")
337/// # .unwrap();
338/// # assert_eq!(remainder.to_string(), "b c");
339/// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700340/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400341#[derive(Copy, Clone)]
342pub struct StepCursor<'c, 'a> {
343 scope: Span,
David Tolnay56924f42018-09-02 08:24:58 -0700344 // This field is covariant in 'c.
David Tolnay18c754c2018-08-21 23:26:58 -0400345 cursor: Cursor<'c>,
David Tolnay56924f42018-09-02 08:24:58 -0700346 // This field is contravariant in 'c. Together these make StepCursor
347 // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
348 // different lifetime but can upcast into a StepCursor with a shorter
349 // lifetime 'a.
350 //
351 // As long as we only ever construct a StepCursor for which 'c outlives 'a,
352 // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
353 // outlives 'a.
David Tolnay18c754c2018-08-21 23:26:58 -0400354 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
355}
356
357impl<'c, 'a> Deref for StepCursor<'c, 'a> {
358 type Target = Cursor<'c>;
359
360 fn deref(&self) -> &Self::Target {
361 &self.cursor
362 }
363}
364
365impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700366 /// Triggers an error at the current position of the parse stream.
367 ///
368 /// The `ParseStream::step` invocation will return this same error without
369 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400370 pub fn error<T: Display>(self, message: T) -> Error {
371 error::new_at(self.scope, self.cursor, message)
372 }
373}
374
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700375impl private {
376 pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
David Tolnay56924f42018-09-02 08:24:58 -0700377 // Refer to the comments within the StepCursor definition. We use the
378 // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
379 // Cursor is covariant in its lifetime parameter so we can cast a
380 // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700381 let _ = proof;
382 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
383 }
384}
385
David Tolnay66cb0c42018-08-31 09:01:30 -0700386fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700387 input
388 .step(|cursor| {
389 if let Some((_lifetime, rest)) = cursor.lifetime() {
390 Ok((true, rest))
391 } else if let Some((_token, rest)) = cursor.token_tree() {
392 Ok((true, rest))
393 } else {
394 Ok((false, *cursor))
395 }
David Tolnayfb84fc02018-10-02 21:01:30 -0700396 })
397 .unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700398}
399
David Tolnay10951d52018-08-31 10:27:39 -0700400impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700401 pub fn new_parse_buffer(
402 scope: Span,
403 cursor: Cursor,
404 unexpected: Rc<Cell<Option<Span>>>,
405 ) -> ParseBuffer {
David Tolnay18c754c2018-08-21 23:26:58 -0400406 ParseBuffer {
cad9789bb9452019-01-20 18:33:48 -0500407 scope: Rc::new(scope),
David Tolnay5d7f2252018-09-02 08:21:40 -0700408 // See comment on `cell` in the struct definition.
409 cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
David Tolnay18c754c2018-08-21 23:26:58 -0400410 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400411 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400412 }
413 }
414
David Tolnay94f06632018-08-31 10:17:17 -0700415 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
416 buffer.unexpected.clone()
417 }
418}
419
420impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700421 /// Parses a syntax tree node of type `T`, advancing the position of our
422 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400423 pub fn parse<T: Parse>(&self) -> Result<T> {
424 T::parse(self)
425 }
426
David Tolnay725e1c62018-09-01 12:07:25 -0700427 /// Calls the given parser function to parse a syntax tree node of type `T`
428 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700429 ///
430 /// # Example
431 ///
432 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
433 /// zero or more outer attributes.
434 ///
435 /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
436 ///
David Tolnay95989db2019-01-01 15:05:57 -0500437 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500438 /// use syn::{Attribute, Ident, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800439 /// use syn::parse::{Parse, ParseStream};
David Tolnay21ce84c2018-09-01 15:37:51 -0700440 ///
441 /// // Parses a unit struct with attributes.
442 /// //
443 /// // #[path = "s.tmpl"]
444 /// // struct S;
445 /// struct UnitStruct {
446 /// attrs: Vec<Attribute>,
447 /// struct_token: Token![struct],
448 /// name: Ident,
449 /// semi_token: Token![;],
450 /// }
451 ///
452 /// impl Parse for UnitStruct {
453 /// fn parse(input: ParseStream) -> Result<Self> {
454 /// Ok(UnitStruct {
455 /// attrs: input.call(Attribute::parse_outer)?,
456 /// struct_token: input.parse()?,
457 /// name: input.parse()?,
458 /// semi_token: input.parse()?,
459 /// })
460 /// }
461 /// }
David Tolnay21ce84c2018-09-01 15:37:51 -0700462 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400463 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
464 function(self)
465 }
466
David Tolnay725e1c62018-09-01 12:07:25 -0700467 /// Looks at the next token in the parse stream to determine whether it
468 /// matches the requested type of token.
469 ///
470 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700471 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700472 /// # Syntax
473 ///
474 /// Note that this method does not use turbofish syntax. Pass the peek type
475 /// inside of parentheses.
476 ///
477 /// - `input.peek(Token![struct])`
478 /// - `input.peek(Token![==])`
David Tolnayb8a68e42019-04-22 14:01:56 -0700479 /// - `input.peek(Ident)`&emsp;*(does not accept keywords)*
480 /// - `input.peek(Ident::peek_any)`
David Tolnay7d229e82018-09-01 16:42:34 -0700481 /// - `input.peek(Lifetime)`
482 /// - `input.peek(token::Brace)`
483 ///
David Tolnayddebc3e2018-09-01 16:29:20 -0700484 /// # Example
485 ///
486 /// In this example we finish parsing the list of supertraits when the next
487 /// token in the input is either `where` or an opening curly brace.
488 ///
David Tolnay95989db2019-01-01 15:05:57 -0500489 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500490 /// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
David Tolnay67fea042018-11-24 14:50:20 -0800491 /// use syn::parse::{Parse, ParseStream};
David Tolnayddebc3e2018-09-01 16:29:20 -0700492 /// use syn::punctuated::Punctuated;
493 ///
494 /// // Parses a trait definition containing no associated items.
495 /// //
496 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
497 /// struct MarkerTrait {
498 /// trait_token: Token![trait],
499 /// ident: Ident,
500 /// generics: Generics,
501 /// colon_token: Option<Token![:]>,
502 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
503 /// brace_token: token::Brace,
504 /// }
505 ///
506 /// impl Parse for MarkerTrait {
507 /// fn parse(input: ParseStream) -> Result<Self> {
508 /// let trait_token: Token![trait] = input.parse()?;
509 /// let ident: Ident = input.parse()?;
510 /// let mut generics: Generics = input.parse()?;
511 /// let colon_token: Option<Token![:]> = input.parse()?;
512 ///
513 /// let mut supertraits = Punctuated::new();
514 /// if colon_token.is_some() {
515 /// loop {
516 /// supertraits.push_value(input.parse()?);
517 /// if input.peek(Token![where]) || input.peek(token::Brace) {
518 /// break;
519 /// }
520 /// supertraits.push_punct(input.parse()?);
521 /// }
522 /// }
523 ///
524 /// generics.where_clause = input.parse()?;
525 /// let content;
526 /// let empty_brace_token = braced!(content in input);
527 ///
528 /// Ok(MarkerTrait {
529 /// trait_token: trait_token,
530 /// ident: ident,
531 /// generics: generics,
532 /// colon_token: colon_token,
533 /// supertraits: supertraits,
534 /// brace_token: empty_brace_token,
535 /// })
536 /// }
537 /// }
David Tolnayddebc3e2018-09-01 16:29:20 -0700538 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400539 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700540 let _ = token;
541 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400542 }
543
David Tolnay725e1c62018-09-01 12:07:25 -0700544 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700545 ///
546 /// This is commonly useful as a way to implement contextual keywords.
547 ///
548 /// # Example
549 ///
550 /// This example needs to use `peek2` because the symbol `union` is not a
551 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
552 /// the very next token is `union`, because someone is free to write a `mod
553 /// union` and a macro invocation that looks like `union::some_macro! { ...
554 /// }`. In other words `union` is a contextual keyword.
555 ///
David Tolnay95989db2019-01-01 15:05:57 -0500556 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500557 /// use syn::{Ident, ItemUnion, Macro, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800558 /// use syn::parse::{Parse, ParseStream};
David Tolnaye334b872018-09-01 16:38:10 -0700559 ///
560 /// // Parses either a union or a macro invocation.
561 /// enum UnionOrMacro {
562 /// // union MaybeUninit<T> { uninit: (), value: T }
563 /// Union(ItemUnion),
564 /// // lazy_static! { ... }
565 /// Macro(Macro),
566 /// }
567 ///
568 /// impl Parse for UnionOrMacro {
569 /// fn parse(input: ParseStream) -> Result<Self> {
570 /// if input.peek(Token![union]) && input.peek2(Ident) {
571 /// input.parse().map(UnionOrMacro::Union)
572 /// } else {
573 /// input.parse().map(UnionOrMacro::Macro)
574 /// }
575 /// }
576 /// }
David Tolnaye334b872018-09-01 16:38:10 -0700577 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400578 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400579 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700580 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400581 }
582
David Tolnay725e1c62018-09-01 12:07:25 -0700583 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400584 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400585 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700586 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400587 }
588
David Tolnay725e1c62018-09-01 12:07:25 -0700589 /// Parses zero or more occurrences of `T` separated by punctuation of type
590 /// `P`, with optional trailing punctuation.
591 ///
592 /// Parsing continues until the end of this parse stream. The entire content
593 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700594 ///
595 /// # Example
596 ///
David Tolnay95989db2019-01-01 15:05:57 -0500597 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500598 /// # use quote::quote;
David Tolnay0abe65b2018-09-01 14:31:43 -0700599 /// #
David Tolnayfd5b1172018-12-31 17:54:36 -0500600 /// use syn::{parenthesized, token, Ident, Result, Token, Type};
David Tolnay67fea042018-11-24 14:50:20 -0800601 /// use syn::parse::{Parse, ParseStream};
David Tolnay0abe65b2018-09-01 14:31:43 -0700602 /// use syn::punctuated::Punctuated;
603 ///
604 /// // Parse a simplified tuple struct syntax like:
605 /// //
606 /// // struct S(A, B);
607 /// struct TupleStruct {
608 /// struct_token: Token![struct],
609 /// ident: Ident,
610 /// paren_token: token::Paren,
611 /// fields: Punctuated<Type, Token![,]>,
612 /// semi_token: Token![;],
613 /// }
614 ///
615 /// impl Parse for TupleStruct {
616 /// fn parse(input: ParseStream) -> Result<Self> {
617 /// let content;
618 /// Ok(TupleStruct {
619 /// struct_token: input.parse()?,
620 /// ident: input.parse()?,
621 /// paren_token: parenthesized!(content in input),
622 /// fields: content.parse_terminated(Type::parse)?,
623 /// semi_token: input.parse()?,
624 /// })
625 /// }
626 /// }
627 /// #
628 /// # fn main() {
629 /// # let input = quote! {
630 /// # struct S(A, B);
631 /// # };
632 /// # syn::parse2::<TupleStruct>(input).unwrap();
633 /// # }
634 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400635 pub fn parse_terminated<T, P: Parse>(
636 &self,
637 parser: fn(ParseStream) -> Result<T>,
638 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700639 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400640 }
641
David Tolnay725e1c62018-09-01 12:07:25 -0700642 /// Returns whether there are tokens remaining in this stream.
643 ///
644 /// This method returns true at the end of the content of a set of
645 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700646 ///
647 /// # Example
648 ///
David Tolnay95989db2019-01-01 15:05:57 -0500649 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500650 /// use syn::{braced, token, Ident, Item, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800651 /// use syn::parse::{Parse, ParseStream};
David Tolnaycce6b5f2018-09-01 14:24:46 -0700652 ///
653 /// // Parses a Rust `mod m { ... }` containing zero or more items.
654 /// struct Mod {
655 /// mod_token: Token![mod],
656 /// name: Ident,
657 /// brace_token: token::Brace,
658 /// items: Vec<Item>,
659 /// }
660 ///
661 /// impl Parse for Mod {
662 /// fn parse(input: ParseStream) -> Result<Self> {
663 /// let content;
664 /// Ok(Mod {
665 /// mod_token: input.parse()?,
666 /// name: input.parse()?,
667 /// brace_token: braced!(content in input),
668 /// items: {
669 /// let mut items = Vec::new();
670 /// while !content.is_empty() {
671 /// items.push(content.parse()?);
672 /// }
673 /// items
674 /// },
675 /// })
676 /// }
677 /// }
David Tolnayf2b78602018-11-06 20:42:37 -0800678 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700679 pub fn is_empty(&self) -> bool {
680 self.cursor().eof()
681 }
682
David Tolnay725e1c62018-09-01 12:07:25 -0700683 /// Constructs a helper for peeking at the next token in this stream and
684 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700685 ///
686 /// # Example
687 ///
David Tolnay95989db2019-01-01 15:05:57 -0500688 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500689 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, Token, TypeParam};
David Tolnay67fea042018-11-24 14:50:20 -0800690 /// use syn::parse::{Parse, ParseStream};
David Tolnay2c77e772018-09-01 14:18:46 -0700691 ///
692 /// // A generic parameter, a single one of the comma-separated elements inside
693 /// // angle brackets in:
694 /// //
695 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
696 /// //
697 /// // On invalid input, lookahead gives us a reasonable error message.
698 /// //
699 /// // error: expected one of: identifier, lifetime, `const`
700 /// // |
701 /// // 5 | fn f<!Sized>() {}
702 /// // | ^
703 /// enum GenericParam {
704 /// Type(TypeParam),
705 /// Lifetime(LifetimeDef),
706 /// Const(ConstParam),
707 /// }
708 ///
709 /// impl Parse for GenericParam {
710 /// fn parse(input: ParseStream) -> Result<Self> {
711 /// let lookahead = input.lookahead1();
712 /// if lookahead.peek(Ident) {
713 /// input.parse().map(GenericParam::Type)
714 /// } else if lookahead.peek(Lifetime) {
715 /// input.parse().map(GenericParam::Lifetime)
716 /// } else if lookahead.peek(Token![const]) {
717 /// input.parse().map(GenericParam::Const)
718 /// } else {
719 /// Err(lookahead.error())
720 /// }
721 /// }
722 /// }
David Tolnay2c77e772018-09-01 14:18:46 -0700723 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700724 pub fn lookahead1(&self) -> Lookahead1<'a> {
cad9789bb9452019-01-20 18:33:48 -0500725 lookahead::new(*self.scope, self.cursor())
David Tolnayf5d30452018-09-01 02:29:04 -0700726 }
727
David Tolnay725e1c62018-09-01 12:07:25 -0700728 /// Forks a parse stream so that parsing tokens out of either the original
729 /// or the fork does not advance the position of the other.
730 ///
731 /// # Performance
732 ///
733 /// Forking a parse stream is a cheap fixed amount of work and does not
734 /// involve copying token buffers. Where you might hit performance problems
735 /// is if your macro ends up parsing a large amount of content more than
736 /// once.
737 ///
David Tolnay95989db2019-01-01 15:05:57 -0500738 /// ```edition2018
David Tolnay67fea042018-11-24 14:50:20 -0800739 /// # use syn::{Expr, Result};
740 /// # use syn::parse::ParseStream;
David Tolnay725e1c62018-09-01 12:07:25 -0700741 /// #
742 /// # fn bad(input: ParseStream) -> Result<Expr> {
743 /// // Do not do this.
744 /// if input.fork().parse::<Expr>().is_ok() {
745 /// return input.parse::<Expr>();
746 /// }
747 /// # unimplemented!()
748 /// # }
749 /// ```
750 ///
751 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
752 /// parse stream. Only use a fork when the amount of work performed against
753 /// the fork is small and bounded.
754 ///
cad9789bb9452019-01-20 18:33:48 -0500755 /// For higher level speculative parsing, [`parse::discouraged::Speculative`]
756 /// is provided alongside matching tradeoffs to enable the pattern.
David Tolnayec149b02018-09-01 14:17:28 -0700757 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700758 /// speculative parsing, consider using [`ParseStream::step`] instead.
759 ///
760 /// [`ParseStream::step`]: #method.step
cad9789bb9452019-01-20 18:33:48 -0500761 /// [`parse::discouraged::Speculative`]: ./discouraged/trait.Speculative.html
David Tolnayec149b02018-09-01 14:17:28 -0700762 ///
763 /// # Example
764 ///
765 /// The parse implementation shown here parses possibly restricted `pub`
766 /// visibilities.
767 ///
768 /// - `pub`
769 /// - `pub(crate)`
770 /// - `pub(self)`
771 /// - `pub(super)`
772 /// - `pub(in some::path)`
773 ///
774 /// To handle the case of visibilities inside of tuple structs, the parser
775 /// needs to distinguish parentheses that specify visibility restrictions
776 /// from parentheses that form part of a tuple type.
777 ///
David Tolnay95989db2019-01-01 15:05:57 -0500778 /// ```edition2018
David Tolnayec149b02018-09-01 14:17:28 -0700779 /// # struct A;
780 /// # struct B;
781 /// # struct C;
782 /// #
783 /// struct S(pub(crate) A, pub (B, C));
784 /// ```
785 ///
786 /// In this example input the first tuple struct element of `S` has
787 /// `pub(crate)` visibility while the second tuple struct element has `pub`
788 /// visibility; the parentheses around `(B, C)` are part of the type rather
789 /// than part of a visibility restriction.
790 ///
791 /// The parser uses a forked parse stream to check the first token inside of
792 /// parentheses after the `pub` keyword. This is a small bounded amount of
793 /// work performed against the forked parse stream.
794 ///
David Tolnay95989db2019-01-01 15:05:57 -0500795 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500796 /// use syn::{parenthesized, token, Ident, Path, Result, Token};
David Tolnayec149b02018-09-01 14:17:28 -0700797 /// use syn::ext::IdentExt;
David Tolnay67fea042018-11-24 14:50:20 -0800798 /// use syn::parse::{Parse, ParseStream};
David Tolnayec149b02018-09-01 14:17:28 -0700799 ///
800 /// struct PubVisibility {
801 /// pub_token: Token![pub],
802 /// restricted: Option<Restricted>,
803 /// }
804 ///
805 /// struct Restricted {
806 /// paren_token: token::Paren,
807 /// in_token: Option<Token![in]>,
808 /// path: Path,
809 /// }
810 ///
811 /// impl Parse for PubVisibility {
812 /// fn parse(input: ParseStream) -> Result<Self> {
813 /// let pub_token: Token![pub] = input.parse()?;
814 ///
815 /// if input.peek(token::Paren) {
816 /// let ahead = input.fork();
817 /// let mut content;
818 /// parenthesized!(content in ahead);
819 ///
820 /// if content.peek(Token![crate])
821 /// || content.peek(Token![self])
822 /// || content.peek(Token![super])
823 /// {
824 /// return Ok(PubVisibility {
825 /// pub_token: pub_token,
826 /// restricted: Some(Restricted {
827 /// paren_token: parenthesized!(content in input),
828 /// in_token: None,
829 /// path: Path::from(content.call(Ident::parse_any)?),
830 /// }),
831 /// });
832 /// } else if content.peek(Token![in]) {
833 /// return Ok(PubVisibility {
834 /// pub_token: pub_token,
835 /// restricted: Some(Restricted {
836 /// paren_token: parenthesized!(content in input),
837 /// in_token: Some(content.parse()?),
838 /// path: content.call(Path::parse_mod_style)?,
839 /// }),
840 /// });
841 /// }
842 /// }
843 ///
844 /// Ok(PubVisibility {
845 /// pub_token: pub_token,
846 /// restricted: None,
847 /// })
848 /// }
849 /// }
David Tolnayec149b02018-09-01 14:17:28 -0700850 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400851 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400852 ParseBuffer {
cad9789bb9452019-01-20 18:33:48 -0500853 scope: Rc::clone(&self.scope),
David Tolnay6456a9d2018-08-26 08:11:18 -0400854 cell: self.cell.clone(),
855 marker: PhantomData,
856 // Not the parent's unexpected. Nothing cares whether the clone
857 // parses all the way.
858 unexpected: Rc::new(Cell::new(None)),
859 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400860 }
861
David Tolnay725e1c62018-09-01 12:07:25 -0700862 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700863 ///
864 /// # Example
865 ///
David Tolnay95989db2019-01-01 15:05:57 -0500866 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500867 /// use syn::{Expr, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800868 /// use syn::parse::{Parse, ParseStream};
David Tolnay23fce0b2018-09-01 13:50:31 -0700869 ///
870 /// // Some kind of loop: `while` or `for` or `loop`.
871 /// struct Loop {
872 /// expr: Expr,
873 /// }
874 ///
875 /// impl Parse for Loop {
876 /// fn parse(input: ParseStream) -> Result<Self> {
877 /// if input.peek(Token![while])
878 /// || input.peek(Token![for])
879 /// || input.peek(Token![loop])
880 /// {
881 /// Ok(Loop {
882 /// expr: input.parse()?,
883 /// })
884 /// } else {
885 /// Err(input.error("expected some kind of loop"))
886 /// }
887 /// }
888 /// }
889 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400890 pub fn error<T: Display>(&self, message: T) -> Error {
cad9789bb9452019-01-20 18:33:48 -0500891 error::new_at(*self.scope, self.cursor(), message)
David Tolnay4fb71232018-08-25 23:14:50 -0400892 }
893
David Tolnay725e1c62018-09-01 12:07:25 -0700894 /// Speculatively parses tokens from this parse stream, advancing the
895 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700896 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700897 /// This is a powerful low-level API used for defining the `Parse` impls of
898 /// the basic built-in token types. It is not something that will be used
899 /// widely outside of the Syn codebase.
900 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700901 /// # Example
902 ///
David Tolnay95989db2019-01-01 15:05:57 -0500903 /// ```edition2018
David Tolnay9bd34392018-09-01 13:19:53 -0700904 /// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800905 /// use syn::Result;
906 /// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700907 ///
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;
David Tolnaydb312582018-11-06 20:42:05 -0800914 /// while let Some((tt, next)) = rest.token_tree() {
David Tolnay65336072019-04-22 23:10:52 -0700915 /// match &tt {
916 /// TokenTree::Punct(punct) if punct.as_char() == '@' => {
David Tolnay9bd34392018-09-01 13:19:53 -0700917 /// return Ok(((), next));
918 /// }
919 /// _ => rest = next,
920 /// }
921 /// }
922 /// Err(cursor.error("no `@` was found after this point"))
923 /// })
924 /// }
925 /// #
David Tolnaydb312582018-11-06 20:42:05 -0800926 /// # fn remainder_after_skipping_past_next_at(
927 /// # input: ParseStream,
928 /// # ) -> Result<proc_macro2::TokenStream> {
929 /// # skip_past_next_at(input)?;
930 /// # input.parse()
931 /// # }
932 /// #
933 /// # fn main() {
934 /// # use syn::parse::Parser;
935 /// # let remainder = remainder_after_skipping_past_next_at
936 /// # .parse_str("a @ b c")
937 /// # .unwrap();
938 /// # assert_eq!(remainder.to_string(), "b c");
939 /// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700940 /// ```
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 {
cad9789bb9452019-01-20 18:33:48 -0500963 scope: *self.scope,
David Tolnay18c754c2018-08-21 23:26:58 -0400964 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.
Jethro Beekman33c22332018-12-31 11:16:25 +05301063 ///
1064 /// This function will check that the input is fully parsed. If there are
1065 /// any unparsed tokens at the end of the stream, an error is returned.
David Tolnay80a914f2018-08-30 23:49:53 -07001066 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1067
1068 /// Parse tokens of source code into the chosen syntax tree node.
1069 ///
Jethro Beekman33c22332018-12-31 11:16:25 +05301070 /// This function will check that the input is fully parsed. If there are
1071 /// any unparsed tokens at the end of the stream, an error is returned.
1072 ///
David Tolnay80a914f2018-08-30 23:49:53 -07001073 /// *This method is available if Syn is built with both the `"parsing"` and
1074 /// `"proc-macro"` features.*
1075 #[cfg(all(
1076 not(all(target_arch = "wasm32", target_os = "unknown")),
1077 feature = "proc-macro"
1078 ))]
1079 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1080 self.parse2(proc_macro2::TokenStream::from(tokens))
1081 }
1082
1083 /// Parse a string of Rust code into the chosen syntax tree node.
1084 ///
Jethro Beekman33c22332018-12-31 11:16:25 +05301085 /// This function will check that the input is fully parsed. If there are
1086 /// any unparsed tokens at the end of the string, an error is returned.
1087 ///
David Tolnay80a914f2018-08-30 23:49:53 -07001088 /// # Hygiene
1089 ///
1090 /// Every span in the resulting syntax tree will be set to resolve at the
1091 /// macro call site.
1092 fn parse_str(self, s: &str) -> Result<Self::Output> {
1093 self.parse2(proc_macro2::TokenStream::from_str(s)?)
1094 }
1095}
1096
David Tolnay7b07aa12018-09-01 11:41:12 -07001097fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1098 let scope = Span::call_site();
1099 let cursor = tokens.begin();
1100 let unexpected = Rc::new(Cell::new(None));
1101 private::new_parse_buffer(scope, cursor, unexpected)
1102}
1103
David Tolnay80a914f2018-08-30 23:49:53 -07001104impl<F, T> Parser for F
1105where
1106 F: FnOnce(ParseStream) -> Result<T>,
1107{
1108 type Output = T;
1109
1110 fn parse2(self, tokens: TokenStream) -> Result<T> {
1111 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -07001112 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -07001113 let node = self(&state)?;
1114 state.check_unexpected()?;
1115 if state.is_empty() {
1116 Ok(node)
1117 } else {
1118 Err(state.error("unexpected token"))
1119 }
1120 }
1121}