blob: 0dd698ba79697ca078afaab97175942b53b83d70 [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//!
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -070028//! ```
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//!
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700104//! ```
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//! #
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700112//! # run_parser().unwrap();
David Tolnay80a914f2018-08-30 23:49:53 -0700113//! ```
114//!
115//! The [`parse_quote!`] macro also uses this approach.
116//!
117//! [`parse_quote!`]: ../macro.parse_quote.html
118//!
David Tolnay43984452018-09-01 17:43:56 -0700119//! # The `Parser` trait
David Tolnay80a914f2018-08-30 23:49:53 -0700120//!
121//! Some types can be parsed in several ways depending on context. For example
122//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
123//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
124//! may or may not allow trailing punctuation, and parsing it the wrong way
125//! would either reject valid input or accept invalid input.
126//!
127//! [`Attribute`]: ../struct.Attribute.html
128//! [`Punctuated`]: ../punctuated/index.html
129//!
David Tolnaye0c51762018-08-31 11:05:22 -0700130//! The `Parse` trait is not implemented in these cases because there is no good
David Tolnay80a914f2018-08-30 23:49:53 -0700131//! behavior to consider the default.
132//!
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700133//! ```compile_fail
David Tolnay2b45fd42018-11-06 21:16:55 -0800134//! # extern crate proc_macro;
David Tolnay2b45fd42018-11-06 21:16:55 -0800135//! #
David Tolnay2b45fd42018-11-06 21:16:55 -0800136//! # use syn::punctuated::Punctuated;
David Tolnay67fea042018-11-24 14:50:20 -0800137//! # use syn::{PathSegment, Result, Token};
David Tolnay2b45fd42018-11-06 21:16:55 -0800138//! #
139//! # fn f(tokens: proc_macro::TokenStream) -> Result<()> {
140//! #
David Tolnay80a914f2018-08-30 23:49:53 -0700141//! // Can't parse `Punctuated` without knowing whether trailing punctuation
142//! // should be allowed in this context.
143//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
David Tolnay2b45fd42018-11-06 21:16:55 -0800144//! #
145//! # Ok(())
146//! # }
David Tolnay80a914f2018-08-30 23:49:53 -0700147//! ```
148//!
149//! In these cases the types provide a choice of parser functions rather than a
David Tolnaye0c51762018-08-31 11:05:22 -0700150//! single `Parse` implementation, and those parser functions can be invoked
David Tolnay80a914f2018-08-30 23:49:53 -0700151//! through the [`Parser`] trait.
152//!
153//! [`Parser`]: trait.Parser.html
154//!
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700155//! ```
David Tolnay66a23602018-12-31 17:59:21 -0500156//! extern crate proc_macro;
157//!
158//! use proc_macro::TokenStream;
David Tolnay3e3f7752018-08-31 09:33:59 -0700159//! use syn::parse::Parser;
David Tolnay80a914f2018-08-30 23:49:53 -0700160//! use syn::punctuated::Punctuated;
David Tolnay66a23602018-12-31 17:59:21 -0500161//! use syn::{Attribute, Expr, PathSegment, Result, Token};
David Tolnay80a914f2018-08-30 23:49:53 -0700162//!
David Tolnay66a23602018-12-31 17:59:21 -0500163//! fn call_some_parser_methods(input: TokenStream) -> Result<()> {
164//! // Parse a nonempty sequence of path segments separated by `::` punctuation
165//! // with no trailing punctuation.
166//! let tokens = input.clone();
167//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
168//! let _path = parser.parse(tokens)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700169//!
David Tolnay66a23602018-12-31 17:59:21 -0500170//! // Parse a possibly empty sequence of expressions terminated by commas with
171//! // an optional trailing punctuation.
172//! let tokens = input.clone();
173//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
174//! let _args = parser.parse(tokens)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700175//!
David Tolnay66a23602018-12-31 17:59:21 -0500176//! // Parse zero or more outer attributes but not inner attributes.
177//! let tokens = input.clone();
178//! let parser = Attribute::parse_outer;
179//! let _attrs = parser.parse(tokens)?;
180//!
181//! Ok(())
182//! }
David Tolnay80a914f2018-08-30 23:49:53 -0700183//! ```
184//!
David Tolnaye0c51762018-08-31 11:05:22 -0700185//! ---
David Tolnay80a914f2018-08-30 23:49:53 -0700186//!
187//! *This module is available if Syn is built with the `"parsing"` feature.*
David Tolnay18c754c2018-08-21 23:26:58 -0400188
David Tolnayb9e23032019-01-23 21:43:36 -0800189#[path = "discouraged.rs"]
cad9789bb9452019-01-20 18:33:48 -0500190pub mod discouraged;
191
David Tolnay18c754c2018-08-21 23:26:58 -0400192use std::cell::Cell;
Diggory Hardy1c522e12018-11-02 10:10:02 +0000193use std::fmt::{self, Debug, Display};
David Tolnay18c754c2018-08-21 23:26:58 -0400194use std::marker::PhantomData;
195use std::mem;
196use std::ops::Deref;
David Tolnayeafc8052018-08-25 16:33:53 -0400197use std::rc::Rc;
David Tolnay80a914f2018-08-30 23:49:53 -0700198use std::str::FromStr;
David Tolnayeafc8052018-08-25 16:33:53 -0400199
David Tolnay80a914f2018-08-30 23:49:53 -0700200#[cfg(all(
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700201 not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
David Tolnay80a914f2018-08-30 23:49:53 -0700202 feature = "proc-macro"
203))]
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700204use crate::proc_macro;
David Tolnayf07b3342018-09-01 11:58:11 -0700205use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
David Tolnay18c754c2018-08-21 23:26:58 -0400206
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700207use crate::buffer::{Cursor, TokenBuffer};
208use crate::error;
209use crate::lookahead;
210use crate::punctuated::Punctuated;
211use crate::token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -0400212
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700213pub use crate::error::{Error, Result};
214pub use crate::lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -0400215
216/// Parsing interface implemented by all types that can be parsed in a default
217/// way from a token stream.
218pub trait Parse: Sized {
219 fn parse(input: ParseStream) -> Result<Self>;
220}
221
222/// Input to a Syn parser function.
David Tolnaya0daa482018-09-01 02:09:40 -0700223///
224/// See the methods of this type under the documentation of [`ParseBuffer`]. For
225/// an overview of parsing in Syn, refer to the [module documentation].
226///
David Tolnayb8dec882019-07-20 09:46:14 -0700227/// [module documentation]: self
David Tolnay18c754c2018-08-21 23:26:58 -0400228pub type ParseStream<'a> = &'a ParseBuffer<'a>;
229
230/// Cursor position within a buffered token stream.
David Tolnay20d29a12018-09-01 15:15:33 -0700231///
232/// This type is more commonly used through the type alias [`ParseStream`] which
233/// is an alias for `&ParseBuffer`.
234///
235/// `ParseStream` is the input type for all parser functions in Syn. They have
236/// the signature `fn(ParseStream) -> Result<T>`.
David Tolnay028a7d72018-12-31 17:11:02 -0500237///
238/// ## Calling a parser function
239///
240/// There is no public way to construct a `ParseBuffer`. Instead, if you are
241/// looking to invoke a parser function that requires `ParseStream` as input,
242/// you will need to go through one of the public parsing entry points.
243///
244/// - The [`parse_macro_input!`] macro if parsing input of a procedural macro;
245/// - One of [the `syn::parse*` functions][syn-parse]; or
246/// - A method of the [`Parser`] trait.
247///
David Tolnay028a7d72018-12-31 17:11:02 -0500248/// [syn-parse]: index.html#the-synparse-functions
David Tolnay18c754c2018-08-21 23:26:58 -0400249pub struct ParseBuffer<'a> {
David Tolnay6db0f2a2019-06-23 13:37:39 -0700250 scope: Span,
David Tolnay5d7f2252018-09-02 08:21:40 -0700251 // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
252 // The rest of the code in this module needs to be careful that only a
253 // cursor derived from this `cell` is ever assigned to this `cell`.
254 //
255 // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
256 // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
257 // than 'a, and then assign a Cursor<'short> into the Cell.
258 //
259 // By extension, it would not be safe to expose an API that accepts a
260 // Cursor<'a> and trusts that it lives as long as the cursor currently in
261 // the cell.
David Tolnay18c754c2018-08-21 23:26:58 -0400262 cell: Cell<Cursor<'static>>,
263 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400264 unexpected: Rc<Cell<Option<Span>>>,
265}
266
267impl<'a> Drop for ParseBuffer<'a> {
268 fn drop(&mut self) {
269 if !self.is_empty() && self.unexpected.get().is_none() {
270 self.unexpected.set(Some(self.cursor().span()));
271 }
272 }
David Tolnay18c754c2018-08-21 23:26:58 -0400273}
274
Diggory Hardy1c522e12018-11-02 10:10:02 +0000275impl<'a> Display for ParseBuffer<'a> {
276 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
277 Display::fmt(&self.cursor().token_stream(), f)
278 }
279}
280
281impl<'a> Debug for ParseBuffer<'a> {
282 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
283 Debug::fmt(&self.cursor().token_stream(), f)
284 }
285}
286
David Tolnay642832f2018-09-01 13:08:10 -0700287/// Cursor state associated with speculative parsing.
288///
289/// This type is the input of the closure provided to [`ParseStream::step`].
290///
David Tolnayb8dec882019-07-20 09:46:14 -0700291/// [`ParseStream::step`]: ParseBuffer::step
David Tolnay9bd34392018-09-01 13:19:53 -0700292///
293/// # Example
294///
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700295/// ```
David Tolnay9bd34392018-09-01 13:19:53 -0700296/// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800297/// use syn::Result;
298/// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700299///
300/// // This function advances the stream past the next occurrence of `@`. If
301/// // no `@` is present in the stream, the stream position is unchanged and
302/// // an error is returned.
303/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
304/// input.step(|cursor| {
305/// let mut rest = *cursor;
Sharad Chande1df40a2018-09-08 15:25:52 +0545306/// while let Some((tt, next)) = rest.token_tree() {
David Tolnay65336072019-04-22 23:10:52 -0700307/// match &tt {
308/// TokenTree::Punct(punct) if punct.as_char() == '@' => {
David Tolnay9bd34392018-09-01 13:19:53 -0700309/// return Ok(((), next));
310/// }
311/// _ => rest = next,
312/// }
313/// }
314/// Err(cursor.error("no `@` was found after this point"))
315/// })
316/// }
317/// #
David Tolnaydb312582018-11-06 20:42:05 -0800318/// # fn remainder_after_skipping_past_next_at(
319/// # input: ParseStream,
320/// # ) -> Result<proc_macro2::TokenStream> {
321/// # skip_past_next_at(input)?;
322/// # input.parse()
323/// # }
324/// #
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700325/// # use syn::parse::Parser;
326/// # let remainder = remainder_after_skipping_past_next_at
327/// # .parse_str("a @ b c")
328/// # .unwrap();
329/// # assert_eq!(remainder.to_string(), "b c");
David Tolnay9bd34392018-09-01 13:19:53 -0700330/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400331#[derive(Copy, Clone)]
332pub struct StepCursor<'c, 'a> {
333 scope: Span,
David Tolnay56924f42018-09-02 08:24:58 -0700334 // This field is covariant in 'c.
David Tolnay18c754c2018-08-21 23:26:58 -0400335 cursor: Cursor<'c>,
David Tolnay56924f42018-09-02 08:24:58 -0700336 // This field is contravariant in 'c. Together these make StepCursor
337 // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
338 // different lifetime but can upcast into a StepCursor with a shorter
339 // lifetime 'a.
340 //
341 // As long as we only ever construct a StepCursor for which 'c outlives 'a,
342 // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
343 // outlives 'a.
David Tolnay18c754c2018-08-21 23:26:58 -0400344 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
345}
346
347impl<'c, 'a> Deref for StepCursor<'c, 'a> {
348 type Target = Cursor<'c>;
349
350 fn deref(&self) -> &Self::Target {
351 &self.cursor
352 }
353}
354
355impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700356 /// Triggers an error at the current position of the parse stream.
357 ///
358 /// The `ParseStream::step` invocation will return this same error without
359 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400360 pub fn error<T: Display>(self, message: T) -> Error {
361 error::new_at(self.scope, self.cursor, message)
362 }
363}
364
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700365pub(crate) fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
366 // Refer to the comments within the StepCursor definition. We use the
367 // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
368 // Cursor is covariant in its lifetime parameter so we can cast a
369 // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
370 let _ = proof;
371 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700372}
373
David Tolnay66cb0c42018-08-31 09:01:30 -0700374fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700375 input
376 .step(|cursor| {
377 if let Some((_lifetime, rest)) = cursor.lifetime() {
378 Ok((true, rest))
379 } else if let Some((_token, rest)) = cursor.token_tree() {
380 Ok((true, rest))
381 } else {
382 Ok((false, *cursor))
383 }
David Tolnayfb84fc02018-10-02 21:01:30 -0700384 })
385 .unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700386}
387
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700388pub(crate) fn new_parse_buffer(
389 scope: Span,
390 cursor: Cursor,
391 unexpected: Rc<Cell<Option<Span>>>,
392) -> ParseBuffer {
393 ParseBuffer {
394 scope,
395 // See comment on `cell` in the struct definition.
396 cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
397 marker: PhantomData,
398 unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400399 }
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700400}
David Tolnay18c754c2018-08-21 23:26:58 -0400401
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700402pub(crate) fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
403 buffer.unexpected.clone()
David Tolnay94f06632018-08-31 10:17:17 -0700404}
405
406impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700407 /// Parses a syntax tree node of type `T`, advancing the position of our
408 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400409 pub fn parse<T: Parse>(&self) -> Result<T> {
410 T::parse(self)
411 }
412
David Tolnay725e1c62018-09-01 12:07:25 -0700413 /// Calls the given parser function to parse a syntax tree node of type `T`
414 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700415 ///
416 /// # Example
417 ///
418 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
419 /// zero or more outer attributes.
420 ///
David Tolnayb8dec882019-07-20 09:46:14 -0700421 /// [`Attribute::parse_outer`]: crate::Attribute::parse_outer
David Tolnay21ce84c2018-09-01 15:37:51 -0700422 ///
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700423 /// ```
David Tolnayfd5b1172018-12-31 17:54:36 -0500424 /// use syn::{Attribute, Ident, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800425 /// use syn::parse::{Parse, ParseStream};
David Tolnay21ce84c2018-09-01 15:37:51 -0700426 ///
427 /// // Parses a unit struct with attributes.
428 /// //
429 /// // #[path = "s.tmpl"]
430 /// // struct S;
431 /// struct UnitStruct {
432 /// attrs: Vec<Attribute>,
433 /// struct_token: Token![struct],
434 /// name: Ident,
435 /// semi_token: Token![;],
436 /// }
437 ///
438 /// impl Parse for UnitStruct {
439 /// fn parse(input: ParseStream) -> Result<Self> {
440 /// Ok(UnitStruct {
441 /// attrs: input.call(Attribute::parse_outer)?,
442 /// struct_token: input.parse()?,
443 /// name: input.parse()?,
444 /// semi_token: input.parse()?,
445 /// })
446 /// }
447 /// }
David Tolnay21ce84c2018-09-01 15:37:51 -0700448 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400449 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
450 function(self)
451 }
452
David Tolnay725e1c62018-09-01 12:07:25 -0700453 /// Looks at the next token in the parse stream to determine whether it
454 /// matches the requested type of token.
455 ///
456 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700457 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700458 /// # Syntax
459 ///
460 /// Note that this method does not use turbofish syntax. Pass the peek type
461 /// inside of parentheses.
462 ///
463 /// - `input.peek(Token![struct])`
464 /// - `input.peek(Token![==])`
David Tolnayb8a68e42019-04-22 14:01:56 -0700465 /// - `input.peek(Ident)`&emsp;*(does not accept keywords)*
466 /// - `input.peek(Ident::peek_any)`
David Tolnay7d229e82018-09-01 16:42:34 -0700467 /// - `input.peek(Lifetime)`
468 /// - `input.peek(token::Brace)`
469 ///
David Tolnayddebc3e2018-09-01 16:29:20 -0700470 /// # Example
471 ///
472 /// In this example we finish parsing the list of supertraits when the next
473 /// token in the input is either `where` or an opening curly brace.
474 ///
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700475 /// ```
David Tolnayfd5b1172018-12-31 17:54:36 -0500476 /// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
David Tolnay67fea042018-11-24 14:50:20 -0800477 /// use syn::parse::{Parse, ParseStream};
David Tolnayddebc3e2018-09-01 16:29:20 -0700478 /// use syn::punctuated::Punctuated;
479 ///
480 /// // Parses a trait definition containing no associated items.
481 /// //
482 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
483 /// struct MarkerTrait {
484 /// trait_token: Token![trait],
485 /// ident: Ident,
486 /// generics: Generics,
487 /// colon_token: Option<Token![:]>,
488 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
489 /// brace_token: token::Brace,
490 /// }
491 ///
492 /// impl Parse for MarkerTrait {
493 /// fn parse(input: ParseStream) -> Result<Self> {
494 /// let trait_token: Token![trait] = input.parse()?;
495 /// let ident: Ident = input.parse()?;
496 /// let mut generics: Generics = input.parse()?;
497 /// let colon_token: Option<Token![:]> = input.parse()?;
498 ///
499 /// let mut supertraits = Punctuated::new();
500 /// if colon_token.is_some() {
501 /// loop {
502 /// supertraits.push_value(input.parse()?);
503 /// if input.peek(Token![where]) || input.peek(token::Brace) {
504 /// break;
505 /// }
506 /// supertraits.push_punct(input.parse()?);
507 /// }
508 /// }
509 ///
510 /// generics.where_clause = input.parse()?;
511 /// let content;
512 /// let empty_brace_token = braced!(content in input);
513 ///
514 /// Ok(MarkerTrait {
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700515 /// trait_token,
516 /// ident,
517 /// generics,
518 /// colon_token,
519 /// supertraits,
David Tolnayddebc3e2018-09-01 16:29:20 -0700520 /// brace_token: empty_brace_token,
521 /// })
522 /// }
523 /// }
David Tolnayddebc3e2018-09-01 16:29:20 -0700524 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400525 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700526 let _ = token;
527 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400528 }
529
David Tolnay725e1c62018-09-01 12:07:25 -0700530 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700531 ///
532 /// This is commonly useful as a way to implement contextual keywords.
533 ///
534 /// # Example
535 ///
536 /// This example needs to use `peek2` because the symbol `union` is not a
537 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
538 /// the very next token is `union`, because someone is free to write a `mod
539 /// union` and a macro invocation that looks like `union::some_macro! { ...
540 /// }`. In other words `union` is a contextual keyword.
541 ///
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700542 /// ```
David Tolnayfd5b1172018-12-31 17:54:36 -0500543 /// use syn::{Ident, ItemUnion, Macro, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800544 /// use syn::parse::{Parse, ParseStream};
David Tolnaye334b872018-09-01 16:38:10 -0700545 ///
546 /// // Parses either a union or a macro invocation.
547 /// enum UnionOrMacro {
548 /// // union MaybeUninit<T> { uninit: (), value: T }
549 /// Union(ItemUnion),
550 /// // lazy_static! { ... }
551 /// Macro(Macro),
552 /// }
553 ///
554 /// impl Parse for UnionOrMacro {
555 /// fn parse(input: ParseStream) -> Result<Self> {
556 /// if input.peek(Token![union]) && input.peek2(Ident) {
557 /// input.parse().map(UnionOrMacro::Union)
558 /// } else {
559 /// input.parse().map(UnionOrMacro::Macro)
560 /// }
561 /// }
562 /// }
David Tolnaye334b872018-09-01 16:38:10 -0700563 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400564 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400565 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700566 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400567 }
568
David Tolnay725e1c62018-09-01 12:07:25 -0700569 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400570 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400571 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700572 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400573 }
574
David Tolnay725e1c62018-09-01 12:07:25 -0700575 /// Parses zero or more occurrences of `T` separated by punctuation of type
576 /// `P`, with optional trailing punctuation.
577 ///
578 /// Parsing continues until the end of this parse stream. The entire content
579 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700580 ///
581 /// # Example
582 ///
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700583 /// ```
David Tolnayfd5b1172018-12-31 17:54:36 -0500584 /// # use quote::quote;
David Tolnay0abe65b2018-09-01 14:31:43 -0700585 /// #
David Tolnayfd5b1172018-12-31 17:54:36 -0500586 /// use syn::{parenthesized, token, Ident, Result, Token, Type};
David Tolnay67fea042018-11-24 14:50:20 -0800587 /// use syn::parse::{Parse, ParseStream};
David Tolnay0abe65b2018-09-01 14:31:43 -0700588 /// use syn::punctuated::Punctuated;
589 ///
590 /// // Parse a simplified tuple struct syntax like:
591 /// //
592 /// // struct S(A, B);
593 /// struct TupleStruct {
594 /// struct_token: Token![struct],
595 /// ident: Ident,
596 /// paren_token: token::Paren,
597 /// fields: Punctuated<Type, Token![,]>,
598 /// semi_token: Token![;],
599 /// }
600 ///
601 /// impl Parse for TupleStruct {
602 /// fn parse(input: ParseStream) -> Result<Self> {
603 /// let content;
604 /// Ok(TupleStruct {
605 /// struct_token: input.parse()?,
606 /// ident: input.parse()?,
607 /// paren_token: parenthesized!(content in input),
608 /// fields: content.parse_terminated(Type::parse)?,
609 /// semi_token: input.parse()?,
610 /// })
611 /// }
612 /// }
613 /// #
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700614 /// # let input = quote! {
615 /// # struct S(A, B);
616 /// # };
617 /// # syn::parse2::<TupleStruct>(input).unwrap();
David Tolnay0abe65b2018-09-01 14:31:43 -0700618 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400619 pub fn parse_terminated<T, P: Parse>(
620 &self,
621 parser: fn(ParseStream) -> Result<T>,
622 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700623 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400624 }
625
David Tolnay725e1c62018-09-01 12:07:25 -0700626 /// Returns whether there are tokens remaining in this stream.
627 ///
628 /// This method returns true at the end of the content of a set of
629 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700630 ///
631 /// # Example
632 ///
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700633 /// ```
David Tolnayfd5b1172018-12-31 17:54:36 -0500634 /// use syn::{braced, token, Ident, Item, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800635 /// use syn::parse::{Parse, ParseStream};
David Tolnaycce6b5f2018-09-01 14:24:46 -0700636 ///
637 /// // Parses a Rust `mod m { ... }` containing zero or more items.
638 /// struct Mod {
639 /// mod_token: Token![mod],
640 /// name: Ident,
641 /// brace_token: token::Brace,
642 /// items: Vec<Item>,
643 /// }
644 ///
645 /// impl Parse for Mod {
646 /// fn parse(input: ParseStream) -> Result<Self> {
647 /// let content;
648 /// Ok(Mod {
649 /// mod_token: input.parse()?,
650 /// name: input.parse()?,
651 /// brace_token: braced!(content in input),
652 /// items: {
653 /// let mut items = Vec::new();
654 /// while !content.is_empty() {
655 /// items.push(content.parse()?);
656 /// }
657 /// items
658 /// },
659 /// })
660 /// }
661 /// }
David Tolnayf2b78602018-11-06 20:42:37 -0800662 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700663 pub fn is_empty(&self) -> bool {
664 self.cursor().eof()
665 }
666
David Tolnay725e1c62018-09-01 12:07:25 -0700667 /// Constructs a helper for peeking at the next token in this stream and
668 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700669 ///
670 /// # Example
671 ///
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700672 /// ```
David Tolnayfd5b1172018-12-31 17:54:36 -0500673 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, Token, TypeParam};
David Tolnay67fea042018-11-24 14:50:20 -0800674 /// use syn::parse::{Parse, ParseStream};
David Tolnay2c77e772018-09-01 14:18:46 -0700675 ///
676 /// // A generic parameter, a single one of the comma-separated elements inside
677 /// // angle brackets in:
678 /// //
679 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
680 /// //
681 /// // On invalid input, lookahead gives us a reasonable error message.
682 /// //
683 /// // error: expected one of: identifier, lifetime, `const`
684 /// // |
685 /// // 5 | fn f<!Sized>() {}
686 /// // | ^
687 /// enum GenericParam {
688 /// Type(TypeParam),
689 /// Lifetime(LifetimeDef),
690 /// Const(ConstParam),
691 /// }
692 ///
693 /// impl Parse for GenericParam {
694 /// fn parse(input: ParseStream) -> Result<Self> {
695 /// let lookahead = input.lookahead1();
696 /// if lookahead.peek(Ident) {
697 /// input.parse().map(GenericParam::Type)
698 /// } else if lookahead.peek(Lifetime) {
699 /// input.parse().map(GenericParam::Lifetime)
700 /// } else if lookahead.peek(Token![const]) {
701 /// input.parse().map(GenericParam::Const)
702 /// } else {
703 /// Err(lookahead.error())
704 /// }
705 /// }
706 /// }
David Tolnay2c77e772018-09-01 14:18:46 -0700707 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700708 pub fn lookahead1(&self) -> Lookahead1<'a> {
David Tolnay6db0f2a2019-06-23 13:37:39 -0700709 lookahead::new(self.scope, self.cursor())
David Tolnayf5d30452018-09-01 02:29:04 -0700710 }
711
David Tolnay725e1c62018-09-01 12:07:25 -0700712 /// Forks a parse stream so that parsing tokens out of either the original
713 /// or the fork does not advance the position of the other.
714 ///
715 /// # Performance
716 ///
717 /// Forking a parse stream is a cheap fixed amount of work and does not
718 /// involve copying token buffers. Where you might hit performance problems
719 /// is if your macro ends up parsing a large amount of content more than
720 /// once.
721 ///
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700722 /// ```
David Tolnay67fea042018-11-24 14:50:20 -0800723 /// # use syn::{Expr, Result};
724 /// # use syn::parse::ParseStream;
David Tolnay725e1c62018-09-01 12:07:25 -0700725 /// #
726 /// # fn bad(input: ParseStream) -> Result<Expr> {
727 /// // Do not do this.
728 /// if input.fork().parse::<Expr>().is_ok() {
729 /// return input.parse::<Expr>();
730 /// }
731 /// # unimplemented!()
732 /// # }
733 /// ```
734 ///
735 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
736 /// parse stream. Only use a fork when the amount of work performed against
737 /// the fork is small and bounded.
738 ///
David Tolnay34506d92019-06-23 14:13:54 -0700739 /// When complex speculative parsing against the forked stream is
740 /// unavoidable, use [`parse::discouraged::Speculative`] to advance the
741 /// original stream once the fork's parse is determined to have been
742 /// successful.
David Tolnay725e1c62018-09-01 12:07:25 -0700743 ///
David Tolnay34506d92019-06-23 14:13:54 -0700744 /// For a lower level way to perform speculative parsing at the token level,
745 /// consider using [`ParseStream::step`] instead.
746 ///
David Tolnayb8dec882019-07-20 09:46:14 -0700747 /// [`parse::discouraged::Speculative`]: discouraged::Speculative
748 /// [`ParseStream::step`]: ParseBuffer::step
David Tolnayec149b02018-09-01 14:17:28 -0700749 ///
750 /// # Example
751 ///
752 /// The parse implementation shown here parses possibly restricted `pub`
753 /// visibilities.
754 ///
755 /// - `pub`
756 /// - `pub(crate)`
757 /// - `pub(self)`
758 /// - `pub(super)`
759 /// - `pub(in some::path)`
760 ///
761 /// To handle the case of visibilities inside of tuple structs, the parser
762 /// needs to distinguish parentheses that specify visibility restrictions
763 /// from parentheses that form part of a tuple type.
764 ///
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700765 /// ```
David Tolnayec149b02018-09-01 14:17:28 -0700766 /// # struct A;
767 /// # struct B;
768 /// # struct C;
769 /// #
770 /// struct S(pub(crate) A, pub (B, C));
771 /// ```
772 ///
773 /// In this example input the first tuple struct element of `S` has
774 /// `pub(crate)` visibility while the second tuple struct element has `pub`
775 /// visibility; the parentheses around `(B, C)` are part of the type rather
776 /// than part of a visibility restriction.
777 ///
778 /// The parser uses a forked parse stream to check the first token inside of
779 /// parentheses after the `pub` keyword. This is a small bounded amount of
780 /// work performed against the forked parse stream.
781 ///
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700782 /// ```
David Tolnayfd5b1172018-12-31 17:54:36 -0500783 /// use syn::{parenthesized, token, Ident, Path, Result, Token};
David Tolnayec149b02018-09-01 14:17:28 -0700784 /// use syn::ext::IdentExt;
David Tolnay67fea042018-11-24 14:50:20 -0800785 /// use syn::parse::{Parse, ParseStream};
David Tolnayec149b02018-09-01 14:17:28 -0700786 ///
787 /// struct PubVisibility {
788 /// pub_token: Token![pub],
789 /// restricted: Option<Restricted>,
790 /// }
791 ///
792 /// struct Restricted {
793 /// paren_token: token::Paren,
794 /// in_token: Option<Token![in]>,
795 /// path: Path,
796 /// }
797 ///
798 /// impl Parse for PubVisibility {
799 /// fn parse(input: ParseStream) -> Result<Self> {
800 /// let pub_token: Token![pub] = input.parse()?;
801 ///
802 /// if input.peek(token::Paren) {
803 /// let ahead = input.fork();
804 /// let mut content;
805 /// parenthesized!(content in ahead);
806 ///
807 /// if content.peek(Token![crate])
808 /// || content.peek(Token![self])
809 /// || content.peek(Token![super])
810 /// {
811 /// return Ok(PubVisibility {
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700812 /// pub_token,
David Tolnayec149b02018-09-01 14:17:28 -0700813 /// restricted: Some(Restricted {
814 /// paren_token: parenthesized!(content in input),
815 /// in_token: None,
816 /// path: Path::from(content.call(Ident::parse_any)?),
817 /// }),
818 /// });
819 /// } else if content.peek(Token![in]) {
820 /// return Ok(PubVisibility {
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700821 /// pub_token,
David Tolnayec149b02018-09-01 14:17:28 -0700822 /// restricted: Some(Restricted {
823 /// paren_token: parenthesized!(content in input),
824 /// in_token: Some(content.parse()?),
825 /// path: content.call(Path::parse_mod_style)?,
826 /// }),
827 /// });
828 /// }
829 /// }
830 ///
831 /// Ok(PubVisibility {
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700832 /// pub_token,
David Tolnayec149b02018-09-01 14:17:28 -0700833 /// restricted: None,
834 /// })
835 /// }
836 /// }
David Tolnayec149b02018-09-01 14:17:28 -0700837 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400838 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400839 ParseBuffer {
David Tolnay6db0f2a2019-06-23 13:37:39 -0700840 scope: self.scope,
David Tolnay6456a9d2018-08-26 08:11:18 -0400841 cell: self.cell.clone(),
842 marker: PhantomData,
843 // Not the parent's unexpected. Nothing cares whether the clone
844 // parses all the way.
845 unexpected: Rc::new(Cell::new(None)),
846 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400847 }
848
David Tolnay725e1c62018-09-01 12:07:25 -0700849 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700850 ///
851 /// # Example
852 ///
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700853 /// ```
David Tolnayfd5b1172018-12-31 17:54:36 -0500854 /// use syn::{Expr, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800855 /// use syn::parse::{Parse, ParseStream};
David Tolnay23fce0b2018-09-01 13:50:31 -0700856 ///
857 /// // Some kind of loop: `while` or `for` or `loop`.
858 /// struct Loop {
859 /// expr: Expr,
860 /// }
861 ///
862 /// impl Parse for Loop {
863 /// fn parse(input: ParseStream) -> Result<Self> {
864 /// if input.peek(Token![while])
865 /// || input.peek(Token![for])
866 /// || input.peek(Token![loop])
867 /// {
868 /// Ok(Loop {
869 /// expr: input.parse()?,
870 /// })
871 /// } else {
872 /// Err(input.error("expected some kind of loop"))
873 /// }
874 /// }
875 /// }
876 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400877 pub fn error<T: Display>(&self, message: T) -> Error {
David Tolnay6db0f2a2019-06-23 13:37:39 -0700878 error::new_at(self.scope, self.cursor(), message)
David Tolnay4fb71232018-08-25 23:14:50 -0400879 }
880
David Tolnay725e1c62018-09-01 12:07:25 -0700881 /// Speculatively parses tokens from this parse stream, advancing the
882 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700883 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700884 /// This is a powerful low-level API used for defining the `Parse` impls of
885 /// the basic built-in token types. It is not something that will be used
886 /// widely outside of the Syn codebase.
887 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700888 /// # Example
889 ///
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700890 /// ```
David Tolnay9bd34392018-09-01 13:19:53 -0700891 /// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800892 /// use syn::Result;
893 /// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700894 ///
895 /// // This function advances the stream past the next occurrence of `@`. If
896 /// // no `@` is present in the stream, the stream position is unchanged and
897 /// // an error is returned.
898 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
899 /// input.step(|cursor| {
900 /// let mut rest = *cursor;
David Tolnaydb312582018-11-06 20:42:05 -0800901 /// while let Some((tt, next)) = rest.token_tree() {
David Tolnay65336072019-04-22 23:10:52 -0700902 /// match &tt {
903 /// TokenTree::Punct(punct) if punct.as_char() == '@' => {
David Tolnay9bd34392018-09-01 13:19:53 -0700904 /// return Ok(((), next));
905 /// }
906 /// _ => rest = next,
907 /// }
908 /// }
909 /// Err(cursor.error("no `@` was found after this point"))
910 /// })
911 /// }
912 /// #
David Tolnaydb312582018-11-06 20:42:05 -0800913 /// # fn remainder_after_skipping_past_next_at(
914 /// # input: ParseStream,
915 /// # ) -> Result<proc_macro2::TokenStream> {
916 /// # skip_past_next_at(input)?;
917 /// # input.parse()
918 /// # }
919 /// #
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700920 /// # use syn::parse::Parser;
921 /// # let remainder = remainder_after_skipping_past_next_at
922 /// # .parse_str("a @ b c")
923 /// # .unwrap();
924 /// # assert_eq!(remainder.to_string(), "b c");
David Tolnay9bd34392018-09-01 13:19:53 -0700925 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700926 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400927 where
928 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
929 {
David Tolnayc142b092018-09-02 08:52:52 -0700930 // Since the user's function is required to work for any 'c, we know
931 // that the Cursor<'c> they return is either derived from the input
932 // StepCursor<'c, 'a> or from a Cursor<'static>.
933 //
934 // It would not be legal to write this function without the invariant
935 // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
936 // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
937 // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
938 // `step` on their ParseBuffer<'short> with a closure that returns
939 // Cursor<'short>, and we would wrongly write that Cursor<'short> into
940 // the Cell intended to hold Cursor<'a>.
941 //
942 // In some cases it may be necessary for R to contain a Cursor<'a>.
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -0700943 // Within Syn we solve this using `advance_step_cursor` which uses the
944 // existence of a StepCursor<'c, 'a> as proof that it is safe to cast
945 // from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it would be
946 // safe to expose that API as a method on StepCursor.
David Tolnay6b65f852018-09-01 11:56:25 -0700947 let (node, rest) = function(StepCursor {
David Tolnay6db0f2a2019-06-23 13:37:39 -0700948 scope: self.scope,
David Tolnay18c754c2018-08-21 23:26:58 -0400949 cursor: self.cell.get(),
950 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700951 })?;
952 self.cell.set(rest);
953 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -0400954 }
David Tolnayeafc8052018-08-25 16:33:53 -0400955
David Tolnay725e1c62018-09-01 12:07:25 -0700956 /// Provides low-level access to the token representation underlying this
957 /// parse stream.
958 ///
959 /// Cursors are immutable so no operations you perform against the cursor
960 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -0700961 pub fn cursor(&self) -> Cursor<'a> {
962 self.cell.get()
963 }
964
David Tolnay94f06632018-08-31 10:17:17 -0700965 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -0400966 match self.unexpected.get() {
967 Some(span) => Err(Error::new(span, "unexpected token")),
968 None => Ok(()),
969 }
970 }
David Tolnay18c754c2018-08-21 23:26:58 -0400971}
972
David Tolnaya7d69fc2018-08-26 13:30:24 -0400973impl<T: Parse> Parse for Box<T> {
974 fn parse(input: ParseStream) -> Result<Self> {
975 input.parse().map(Box::new)
976 }
977}
978
David Tolnay4fb71232018-08-25 23:14:50 -0400979impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400980 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -0700981 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -0400982 Ok(Some(input.parse()?))
983 } else {
984 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400985 }
David Tolnay18c754c2018-08-21 23:26:58 -0400986 }
987}
David Tolnay4ac232d2018-08-31 10:18:03 -0700988
David Tolnay80a914f2018-08-30 23:49:53 -0700989impl Parse for TokenStream {
990 fn parse(input: ParseStream) -> Result<Self> {
991 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
992 }
993}
994
995impl Parse for TokenTree {
996 fn parse(input: ParseStream) -> Result<Self> {
997 input.step(|cursor| match cursor.token_tree() {
998 Some((tt, rest)) => Ok((tt, rest)),
999 None => Err(cursor.error("expected token tree")),
1000 })
1001 }
1002}
1003
1004impl Parse for Group {
1005 fn parse(input: ParseStream) -> Result<Self> {
1006 input.step(|cursor| {
1007 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
1008 if let Some((inside, span, rest)) = cursor.group(*delim) {
1009 let mut group = Group::new(*delim, inside.token_stream());
1010 group.set_span(span);
1011 return Ok((group, rest));
1012 }
1013 }
1014 Err(cursor.error("expected group token"))
1015 })
1016 }
1017}
1018
1019impl Parse for Punct {
1020 fn parse(input: ParseStream) -> Result<Self> {
1021 input.step(|cursor| match cursor.punct() {
1022 Some((punct, rest)) => Ok((punct, rest)),
1023 None => Err(cursor.error("expected punctuation token")),
1024 })
1025 }
1026}
1027
1028impl Parse for Literal {
1029 fn parse(input: ParseStream) -> Result<Self> {
1030 input.step(|cursor| match cursor.literal() {
1031 Some((literal, rest)) => Ok((literal, rest)),
1032 None => Err(cursor.error("expected literal token")),
1033 })
1034 }
1035}
1036
1037/// Parser that can parse Rust tokens into a particular syntax tree node.
1038///
1039/// Refer to the [module documentation] for details about parsing in Syn.
1040///
David Tolnayb8dec882019-07-20 09:46:14 -07001041/// [module documentation]: self
David Tolnay80a914f2018-08-30 23:49:53 -07001042///
1043/// *This trait is available if Syn is built with the `"parsing"` feature.*
1044pub trait Parser: Sized {
1045 type Output;
1046
1047 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
Jethro Beekman33c22332018-12-31 11:16:25 +05301048 ///
1049 /// This function will check that the input is fully parsed. If there are
1050 /// any unparsed tokens at the end of the stream, an error is returned.
David Tolnay80a914f2018-08-30 23:49:53 -07001051 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1052
1053 /// Parse tokens of source code into the chosen syntax tree node.
1054 ///
Jethro Beekman33c22332018-12-31 11:16:25 +05301055 /// This function will check that the input is fully parsed. If there are
1056 /// any unparsed tokens at the end of the stream, an error is returned.
1057 ///
David Tolnay80a914f2018-08-30 23:49:53 -07001058 /// *This method is available if Syn is built with both the `"parsing"` and
1059 /// `"proc-macro"` features.*
1060 #[cfg(all(
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -07001061 not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
David Tolnay80a914f2018-08-30 23:49:53 -07001062 feature = "proc-macro"
1063 ))]
1064 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1065 self.parse2(proc_macro2::TokenStream::from(tokens))
1066 }
1067
1068 /// Parse a string of Rust 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 string, an error is returned.
1072 ///
David Tolnay80a914f2018-08-30 23:49:53 -07001073 /// # Hygiene
1074 ///
1075 /// Every span in the resulting syntax tree will be set to resolve at the
1076 /// macro call site.
1077 fn parse_str(self, s: &str) -> Result<Self::Output> {
1078 self.parse2(proc_macro2::TokenStream::from_str(s)?)
1079 }
David Tolnayd639f612019-06-09 03:36:01 -07001080
1081 // Not public API.
1082 #[doc(hidden)]
1083 fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> {
1084 let _ = scope;
1085 self.parse2(tokens)
1086 }
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -07001087
1088 // Not public API.
1089 #[doc(hidden)]
1090 fn __parse_stream(self, input: ParseStream) -> Result<Self::Output> {
1091 input.parse().and_then(|tokens| self.parse2(tokens))
1092 }
David Tolnay80a914f2018-08-30 23:49:53 -07001093}
1094
David Tolnay7b07aa12018-09-01 11:41:12 -07001095fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1096 let scope = Span::call_site();
1097 let cursor = tokens.begin();
1098 let unexpected = Rc::new(Cell::new(None));
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -07001099 new_parse_buffer(scope, cursor, unexpected)
David Tolnay7b07aa12018-09-01 11:41:12 -07001100}
1101
David Tolnay80a914f2018-08-30 23:49:53 -07001102impl<F, T> Parser for F
1103where
1104 F: FnOnce(ParseStream) -> Result<T>,
1105{
1106 type Output = T;
1107
1108 fn parse2(self, tokens: TokenStream) -> Result<T> {
1109 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -07001110 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -07001111 let node = self(&state)?;
1112 state.check_unexpected()?;
1113 if state.is_empty() {
1114 Ok(node)
1115 } else {
1116 Err(state.error("unexpected token"))
1117 }
1118 }
David Tolnayd639f612019-06-09 03:36:01 -07001119
1120 #[doc(hidden)]
1121 fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> {
1122 let buf = TokenBuffer::new2(tokens);
1123 let cursor = buf.begin();
1124 let unexpected = Rc::new(Cell::new(None));
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -07001125 let state = new_parse_buffer(scope, cursor, unexpected);
David Tolnayd639f612019-06-09 03:36:01 -07001126 let node = self(&state)?;
1127 state.check_unexpected()?;
1128 if state.is_empty() {
1129 Ok(node)
1130 } else {
1131 Err(state.error("unexpected token"))
1132 }
1133 }
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -07001134
1135 #[doc(hidden)]
1136 fn __parse_stream(self, input: ParseStream) -> Result<Self::Output> {
1137 self(input)
1138 }
David Tolnayd639f612019-06-09 03:36:01 -07001139}
1140
Chih-Hung Hsieh467ea212019-10-31 17:36:47 -07001141pub(crate) fn parse_scoped<F: Parser>(f: F, scope: Span, tokens: TokenStream) -> Result<F::Output> {
1142 f.__parse_scoped(scope, tokens)
1143}
1144
1145pub(crate) fn parse_stream<F: Parser>(f: F, input: ParseStream) -> Result<F::Output> {
1146 f.__parse_stream(input)
1147}
1148
1149/// An empty syntax tree node that consumes no tokens when parsed.
1150///
1151/// This is useful for attribute macros that want to ensure they are not
1152/// provided any attribute args.
1153///
1154/// ```
1155/// extern crate proc_macro;
1156///
1157/// use proc_macro::TokenStream;
1158/// use syn::parse_macro_input;
1159/// use syn::parse::Nothing;
1160///
1161/// # const IGNORE: &str = stringify! {
1162/// #[proc_macro_attribute]
1163/// # };
1164/// pub fn my_attr(args: TokenStream, input: TokenStream) -> TokenStream {
1165/// parse_macro_input!(args as Nothing);
1166///
1167/// /* ... */
1168/// # "".parse().unwrap()
1169/// }
1170/// ```
1171///
1172/// ```text
1173/// error: unexpected token
1174/// --> src/main.rs:3:19
1175/// |
1176/// 3 | #[my_attr(asdf)]
1177/// | ^^^^
1178/// ```
1179pub struct Nothing;
1180
1181impl Parse for Nothing {
1182 fn parse(_input: ParseStream) -> Result<Self> {
1183 Ok(Nothing)
David Tolnayd639f612019-06-09 03:36:01 -07001184 }
David Tolnay80a914f2018-08-30 23:49:53 -07001185}