blob: b4da36cc8a8fc3c144c98c45c7ca55b6f72ca198 [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 Tolnay43984452018-09-01 17:43:56 -070028//! ```
David Tolnaya1c98072018-09-06 08:58:10 -070029//! #[macro_use]
30//! extern crate syn;
31//!
32//! extern crate proc_macro;
33//!
David Tolnay88d9f622018-09-01 17:52:33 -070034//! use proc_macro::TokenStream;
David Tolnay67fea042018-11-24 14:50:20 -080035//! use syn::{token, Field, Ident, Result};
36//! use syn::parse::{Parse, ParseStream};
David Tolnay43984452018-09-01 17:43:56 -070037//! use syn::punctuated::Punctuated;
38//!
39//! enum Item {
40//! Struct(ItemStruct),
41//! Enum(ItemEnum),
42//! }
43//!
44//! struct ItemStruct {
45//! struct_token: Token![struct],
46//! ident: Ident,
47//! brace_token: token::Brace,
48//! fields: Punctuated<Field, Token![,]>,
49//! }
50//! #
51//! # enum ItemEnum {}
52//!
53//! impl Parse for Item {
54//! fn parse(input: ParseStream) -> Result<Self> {
55//! let lookahead = input.lookahead1();
56//! if lookahead.peek(Token![struct]) {
57//! input.parse().map(Item::Struct)
58//! } else if lookahead.peek(Token![enum]) {
59//! input.parse().map(Item::Enum)
60//! } else {
61//! Err(lookahead.error())
62//! }
63//! }
64//! }
65//!
66//! impl Parse for ItemStruct {
67//! fn parse(input: ParseStream) -> Result<Self> {
68//! let content;
69//! Ok(ItemStruct {
70//! struct_token: input.parse()?,
71//! ident: input.parse()?,
72//! brace_token: braced!(content in input),
73//! fields: content.parse_terminated(Field::parse_named)?,
74//! })
75//! }
76//! }
77//! #
78//! # impl Parse for ItemEnum {
79//! # fn parse(input: ParseStream) -> Result<Self> {
80//! # unimplemented!()
81//! # }
82//! # }
David Tolnay88d9f622018-09-01 17:52:33 -070083//!
84//! # const IGNORE: &str = stringify! {
85//! #[proc_macro]
86//! # };
87//! pub fn my_macro(tokens: TokenStream) -> TokenStream {
88//! let input = parse_macro_input!(tokens as Item);
89//!
90//! /* ... */
91//! # "".parse().unwrap()
92//! }
93//! #
94//! # fn main() {}
David Tolnay43984452018-09-01 17:43:56 -070095//! ```
96//!
97//! # The `syn::parse*` functions
David Tolnay80a914f2018-08-30 23:49:53 -070098//!
99//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
100//! as an entry point for parsing syntax tree nodes that can be parsed in an
101//! obvious default way. These functions can return any syntax tree node that
David Tolnay8aacee12018-08-31 09:15:15 -0700102//! implements the [`Parse`] trait, which includes most types in Syn.
David Tolnay80a914f2018-08-30 23:49:53 -0700103//!
104//! [`syn::parse`]: ../fn.parse.html
105//! [`syn::parse2`]: ../fn.parse2.html
106//! [`syn::parse_str`]: ../fn.parse_str.html
David Tolnay8aacee12018-08-31 09:15:15 -0700107//! [`Parse`]: trait.Parse.html
David Tolnay80a914f2018-08-30 23:49:53 -0700108//!
109//! ```
110//! use syn::Type;
111//!
David Tolnay67fea042018-11-24 14:50:20 -0800112//! # fn run_parser() -> syn::Result<()> {
David Tolnay80a914f2018-08-30 23:49:53 -0700113//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
114//! # Ok(())
115//! # }
116//! #
117//! # fn main() {
118//! # run_parser().unwrap();
119//! # }
120//! ```
121//!
122//! The [`parse_quote!`] macro also uses this approach.
123//!
124//! [`parse_quote!`]: ../macro.parse_quote.html
125//!
David Tolnay43984452018-09-01 17:43:56 -0700126//! # The `Parser` trait
David Tolnay80a914f2018-08-30 23:49:53 -0700127//!
128//! Some types can be parsed in several ways depending on context. For example
129//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
130//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
131//! may or may not allow trailing punctuation, and parsing it the wrong way
132//! would either reject valid input or accept invalid input.
133//!
134//! [`Attribute`]: ../struct.Attribute.html
135//! [`Punctuated`]: ../punctuated/index.html
136//!
David Tolnaye0c51762018-08-31 11:05:22 -0700137//! The `Parse` trait is not implemented in these cases because there is no good
David Tolnay80a914f2018-08-30 23:49:53 -0700138//! behavior to consider the default.
139//!
David Tolnay2b45fd42018-11-06 21:16:55 -0800140//! ```compile_fail
141//! # extern crate proc_macro;
142//! # extern crate syn;
143//! #
David Tolnay2b45fd42018-11-06 21:16:55 -0800144//! # use syn::punctuated::Punctuated;
David Tolnay67fea042018-11-24 14:50:20 -0800145//! # use syn::{PathSegment, Result, Token};
David Tolnay2b45fd42018-11-06 21:16:55 -0800146//! #
147//! # fn f(tokens: proc_macro::TokenStream) -> Result<()> {
148//! #
David Tolnay80a914f2018-08-30 23:49:53 -0700149//! // Can't parse `Punctuated` without knowing whether trailing punctuation
150//! // should be allowed in this context.
151//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
David Tolnay2b45fd42018-11-06 21:16:55 -0800152//! #
153//! # Ok(())
154//! # }
David Tolnay80a914f2018-08-30 23:49:53 -0700155//! ```
156//!
157//! In these cases the types provide a choice of parser functions rather than a
David Tolnaye0c51762018-08-31 11:05:22 -0700158//! single `Parse` implementation, and those parser functions can be invoked
David Tolnay80a914f2018-08-30 23:49:53 -0700159//! through the [`Parser`] trait.
160//!
161//! [`Parser`]: trait.Parser.html
162//!
163//! ```
David Tolnaya1c98072018-09-06 08:58:10 -0700164//! #[macro_use]
165//! extern crate syn;
166//!
167//! extern crate proc_macro2;
168//!
169//! use proc_macro2::TokenStream;
David Tolnay3e3f7752018-08-31 09:33:59 -0700170//! use syn::parse::Parser;
David Tolnay80a914f2018-08-30 23:49:53 -0700171//! use syn::punctuated::Punctuated;
David Tolnaya1c98072018-09-06 08:58:10 -0700172//! use syn::{Attribute, Expr, PathSegment};
David Tolnay80a914f2018-08-30 23:49:53 -0700173//!
David Tolnay67fea042018-11-24 14:50:20 -0800174//! # fn run_parsers() -> syn::Result<()> {
David Tolnay80a914f2018-08-30 23:49:53 -0700175//! # let tokens = TokenStream::new().into();
176//! // Parse a nonempty sequence of path segments separated by `::` punctuation
177//! // with no trailing punctuation.
178//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
179//! let path = parser.parse(tokens)?;
180//!
181//! # let tokens = TokenStream::new().into();
182//! // Parse a possibly empty sequence of expressions terminated by commas with
183//! // an optional trailing punctuation.
184//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
185//! let args = parser.parse(tokens)?;
186//!
187//! # let tokens = TokenStream::new().into();
188//! // Parse zero or more outer attributes but not inner attributes.
David Tolnay3e3f7752018-08-31 09:33:59 -0700189//! let parser = Attribute::parse_outer;
190//! let attrs = parser.parse(tokens)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700191//! #
192//! # Ok(())
193//! # }
194//! #
195//! # fn main() {}
196//! ```
197//!
David Tolnaye0c51762018-08-31 11:05:22 -0700198//! ---
David Tolnay80a914f2018-08-30 23:49:53 -0700199//!
200//! *This module is available if Syn is built with the `"parsing"` feature.*
David Tolnay18c754c2018-08-21 23:26:58 -0400201
202use std::cell::Cell;
Diggory Hardy1c522e12018-11-02 10:10:02 +0000203use std::fmt::{self, Debug, Display};
David Tolnay18c754c2018-08-21 23:26:58 -0400204use std::marker::PhantomData;
205use std::mem;
206use std::ops::Deref;
David Tolnayeafc8052018-08-25 16:33:53 -0400207use std::rc::Rc;
David Tolnay80a914f2018-08-30 23:49:53 -0700208use std::str::FromStr;
David Tolnayeafc8052018-08-25 16:33:53 -0400209
David Tolnay80a914f2018-08-30 23:49:53 -0700210#[cfg(all(
211 not(all(target_arch = "wasm32", target_os = "unknown")),
212 feature = "proc-macro"
213))]
214use proc_macro;
David Tolnayf07b3342018-09-01 11:58:11 -0700215use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
David Tolnay18c754c2018-08-21 23:26:58 -0400216
David Tolnay80a914f2018-08-30 23:49:53 -0700217use buffer::{Cursor, TokenBuffer};
David Tolnayb6254182018-08-25 08:44:54 -0400218use error;
David Tolnay94f06632018-08-31 10:17:17 -0700219use lookahead;
220use private;
David Tolnay577d0332018-08-25 21:45:24 -0400221use punctuated::Punctuated;
David Tolnay4fb71232018-08-25 23:14:50 -0400222use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -0400223
David Tolnayb6254182018-08-25 08:44:54 -0400224pub use error::{Error, Result};
225pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -0400226
227/// Parsing interface implemented by all types that can be parsed in a default
228/// way from a token stream.
229pub trait Parse: Sized {
230 fn parse(input: ParseStream) -> Result<Self>;
231}
232
233/// Input to a Syn parser function.
David Tolnaya0daa482018-09-01 02:09:40 -0700234///
235/// See the methods of this type under the documentation of [`ParseBuffer`]. For
236/// an overview of parsing in Syn, refer to the [module documentation].
237///
238/// [module documentation]: index.html
David Tolnay18c754c2018-08-21 23:26:58 -0400239pub type ParseStream<'a> = &'a ParseBuffer<'a>;
240
241/// Cursor position within a buffered token stream.
David Tolnay20d29a12018-09-01 15:15:33 -0700242///
243/// This type is more commonly used through the type alias [`ParseStream`] which
244/// is an alias for `&ParseBuffer`.
245///
246/// `ParseStream` is the input type for all parser functions in Syn. They have
247/// the signature `fn(ParseStream) -> Result<T>`.
David Tolnay18c754c2018-08-21 23:26:58 -0400248pub struct ParseBuffer<'a> {
249 scope: Span,
David Tolnay5d7f2252018-09-02 08:21:40 -0700250 // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
251 // The rest of the code in this module needs to be careful that only a
252 // cursor derived from this `cell` is ever assigned to this `cell`.
253 //
254 // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
255 // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
256 // than 'a, and then assign a Cursor<'short> into the Cell.
257 //
258 // By extension, it would not be safe to expose an API that accepts a
259 // Cursor<'a> and trusts that it lives as long as the cursor currently in
260 // the cell.
David Tolnay18c754c2018-08-21 23:26:58 -0400261 cell: Cell<Cursor<'static>>,
262 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400263 unexpected: Rc<Cell<Option<Span>>>,
264}
265
266impl<'a> Drop for ParseBuffer<'a> {
267 fn drop(&mut self) {
268 if !self.is_empty() && self.unexpected.get().is_none() {
269 self.unexpected.set(Some(self.cursor().span()));
270 }
271 }
David Tolnay18c754c2018-08-21 23:26:58 -0400272}
273
Diggory Hardy1c522e12018-11-02 10:10:02 +0000274impl<'a> Display for ParseBuffer<'a> {
275 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
276 Display::fmt(&self.cursor().token_stream(), f)
277 }
278}
279
280impl<'a> Debug for ParseBuffer<'a> {
281 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
282 Debug::fmt(&self.cursor().token_stream(), f)
283 }
284}
285
David Tolnay642832f2018-09-01 13:08:10 -0700286/// Cursor state associated with speculative parsing.
287///
288/// This type is the input of the closure provided to [`ParseStream::step`].
289///
290/// [`ParseStream::step`]: struct.ParseBuffer.html#method.step
David Tolnay9bd34392018-09-01 13:19:53 -0700291///
292/// # Example
293///
294/// ```
295/// # extern crate proc_macro2;
296/// # extern crate syn;
297/// #
298/// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800299/// use syn::Result;
300/// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700301///
302/// // This function advances the stream past the next occurrence of `@`. If
303/// // no `@` is present in the stream, the stream position is unchanged and
304/// // an error is returned.
305/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
306/// input.step(|cursor| {
307/// let mut rest = *cursor;
Sharad Chande1df40a2018-09-08 15:25:52 +0545308/// while let Some((tt, next)) = rest.token_tree() {
David Tolnay9bd34392018-09-01 13:19:53 -0700309/// match tt {
310/// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
311/// return Ok(((), next));
312/// }
313/// _ => rest = next,
314/// }
315/// }
316/// Err(cursor.error("no `@` was found after this point"))
317/// })
318/// }
319/// #
David Tolnaydb312582018-11-06 20:42:05 -0800320/// #
321/// # fn remainder_after_skipping_past_next_at(
322/// # input: ParseStream,
323/// # ) -> Result<proc_macro2::TokenStream> {
324/// # skip_past_next_at(input)?;
325/// # input.parse()
326/// # }
327/// #
328/// # fn main() {
329/// # use syn::parse::Parser;
330/// # let remainder = remainder_after_skipping_past_next_at
331/// # .parse_str("a @ b c")
332/// # .unwrap();
333/// # assert_eq!(remainder.to_string(), "b c");
334/// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700335/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400336#[derive(Copy, Clone)]
337pub struct StepCursor<'c, 'a> {
338 scope: Span,
David Tolnay56924f42018-09-02 08:24:58 -0700339 // This field is covariant in 'c.
David Tolnay18c754c2018-08-21 23:26:58 -0400340 cursor: Cursor<'c>,
David Tolnay56924f42018-09-02 08:24:58 -0700341 // This field is contravariant in 'c. Together these make StepCursor
342 // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
343 // different lifetime but can upcast into a StepCursor with a shorter
344 // lifetime 'a.
345 //
346 // As long as we only ever construct a StepCursor for which 'c outlives 'a,
347 // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
348 // outlives 'a.
David Tolnay18c754c2018-08-21 23:26:58 -0400349 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
350}
351
352impl<'c, 'a> Deref for StepCursor<'c, 'a> {
353 type Target = Cursor<'c>;
354
355 fn deref(&self) -> &Self::Target {
356 &self.cursor
357 }
358}
359
360impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700361 /// Triggers an error at the current position of the parse stream.
362 ///
363 /// The `ParseStream::step` invocation will return this same error without
364 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400365 pub fn error<T: Display>(self, message: T) -> Error {
366 error::new_at(self.scope, self.cursor, message)
367 }
368}
369
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700370impl private {
371 pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
David Tolnay56924f42018-09-02 08:24:58 -0700372 // Refer to the comments within the StepCursor definition. We use the
373 // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
374 // Cursor is covariant in its lifetime parameter so we can cast a
375 // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700376 let _ = proof;
377 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
378 }
379}
380
David Tolnay66cb0c42018-08-31 09:01:30 -0700381fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700382 input
383 .step(|cursor| {
384 if let Some((_lifetime, rest)) = cursor.lifetime() {
385 Ok((true, rest))
386 } else if let Some((_token, rest)) = cursor.token_tree() {
387 Ok((true, rest))
388 } else {
389 Ok((false, *cursor))
390 }
David Tolnayfb84fc02018-10-02 21:01:30 -0700391 })
392 .unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700393}
394
David Tolnay10951d52018-08-31 10:27:39 -0700395impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700396 pub fn new_parse_buffer(
397 scope: Span,
398 cursor: Cursor,
399 unexpected: Rc<Cell<Option<Span>>>,
400 ) -> ParseBuffer {
David Tolnay18c754c2018-08-21 23:26:58 -0400401 ParseBuffer {
402 scope: scope,
David Tolnay5d7f2252018-09-02 08:21:40 -0700403 // See comment on `cell` in the struct definition.
404 cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
David Tolnay18c754c2018-08-21 23:26:58 -0400405 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400406 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400407 }
408 }
409
David Tolnay94f06632018-08-31 10:17:17 -0700410 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
411 buffer.unexpected.clone()
412 }
413}
414
415impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700416 /// Parses a syntax tree node of type `T`, advancing the position of our
417 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400418 pub fn parse<T: Parse>(&self) -> Result<T> {
419 T::parse(self)
420 }
421
David Tolnay725e1c62018-09-01 12:07:25 -0700422 /// Calls the given parser function to parse a syntax tree node of type `T`
423 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700424 ///
425 /// # Example
426 ///
427 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
428 /// zero or more outer attributes.
429 ///
430 /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
431 ///
432 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700433 /// #[macro_use]
434 /// extern crate syn;
435 ///
David Tolnay67fea042018-11-24 14:50:20 -0800436 /// use syn::{Attribute, Ident, Result};
437 /// use syn::parse::{Parse, ParseStream};
David Tolnay21ce84c2018-09-01 15:37:51 -0700438 ///
439 /// // Parses a unit struct with attributes.
440 /// //
441 /// // #[path = "s.tmpl"]
442 /// // struct S;
443 /// struct UnitStruct {
444 /// attrs: Vec<Attribute>,
445 /// struct_token: Token![struct],
446 /// name: Ident,
447 /// semi_token: Token![;],
448 /// }
449 ///
450 /// impl Parse for UnitStruct {
451 /// fn parse(input: ParseStream) -> Result<Self> {
452 /// Ok(UnitStruct {
453 /// attrs: input.call(Attribute::parse_outer)?,
454 /// struct_token: input.parse()?,
455 /// name: input.parse()?,
456 /// semi_token: input.parse()?,
457 /// })
458 /// }
459 /// }
460 /// #
461 /// # fn main() {}
462 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400463 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
464 function(self)
465 }
466
David Tolnay725e1c62018-09-01 12:07:25 -0700467 /// Looks at the next token in the parse stream to determine whether it
468 /// matches the requested type of token.
469 ///
470 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700471 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700472 /// # Syntax
473 ///
474 /// Note that this method does not use turbofish syntax. Pass the peek type
475 /// inside of parentheses.
476 ///
477 /// - `input.peek(Token![struct])`
478 /// - `input.peek(Token![==])`
479 /// - `input.peek(Ident)`
480 /// - `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 ///
488 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700489 /// #[macro_use]
490 /// extern crate syn;
491 ///
David Tolnay67fea042018-11-24 14:50:20 -0800492 /// use syn::{token, Generics, Ident, Result, TypeParamBound};
493 /// use syn::parse::{Parse, ParseStream};
David Tolnayddebc3e2018-09-01 16:29:20 -0700494 /// use syn::punctuated::Punctuated;
495 ///
496 /// // Parses a trait definition containing no associated items.
497 /// //
498 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
499 /// struct MarkerTrait {
500 /// trait_token: Token![trait],
501 /// ident: Ident,
502 /// generics: Generics,
503 /// colon_token: Option<Token![:]>,
504 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
505 /// brace_token: token::Brace,
506 /// }
507 ///
508 /// impl Parse for MarkerTrait {
509 /// fn parse(input: ParseStream) -> Result<Self> {
510 /// let trait_token: Token![trait] = input.parse()?;
511 /// let ident: Ident = input.parse()?;
512 /// let mut generics: Generics = input.parse()?;
513 /// let colon_token: Option<Token![:]> = input.parse()?;
514 ///
515 /// let mut supertraits = Punctuated::new();
516 /// if colon_token.is_some() {
517 /// loop {
518 /// supertraits.push_value(input.parse()?);
519 /// if input.peek(Token![where]) || input.peek(token::Brace) {
520 /// break;
521 /// }
522 /// supertraits.push_punct(input.parse()?);
523 /// }
524 /// }
525 ///
526 /// generics.where_clause = input.parse()?;
527 /// let content;
528 /// let empty_brace_token = braced!(content in input);
529 ///
530 /// Ok(MarkerTrait {
531 /// trait_token: trait_token,
532 /// ident: ident,
533 /// generics: generics,
534 /// colon_token: colon_token,
535 /// supertraits: supertraits,
536 /// brace_token: empty_brace_token,
537 /// })
538 /// }
539 /// }
540 /// #
541 /// # fn main() {}
542 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400543 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700544 let _ = token;
545 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400546 }
547
David Tolnay725e1c62018-09-01 12:07:25 -0700548 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700549 ///
550 /// This is commonly useful as a way to implement contextual keywords.
551 ///
552 /// # Example
553 ///
554 /// This example needs to use `peek2` because the symbol `union` is not a
555 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
556 /// the very next token is `union`, because someone is free to write a `mod
557 /// union` and a macro invocation that looks like `union::some_macro! { ...
558 /// }`. In other words `union` is a contextual keyword.
559 ///
560 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700561 /// #[macro_use]
562 /// extern crate syn;
563 ///
David Tolnay67fea042018-11-24 14:50:20 -0800564 /// use syn::{Ident, ItemUnion, Macro, Result};
565 /// use syn::parse::{Parse, ParseStream};
David Tolnaye334b872018-09-01 16:38:10 -0700566 ///
567 /// // Parses either a union or a macro invocation.
568 /// enum UnionOrMacro {
569 /// // union MaybeUninit<T> { uninit: (), value: T }
570 /// Union(ItemUnion),
571 /// // lazy_static! { ... }
572 /// Macro(Macro),
573 /// }
574 ///
575 /// impl Parse for UnionOrMacro {
576 /// fn parse(input: ParseStream) -> Result<Self> {
577 /// if input.peek(Token![union]) && input.peek2(Ident) {
578 /// input.parse().map(UnionOrMacro::Union)
579 /// } else {
580 /// input.parse().map(UnionOrMacro::Macro)
581 /// }
582 /// }
583 /// }
584 /// #
585 /// # fn main() {}
586 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400587 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400588 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700589 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400590 }
591
David Tolnay725e1c62018-09-01 12:07:25 -0700592 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400593 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400594 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700595 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400596 }
597
David Tolnay725e1c62018-09-01 12:07:25 -0700598 /// Parses zero or more occurrences of `T` separated by punctuation of type
599 /// `P`, with optional trailing punctuation.
600 ///
601 /// Parsing continues until the end of this parse stream. The entire content
602 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700603 ///
604 /// # Example
605 ///
606 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700607 /// # #[macro_use]
David Tolnay0abe65b2018-09-01 14:31:43 -0700608 /// # extern crate quote;
David Tolnay0abe65b2018-09-01 14:31:43 -0700609 /// #
David Tolnaya1c98072018-09-06 08:58:10 -0700610 /// #[macro_use]
611 /// extern crate syn;
612 ///
David Tolnay67fea042018-11-24 14:50:20 -0800613 /// use syn::{token, Ident, Result, Type};
614 /// use syn::parse::{Parse, ParseStream};
David Tolnay0abe65b2018-09-01 14:31:43 -0700615 /// use syn::punctuated::Punctuated;
616 ///
617 /// // Parse a simplified tuple struct syntax like:
618 /// //
619 /// // struct S(A, B);
620 /// struct TupleStruct {
621 /// struct_token: Token![struct],
622 /// ident: Ident,
623 /// paren_token: token::Paren,
624 /// fields: Punctuated<Type, Token![,]>,
625 /// semi_token: Token![;],
626 /// }
627 ///
628 /// impl Parse for TupleStruct {
629 /// fn parse(input: ParseStream) -> Result<Self> {
630 /// let content;
631 /// Ok(TupleStruct {
632 /// struct_token: input.parse()?,
633 /// ident: input.parse()?,
634 /// paren_token: parenthesized!(content in input),
635 /// fields: content.parse_terminated(Type::parse)?,
636 /// semi_token: input.parse()?,
637 /// })
638 /// }
639 /// }
640 /// #
641 /// # fn main() {
642 /// # let input = quote! {
643 /// # struct S(A, B);
644 /// # };
645 /// # syn::parse2::<TupleStruct>(input).unwrap();
646 /// # }
647 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400648 pub fn parse_terminated<T, P: Parse>(
649 &self,
650 parser: fn(ParseStream) -> Result<T>,
651 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700652 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400653 }
654
David Tolnay725e1c62018-09-01 12:07:25 -0700655 /// Returns whether there are tokens remaining in this stream.
656 ///
657 /// This method returns true at the end of the content of a set of
658 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700659 ///
660 /// # Example
661 ///
662 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700663 /// #[macro_use]
664 /// extern crate syn;
665 ///
David Tolnay67fea042018-11-24 14:50:20 -0800666 /// use syn::{token, Ident, Item, Result};
667 /// use syn::parse::{Parse, ParseStream};
David Tolnaycce6b5f2018-09-01 14:24:46 -0700668 ///
669 /// // Parses a Rust `mod m { ... }` containing zero or more items.
670 /// struct Mod {
671 /// mod_token: Token![mod],
672 /// name: Ident,
673 /// brace_token: token::Brace,
674 /// items: Vec<Item>,
675 /// }
676 ///
677 /// impl Parse for Mod {
678 /// fn parse(input: ParseStream) -> Result<Self> {
679 /// let content;
680 /// Ok(Mod {
681 /// mod_token: input.parse()?,
682 /// name: input.parse()?,
683 /// brace_token: braced!(content in input),
684 /// items: {
685 /// let mut items = Vec::new();
686 /// while !content.is_empty() {
687 /// items.push(content.parse()?);
688 /// }
689 /// items
690 /// },
691 /// })
692 /// }
693 /// }
694 /// #
695 /// # fn main() {}
David Tolnayf2b78602018-11-06 20:42:37 -0800696 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700697 pub fn is_empty(&self) -> bool {
698 self.cursor().eof()
699 }
700
David Tolnay725e1c62018-09-01 12:07:25 -0700701 /// Constructs a helper for peeking at the next token in this stream and
702 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700703 ///
704 /// # Example
705 ///
706 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700707 /// #[macro_use]
708 /// extern crate syn;
709 ///
David Tolnay67fea042018-11-24 14:50:20 -0800710 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, TypeParam};
711 /// use syn::parse::{Parse, ParseStream};
David Tolnay2c77e772018-09-01 14:18:46 -0700712 ///
713 /// // A generic parameter, a single one of the comma-separated elements inside
714 /// // angle brackets in:
715 /// //
716 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
717 /// //
718 /// // On invalid input, lookahead gives us a reasonable error message.
719 /// //
720 /// // error: expected one of: identifier, lifetime, `const`
721 /// // |
722 /// // 5 | fn f<!Sized>() {}
723 /// // | ^
724 /// enum GenericParam {
725 /// Type(TypeParam),
726 /// Lifetime(LifetimeDef),
727 /// Const(ConstParam),
728 /// }
729 ///
730 /// impl Parse for GenericParam {
731 /// fn parse(input: ParseStream) -> Result<Self> {
732 /// let lookahead = input.lookahead1();
733 /// if lookahead.peek(Ident) {
734 /// input.parse().map(GenericParam::Type)
735 /// } else if lookahead.peek(Lifetime) {
736 /// input.parse().map(GenericParam::Lifetime)
737 /// } else if lookahead.peek(Token![const]) {
738 /// input.parse().map(GenericParam::Const)
739 /// } else {
740 /// Err(lookahead.error())
741 /// }
742 /// }
743 /// }
744 /// #
745 /// # fn main() {}
746 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700747 pub fn lookahead1(&self) -> Lookahead1<'a> {
748 lookahead::new(self.scope, self.cursor())
749 }
750
David Tolnay725e1c62018-09-01 12:07:25 -0700751 /// Forks a parse stream so that parsing tokens out of either the original
752 /// or the fork does not advance the position of the other.
753 ///
754 /// # Performance
755 ///
756 /// Forking a parse stream is a cheap fixed amount of work and does not
757 /// involve copying token buffers. Where you might hit performance problems
758 /// is if your macro ends up parsing a large amount of content more than
759 /// once.
760 ///
761 /// ```
David Tolnay67fea042018-11-24 14:50:20 -0800762 /// # use syn::{Expr, Result};
763 /// # use syn::parse::ParseStream;
David Tolnay725e1c62018-09-01 12:07:25 -0700764 /// #
765 /// # fn bad(input: ParseStream) -> Result<Expr> {
766 /// // Do not do this.
767 /// if input.fork().parse::<Expr>().is_ok() {
768 /// return input.parse::<Expr>();
769 /// }
770 /// # unimplemented!()
771 /// # }
772 /// ```
773 ///
774 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
775 /// parse stream. Only use a fork when the amount of work performed against
776 /// the fork is small and bounded.
777 ///
David Tolnayec149b02018-09-01 14:17:28 -0700778 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700779 /// speculative parsing, consider using [`ParseStream::step`] instead.
780 ///
781 /// [`ParseStream::step`]: #method.step
David Tolnayec149b02018-09-01 14:17:28 -0700782 ///
783 /// # Example
784 ///
785 /// The parse implementation shown here parses possibly restricted `pub`
786 /// visibilities.
787 ///
788 /// - `pub`
789 /// - `pub(crate)`
790 /// - `pub(self)`
791 /// - `pub(super)`
792 /// - `pub(in some::path)`
793 ///
794 /// To handle the case of visibilities inside of tuple structs, the parser
795 /// needs to distinguish parentheses that specify visibility restrictions
796 /// from parentheses that form part of a tuple type.
797 ///
798 /// ```
799 /// # struct A;
800 /// # struct B;
801 /// # struct C;
802 /// #
803 /// struct S(pub(crate) A, pub (B, C));
804 /// ```
805 ///
806 /// In this example input the first tuple struct element of `S` has
807 /// `pub(crate)` visibility while the second tuple struct element has `pub`
808 /// visibility; the parentheses around `(B, C)` are part of the type rather
809 /// than part of a visibility restriction.
810 ///
811 /// The parser uses a forked parse stream to check the first token inside of
812 /// parentheses after the `pub` keyword. This is a small bounded amount of
813 /// work performed against the forked parse stream.
814 ///
815 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700816 /// #[macro_use]
817 /// extern crate syn;
818 ///
David Tolnay67fea042018-11-24 14:50:20 -0800819 /// use syn::{token, Ident, Path, Result};
David Tolnayec149b02018-09-01 14:17:28 -0700820 /// use syn::ext::IdentExt;
David Tolnay67fea042018-11-24 14:50:20 -0800821 /// use syn::parse::{Parse, ParseStream};
David Tolnayec149b02018-09-01 14:17:28 -0700822 ///
823 /// struct PubVisibility {
824 /// pub_token: Token![pub],
825 /// restricted: Option<Restricted>,
826 /// }
827 ///
828 /// struct Restricted {
829 /// paren_token: token::Paren,
830 /// in_token: Option<Token![in]>,
831 /// path: Path,
832 /// }
833 ///
834 /// impl Parse for PubVisibility {
835 /// fn parse(input: ParseStream) -> Result<Self> {
836 /// let pub_token: Token![pub] = input.parse()?;
837 ///
838 /// if input.peek(token::Paren) {
839 /// let ahead = input.fork();
840 /// let mut content;
841 /// parenthesized!(content in ahead);
842 ///
843 /// if content.peek(Token![crate])
844 /// || content.peek(Token![self])
845 /// || content.peek(Token![super])
846 /// {
847 /// return Ok(PubVisibility {
848 /// pub_token: pub_token,
849 /// restricted: Some(Restricted {
850 /// paren_token: parenthesized!(content in input),
851 /// in_token: None,
852 /// path: Path::from(content.call(Ident::parse_any)?),
853 /// }),
854 /// });
855 /// } else if content.peek(Token![in]) {
856 /// return Ok(PubVisibility {
857 /// pub_token: pub_token,
858 /// restricted: Some(Restricted {
859 /// paren_token: parenthesized!(content in input),
860 /// in_token: Some(content.parse()?),
861 /// path: content.call(Path::parse_mod_style)?,
862 /// }),
863 /// });
864 /// }
865 /// }
866 ///
867 /// Ok(PubVisibility {
868 /// pub_token: pub_token,
869 /// restricted: None,
870 /// })
871 /// }
872 /// }
873 /// #
874 /// # fn main() {}
875 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400876 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400877 ParseBuffer {
878 scope: self.scope,
879 cell: self.cell.clone(),
880 marker: PhantomData,
881 // Not the parent's unexpected. Nothing cares whether the clone
882 // parses all the way.
883 unexpected: Rc::new(Cell::new(None)),
884 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400885 }
886
David Tolnay725e1c62018-09-01 12:07:25 -0700887 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700888 ///
889 /// # Example
890 ///
891 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700892 /// #[macro_use]
893 /// extern crate syn;
894 ///
David Tolnay67fea042018-11-24 14:50:20 -0800895 /// use syn::{Expr, Result};
896 /// use syn::parse::{Parse, ParseStream};
David Tolnay23fce0b2018-09-01 13:50:31 -0700897 ///
898 /// // Some kind of loop: `while` or `for` or `loop`.
899 /// struct Loop {
900 /// expr: Expr,
901 /// }
902 ///
903 /// impl Parse for Loop {
904 /// fn parse(input: ParseStream) -> Result<Self> {
905 /// if input.peek(Token![while])
906 /// || input.peek(Token![for])
907 /// || input.peek(Token![loop])
908 /// {
909 /// Ok(Loop {
910 /// expr: input.parse()?,
911 /// })
912 /// } else {
913 /// Err(input.error("expected some kind of loop"))
914 /// }
915 /// }
916 /// }
David Tolnaya1c98072018-09-06 08:58:10 -0700917 /// #
918 /// # fn main() {}
David Tolnay23fce0b2018-09-01 13:50:31 -0700919 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400920 pub fn error<T: Display>(&self, message: T) -> Error {
921 error::new_at(self.scope, self.cursor(), message)
922 }
923
David Tolnay725e1c62018-09-01 12:07:25 -0700924 /// Speculatively parses tokens from this parse stream, advancing the
925 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700926 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700927 /// This is a powerful low-level API used for defining the `Parse` impls of
928 /// the basic built-in token types. It is not something that will be used
929 /// widely outside of the Syn codebase.
930 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700931 /// # Example
932 ///
933 /// ```
934 /// # extern crate proc_macro2;
935 /// # extern crate syn;
936 /// #
937 /// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800938 /// use syn::Result;
939 /// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700940 ///
941 /// // This function advances the stream past the next occurrence of `@`. If
942 /// // no `@` is present in the stream, the stream position is unchanged and
943 /// // an error is returned.
944 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
945 /// input.step(|cursor| {
946 /// let mut rest = *cursor;
David Tolnaydb312582018-11-06 20:42:05 -0800947 /// while let Some((tt, next)) = rest.token_tree() {
David Tolnay9bd34392018-09-01 13:19:53 -0700948 /// match tt {
949 /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
950 /// return Ok(((), next));
951 /// }
952 /// _ => rest = next,
953 /// }
954 /// }
955 /// Err(cursor.error("no `@` was found after this point"))
956 /// })
957 /// }
958 /// #
David Tolnaydb312582018-11-06 20:42:05 -0800959 /// # fn remainder_after_skipping_past_next_at(
960 /// # input: ParseStream,
961 /// # ) -> Result<proc_macro2::TokenStream> {
962 /// # skip_past_next_at(input)?;
963 /// # input.parse()
964 /// # }
965 /// #
966 /// # fn main() {
967 /// # use syn::parse::Parser;
968 /// # let remainder = remainder_after_skipping_past_next_at
969 /// # .parse_str("a @ b c")
970 /// # .unwrap();
971 /// # assert_eq!(remainder.to_string(), "b c");
972 /// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700973 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700974 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400975 where
976 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
977 {
David Tolnayc142b092018-09-02 08:52:52 -0700978 // Since the user's function is required to work for any 'c, we know
979 // that the Cursor<'c> they return is either derived from the input
980 // StepCursor<'c, 'a> or from a Cursor<'static>.
981 //
982 // It would not be legal to write this function without the invariant
983 // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
984 // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
985 // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
986 // `step` on their ParseBuffer<'short> with a closure that returns
987 // Cursor<'short>, and we would wrongly write that Cursor<'short> into
988 // the Cell intended to hold Cursor<'a>.
989 //
990 // In some cases it may be necessary for R to contain a Cursor<'a>.
991 // Within Syn we solve this using `private::advance_step_cursor` which
992 // uses the existence of a StepCursor<'c, 'a> as proof that it is safe
993 // to cast from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it
994 // would be safe to expose that API as a method on StepCursor.
David Tolnay6b65f852018-09-01 11:56:25 -0700995 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -0400996 scope: self.scope,
997 cursor: self.cell.get(),
998 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700999 })?;
1000 self.cell.set(rest);
1001 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -04001002 }
David Tolnayeafc8052018-08-25 16:33:53 -04001003
David Tolnay725e1c62018-09-01 12:07:25 -07001004 /// Provides low-level access to the token representation underlying this
1005 /// parse stream.
1006 ///
1007 /// Cursors are immutable so no operations you perform against the cursor
1008 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -07001009 pub fn cursor(&self) -> Cursor<'a> {
1010 self.cell.get()
1011 }
1012
David Tolnay94f06632018-08-31 10:17:17 -07001013 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -04001014 match self.unexpected.get() {
1015 Some(span) => Err(Error::new(span, "unexpected token")),
1016 None => Ok(()),
1017 }
1018 }
David Tolnay18c754c2018-08-21 23:26:58 -04001019}
1020
David Tolnaya7d69fc2018-08-26 13:30:24 -04001021impl<T: Parse> Parse for Box<T> {
1022 fn parse(input: ParseStream) -> Result<Self> {
1023 input.parse().map(Box::new)
1024 }
1025}
1026
David Tolnay4fb71232018-08-25 23:14:50 -04001027impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -04001028 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -07001029 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -04001030 Ok(Some(input.parse()?))
1031 } else {
1032 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -04001033 }
David Tolnay18c754c2018-08-21 23:26:58 -04001034 }
1035}
David Tolnay4ac232d2018-08-31 10:18:03 -07001036
David Tolnay80a914f2018-08-30 23:49:53 -07001037impl Parse for TokenStream {
1038 fn parse(input: ParseStream) -> Result<Self> {
1039 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
1040 }
1041}
1042
1043impl Parse for TokenTree {
1044 fn parse(input: ParseStream) -> Result<Self> {
1045 input.step(|cursor| match cursor.token_tree() {
1046 Some((tt, rest)) => Ok((tt, rest)),
1047 None => Err(cursor.error("expected token tree")),
1048 })
1049 }
1050}
1051
1052impl Parse for Group {
1053 fn parse(input: ParseStream) -> Result<Self> {
1054 input.step(|cursor| {
1055 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
1056 if let Some((inside, span, rest)) = cursor.group(*delim) {
1057 let mut group = Group::new(*delim, inside.token_stream());
1058 group.set_span(span);
1059 return Ok((group, rest));
1060 }
1061 }
1062 Err(cursor.error("expected group token"))
1063 })
1064 }
1065}
1066
1067impl Parse for Punct {
1068 fn parse(input: ParseStream) -> Result<Self> {
1069 input.step(|cursor| match cursor.punct() {
1070 Some((punct, rest)) => Ok((punct, rest)),
1071 None => Err(cursor.error("expected punctuation token")),
1072 })
1073 }
1074}
1075
1076impl Parse for Literal {
1077 fn parse(input: ParseStream) -> Result<Self> {
1078 input.step(|cursor| match cursor.literal() {
1079 Some((literal, rest)) => Ok((literal, rest)),
1080 None => Err(cursor.error("expected literal token")),
1081 })
1082 }
1083}
1084
1085/// Parser that can parse Rust tokens into a particular syntax tree node.
1086///
1087/// Refer to the [module documentation] for details about parsing in Syn.
1088///
1089/// [module documentation]: index.html
1090///
1091/// *This trait is available if Syn is built with the `"parsing"` feature.*
1092pub trait Parser: Sized {
1093 type Output;
1094
1095 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
Jethro Beekman33c22332018-12-31 11:16:25 +05301096 ///
1097 /// This function will check that the input is fully parsed. If there are
1098 /// any unparsed tokens at the end of the stream, an error is returned.
David Tolnay80a914f2018-08-30 23:49:53 -07001099 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1100
1101 /// Parse tokens of source code into the chosen syntax tree node.
1102 ///
Jethro Beekman33c22332018-12-31 11:16:25 +05301103 /// This function will check that the input is fully parsed. If there are
1104 /// any unparsed tokens at the end of the stream, an error is returned.
1105 ///
David Tolnay80a914f2018-08-30 23:49:53 -07001106 /// *This method is available if Syn is built with both the `"parsing"` and
1107 /// `"proc-macro"` features.*
1108 #[cfg(all(
1109 not(all(target_arch = "wasm32", target_os = "unknown")),
1110 feature = "proc-macro"
1111 ))]
1112 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1113 self.parse2(proc_macro2::TokenStream::from(tokens))
1114 }
1115
1116 /// Parse a string of Rust code into the chosen syntax tree node.
1117 ///
Jethro Beekman33c22332018-12-31 11:16:25 +05301118 /// This function will check that the input is fully parsed. If there are
1119 /// any unparsed tokens at the end of the string, an error is returned.
1120 ///
David Tolnay80a914f2018-08-30 23:49:53 -07001121 /// # Hygiene
1122 ///
1123 /// Every span in the resulting syntax tree will be set to resolve at the
1124 /// macro call site.
1125 fn parse_str(self, s: &str) -> Result<Self::Output> {
1126 self.parse2(proc_macro2::TokenStream::from_str(s)?)
1127 }
1128}
1129
David Tolnay7b07aa12018-09-01 11:41:12 -07001130fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1131 let scope = Span::call_site();
1132 let cursor = tokens.begin();
1133 let unexpected = Rc::new(Cell::new(None));
1134 private::new_parse_buffer(scope, cursor, unexpected)
1135}
1136
David Tolnay80a914f2018-08-30 23:49:53 -07001137impl<F, T> Parser for F
1138where
1139 F: FnOnce(ParseStream) -> Result<T>,
1140{
1141 type Output = T;
1142
1143 fn parse2(self, tokens: TokenStream) -> Result<T> {
1144 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -07001145 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -07001146 let node = self(&state)?;
1147 state.check_unexpected()?;
1148 if state.is_empty() {
1149 Ok(node)
1150 } else {
1151 Err(state.error("unexpected token"))
1152 }
1153 }
1154}