blob: dc724ca6b0abc4751a6156b38c16fefaddf8f747 [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
cad9789bb9452019-01-20 18:33:48 -0500191pub mod discouraged;
192
David Tolnay18c754c2018-08-21 23:26:58 -0400193use std::cell::Cell;
Diggory Hardy1c522e12018-11-02 10:10:02 +0000194use std::fmt::{self, Debug, Display};
David Tolnay18c754c2018-08-21 23:26:58 -0400195use std::marker::PhantomData;
196use std::mem;
197use std::ops::Deref;
David Tolnayeafc8052018-08-25 16:33:53 -0400198use std::rc::Rc;
David Tolnay80a914f2018-08-30 23:49:53 -0700199use std::str::FromStr;
David Tolnayeafc8052018-08-25 16:33:53 -0400200
David Tolnay80a914f2018-08-30 23:49:53 -0700201#[cfg(all(
202 not(all(target_arch = "wasm32", target_os = "unknown")),
203 feature = "proc-macro"
204))]
205use proc_macro;
David Tolnayf07b3342018-09-01 11:58:11 -0700206use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
David Tolnay18c754c2018-08-21 23:26:58 -0400207
David Tolnay80a914f2018-08-30 23:49:53 -0700208use buffer::{Cursor, TokenBuffer};
David Tolnayb6254182018-08-25 08:44:54 -0400209use error;
David Tolnay94f06632018-08-31 10:17:17 -0700210use lookahead;
211use private;
David Tolnay577d0332018-08-25 21:45:24 -0400212use punctuated::Punctuated;
David Tolnay4fb71232018-08-25 23:14:50 -0400213use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -0400214
David Tolnayb6254182018-08-25 08:44:54 -0400215pub use error::{Error, Result};
216pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -0400217
218/// Parsing interface implemented by all types that can be parsed in a default
219/// way from a token stream.
220pub trait Parse: Sized {
221 fn parse(input: ParseStream) -> Result<Self>;
222}
223
224/// Input to a Syn parser function.
David Tolnaya0daa482018-09-01 02:09:40 -0700225///
226/// See the methods of this type under the documentation of [`ParseBuffer`]. For
227/// an overview of parsing in Syn, refer to the [module documentation].
228///
229/// [module documentation]: index.html
David Tolnay18c754c2018-08-21 23:26:58 -0400230pub type ParseStream<'a> = &'a ParseBuffer<'a>;
231
232/// Cursor position within a buffered token stream.
David Tolnay20d29a12018-09-01 15:15:33 -0700233///
234/// This type is more commonly used through the type alias [`ParseStream`] which
235/// is an alias for `&ParseBuffer`.
236///
237/// `ParseStream` is the input type for all parser functions in Syn. They have
238/// the signature `fn(ParseStream) -> Result<T>`.
David Tolnay028a7d72018-12-31 17:11:02 -0500239///
240/// ## Calling a parser function
241///
242/// There is no public way to construct a `ParseBuffer`. Instead, if you are
243/// looking to invoke a parser function that requires `ParseStream` as input,
244/// you will need to go through one of the public parsing entry points.
245///
246/// - The [`parse_macro_input!`] macro if parsing input of a procedural macro;
247/// - One of [the `syn::parse*` functions][syn-parse]; or
248/// - A method of the [`Parser`] trait.
249///
250/// [`parse_macro_input!`]: ../macro.parse_macro_input.html
251/// [syn-parse]: index.html#the-synparse-functions
David Tolnay18c754c2018-08-21 23:26:58 -0400252pub struct ParseBuffer<'a> {
cad9789bb9452019-01-20 18:33:48 -0500253 // The identity of this Rc tracks the origin of forks.
254 // That is, any Rc which is Rc::ptr_eq are derived from the same cursor,
255 // and thus the cursor may be copied between them safely.
256 // Thus a new Rc must be created for a new buffer, and only be cloned on fork.
257 scope: Rc<Span>,
David Tolnay5d7f2252018-09-02 08:21:40 -0700258 // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
259 // The rest of the code in this module needs to be careful that only a
260 // cursor derived from this `cell` is ever assigned to this `cell`.
261 //
262 // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
263 // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
264 // than 'a, and then assign a Cursor<'short> into the Cell.
265 //
266 // By extension, it would not be safe to expose an API that accepts a
267 // Cursor<'a> and trusts that it lives as long as the cursor currently in
268 // the cell.
David Tolnay18c754c2018-08-21 23:26:58 -0400269 cell: Cell<Cursor<'static>>,
270 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400271 unexpected: Rc<Cell<Option<Span>>>,
272}
273
274impl<'a> Drop for ParseBuffer<'a> {
275 fn drop(&mut self) {
276 if !self.is_empty() && self.unexpected.get().is_none() {
277 self.unexpected.set(Some(self.cursor().span()));
278 }
279 }
David Tolnay18c754c2018-08-21 23:26:58 -0400280}
281
Diggory Hardy1c522e12018-11-02 10:10:02 +0000282impl<'a> Display for ParseBuffer<'a> {
283 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
284 Display::fmt(&self.cursor().token_stream(), f)
285 }
286}
287
288impl<'a> Debug for ParseBuffer<'a> {
289 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
290 Debug::fmt(&self.cursor().token_stream(), f)
291 }
292}
293
David Tolnay642832f2018-09-01 13:08:10 -0700294/// Cursor state associated with speculative parsing.
295///
296/// This type is the input of the closure provided to [`ParseStream::step`].
297///
298/// [`ParseStream::step`]: struct.ParseBuffer.html#method.step
David Tolnay9bd34392018-09-01 13:19:53 -0700299///
300/// # Example
301///
David Tolnay95989db2019-01-01 15:05:57 -0500302/// ```edition2018
David Tolnay9bd34392018-09-01 13:19:53 -0700303/// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800304/// use syn::Result;
305/// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700306///
307/// // This function advances the stream past the next occurrence of `@`. If
308/// // no `@` is present in the stream, the stream position is unchanged and
309/// // an error is returned.
310/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
311/// input.step(|cursor| {
312/// let mut rest = *cursor;
Sharad Chande1df40a2018-09-08 15:25:52 +0545313/// while let Some((tt, next)) = rest.token_tree() {
David Tolnay65336072019-04-22 23:10:52 -0700314/// match &tt {
315/// TokenTree::Punct(punct) if punct.as_char() == '@' => {
David Tolnay9bd34392018-09-01 13:19:53 -0700316/// return Ok(((), next));
317/// }
318/// _ => rest = next,
319/// }
320/// }
321/// Err(cursor.error("no `@` was found after this point"))
322/// })
323/// }
324/// #
David Tolnaydb312582018-11-06 20:42:05 -0800325/// # fn remainder_after_skipping_past_next_at(
326/// # input: ParseStream,
327/// # ) -> Result<proc_macro2::TokenStream> {
328/// # skip_past_next_at(input)?;
329/// # input.parse()
330/// # }
331/// #
332/// # fn main() {
333/// # use syn::parse::Parser;
334/// # let remainder = remainder_after_skipping_past_next_at
335/// # .parse_str("a @ b c")
336/// # .unwrap();
337/// # assert_eq!(remainder.to_string(), "b c");
338/// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700339/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400340#[derive(Copy, Clone)]
341pub struct StepCursor<'c, 'a> {
342 scope: Span,
David Tolnay56924f42018-09-02 08:24:58 -0700343 // This field is covariant in 'c.
David Tolnay18c754c2018-08-21 23:26:58 -0400344 cursor: Cursor<'c>,
David Tolnay56924f42018-09-02 08:24:58 -0700345 // This field is contravariant in 'c. Together these make StepCursor
346 // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
347 // different lifetime but can upcast into a StepCursor with a shorter
348 // lifetime 'a.
349 //
350 // As long as we only ever construct a StepCursor for which 'c outlives 'a,
351 // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
352 // outlives 'a.
David Tolnay18c754c2018-08-21 23:26:58 -0400353 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
354}
355
356impl<'c, 'a> Deref for StepCursor<'c, 'a> {
357 type Target = Cursor<'c>;
358
359 fn deref(&self) -> &Self::Target {
360 &self.cursor
361 }
362}
363
364impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700365 /// Triggers an error at the current position of the parse stream.
366 ///
367 /// The `ParseStream::step` invocation will return this same error without
368 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400369 pub fn error<T: Display>(self, message: T) -> Error {
370 error::new_at(self.scope, self.cursor, message)
371 }
372}
373
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700374impl private {
375 pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
David Tolnay56924f42018-09-02 08:24:58 -0700376 // Refer to the comments within the StepCursor definition. We use the
377 // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
378 // Cursor is covariant in its lifetime parameter so we can cast a
379 // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700380 let _ = proof;
381 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
382 }
383}
384
David Tolnay66cb0c42018-08-31 09:01:30 -0700385fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700386 input
387 .step(|cursor| {
388 if let Some((_lifetime, rest)) = cursor.lifetime() {
389 Ok((true, rest))
390 } else if let Some((_token, rest)) = cursor.token_tree() {
391 Ok((true, rest))
392 } else {
393 Ok((false, *cursor))
394 }
David Tolnayfb84fc02018-10-02 21:01:30 -0700395 })
396 .unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700397}
398
David Tolnay10951d52018-08-31 10:27:39 -0700399impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700400 pub fn new_parse_buffer(
401 scope: Span,
402 cursor: Cursor,
403 unexpected: Rc<Cell<Option<Span>>>,
404 ) -> ParseBuffer {
David Tolnay18c754c2018-08-21 23:26:58 -0400405 ParseBuffer {
cad9789bb9452019-01-20 18:33:48 -0500406 scope: Rc::new(scope),
David Tolnay5d7f2252018-09-02 08:21:40 -0700407 // See comment on `cell` in the struct definition.
408 cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
David Tolnay18c754c2018-08-21 23:26:58 -0400409 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400410 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400411 }
412 }
413
David Tolnay94f06632018-08-31 10:17:17 -0700414 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
415 buffer.unexpected.clone()
416 }
417}
418
419impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700420 /// Parses a syntax tree node of type `T`, advancing the position of our
421 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400422 pub fn parse<T: Parse>(&self) -> Result<T> {
423 T::parse(self)
424 }
425
David Tolnay725e1c62018-09-01 12:07:25 -0700426 /// Calls the given parser function to parse a syntax tree node of type `T`
427 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700428 ///
429 /// # Example
430 ///
431 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
432 /// zero or more outer attributes.
433 ///
434 /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
435 ///
David Tolnay95989db2019-01-01 15:05:57 -0500436 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500437 /// use syn::{Attribute, Ident, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800438 /// use syn::parse::{Parse, ParseStream};
David Tolnay21ce84c2018-09-01 15:37:51 -0700439 ///
440 /// // Parses a unit struct with attributes.
441 /// //
442 /// // #[path = "s.tmpl"]
443 /// // struct S;
444 /// struct UnitStruct {
445 /// attrs: Vec<Attribute>,
446 /// struct_token: Token![struct],
447 /// name: Ident,
448 /// semi_token: Token![;],
449 /// }
450 ///
451 /// impl Parse for UnitStruct {
452 /// fn parse(input: ParseStream) -> Result<Self> {
453 /// Ok(UnitStruct {
454 /// attrs: input.call(Attribute::parse_outer)?,
455 /// struct_token: input.parse()?,
456 /// name: input.parse()?,
457 /// semi_token: input.parse()?,
458 /// })
459 /// }
460 /// }
David Tolnay21ce84c2018-09-01 15:37:51 -0700461 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400462 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
463 function(self)
464 }
465
David Tolnay725e1c62018-09-01 12:07:25 -0700466 /// Looks at the next token in the parse stream to determine whether it
467 /// matches the requested type of token.
468 ///
469 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700470 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700471 /// # Syntax
472 ///
473 /// Note that this method does not use turbofish syntax. Pass the peek type
474 /// inside of parentheses.
475 ///
476 /// - `input.peek(Token![struct])`
477 /// - `input.peek(Token![==])`
David Tolnayb8a68e42019-04-22 14:01:56 -0700478 /// - `input.peek(Ident)`&emsp;*(does not accept keywords)*
479 /// - `input.peek(Ident::peek_any)`
David Tolnay7d229e82018-09-01 16:42:34 -0700480 /// - `input.peek(Lifetime)`
481 /// - `input.peek(token::Brace)`
482 ///
David Tolnayddebc3e2018-09-01 16:29:20 -0700483 /// # Example
484 ///
485 /// In this example we finish parsing the list of supertraits when the next
486 /// token in the input is either `where` or an opening curly brace.
487 ///
David Tolnay95989db2019-01-01 15:05:57 -0500488 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500489 /// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
David Tolnay67fea042018-11-24 14:50:20 -0800490 /// use syn::parse::{Parse, ParseStream};
David Tolnayddebc3e2018-09-01 16:29:20 -0700491 /// use syn::punctuated::Punctuated;
492 ///
493 /// // Parses a trait definition containing no associated items.
494 /// //
495 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
496 /// struct MarkerTrait {
497 /// trait_token: Token![trait],
498 /// ident: Ident,
499 /// generics: Generics,
500 /// colon_token: Option<Token![:]>,
501 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
502 /// brace_token: token::Brace,
503 /// }
504 ///
505 /// impl Parse for MarkerTrait {
506 /// fn parse(input: ParseStream) -> Result<Self> {
507 /// let trait_token: Token![trait] = input.parse()?;
508 /// let ident: Ident = input.parse()?;
509 /// let mut generics: Generics = input.parse()?;
510 /// let colon_token: Option<Token![:]> = input.parse()?;
511 ///
512 /// let mut supertraits = Punctuated::new();
513 /// if colon_token.is_some() {
514 /// loop {
515 /// supertraits.push_value(input.parse()?);
516 /// if input.peek(Token![where]) || input.peek(token::Brace) {
517 /// break;
518 /// }
519 /// supertraits.push_punct(input.parse()?);
520 /// }
521 /// }
522 ///
523 /// generics.where_clause = input.parse()?;
524 /// let content;
525 /// let empty_brace_token = braced!(content in input);
526 ///
527 /// Ok(MarkerTrait {
528 /// trait_token: trait_token,
529 /// ident: ident,
530 /// generics: generics,
531 /// colon_token: colon_token,
532 /// supertraits: supertraits,
533 /// brace_token: empty_brace_token,
534 /// })
535 /// }
536 /// }
David Tolnayddebc3e2018-09-01 16:29:20 -0700537 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400538 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700539 let _ = token;
540 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400541 }
542
David Tolnay725e1c62018-09-01 12:07:25 -0700543 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700544 ///
545 /// This is commonly useful as a way to implement contextual keywords.
546 ///
547 /// # Example
548 ///
549 /// This example needs to use `peek2` because the symbol `union` is not a
550 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
551 /// the very next token is `union`, because someone is free to write a `mod
552 /// union` and a macro invocation that looks like `union::some_macro! { ...
553 /// }`. In other words `union` is a contextual keyword.
554 ///
David Tolnay95989db2019-01-01 15:05:57 -0500555 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500556 /// use syn::{Ident, ItemUnion, Macro, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800557 /// use syn::parse::{Parse, ParseStream};
David Tolnaye334b872018-09-01 16:38:10 -0700558 ///
559 /// // Parses either a union or a macro invocation.
560 /// enum UnionOrMacro {
561 /// // union MaybeUninit<T> { uninit: (), value: T }
562 /// Union(ItemUnion),
563 /// // lazy_static! { ... }
564 /// Macro(Macro),
565 /// }
566 ///
567 /// impl Parse for UnionOrMacro {
568 /// fn parse(input: ParseStream) -> Result<Self> {
569 /// if input.peek(Token![union]) && input.peek2(Ident) {
570 /// input.parse().map(UnionOrMacro::Union)
571 /// } else {
572 /// input.parse().map(UnionOrMacro::Macro)
573 /// }
574 /// }
575 /// }
David Tolnaye334b872018-09-01 16:38:10 -0700576 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400577 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400578 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700579 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400580 }
581
David Tolnay725e1c62018-09-01 12:07:25 -0700582 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400583 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400584 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700585 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400586 }
587
David Tolnay725e1c62018-09-01 12:07:25 -0700588 /// Parses zero or more occurrences of `T` separated by punctuation of type
589 /// `P`, with optional trailing punctuation.
590 ///
591 /// Parsing continues until the end of this parse stream. The entire content
592 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700593 ///
594 /// # Example
595 ///
David Tolnay95989db2019-01-01 15:05:57 -0500596 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500597 /// # use quote::quote;
David Tolnay0abe65b2018-09-01 14:31:43 -0700598 /// #
David Tolnayfd5b1172018-12-31 17:54:36 -0500599 /// use syn::{parenthesized, token, Ident, Result, Token, Type};
David Tolnay67fea042018-11-24 14:50:20 -0800600 /// use syn::parse::{Parse, ParseStream};
David Tolnay0abe65b2018-09-01 14:31:43 -0700601 /// use syn::punctuated::Punctuated;
602 ///
603 /// // Parse a simplified tuple struct syntax like:
604 /// //
605 /// // struct S(A, B);
606 /// struct TupleStruct {
607 /// struct_token: Token![struct],
608 /// ident: Ident,
609 /// paren_token: token::Paren,
610 /// fields: Punctuated<Type, Token![,]>,
611 /// semi_token: Token![;],
612 /// }
613 ///
614 /// impl Parse for TupleStruct {
615 /// fn parse(input: ParseStream) -> Result<Self> {
616 /// let content;
617 /// Ok(TupleStruct {
618 /// struct_token: input.parse()?,
619 /// ident: input.parse()?,
620 /// paren_token: parenthesized!(content in input),
621 /// fields: content.parse_terminated(Type::parse)?,
622 /// semi_token: input.parse()?,
623 /// })
624 /// }
625 /// }
626 /// #
627 /// # fn main() {
628 /// # let input = quote! {
629 /// # struct S(A, B);
630 /// # };
631 /// # syn::parse2::<TupleStruct>(input).unwrap();
632 /// # }
633 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400634 pub fn parse_terminated<T, P: Parse>(
635 &self,
636 parser: fn(ParseStream) -> Result<T>,
637 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700638 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400639 }
640
David Tolnay725e1c62018-09-01 12:07:25 -0700641 /// Returns whether there are tokens remaining in this stream.
642 ///
643 /// This method returns true at the end of the content of a set of
644 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700645 ///
646 /// # Example
647 ///
David Tolnay95989db2019-01-01 15:05:57 -0500648 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500649 /// use syn::{braced, token, Ident, Item, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800650 /// use syn::parse::{Parse, ParseStream};
David Tolnaycce6b5f2018-09-01 14:24:46 -0700651 ///
652 /// // Parses a Rust `mod m { ... }` containing zero or more items.
653 /// struct Mod {
654 /// mod_token: Token![mod],
655 /// name: Ident,
656 /// brace_token: token::Brace,
657 /// items: Vec<Item>,
658 /// }
659 ///
660 /// impl Parse for Mod {
661 /// fn parse(input: ParseStream) -> Result<Self> {
662 /// let content;
663 /// Ok(Mod {
664 /// mod_token: input.parse()?,
665 /// name: input.parse()?,
666 /// brace_token: braced!(content in input),
667 /// items: {
668 /// let mut items = Vec::new();
669 /// while !content.is_empty() {
670 /// items.push(content.parse()?);
671 /// }
672 /// items
673 /// },
674 /// })
675 /// }
676 /// }
David Tolnayf2b78602018-11-06 20:42:37 -0800677 /// ```
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 ///
David Tolnay95989db2019-01-01 15:05:57 -0500687 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500688 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, Token, TypeParam};
David Tolnay67fea042018-11-24 14:50:20 -0800689 /// use syn::parse::{Parse, ParseStream};
David Tolnay2c77e772018-09-01 14:18:46 -0700690 ///
691 /// // A generic parameter, a single one of the comma-separated elements inside
692 /// // angle brackets in:
693 /// //
694 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
695 /// //
696 /// // On invalid input, lookahead gives us a reasonable error message.
697 /// //
698 /// // error: expected one of: identifier, lifetime, `const`
699 /// // |
700 /// // 5 | fn f<!Sized>() {}
701 /// // | ^
702 /// enum GenericParam {
703 /// Type(TypeParam),
704 /// Lifetime(LifetimeDef),
705 /// Const(ConstParam),
706 /// }
707 ///
708 /// impl Parse for GenericParam {
709 /// fn parse(input: ParseStream) -> Result<Self> {
710 /// let lookahead = input.lookahead1();
711 /// if lookahead.peek(Ident) {
712 /// input.parse().map(GenericParam::Type)
713 /// } else if lookahead.peek(Lifetime) {
714 /// input.parse().map(GenericParam::Lifetime)
715 /// } else if lookahead.peek(Token![const]) {
716 /// input.parse().map(GenericParam::Const)
717 /// } else {
718 /// Err(lookahead.error())
719 /// }
720 /// }
721 /// }
David Tolnay2c77e772018-09-01 14:18:46 -0700722 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700723 pub fn lookahead1(&self) -> Lookahead1<'a> {
cad9789bb9452019-01-20 18:33:48 -0500724 lookahead::new(*self.scope, self.cursor())
David Tolnayf5d30452018-09-01 02:29:04 -0700725 }
726
David Tolnay725e1c62018-09-01 12:07:25 -0700727 /// Forks a parse stream so that parsing tokens out of either the original
728 /// or the fork does not advance the position of the other.
729 ///
730 /// # Performance
731 ///
732 /// Forking a parse stream is a cheap fixed amount of work and does not
733 /// involve copying token buffers. Where you might hit performance problems
734 /// is if your macro ends up parsing a large amount of content more than
735 /// once.
736 ///
David Tolnay95989db2019-01-01 15:05:57 -0500737 /// ```edition2018
David Tolnay67fea042018-11-24 14:50:20 -0800738 /// # use syn::{Expr, Result};
739 /// # use syn::parse::ParseStream;
David Tolnay725e1c62018-09-01 12:07:25 -0700740 /// #
741 /// # fn bad(input: ParseStream) -> Result<Expr> {
742 /// // Do not do this.
743 /// if input.fork().parse::<Expr>().is_ok() {
744 /// return input.parse::<Expr>();
745 /// }
746 /// # unimplemented!()
747 /// # }
748 /// ```
749 ///
750 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
751 /// parse stream. Only use a fork when the amount of work performed against
752 /// the fork is small and bounded.
753 ///
cad9789bb9452019-01-20 18:33:48 -0500754 /// For higher level speculative parsing, [`parse::discouraged::Speculative`]
755 /// is provided alongside matching tradeoffs to enable the pattern.
David Tolnayec149b02018-09-01 14:17:28 -0700756 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700757 /// speculative parsing, consider using [`ParseStream::step`] instead.
758 ///
759 /// [`ParseStream::step`]: #method.step
cad9789bb9452019-01-20 18:33:48 -0500760 /// [`parse::discouraged::Speculative`]: ./discouraged/trait.Speculative.html
David Tolnayec149b02018-09-01 14:17:28 -0700761 ///
762 /// # Example
763 ///
764 /// The parse implementation shown here parses possibly restricted `pub`
765 /// visibilities.
766 ///
767 /// - `pub`
768 /// - `pub(crate)`
769 /// - `pub(self)`
770 /// - `pub(super)`
771 /// - `pub(in some::path)`
772 ///
773 /// To handle the case of visibilities inside of tuple structs, the parser
774 /// needs to distinguish parentheses that specify visibility restrictions
775 /// from parentheses that form part of a tuple type.
776 ///
David Tolnay95989db2019-01-01 15:05:57 -0500777 /// ```edition2018
David Tolnayec149b02018-09-01 14:17:28 -0700778 /// # struct A;
779 /// # struct B;
780 /// # struct C;
781 /// #
782 /// struct S(pub(crate) A, pub (B, C));
783 /// ```
784 ///
785 /// In this example input the first tuple struct element of `S` has
786 /// `pub(crate)` visibility while the second tuple struct element has `pub`
787 /// visibility; the parentheses around `(B, C)` are part of the type rather
788 /// than part of a visibility restriction.
789 ///
790 /// The parser uses a forked parse stream to check the first token inside of
791 /// parentheses after the `pub` keyword. This is a small bounded amount of
792 /// work performed against the forked parse stream.
793 ///
David Tolnay95989db2019-01-01 15:05:57 -0500794 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500795 /// use syn::{parenthesized, token, Ident, Path, Result, Token};
David Tolnayec149b02018-09-01 14:17:28 -0700796 /// use syn::ext::IdentExt;
David Tolnay67fea042018-11-24 14:50:20 -0800797 /// use syn::parse::{Parse, ParseStream};
David Tolnayec149b02018-09-01 14:17:28 -0700798 ///
799 /// struct PubVisibility {
800 /// pub_token: Token![pub],
801 /// restricted: Option<Restricted>,
802 /// }
803 ///
804 /// struct Restricted {
805 /// paren_token: token::Paren,
806 /// in_token: Option<Token![in]>,
807 /// path: Path,
808 /// }
809 ///
810 /// impl Parse for PubVisibility {
811 /// fn parse(input: ParseStream) -> Result<Self> {
812 /// let pub_token: Token![pub] = input.parse()?;
813 ///
814 /// if input.peek(token::Paren) {
815 /// let ahead = input.fork();
816 /// let mut content;
817 /// parenthesized!(content in ahead);
818 ///
819 /// if content.peek(Token![crate])
820 /// || content.peek(Token![self])
821 /// || content.peek(Token![super])
822 /// {
823 /// return Ok(PubVisibility {
824 /// pub_token: pub_token,
825 /// restricted: Some(Restricted {
826 /// paren_token: parenthesized!(content in input),
827 /// in_token: None,
828 /// path: Path::from(content.call(Ident::parse_any)?),
829 /// }),
830 /// });
831 /// } else if content.peek(Token![in]) {
832 /// return Ok(PubVisibility {
833 /// pub_token: pub_token,
834 /// restricted: Some(Restricted {
835 /// paren_token: parenthesized!(content in input),
836 /// in_token: Some(content.parse()?),
837 /// path: content.call(Path::parse_mod_style)?,
838 /// }),
839 /// });
840 /// }
841 /// }
842 ///
843 /// Ok(PubVisibility {
844 /// pub_token: pub_token,
845 /// restricted: None,
846 /// })
847 /// }
848 /// }
David Tolnayec149b02018-09-01 14:17:28 -0700849 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400850 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400851 ParseBuffer {
cad9789bb9452019-01-20 18:33:48 -0500852 scope: Rc::clone(&self.scope),
David Tolnay6456a9d2018-08-26 08:11:18 -0400853 cell: self.cell.clone(),
854 marker: PhantomData,
855 // Not the parent's unexpected. Nothing cares whether the clone
856 // parses all the way.
857 unexpected: Rc::new(Cell::new(None)),
858 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400859 }
860
David Tolnay725e1c62018-09-01 12:07:25 -0700861 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700862 ///
863 /// # Example
864 ///
David Tolnay95989db2019-01-01 15:05:57 -0500865 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500866 /// use syn::{Expr, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800867 /// use syn::parse::{Parse, ParseStream};
David Tolnay23fce0b2018-09-01 13:50:31 -0700868 ///
869 /// // Some kind of loop: `while` or `for` or `loop`.
870 /// struct Loop {
871 /// expr: Expr,
872 /// }
873 ///
874 /// impl Parse for Loop {
875 /// fn parse(input: ParseStream) -> Result<Self> {
876 /// if input.peek(Token![while])
877 /// || input.peek(Token![for])
878 /// || input.peek(Token![loop])
879 /// {
880 /// Ok(Loop {
881 /// expr: input.parse()?,
882 /// })
883 /// } else {
884 /// Err(input.error("expected some kind of loop"))
885 /// }
886 /// }
887 /// }
888 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400889 pub fn error<T: Display>(&self, message: T) -> Error {
cad9789bb9452019-01-20 18:33:48 -0500890 error::new_at(*self.scope, self.cursor(), message)
David Tolnay4fb71232018-08-25 23:14:50 -0400891 }
892
David Tolnay725e1c62018-09-01 12:07:25 -0700893 /// Speculatively parses tokens from this parse stream, advancing the
894 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700895 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700896 /// This is a powerful low-level API used for defining the `Parse` impls of
897 /// the basic built-in token types. It is not something that will be used
898 /// widely outside of the Syn codebase.
899 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700900 /// # Example
901 ///
David Tolnay95989db2019-01-01 15:05:57 -0500902 /// ```edition2018
David Tolnay9bd34392018-09-01 13:19:53 -0700903 /// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800904 /// use syn::Result;
905 /// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700906 ///
907 /// // This function advances the stream past the next occurrence of `@`. If
908 /// // no `@` is present in the stream, the stream position is unchanged and
909 /// // an error is returned.
910 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
911 /// input.step(|cursor| {
912 /// let mut rest = *cursor;
David Tolnaydb312582018-11-06 20:42:05 -0800913 /// while let Some((tt, next)) = rest.token_tree() {
David Tolnay65336072019-04-22 23:10:52 -0700914 /// match &tt {
915 /// TokenTree::Punct(punct) if punct.as_char() == '@' => {
David Tolnay9bd34392018-09-01 13:19:53 -0700916 /// return Ok(((), next));
917 /// }
918 /// _ => rest = next,
919 /// }
920 /// }
921 /// Err(cursor.error("no `@` was found after this point"))
922 /// })
923 /// }
924 /// #
David Tolnaydb312582018-11-06 20:42:05 -0800925 /// # fn remainder_after_skipping_past_next_at(
926 /// # input: ParseStream,
927 /// # ) -> Result<proc_macro2::TokenStream> {
928 /// # skip_past_next_at(input)?;
929 /// # input.parse()
930 /// # }
931 /// #
932 /// # fn main() {
933 /// # use syn::parse::Parser;
934 /// # let remainder = remainder_after_skipping_past_next_at
935 /// # .parse_str("a @ b c")
936 /// # .unwrap();
937 /// # assert_eq!(remainder.to_string(), "b c");
938 /// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700939 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700940 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400941 where
942 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
943 {
David Tolnayc142b092018-09-02 08:52:52 -0700944 // Since the user's function is required to work for any 'c, we know
945 // that the Cursor<'c> they return is either derived from the input
946 // StepCursor<'c, 'a> or from a Cursor<'static>.
947 //
948 // It would not be legal to write this function without the invariant
949 // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
950 // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
951 // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
952 // `step` on their ParseBuffer<'short> with a closure that returns
953 // Cursor<'short>, and we would wrongly write that Cursor<'short> into
954 // the Cell intended to hold Cursor<'a>.
955 //
956 // In some cases it may be necessary for R to contain a Cursor<'a>.
957 // Within Syn we solve this using `private::advance_step_cursor` which
958 // uses the existence of a StepCursor<'c, 'a> as proof that it is safe
959 // to cast from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it
960 // would be safe to expose that API as a method on StepCursor.
David Tolnay6b65f852018-09-01 11:56:25 -0700961 let (node, rest) = function(StepCursor {
cad9789bb9452019-01-20 18:33:48 -0500962 scope: *self.scope,
David Tolnay18c754c2018-08-21 23:26:58 -0400963 cursor: self.cell.get(),
964 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700965 })?;
966 self.cell.set(rest);
967 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -0400968 }
David Tolnayeafc8052018-08-25 16:33:53 -0400969
David Tolnay725e1c62018-09-01 12:07:25 -0700970 /// Provides low-level access to the token representation underlying this
971 /// parse stream.
972 ///
973 /// Cursors are immutable so no operations you perform against the cursor
974 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -0700975 pub fn cursor(&self) -> Cursor<'a> {
976 self.cell.get()
977 }
978
David Tolnay94f06632018-08-31 10:17:17 -0700979 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -0400980 match self.unexpected.get() {
981 Some(span) => Err(Error::new(span, "unexpected token")),
982 None => Ok(()),
983 }
984 }
David Tolnay18c754c2018-08-21 23:26:58 -0400985}
986
David Tolnaya7d69fc2018-08-26 13:30:24 -0400987impl<T: Parse> Parse for Box<T> {
988 fn parse(input: ParseStream) -> Result<Self> {
989 input.parse().map(Box::new)
990 }
991}
992
David Tolnay4fb71232018-08-25 23:14:50 -0400993impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400994 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -0700995 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -0400996 Ok(Some(input.parse()?))
997 } else {
998 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400999 }
David Tolnay18c754c2018-08-21 23:26:58 -04001000 }
1001}
David Tolnay4ac232d2018-08-31 10:18:03 -07001002
David Tolnay80a914f2018-08-30 23:49:53 -07001003impl Parse for TokenStream {
1004 fn parse(input: ParseStream) -> Result<Self> {
1005 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
1006 }
1007}
1008
1009impl Parse for TokenTree {
1010 fn parse(input: ParseStream) -> Result<Self> {
1011 input.step(|cursor| match cursor.token_tree() {
1012 Some((tt, rest)) => Ok((tt, rest)),
1013 None => Err(cursor.error("expected token tree")),
1014 })
1015 }
1016}
1017
1018impl Parse for Group {
1019 fn parse(input: ParseStream) -> Result<Self> {
1020 input.step(|cursor| {
1021 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
1022 if let Some((inside, span, rest)) = cursor.group(*delim) {
1023 let mut group = Group::new(*delim, inside.token_stream());
1024 group.set_span(span);
1025 return Ok((group, rest));
1026 }
1027 }
1028 Err(cursor.error("expected group token"))
1029 })
1030 }
1031}
1032
1033impl Parse for Punct {
1034 fn parse(input: ParseStream) -> Result<Self> {
1035 input.step(|cursor| match cursor.punct() {
1036 Some((punct, rest)) => Ok((punct, rest)),
1037 None => Err(cursor.error("expected punctuation token")),
1038 })
1039 }
1040}
1041
1042impl Parse for Literal {
1043 fn parse(input: ParseStream) -> Result<Self> {
1044 input.step(|cursor| match cursor.literal() {
1045 Some((literal, rest)) => Ok((literal, rest)),
1046 None => Err(cursor.error("expected literal token")),
1047 })
1048 }
1049}
1050
1051/// Parser that can parse Rust tokens into a particular syntax tree node.
1052///
1053/// Refer to the [module documentation] for details about parsing in Syn.
1054///
1055/// [module documentation]: index.html
1056///
1057/// *This trait is available if Syn is built with the `"parsing"` feature.*
1058pub trait Parser: Sized {
1059 type Output;
1060
1061 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
Jethro Beekman33c22332018-12-31 11:16:25 +05301062 ///
1063 /// This function will check that the input is fully parsed. If there are
1064 /// any unparsed tokens at the end of the stream, an error is returned.
David Tolnay80a914f2018-08-30 23:49:53 -07001065 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1066
1067 /// Parse tokens of source code into the chosen syntax tree node.
1068 ///
Jethro Beekman33c22332018-12-31 11:16:25 +05301069 /// This function will check that the input is fully parsed. If there are
1070 /// any unparsed tokens at the end of the stream, an error is returned.
1071 ///
David Tolnay80a914f2018-08-30 23:49:53 -07001072 /// *This method is available if Syn is built with both the `"parsing"` and
1073 /// `"proc-macro"` features.*
1074 #[cfg(all(
1075 not(all(target_arch = "wasm32", target_os = "unknown")),
1076 feature = "proc-macro"
1077 ))]
1078 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1079 self.parse2(proc_macro2::TokenStream::from(tokens))
1080 }
1081
1082 /// Parse a string of Rust code into the chosen syntax tree node.
1083 ///
Jethro Beekman33c22332018-12-31 11:16:25 +05301084 /// This function will check that the input is fully parsed. If there are
1085 /// any unparsed tokens at the end of the string, an error is returned.
1086 ///
David Tolnay80a914f2018-08-30 23:49:53 -07001087 /// # Hygiene
1088 ///
1089 /// Every span in the resulting syntax tree will be set to resolve at the
1090 /// macro call site.
1091 fn parse_str(self, s: &str) -> Result<Self::Output> {
1092 self.parse2(proc_macro2::TokenStream::from_str(s)?)
1093 }
1094}
1095
David Tolnay7b07aa12018-09-01 11:41:12 -07001096fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1097 let scope = Span::call_site();
1098 let cursor = tokens.begin();
1099 let unexpected = Rc::new(Cell::new(None));
1100 private::new_parse_buffer(scope, cursor, unexpected)
1101}
1102
David Tolnay80a914f2018-08-30 23:49:53 -07001103impl<F, T> Parser for F
1104where
1105 F: FnOnce(ParseStream) -> Result<T>,
1106{
1107 type Output = T;
1108
1109 fn parse2(self, tokens: TokenStream) -> Result<T> {
1110 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -07001111 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -07001112 let node = self(&state)?;
1113 state.check_unexpected()?;
1114 if state.is_empty() {
1115 Ok(node)
1116 } else {
1117 Err(state.error("unexpected token"))
1118 }
1119 }
1120}