blob: 80e00044e1c34600b6116effbab116a173180078 [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 Tolnay028a7d72018-12-31 17:11:02 -0500248///
249/// ## Calling a parser function
250///
251/// There is no public way to construct a `ParseBuffer`. Instead, if you are
252/// looking to invoke a parser function that requires `ParseStream` as input,
253/// you will need to go through one of the public parsing entry points.
254///
255/// - The [`parse_macro_input!`] macro if parsing input of a procedural macro;
256/// - One of [the `syn::parse*` functions][syn-parse]; or
257/// - A method of the [`Parser`] trait.
258///
259/// [`parse_macro_input!`]: ../macro.parse_macro_input.html
260/// [syn-parse]: index.html#the-synparse-functions
David Tolnay18c754c2018-08-21 23:26:58 -0400261pub struct ParseBuffer<'a> {
262 scope: Span,
David Tolnay5d7f2252018-09-02 08:21:40 -0700263 // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
264 // The rest of the code in this module needs to be careful that only a
265 // cursor derived from this `cell` is ever assigned to this `cell`.
266 //
267 // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
268 // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
269 // than 'a, and then assign a Cursor<'short> into the Cell.
270 //
271 // By extension, it would not be safe to expose an API that accepts a
272 // Cursor<'a> and trusts that it lives as long as the cursor currently in
273 // the cell.
David Tolnay18c754c2018-08-21 23:26:58 -0400274 cell: Cell<Cursor<'static>>,
275 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400276 unexpected: Rc<Cell<Option<Span>>>,
277}
278
279impl<'a> Drop for ParseBuffer<'a> {
280 fn drop(&mut self) {
281 if !self.is_empty() && self.unexpected.get().is_none() {
282 self.unexpected.set(Some(self.cursor().span()));
283 }
284 }
David Tolnay18c754c2018-08-21 23:26:58 -0400285}
286
Diggory Hardy1c522e12018-11-02 10:10:02 +0000287impl<'a> Display for ParseBuffer<'a> {
288 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
289 Display::fmt(&self.cursor().token_stream(), f)
290 }
291}
292
293impl<'a> Debug for ParseBuffer<'a> {
294 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
295 Debug::fmt(&self.cursor().token_stream(), f)
296 }
297}
298
David Tolnay642832f2018-09-01 13:08:10 -0700299/// Cursor state associated with speculative parsing.
300///
301/// This type is the input of the closure provided to [`ParseStream::step`].
302///
303/// [`ParseStream::step`]: struct.ParseBuffer.html#method.step
David Tolnay9bd34392018-09-01 13:19:53 -0700304///
305/// # Example
306///
307/// ```
308/// # extern crate proc_macro2;
309/// # extern crate syn;
310/// #
311/// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800312/// use syn::Result;
313/// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700314///
315/// // This function advances the stream past the next occurrence of `@`. If
316/// // no `@` is present in the stream, the stream position is unchanged and
317/// // an error is returned.
318/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
319/// input.step(|cursor| {
320/// let mut rest = *cursor;
Sharad Chande1df40a2018-09-08 15:25:52 +0545321/// while let Some((tt, next)) = rest.token_tree() {
David Tolnay9bd34392018-09-01 13:19:53 -0700322/// match tt {
323/// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
324/// return Ok(((), next));
325/// }
326/// _ => rest = next,
327/// }
328/// }
329/// Err(cursor.error("no `@` was found after this point"))
330/// })
331/// }
332/// #
David Tolnaydb312582018-11-06 20:42:05 -0800333/// #
334/// # fn remainder_after_skipping_past_next_at(
335/// # input: ParseStream,
336/// # ) -> Result<proc_macro2::TokenStream> {
337/// # skip_past_next_at(input)?;
338/// # input.parse()
339/// # }
340/// #
341/// # fn main() {
342/// # use syn::parse::Parser;
343/// # let remainder = remainder_after_skipping_past_next_at
344/// # .parse_str("a @ b c")
345/// # .unwrap();
346/// # assert_eq!(remainder.to_string(), "b c");
347/// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700348/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400349#[derive(Copy, Clone)]
350pub struct StepCursor<'c, 'a> {
351 scope: Span,
David Tolnay56924f42018-09-02 08:24:58 -0700352 // This field is covariant in 'c.
David Tolnay18c754c2018-08-21 23:26:58 -0400353 cursor: Cursor<'c>,
David Tolnay56924f42018-09-02 08:24:58 -0700354 // This field is contravariant in 'c. Together these make StepCursor
355 // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
356 // different lifetime but can upcast into a StepCursor with a shorter
357 // lifetime 'a.
358 //
359 // As long as we only ever construct a StepCursor for which 'c outlives 'a,
360 // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
361 // outlives 'a.
David Tolnay18c754c2018-08-21 23:26:58 -0400362 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
363}
364
365impl<'c, 'a> Deref for StepCursor<'c, 'a> {
366 type Target = Cursor<'c>;
367
368 fn deref(&self) -> &Self::Target {
369 &self.cursor
370 }
371}
372
373impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700374 /// Triggers an error at the current position of the parse stream.
375 ///
376 /// The `ParseStream::step` invocation will return this same error without
377 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400378 pub fn error<T: Display>(self, message: T) -> Error {
379 error::new_at(self.scope, self.cursor, message)
380 }
381}
382
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700383impl private {
384 pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
David Tolnay56924f42018-09-02 08:24:58 -0700385 // Refer to the comments within the StepCursor definition. We use the
386 // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
387 // Cursor is covariant in its lifetime parameter so we can cast a
388 // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700389 let _ = proof;
390 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
391 }
392}
393
David Tolnay66cb0c42018-08-31 09:01:30 -0700394fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700395 input
396 .step(|cursor| {
397 if let Some((_lifetime, rest)) = cursor.lifetime() {
398 Ok((true, rest))
399 } else if let Some((_token, rest)) = cursor.token_tree() {
400 Ok((true, rest))
401 } else {
402 Ok((false, *cursor))
403 }
David Tolnayfb84fc02018-10-02 21:01:30 -0700404 })
405 .unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700406}
407
David Tolnay10951d52018-08-31 10:27:39 -0700408impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700409 pub fn new_parse_buffer(
410 scope: Span,
411 cursor: Cursor,
412 unexpected: Rc<Cell<Option<Span>>>,
413 ) -> ParseBuffer {
David Tolnay18c754c2018-08-21 23:26:58 -0400414 ParseBuffer {
415 scope: scope,
David Tolnay5d7f2252018-09-02 08:21:40 -0700416 // See comment on `cell` in the struct definition.
417 cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
David Tolnay18c754c2018-08-21 23:26:58 -0400418 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400419 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400420 }
421 }
422
David Tolnay94f06632018-08-31 10:17:17 -0700423 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
424 buffer.unexpected.clone()
425 }
426}
427
428impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700429 /// Parses a syntax tree node of type `T`, advancing the position of our
430 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400431 pub fn parse<T: Parse>(&self) -> Result<T> {
432 T::parse(self)
433 }
434
David Tolnay725e1c62018-09-01 12:07:25 -0700435 /// Calls the given parser function to parse a syntax tree node of type `T`
436 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700437 ///
438 /// # Example
439 ///
440 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
441 /// zero or more outer attributes.
442 ///
443 /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
444 ///
445 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700446 /// #[macro_use]
447 /// extern crate syn;
448 ///
David Tolnay67fea042018-11-24 14:50:20 -0800449 /// use syn::{Attribute, Ident, Result};
450 /// use syn::parse::{Parse, ParseStream};
David Tolnay21ce84c2018-09-01 15:37:51 -0700451 ///
452 /// // Parses a unit struct with attributes.
453 /// //
454 /// // #[path = "s.tmpl"]
455 /// // struct S;
456 /// struct UnitStruct {
457 /// attrs: Vec<Attribute>,
458 /// struct_token: Token![struct],
459 /// name: Ident,
460 /// semi_token: Token![;],
461 /// }
462 ///
463 /// impl Parse for UnitStruct {
464 /// fn parse(input: ParseStream) -> Result<Self> {
465 /// Ok(UnitStruct {
466 /// attrs: input.call(Attribute::parse_outer)?,
467 /// struct_token: input.parse()?,
468 /// name: input.parse()?,
469 /// semi_token: input.parse()?,
470 /// })
471 /// }
472 /// }
473 /// #
474 /// # fn main() {}
475 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400476 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
477 function(self)
478 }
479
David Tolnay725e1c62018-09-01 12:07:25 -0700480 /// Looks at the next token in the parse stream to determine whether it
481 /// matches the requested type of token.
482 ///
483 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700484 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700485 /// # Syntax
486 ///
487 /// Note that this method does not use turbofish syntax. Pass the peek type
488 /// inside of parentheses.
489 ///
490 /// - `input.peek(Token![struct])`
491 /// - `input.peek(Token![==])`
492 /// - `input.peek(Ident)`
493 /// - `input.peek(Lifetime)`
494 /// - `input.peek(token::Brace)`
495 ///
David Tolnayddebc3e2018-09-01 16:29:20 -0700496 /// # Example
497 ///
498 /// In this example we finish parsing the list of supertraits when the next
499 /// token in the input is either `where` or an opening curly brace.
500 ///
501 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700502 /// #[macro_use]
503 /// extern crate syn;
504 ///
David Tolnay67fea042018-11-24 14:50:20 -0800505 /// use syn::{token, Generics, Ident, Result, TypeParamBound};
506 /// use syn::parse::{Parse, ParseStream};
David Tolnayddebc3e2018-09-01 16:29:20 -0700507 /// use syn::punctuated::Punctuated;
508 ///
509 /// // Parses a trait definition containing no associated items.
510 /// //
511 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
512 /// struct MarkerTrait {
513 /// trait_token: Token![trait],
514 /// ident: Ident,
515 /// generics: Generics,
516 /// colon_token: Option<Token![:]>,
517 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
518 /// brace_token: token::Brace,
519 /// }
520 ///
521 /// impl Parse for MarkerTrait {
522 /// fn parse(input: ParseStream) -> Result<Self> {
523 /// let trait_token: Token![trait] = input.parse()?;
524 /// let ident: Ident = input.parse()?;
525 /// let mut generics: Generics = input.parse()?;
526 /// let colon_token: Option<Token![:]> = input.parse()?;
527 ///
528 /// let mut supertraits = Punctuated::new();
529 /// if colon_token.is_some() {
530 /// loop {
531 /// supertraits.push_value(input.parse()?);
532 /// if input.peek(Token![where]) || input.peek(token::Brace) {
533 /// break;
534 /// }
535 /// supertraits.push_punct(input.parse()?);
536 /// }
537 /// }
538 ///
539 /// generics.where_clause = input.parse()?;
540 /// let content;
541 /// let empty_brace_token = braced!(content in input);
542 ///
543 /// Ok(MarkerTrait {
544 /// trait_token: trait_token,
545 /// ident: ident,
546 /// generics: generics,
547 /// colon_token: colon_token,
548 /// supertraits: supertraits,
549 /// brace_token: empty_brace_token,
550 /// })
551 /// }
552 /// }
553 /// #
554 /// # fn main() {}
555 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400556 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700557 let _ = token;
558 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400559 }
560
David Tolnay725e1c62018-09-01 12:07:25 -0700561 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700562 ///
563 /// This is commonly useful as a way to implement contextual keywords.
564 ///
565 /// # Example
566 ///
567 /// This example needs to use `peek2` because the symbol `union` is not a
568 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
569 /// the very next token is `union`, because someone is free to write a `mod
570 /// union` and a macro invocation that looks like `union::some_macro! { ...
571 /// }`. In other words `union` is a contextual keyword.
572 ///
573 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700574 /// #[macro_use]
575 /// extern crate syn;
576 ///
David Tolnay67fea042018-11-24 14:50:20 -0800577 /// use syn::{Ident, ItemUnion, Macro, Result};
578 /// use syn::parse::{Parse, ParseStream};
David Tolnaye334b872018-09-01 16:38:10 -0700579 ///
580 /// // Parses either a union or a macro invocation.
581 /// enum UnionOrMacro {
582 /// // union MaybeUninit<T> { uninit: (), value: T }
583 /// Union(ItemUnion),
584 /// // lazy_static! { ... }
585 /// Macro(Macro),
586 /// }
587 ///
588 /// impl Parse for UnionOrMacro {
589 /// fn parse(input: ParseStream) -> Result<Self> {
590 /// if input.peek(Token![union]) && input.peek2(Ident) {
591 /// input.parse().map(UnionOrMacro::Union)
592 /// } else {
593 /// input.parse().map(UnionOrMacro::Macro)
594 /// }
595 /// }
596 /// }
597 /// #
598 /// # fn main() {}
599 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400600 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400601 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700602 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400603 }
604
David Tolnay725e1c62018-09-01 12:07:25 -0700605 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400606 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400607 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700608 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400609 }
610
David Tolnay725e1c62018-09-01 12:07:25 -0700611 /// Parses zero or more occurrences of `T` separated by punctuation of type
612 /// `P`, with optional trailing punctuation.
613 ///
614 /// Parsing continues until the end of this parse stream. The entire content
615 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700616 ///
617 /// # Example
618 ///
619 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700620 /// # #[macro_use]
David Tolnay0abe65b2018-09-01 14:31:43 -0700621 /// # extern crate quote;
David Tolnay0abe65b2018-09-01 14:31:43 -0700622 /// #
David Tolnaya1c98072018-09-06 08:58:10 -0700623 /// #[macro_use]
624 /// extern crate syn;
625 ///
David Tolnay67fea042018-11-24 14:50:20 -0800626 /// use syn::{token, Ident, Result, Type};
627 /// use syn::parse::{Parse, ParseStream};
David Tolnay0abe65b2018-09-01 14:31:43 -0700628 /// use syn::punctuated::Punctuated;
629 ///
630 /// // Parse a simplified tuple struct syntax like:
631 /// //
632 /// // struct S(A, B);
633 /// struct TupleStruct {
634 /// struct_token: Token![struct],
635 /// ident: Ident,
636 /// paren_token: token::Paren,
637 /// fields: Punctuated<Type, Token![,]>,
638 /// semi_token: Token![;],
639 /// }
640 ///
641 /// impl Parse for TupleStruct {
642 /// fn parse(input: ParseStream) -> Result<Self> {
643 /// let content;
644 /// Ok(TupleStruct {
645 /// struct_token: input.parse()?,
646 /// ident: input.parse()?,
647 /// paren_token: parenthesized!(content in input),
648 /// fields: content.parse_terminated(Type::parse)?,
649 /// semi_token: input.parse()?,
650 /// })
651 /// }
652 /// }
653 /// #
654 /// # fn main() {
655 /// # let input = quote! {
656 /// # struct S(A, B);
657 /// # };
658 /// # syn::parse2::<TupleStruct>(input).unwrap();
659 /// # }
660 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400661 pub fn parse_terminated<T, P: Parse>(
662 &self,
663 parser: fn(ParseStream) -> Result<T>,
664 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700665 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400666 }
667
David Tolnay725e1c62018-09-01 12:07:25 -0700668 /// Returns whether there are tokens remaining in this stream.
669 ///
670 /// This method returns true at the end of the content of a set of
671 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700672 ///
673 /// # Example
674 ///
675 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700676 /// #[macro_use]
677 /// extern crate syn;
678 ///
David Tolnay67fea042018-11-24 14:50:20 -0800679 /// use syn::{token, Ident, Item, Result};
680 /// use syn::parse::{Parse, ParseStream};
David Tolnaycce6b5f2018-09-01 14:24:46 -0700681 ///
682 /// // Parses a Rust `mod m { ... }` containing zero or more items.
683 /// struct Mod {
684 /// mod_token: Token![mod],
685 /// name: Ident,
686 /// brace_token: token::Brace,
687 /// items: Vec<Item>,
688 /// }
689 ///
690 /// impl Parse for Mod {
691 /// fn parse(input: ParseStream) -> Result<Self> {
692 /// let content;
693 /// Ok(Mod {
694 /// mod_token: input.parse()?,
695 /// name: input.parse()?,
696 /// brace_token: braced!(content in input),
697 /// items: {
698 /// let mut items = Vec::new();
699 /// while !content.is_empty() {
700 /// items.push(content.parse()?);
701 /// }
702 /// items
703 /// },
704 /// })
705 /// }
706 /// }
707 /// #
708 /// # fn main() {}
David Tolnayf2b78602018-11-06 20:42:37 -0800709 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700710 pub fn is_empty(&self) -> bool {
711 self.cursor().eof()
712 }
713
David Tolnay725e1c62018-09-01 12:07:25 -0700714 /// Constructs a helper for peeking at the next token in this stream and
715 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700716 ///
717 /// # Example
718 ///
719 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700720 /// #[macro_use]
721 /// extern crate syn;
722 ///
David Tolnay67fea042018-11-24 14:50:20 -0800723 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, TypeParam};
724 /// use syn::parse::{Parse, ParseStream};
David Tolnay2c77e772018-09-01 14:18:46 -0700725 ///
726 /// // A generic parameter, a single one of the comma-separated elements inside
727 /// // angle brackets in:
728 /// //
729 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
730 /// //
731 /// // On invalid input, lookahead gives us a reasonable error message.
732 /// //
733 /// // error: expected one of: identifier, lifetime, `const`
734 /// // |
735 /// // 5 | fn f<!Sized>() {}
736 /// // | ^
737 /// enum GenericParam {
738 /// Type(TypeParam),
739 /// Lifetime(LifetimeDef),
740 /// Const(ConstParam),
741 /// }
742 ///
743 /// impl Parse for GenericParam {
744 /// fn parse(input: ParseStream) -> Result<Self> {
745 /// let lookahead = input.lookahead1();
746 /// if lookahead.peek(Ident) {
747 /// input.parse().map(GenericParam::Type)
748 /// } else if lookahead.peek(Lifetime) {
749 /// input.parse().map(GenericParam::Lifetime)
750 /// } else if lookahead.peek(Token![const]) {
751 /// input.parse().map(GenericParam::Const)
752 /// } else {
753 /// Err(lookahead.error())
754 /// }
755 /// }
756 /// }
757 /// #
758 /// # fn main() {}
759 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700760 pub fn lookahead1(&self) -> Lookahead1<'a> {
761 lookahead::new(self.scope, self.cursor())
762 }
763
David Tolnay725e1c62018-09-01 12:07:25 -0700764 /// Forks a parse stream so that parsing tokens out of either the original
765 /// or the fork does not advance the position of the other.
766 ///
767 /// # Performance
768 ///
769 /// Forking a parse stream is a cheap fixed amount of work and does not
770 /// involve copying token buffers. Where you might hit performance problems
771 /// is if your macro ends up parsing a large amount of content more than
772 /// once.
773 ///
774 /// ```
David Tolnay67fea042018-11-24 14:50:20 -0800775 /// # use syn::{Expr, Result};
776 /// # use syn::parse::ParseStream;
David Tolnay725e1c62018-09-01 12:07:25 -0700777 /// #
778 /// # fn bad(input: ParseStream) -> Result<Expr> {
779 /// // Do not do this.
780 /// if input.fork().parse::<Expr>().is_ok() {
781 /// return input.parse::<Expr>();
782 /// }
783 /// # unimplemented!()
784 /// # }
785 /// ```
786 ///
787 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
788 /// parse stream. Only use a fork when the amount of work performed against
789 /// the fork is small and bounded.
790 ///
David Tolnayec149b02018-09-01 14:17:28 -0700791 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700792 /// speculative parsing, consider using [`ParseStream::step`] instead.
793 ///
794 /// [`ParseStream::step`]: #method.step
David Tolnayec149b02018-09-01 14:17:28 -0700795 ///
796 /// # Example
797 ///
798 /// The parse implementation shown here parses possibly restricted `pub`
799 /// visibilities.
800 ///
801 /// - `pub`
802 /// - `pub(crate)`
803 /// - `pub(self)`
804 /// - `pub(super)`
805 /// - `pub(in some::path)`
806 ///
807 /// To handle the case of visibilities inside of tuple structs, the parser
808 /// needs to distinguish parentheses that specify visibility restrictions
809 /// from parentheses that form part of a tuple type.
810 ///
811 /// ```
812 /// # struct A;
813 /// # struct B;
814 /// # struct C;
815 /// #
816 /// struct S(pub(crate) A, pub (B, C));
817 /// ```
818 ///
819 /// In this example input the first tuple struct element of `S` has
820 /// `pub(crate)` visibility while the second tuple struct element has `pub`
821 /// visibility; the parentheses around `(B, C)` are part of the type rather
822 /// than part of a visibility restriction.
823 ///
824 /// The parser uses a forked parse stream to check the first token inside of
825 /// parentheses after the `pub` keyword. This is a small bounded amount of
826 /// work performed against the forked parse stream.
827 ///
828 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700829 /// #[macro_use]
830 /// extern crate syn;
831 ///
David Tolnay67fea042018-11-24 14:50:20 -0800832 /// use syn::{token, Ident, Path, Result};
David Tolnayec149b02018-09-01 14:17:28 -0700833 /// use syn::ext::IdentExt;
David Tolnay67fea042018-11-24 14:50:20 -0800834 /// use syn::parse::{Parse, ParseStream};
David Tolnayec149b02018-09-01 14:17:28 -0700835 ///
836 /// struct PubVisibility {
837 /// pub_token: Token![pub],
838 /// restricted: Option<Restricted>,
839 /// }
840 ///
841 /// struct Restricted {
842 /// paren_token: token::Paren,
843 /// in_token: Option<Token![in]>,
844 /// path: Path,
845 /// }
846 ///
847 /// impl Parse for PubVisibility {
848 /// fn parse(input: ParseStream) -> Result<Self> {
849 /// let pub_token: Token![pub] = input.parse()?;
850 ///
851 /// if input.peek(token::Paren) {
852 /// let ahead = input.fork();
853 /// let mut content;
854 /// parenthesized!(content in ahead);
855 ///
856 /// if content.peek(Token![crate])
857 /// || content.peek(Token![self])
858 /// || content.peek(Token![super])
859 /// {
860 /// return Ok(PubVisibility {
861 /// pub_token: pub_token,
862 /// restricted: Some(Restricted {
863 /// paren_token: parenthesized!(content in input),
864 /// in_token: None,
865 /// path: Path::from(content.call(Ident::parse_any)?),
866 /// }),
867 /// });
868 /// } else if content.peek(Token![in]) {
869 /// return Ok(PubVisibility {
870 /// pub_token: pub_token,
871 /// restricted: Some(Restricted {
872 /// paren_token: parenthesized!(content in input),
873 /// in_token: Some(content.parse()?),
874 /// path: content.call(Path::parse_mod_style)?,
875 /// }),
876 /// });
877 /// }
878 /// }
879 ///
880 /// Ok(PubVisibility {
881 /// pub_token: pub_token,
882 /// restricted: None,
883 /// })
884 /// }
885 /// }
886 /// #
887 /// # fn main() {}
888 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400889 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400890 ParseBuffer {
891 scope: self.scope,
892 cell: self.cell.clone(),
893 marker: PhantomData,
894 // Not the parent's unexpected. Nothing cares whether the clone
895 // parses all the way.
896 unexpected: Rc::new(Cell::new(None)),
897 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400898 }
899
David Tolnay725e1c62018-09-01 12:07:25 -0700900 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700901 ///
902 /// # Example
903 ///
904 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700905 /// #[macro_use]
906 /// extern crate syn;
907 ///
David Tolnay67fea042018-11-24 14:50:20 -0800908 /// use syn::{Expr, Result};
909 /// use syn::parse::{Parse, ParseStream};
David Tolnay23fce0b2018-09-01 13:50:31 -0700910 ///
911 /// // Some kind of loop: `while` or `for` or `loop`.
912 /// struct Loop {
913 /// expr: Expr,
914 /// }
915 ///
916 /// impl Parse for Loop {
917 /// fn parse(input: ParseStream) -> Result<Self> {
918 /// if input.peek(Token![while])
919 /// || input.peek(Token![for])
920 /// || input.peek(Token![loop])
921 /// {
922 /// Ok(Loop {
923 /// expr: input.parse()?,
924 /// })
925 /// } else {
926 /// Err(input.error("expected some kind of loop"))
927 /// }
928 /// }
929 /// }
David Tolnaya1c98072018-09-06 08:58:10 -0700930 /// #
931 /// # fn main() {}
David Tolnay23fce0b2018-09-01 13:50:31 -0700932 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400933 pub fn error<T: Display>(&self, message: T) -> Error {
934 error::new_at(self.scope, self.cursor(), message)
935 }
936
David Tolnay725e1c62018-09-01 12:07:25 -0700937 /// Speculatively parses tokens from this parse stream, advancing the
938 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700939 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700940 /// This is a powerful low-level API used for defining the `Parse` impls of
941 /// the basic built-in token types. It is not something that will be used
942 /// widely outside of the Syn codebase.
943 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700944 /// # Example
945 ///
946 /// ```
947 /// # extern crate proc_macro2;
948 /// # extern crate syn;
949 /// #
950 /// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800951 /// use syn::Result;
952 /// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700953 ///
954 /// // This function advances the stream past the next occurrence of `@`. If
955 /// // no `@` is present in the stream, the stream position is unchanged and
956 /// // an error is returned.
957 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
958 /// input.step(|cursor| {
959 /// let mut rest = *cursor;
David Tolnaydb312582018-11-06 20:42:05 -0800960 /// while let Some((tt, next)) = rest.token_tree() {
David Tolnay9bd34392018-09-01 13:19:53 -0700961 /// match tt {
962 /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
963 /// return Ok(((), next));
964 /// }
965 /// _ => rest = next,
966 /// }
967 /// }
968 /// Err(cursor.error("no `@` was found after this point"))
969 /// })
970 /// }
971 /// #
David Tolnaydb312582018-11-06 20:42:05 -0800972 /// # fn remainder_after_skipping_past_next_at(
973 /// # input: ParseStream,
974 /// # ) -> Result<proc_macro2::TokenStream> {
975 /// # skip_past_next_at(input)?;
976 /// # input.parse()
977 /// # }
978 /// #
979 /// # fn main() {
980 /// # use syn::parse::Parser;
981 /// # let remainder = remainder_after_skipping_past_next_at
982 /// # .parse_str("a @ b c")
983 /// # .unwrap();
984 /// # assert_eq!(remainder.to_string(), "b c");
985 /// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700986 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700987 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400988 where
989 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
990 {
David Tolnayc142b092018-09-02 08:52:52 -0700991 // Since the user's function is required to work for any 'c, we know
992 // that the Cursor<'c> they return is either derived from the input
993 // StepCursor<'c, 'a> or from a Cursor<'static>.
994 //
995 // It would not be legal to write this function without the invariant
996 // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
997 // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
998 // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
999 // `step` on their ParseBuffer<'short> with a closure that returns
1000 // Cursor<'short>, and we would wrongly write that Cursor<'short> into
1001 // the Cell intended to hold Cursor<'a>.
1002 //
1003 // In some cases it may be necessary for R to contain a Cursor<'a>.
1004 // Within Syn we solve this using `private::advance_step_cursor` which
1005 // uses the existence of a StepCursor<'c, 'a> as proof that it is safe
1006 // to cast from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it
1007 // would be safe to expose that API as a method on StepCursor.
David Tolnay6b65f852018-09-01 11:56:25 -07001008 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -04001009 scope: self.scope,
1010 cursor: self.cell.get(),
1011 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -07001012 })?;
1013 self.cell.set(rest);
1014 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -04001015 }
David Tolnayeafc8052018-08-25 16:33:53 -04001016
David Tolnay725e1c62018-09-01 12:07:25 -07001017 /// Provides low-level access to the token representation underlying this
1018 /// parse stream.
1019 ///
1020 /// Cursors are immutable so no operations you perform against the cursor
1021 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -07001022 pub fn cursor(&self) -> Cursor<'a> {
1023 self.cell.get()
1024 }
1025
David Tolnay94f06632018-08-31 10:17:17 -07001026 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -04001027 match self.unexpected.get() {
1028 Some(span) => Err(Error::new(span, "unexpected token")),
1029 None => Ok(()),
1030 }
1031 }
David Tolnay18c754c2018-08-21 23:26:58 -04001032}
1033
David Tolnaya7d69fc2018-08-26 13:30:24 -04001034impl<T: Parse> Parse for Box<T> {
1035 fn parse(input: ParseStream) -> Result<Self> {
1036 input.parse().map(Box::new)
1037 }
1038}
1039
David Tolnay4fb71232018-08-25 23:14:50 -04001040impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -04001041 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -07001042 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -04001043 Ok(Some(input.parse()?))
1044 } else {
1045 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -04001046 }
David Tolnay18c754c2018-08-21 23:26:58 -04001047 }
1048}
David Tolnay4ac232d2018-08-31 10:18:03 -07001049
David Tolnay80a914f2018-08-30 23:49:53 -07001050impl Parse for TokenStream {
1051 fn parse(input: ParseStream) -> Result<Self> {
1052 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
1053 }
1054}
1055
1056impl Parse for TokenTree {
1057 fn parse(input: ParseStream) -> Result<Self> {
1058 input.step(|cursor| match cursor.token_tree() {
1059 Some((tt, rest)) => Ok((tt, rest)),
1060 None => Err(cursor.error("expected token tree")),
1061 })
1062 }
1063}
1064
1065impl Parse for Group {
1066 fn parse(input: ParseStream) -> Result<Self> {
1067 input.step(|cursor| {
1068 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
1069 if let Some((inside, span, rest)) = cursor.group(*delim) {
1070 let mut group = Group::new(*delim, inside.token_stream());
1071 group.set_span(span);
1072 return Ok((group, rest));
1073 }
1074 }
1075 Err(cursor.error("expected group token"))
1076 })
1077 }
1078}
1079
1080impl Parse for Punct {
1081 fn parse(input: ParseStream) -> Result<Self> {
1082 input.step(|cursor| match cursor.punct() {
1083 Some((punct, rest)) => Ok((punct, rest)),
1084 None => Err(cursor.error("expected punctuation token")),
1085 })
1086 }
1087}
1088
1089impl Parse for Literal {
1090 fn parse(input: ParseStream) -> Result<Self> {
1091 input.step(|cursor| match cursor.literal() {
1092 Some((literal, rest)) => Ok((literal, rest)),
1093 None => Err(cursor.error("expected literal token")),
1094 })
1095 }
1096}
1097
1098/// Parser that can parse Rust tokens into a particular syntax tree node.
1099///
1100/// Refer to the [module documentation] for details about parsing in Syn.
1101///
1102/// [module documentation]: index.html
1103///
1104/// *This trait is available if Syn is built with the `"parsing"` feature.*
1105pub trait Parser: Sized {
1106 type Output;
1107
1108 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
Jethro Beekman33c22332018-12-31 11:16:25 +05301109 ///
1110 /// This function will check that the input is fully parsed. If there are
1111 /// any unparsed tokens at the end of the stream, an error is returned.
David Tolnay80a914f2018-08-30 23:49:53 -07001112 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1113
1114 /// Parse tokens of source code into the chosen syntax tree node.
1115 ///
Jethro Beekman33c22332018-12-31 11:16:25 +05301116 /// This function will check that the input is fully parsed. If there are
1117 /// any unparsed tokens at the end of the stream, an error is returned.
1118 ///
David Tolnay80a914f2018-08-30 23:49:53 -07001119 /// *This method is available if Syn is built with both the `"parsing"` and
1120 /// `"proc-macro"` features.*
1121 #[cfg(all(
1122 not(all(target_arch = "wasm32", target_os = "unknown")),
1123 feature = "proc-macro"
1124 ))]
1125 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1126 self.parse2(proc_macro2::TokenStream::from(tokens))
1127 }
1128
1129 /// Parse a string of Rust code into the chosen syntax tree node.
1130 ///
Jethro Beekman33c22332018-12-31 11:16:25 +05301131 /// This function will check that the input is fully parsed. If there are
1132 /// any unparsed tokens at the end of the string, an error is returned.
1133 ///
David Tolnay80a914f2018-08-30 23:49:53 -07001134 /// # Hygiene
1135 ///
1136 /// Every span in the resulting syntax tree will be set to resolve at the
1137 /// macro call site.
1138 fn parse_str(self, s: &str) -> Result<Self::Output> {
1139 self.parse2(proc_macro2::TokenStream::from_str(s)?)
1140 }
1141}
1142
David Tolnay7b07aa12018-09-01 11:41:12 -07001143fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1144 let scope = Span::call_site();
1145 let cursor = tokens.begin();
1146 let unexpected = Rc::new(Cell::new(None));
1147 private::new_parse_buffer(scope, cursor, unexpected)
1148}
1149
David Tolnay80a914f2018-08-30 23:49:53 -07001150impl<F, T> Parser for F
1151where
1152 F: FnOnce(ParseStream) -> Result<T>,
1153{
1154 type Output = T;
1155
1156 fn parse2(self, tokens: TokenStream) -> Result<T> {
1157 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -07001158 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -07001159 let node = self(&state)?;
1160 state.check_unexpected()?;
1161 if state.is_empty() {
1162 Ok(node)
1163 } else {
1164 Err(state.error("unexpected token"))
1165 }
1166 }
1167}