blob: a6afe018966a3b8ce7654029306582099c9e9ea1 [file] [log] [blame]
David Tolnay80a914f2018-08-30 23:49:53 -07001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
David Tolnay18c754c2018-08-21 23:26:58 -04009//! Parsing interface for parsing a token stream into a syntax tree node.
David Tolnay80a914f2018-08-30 23:49:53 -070010//!
David Tolnaye0c51762018-08-31 11:05:22 -070011//! Parsing in Syn is built on parser functions that take in a [`ParseStream`]
12//! and produce a [`Result<T>`] where `T` is some syntax tree node. Underlying
13//! these parser functions is a lower level mechanism built around the
14//! [`Cursor`] type. `Cursor` is a cheaply copyable cursor over a range of
15//! tokens in a token stream.
David Tolnay80a914f2018-08-30 23:49:53 -070016//!
David Tolnaye0c51762018-08-31 11:05:22 -070017//! [`ParseStream`]: type.ParseStream.html
18//! [`Result<T>`]: type.Result.html
David Tolnay80a914f2018-08-30 23:49:53 -070019//! [`Cursor`]: ../buffer/index.html
David Tolnay80a914f2018-08-30 23:49:53 -070020//!
David Tolnay43984452018-09-01 17:43:56 -070021//! # Example
David Tolnay80a914f2018-08-30 23:49:53 -070022//!
David Tolnay43984452018-09-01 17:43:56 -070023//! Here is a snippet of parsing code to get a feel for the style of the
24//! library. We define data structures for a subset of Rust syntax including
25//! enums (not shown) and structs, then provide implementations of the [`Parse`]
26//! trait to parse these syntax tree data structures from a token stream.
27//!
David Tolnay88d9f622018-09-01 17:52:33 -070028//! Once `Parse` impls have been defined, they can be called conveniently from a
David Tolnay8e6096a2018-09-06 02:14:47 -070029//! procedural macro through [`parse_macro_input!`] as shown at the bottom of
30//! the snippet. If the caller provides syntactically invalid input to the
31//! procedural macro, they will receive a helpful compiler error message
32//! pointing out the exact token that triggered the failure to parse.
33//!
34//! [`parse_macro_input!`]: ../macro.parse_macro_input.html
David Tolnay88d9f622018-09-01 17:52:33 -070035//!
David Tolnay43984452018-09-01 17:43:56 -070036//! ```
David Tolnaya1c98072018-09-06 08:58:10 -070037//! #[macro_use]
38//! extern crate syn;
39//!
40//! extern crate proc_macro;
41//!
David Tolnay88d9f622018-09-01 17:52:33 -070042//! use proc_macro::TokenStream;
David Tolnaya1c98072018-09-06 08:58:10 -070043//! use syn::{token, Field, Ident};
David Tolnay43984452018-09-01 17:43:56 -070044//! use syn::parse::{Parse, ParseStream, Result};
45//! use syn::punctuated::Punctuated;
46//!
47//! enum Item {
48//! Struct(ItemStruct),
49//! Enum(ItemEnum),
50//! }
51//!
52//! struct ItemStruct {
53//! struct_token: Token![struct],
54//! ident: Ident,
55//! brace_token: token::Brace,
56//! fields: Punctuated<Field, Token![,]>,
57//! }
58//! #
59//! # enum ItemEnum {}
60//!
61//! impl Parse for Item {
62//! fn parse(input: ParseStream) -> Result<Self> {
63//! let lookahead = input.lookahead1();
64//! if lookahead.peek(Token![struct]) {
65//! input.parse().map(Item::Struct)
66//! } else if lookahead.peek(Token![enum]) {
67//! input.parse().map(Item::Enum)
68//! } else {
69//! Err(lookahead.error())
70//! }
71//! }
72//! }
73//!
74//! impl Parse for ItemStruct {
75//! fn parse(input: ParseStream) -> Result<Self> {
76//! let content;
77//! Ok(ItemStruct {
78//! struct_token: input.parse()?,
79//! ident: input.parse()?,
80//! brace_token: braced!(content in input),
81//! fields: content.parse_terminated(Field::parse_named)?,
82//! })
83//! }
84//! }
85//! #
86//! # impl Parse for ItemEnum {
87//! # fn parse(input: ParseStream) -> Result<Self> {
88//! # unimplemented!()
89//! # }
90//! # }
David Tolnay88d9f622018-09-01 17:52:33 -070091//!
92//! # const IGNORE: &str = stringify! {
93//! #[proc_macro]
94//! # };
95//! pub fn my_macro(tokens: TokenStream) -> TokenStream {
96//! let input = parse_macro_input!(tokens as Item);
97//!
98//! /* ... */
99//! # "".parse().unwrap()
100//! }
101//! #
102//! # fn main() {}
David Tolnay43984452018-09-01 17:43:56 -0700103//! ```
104//!
105//! # The `syn::parse*` functions
David Tolnay80a914f2018-08-30 23:49:53 -0700106//!
107//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
108//! as an entry point for parsing syntax tree nodes that can be parsed in an
109//! obvious default way. These functions can return any syntax tree node that
David Tolnay8aacee12018-08-31 09:15:15 -0700110//! implements the [`Parse`] trait, which includes most types in Syn.
David Tolnay80a914f2018-08-30 23:49:53 -0700111//!
112//! [`syn::parse`]: ../fn.parse.html
113//! [`syn::parse2`]: ../fn.parse2.html
114//! [`syn::parse_str`]: ../fn.parse_str.html
David Tolnay8aacee12018-08-31 09:15:15 -0700115//! [`Parse`]: trait.Parse.html
David Tolnay80a914f2018-08-30 23:49:53 -0700116//!
117//! ```
118//! use syn::Type;
119//!
David Tolnay8aacee12018-08-31 09:15:15 -0700120//! # fn run_parser() -> Result<(), syn::parse::Error> {
David Tolnay80a914f2018-08-30 23:49:53 -0700121//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
122//! # Ok(())
123//! # }
124//! #
125//! # fn main() {
126//! # run_parser().unwrap();
127//! # }
128//! ```
129//!
130//! The [`parse_quote!`] macro also uses this approach.
131//!
132//! [`parse_quote!`]: ../macro.parse_quote.html
133//!
David Tolnay43984452018-09-01 17:43:56 -0700134//! # The `Parser` trait
David Tolnay80a914f2018-08-30 23:49:53 -0700135//!
136//! Some types can be parsed in several ways depending on context. For example
137//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
138//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
139//! may or may not allow trailing punctuation, and parsing it the wrong way
140//! would either reject valid input or accept invalid input.
141//!
142//! [`Attribute`]: ../struct.Attribute.html
143//! [`Punctuated`]: ../punctuated/index.html
144//!
David Tolnaye0c51762018-08-31 11:05:22 -0700145//! The `Parse` trait is not implemented in these cases because there is no good
David Tolnay80a914f2018-08-30 23:49:53 -0700146//! behavior to consider the default.
147//!
148//! ```ignore
149//! // 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)?;
152//! ```
153//!
154//! In these cases the types provide a choice of parser functions rather than a
David Tolnaye0c51762018-08-31 11:05:22 -0700155//! single `Parse` implementation, and those parser functions can be invoked
David Tolnay80a914f2018-08-30 23:49:53 -0700156//! through the [`Parser`] trait.
157//!
158//! [`Parser`]: trait.Parser.html
159//!
160//! ```
David Tolnaya1c98072018-09-06 08:58:10 -0700161//! #[macro_use]
162//! extern crate syn;
163//!
164//! extern crate proc_macro2;
165//!
166//! use proc_macro2::TokenStream;
David Tolnay3e3f7752018-08-31 09:33:59 -0700167//! use syn::parse::Parser;
David Tolnay80a914f2018-08-30 23:49:53 -0700168//! use syn::punctuated::Punctuated;
David Tolnaya1c98072018-09-06 08:58:10 -0700169//! use syn::{Attribute, Expr, PathSegment};
David Tolnay80a914f2018-08-30 23:49:53 -0700170//!
David Tolnay3e3f7752018-08-31 09:33:59 -0700171//! # fn run_parsers() -> Result<(), syn::parse::Error> {
David Tolnay80a914f2018-08-30 23:49:53 -0700172//! # let tokens = TokenStream::new().into();
173//! // Parse a nonempty sequence of path segments separated by `::` punctuation
174//! // with no trailing punctuation.
175//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
176//! let path = parser.parse(tokens)?;
177//!
178//! # let tokens = TokenStream::new().into();
179//! // Parse a possibly empty sequence of expressions terminated by commas with
180//! // an optional trailing punctuation.
181//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
182//! let args = parser.parse(tokens)?;
183//!
184//! # let tokens = TokenStream::new().into();
185//! // Parse zero or more outer attributes but not inner attributes.
David Tolnay3e3f7752018-08-31 09:33:59 -0700186//! let parser = Attribute::parse_outer;
187//! let attrs = parser.parse(tokens)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700188//! #
189//! # Ok(())
190//! # }
191//! #
192//! # fn main() {}
193//! ```
194//!
David Tolnaye0c51762018-08-31 11:05:22 -0700195//! ---
David Tolnay80a914f2018-08-30 23:49:53 -0700196//!
197//! *This module is available if Syn is built with the `"parsing"` feature.*
David Tolnay18c754c2018-08-21 23:26:58 -0400198
199use std::cell::Cell;
Diggory Hardy1c522e12018-11-02 10:10:02 +0000200use std::fmt::{self, Debug, Display};
David Tolnay18c754c2018-08-21 23:26:58 -0400201use std::marker::PhantomData;
202use std::mem;
203use std::ops::Deref;
David Tolnayeafc8052018-08-25 16:33:53 -0400204use std::rc::Rc;
David Tolnay80a914f2018-08-30 23:49:53 -0700205use std::str::FromStr;
David Tolnayeafc8052018-08-25 16:33:53 -0400206
David Tolnay80a914f2018-08-30 23:49:53 -0700207#[cfg(all(
208 not(all(target_arch = "wasm32", target_os = "unknown")),
209 feature = "proc-macro"
210))]
211use proc_macro;
David Tolnayf07b3342018-09-01 11:58:11 -0700212use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
David Tolnay18c754c2018-08-21 23:26:58 -0400213
David Tolnay80a914f2018-08-30 23:49:53 -0700214use buffer::{Cursor, TokenBuffer};
David Tolnayb6254182018-08-25 08:44:54 -0400215use error;
David Tolnay94f06632018-08-31 10:17:17 -0700216use lookahead;
217use private;
David Tolnay577d0332018-08-25 21:45:24 -0400218use punctuated::Punctuated;
David Tolnay4fb71232018-08-25 23:14:50 -0400219use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -0400220
David Tolnayb6254182018-08-25 08:44:54 -0400221pub use error::{Error, Result};
222pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -0400223
224/// Parsing interface implemented by all types that can be parsed in a default
225/// way from a token stream.
226pub trait Parse: Sized {
227 fn parse(input: ParseStream) -> Result<Self>;
228}
229
230/// Input to a Syn parser function.
David Tolnaya0daa482018-09-01 02:09:40 -0700231///
232/// See the methods of this type under the documentation of [`ParseBuffer`]. For
233/// an overview of parsing in Syn, refer to the [module documentation].
234///
235/// [module documentation]: index.html
David Tolnay18c754c2018-08-21 23:26:58 -0400236pub type ParseStream<'a> = &'a ParseBuffer<'a>;
237
238/// Cursor position within a buffered token stream.
David Tolnay20d29a12018-09-01 15:15:33 -0700239///
240/// This type is more commonly used through the type alias [`ParseStream`] which
241/// is an alias for `&ParseBuffer`.
242///
243/// `ParseStream` is the input type for all parser functions in Syn. They have
244/// the signature `fn(ParseStream) -> Result<T>`.
David Tolnay18c754c2018-08-21 23:26:58 -0400245pub struct ParseBuffer<'a> {
246 scope: Span,
David Tolnay5d7f2252018-09-02 08:21:40 -0700247 // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
248 // The rest of the code in this module needs to be careful that only a
249 // cursor derived from this `cell` is ever assigned to this `cell`.
250 //
251 // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
252 // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
253 // than 'a, and then assign a Cursor<'short> into the Cell.
254 //
255 // By extension, it would not be safe to expose an API that accepts a
256 // Cursor<'a> and trusts that it lives as long as the cursor currently in
257 // the cell.
David Tolnay18c754c2018-08-21 23:26:58 -0400258 cell: Cell<Cursor<'static>>,
259 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400260 unexpected: Rc<Cell<Option<Span>>>,
261}
262
263impl<'a> Drop for ParseBuffer<'a> {
264 fn drop(&mut self) {
265 if !self.is_empty() && self.unexpected.get().is_none() {
266 self.unexpected.set(Some(self.cursor().span()));
267 }
268 }
David Tolnay18c754c2018-08-21 23:26:58 -0400269}
270
Diggory Hardy1c522e12018-11-02 10:10:02 +0000271impl<'a> Display for ParseBuffer<'a> {
272 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
273 Display::fmt(&self.cursor().token_stream(), f)
274 }
275}
276
277impl<'a> Debug for ParseBuffer<'a> {
278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
279 Debug::fmt(&self.cursor().token_stream(), f)
280 }
281}
282
David Tolnay642832f2018-09-01 13:08:10 -0700283/// Cursor state associated with speculative parsing.
284///
285/// This type is the input of the closure provided to [`ParseStream::step`].
286///
287/// [`ParseStream::step`]: struct.ParseBuffer.html#method.step
David Tolnay9bd34392018-09-01 13:19:53 -0700288///
289/// # Example
290///
291/// ```
292/// # extern crate proc_macro2;
293/// # extern crate syn;
294/// #
295/// use proc_macro2::TokenTree;
296/// use syn::parse::{ParseStream, Result};
297///
298/// // This function advances the stream past the next occurrence of `@`. If
299/// // no `@` is present in the stream, the stream position is unchanged and
300/// // an error is returned.
301/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
302/// input.step(|cursor| {
303/// let mut rest = *cursor;
Sharad Chande1df40a2018-09-08 15:25:52 +0545304/// while let Some((tt, next)) = rest.token_tree() {
David Tolnay9bd34392018-09-01 13:19:53 -0700305/// match tt {
306/// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
307/// return Ok(((), next));
308/// }
309/// _ => rest = next,
310/// }
311/// }
312/// Err(cursor.error("no `@` was found after this point"))
313/// })
314/// }
315/// #
David Tolnaydb312582018-11-06 20:42:05 -0800316/// #
317/// # fn remainder_after_skipping_past_next_at(
318/// # input: ParseStream,
319/// # ) -> Result<proc_macro2::TokenStream> {
320/// # skip_past_next_at(input)?;
321/// # input.parse()
322/// # }
323/// #
324/// # fn main() {
325/// # use syn::parse::Parser;
326/// # let remainder = remainder_after_skipping_past_next_at
327/// # .parse_str("a @ b c")
328/// # .unwrap();
329/// # assert_eq!(remainder.to_string(), "b c");
330/// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700331/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400332#[derive(Copy, Clone)]
333pub struct StepCursor<'c, 'a> {
334 scope: Span,
David Tolnay56924f42018-09-02 08:24:58 -0700335 // This field is covariant in 'c.
David Tolnay18c754c2018-08-21 23:26:58 -0400336 cursor: Cursor<'c>,
David Tolnay56924f42018-09-02 08:24:58 -0700337 // This field is contravariant in 'c. Together these make StepCursor
338 // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
339 // different lifetime but can upcast into a StepCursor with a shorter
340 // lifetime 'a.
341 //
342 // As long as we only ever construct a StepCursor for which 'c outlives 'a,
343 // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
344 // outlives 'a.
David Tolnay18c754c2018-08-21 23:26:58 -0400345 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
346}
347
348impl<'c, 'a> Deref for StepCursor<'c, 'a> {
349 type Target = Cursor<'c>;
350
351 fn deref(&self) -> &Self::Target {
352 &self.cursor
353 }
354}
355
356impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700357 /// Triggers an error at the current position of the parse stream.
358 ///
359 /// The `ParseStream::step` invocation will return this same error without
360 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400361 pub fn error<T: Display>(self, message: T) -> Error {
362 error::new_at(self.scope, self.cursor, message)
363 }
364}
365
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700366impl private {
367 pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
David Tolnay56924f42018-09-02 08:24:58 -0700368 // Refer to the comments within the StepCursor definition. We use the
369 // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
370 // Cursor is covariant in its lifetime parameter so we can cast a
371 // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700372 let _ = proof;
373 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
374 }
375}
376
David Tolnay66cb0c42018-08-31 09:01:30 -0700377fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700378 input
379 .step(|cursor| {
380 if let Some((_lifetime, rest)) = cursor.lifetime() {
381 Ok((true, rest))
382 } else if let Some((_token, rest)) = cursor.token_tree() {
383 Ok((true, rest))
384 } else {
385 Ok((false, *cursor))
386 }
David Tolnayfb84fc02018-10-02 21:01:30 -0700387 })
388 .unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700389}
390
David Tolnay10951d52018-08-31 10:27:39 -0700391impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700392 pub fn new_parse_buffer(
393 scope: Span,
394 cursor: Cursor,
395 unexpected: Rc<Cell<Option<Span>>>,
396 ) -> ParseBuffer {
David Tolnay18c754c2018-08-21 23:26:58 -0400397 ParseBuffer {
398 scope: scope,
David Tolnay5d7f2252018-09-02 08:21:40 -0700399 // See comment on `cell` in the struct definition.
400 cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
David Tolnay18c754c2018-08-21 23:26:58 -0400401 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400402 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400403 }
404 }
405
David Tolnay94f06632018-08-31 10:17:17 -0700406 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
407 buffer.unexpected.clone()
408 }
409}
410
411impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700412 /// Parses a syntax tree node of type `T`, advancing the position of our
413 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400414 pub fn parse<T: Parse>(&self) -> Result<T> {
415 T::parse(self)
416 }
417
David Tolnay725e1c62018-09-01 12:07:25 -0700418 /// Calls the given parser function to parse a syntax tree node of type `T`
419 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700420 ///
421 /// # Example
422 ///
423 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
424 /// zero or more outer attributes.
425 ///
426 /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
427 ///
428 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700429 /// #[macro_use]
430 /// extern crate syn;
431 ///
432 /// use syn::{Attribute, Ident};
David Tolnay21ce84c2018-09-01 15:37:51 -0700433 /// use syn::parse::{Parse, ParseStream, Result};
434 ///
435 /// // Parses a unit struct with attributes.
436 /// //
437 /// // #[path = "s.tmpl"]
438 /// // struct S;
439 /// struct UnitStruct {
440 /// attrs: Vec<Attribute>,
441 /// struct_token: Token![struct],
442 /// name: Ident,
443 /// semi_token: Token![;],
444 /// }
445 ///
446 /// impl Parse for UnitStruct {
447 /// fn parse(input: ParseStream) -> Result<Self> {
448 /// Ok(UnitStruct {
449 /// attrs: input.call(Attribute::parse_outer)?,
450 /// struct_token: input.parse()?,
451 /// name: input.parse()?,
452 /// semi_token: input.parse()?,
453 /// })
454 /// }
455 /// }
456 /// #
457 /// # fn main() {}
458 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400459 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
460 function(self)
461 }
462
David Tolnay725e1c62018-09-01 12:07:25 -0700463 /// Looks at the next token in the parse stream to determine whether it
464 /// matches the requested type of token.
465 ///
466 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700467 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700468 /// # Syntax
469 ///
470 /// Note that this method does not use turbofish syntax. Pass the peek type
471 /// inside of parentheses.
472 ///
473 /// - `input.peek(Token![struct])`
474 /// - `input.peek(Token![==])`
475 /// - `input.peek(Ident)`
476 /// - `input.peek(Lifetime)`
477 /// - `input.peek(token::Brace)`
478 ///
David Tolnayddebc3e2018-09-01 16:29:20 -0700479 /// # Example
480 ///
481 /// In this example we finish parsing the list of supertraits when the next
482 /// token in the input is either `where` or an opening curly brace.
483 ///
484 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700485 /// #[macro_use]
486 /// extern crate syn;
487 ///
488 /// use syn::{token, Generics, Ident, TypeParamBound};
David Tolnayddebc3e2018-09-01 16:29:20 -0700489 /// use syn::parse::{Parse, ParseStream, Result};
490 /// use syn::punctuated::Punctuated;
491 ///
492 /// // Parses a trait definition containing no associated items.
493 /// //
494 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
495 /// struct MarkerTrait {
496 /// trait_token: Token![trait],
497 /// ident: Ident,
498 /// generics: Generics,
499 /// colon_token: Option<Token![:]>,
500 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
501 /// brace_token: token::Brace,
502 /// }
503 ///
504 /// impl Parse for MarkerTrait {
505 /// fn parse(input: ParseStream) -> Result<Self> {
506 /// let trait_token: Token![trait] = input.parse()?;
507 /// let ident: Ident = input.parse()?;
508 /// let mut generics: Generics = input.parse()?;
509 /// let colon_token: Option<Token![:]> = input.parse()?;
510 ///
511 /// let mut supertraits = Punctuated::new();
512 /// if colon_token.is_some() {
513 /// loop {
514 /// supertraits.push_value(input.parse()?);
515 /// if input.peek(Token![where]) || input.peek(token::Brace) {
516 /// break;
517 /// }
518 /// supertraits.push_punct(input.parse()?);
519 /// }
520 /// }
521 ///
522 /// generics.where_clause = input.parse()?;
523 /// let content;
524 /// let empty_brace_token = braced!(content in input);
525 ///
526 /// Ok(MarkerTrait {
527 /// trait_token: trait_token,
528 /// ident: ident,
529 /// generics: generics,
530 /// colon_token: colon_token,
531 /// supertraits: supertraits,
532 /// brace_token: empty_brace_token,
533 /// })
534 /// }
535 /// }
536 /// #
537 /// # fn main() {}
538 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400539 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700540 let _ = token;
541 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400542 }
543
David Tolnay725e1c62018-09-01 12:07:25 -0700544 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700545 ///
546 /// This is commonly useful as a way to implement contextual keywords.
547 ///
548 /// # Example
549 ///
550 /// This example needs to use `peek2` because the symbol `union` is not a
551 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
552 /// the very next token is `union`, because someone is free to write a `mod
553 /// union` and a macro invocation that looks like `union::some_macro! { ...
554 /// }`. In other words `union` is a contextual keyword.
555 ///
556 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700557 /// #[macro_use]
558 /// extern crate syn;
559 ///
560 /// use syn::{Ident, ItemUnion, Macro};
David Tolnaye334b872018-09-01 16:38:10 -0700561 /// use syn::parse::{Parse, ParseStream, Result};
562 ///
563 /// // Parses either a union or a macro invocation.
564 /// enum UnionOrMacro {
565 /// // union MaybeUninit<T> { uninit: (), value: T }
566 /// Union(ItemUnion),
567 /// // lazy_static! { ... }
568 /// Macro(Macro),
569 /// }
570 ///
571 /// impl Parse for UnionOrMacro {
572 /// fn parse(input: ParseStream) -> Result<Self> {
573 /// if input.peek(Token![union]) && input.peek2(Ident) {
574 /// input.parse().map(UnionOrMacro::Union)
575 /// } else {
576 /// input.parse().map(UnionOrMacro::Macro)
577 /// }
578 /// }
579 /// }
580 /// #
581 /// # fn main() {}
582 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400583 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400584 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700585 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400586 }
587
David Tolnay725e1c62018-09-01 12:07:25 -0700588 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400589 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400590 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700591 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400592 }
593
David Tolnay725e1c62018-09-01 12:07:25 -0700594 /// Parses zero or more occurrences of `T` separated by punctuation of type
595 /// `P`, with optional trailing punctuation.
596 ///
597 /// Parsing continues until the end of this parse stream. The entire content
598 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700599 ///
600 /// # Example
601 ///
602 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700603 /// # #[macro_use]
David Tolnay0abe65b2018-09-01 14:31:43 -0700604 /// # extern crate quote;
David Tolnay0abe65b2018-09-01 14:31:43 -0700605 /// #
David Tolnaya1c98072018-09-06 08:58:10 -0700606 /// #[macro_use]
607 /// extern crate syn;
608 ///
609 /// use syn::{token, Ident, Type};
David Tolnay0abe65b2018-09-01 14:31:43 -0700610 /// use syn::parse::{Parse, ParseStream, Result};
611 /// use syn::punctuated::Punctuated;
612 ///
613 /// // Parse a simplified tuple struct syntax like:
614 /// //
615 /// // struct S(A, B);
616 /// struct TupleStruct {
617 /// struct_token: Token![struct],
618 /// ident: Ident,
619 /// paren_token: token::Paren,
620 /// fields: Punctuated<Type, Token![,]>,
621 /// semi_token: Token![;],
622 /// }
623 ///
624 /// impl Parse for TupleStruct {
625 /// fn parse(input: ParseStream) -> Result<Self> {
626 /// let content;
627 /// Ok(TupleStruct {
628 /// struct_token: input.parse()?,
629 /// ident: input.parse()?,
630 /// paren_token: parenthesized!(content in input),
631 /// fields: content.parse_terminated(Type::parse)?,
632 /// semi_token: input.parse()?,
633 /// })
634 /// }
635 /// }
636 /// #
637 /// # fn main() {
638 /// # let input = quote! {
639 /// # struct S(A, B);
640 /// # };
641 /// # syn::parse2::<TupleStruct>(input).unwrap();
642 /// # }
643 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400644 pub fn parse_terminated<T, P: Parse>(
645 &self,
646 parser: fn(ParseStream) -> Result<T>,
647 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700648 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400649 }
650
David Tolnay725e1c62018-09-01 12:07:25 -0700651 /// Returns whether there are tokens remaining in this stream.
652 ///
653 /// This method returns true at the end of the content of a set of
654 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700655 ///
656 /// # Example
657 ///
658 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700659 /// #[macro_use]
660 /// extern crate syn;
661 ///
662 /// use syn::{token, Ident, Item};
David Tolnaycce6b5f2018-09-01 14:24:46 -0700663 /// use syn::parse::{Parse, ParseStream, Result};
664 ///
665 /// // Parses a Rust `mod m { ... }` containing zero or more items.
666 /// struct Mod {
667 /// mod_token: Token![mod],
668 /// name: Ident,
669 /// brace_token: token::Brace,
670 /// items: Vec<Item>,
671 /// }
672 ///
673 /// impl Parse for Mod {
674 /// fn parse(input: ParseStream) -> Result<Self> {
675 /// let content;
676 /// Ok(Mod {
677 /// mod_token: input.parse()?,
678 /// name: input.parse()?,
679 /// brace_token: braced!(content in input),
680 /// items: {
681 /// let mut items = Vec::new();
682 /// while !content.is_empty() {
683 /// items.push(content.parse()?);
684 /// }
685 /// items
686 /// },
687 /// })
688 /// }
689 /// }
690 /// #
691 /// # fn main() {}
David Tolnayf5d30452018-09-01 02:29:04 -0700692 pub fn is_empty(&self) -> bool {
693 self.cursor().eof()
694 }
695
David Tolnay725e1c62018-09-01 12:07:25 -0700696 /// Constructs a helper for peeking at the next token in this stream and
697 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700698 ///
699 /// # Example
700 ///
701 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700702 /// #[macro_use]
703 /// extern crate syn;
704 ///
705 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, TypeParam};
David Tolnay2c77e772018-09-01 14:18:46 -0700706 /// use syn::parse::{Parse, ParseStream, Result};
707 ///
708 /// // A generic parameter, a single one of the comma-separated elements inside
709 /// // angle brackets in:
710 /// //
711 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
712 /// //
713 /// // On invalid input, lookahead gives us a reasonable error message.
714 /// //
715 /// // error: expected one of: identifier, lifetime, `const`
716 /// // |
717 /// // 5 | fn f<!Sized>() {}
718 /// // | ^
719 /// enum GenericParam {
720 /// Type(TypeParam),
721 /// Lifetime(LifetimeDef),
722 /// Const(ConstParam),
723 /// }
724 ///
725 /// impl Parse for GenericParam {
726 /// fn parse(input: ParseStream) -> Result<Self> {
727 /// let lookahead = input.lookahead1();
728 /// if lookahead.peek(Ident) {
729 /// input.parse().map(GenericParam::Type)
730 /// } else if lookahead.peek(Lifetime) {
731 /// input.parse().map(GenericParam::Lifetime)
732 /// } else if lookahead.peek(Token![const]) {
733 /// input.parse().map(GenericParam::Const)
734 /// } else {
735 /// Err(lookahead.error())
736 /// }
737 /// }
738 /// }
739 /// #
740 /// # fn main() {}
741 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700742 pub fn lookahead1(&self) -> Lookahead1<'a> {
743 lookahead::new(self.scope, self.cursor())
744 }
745
David Tolnay725e1c62018-09-01 12:07:25 -0700746 /// Forks a parse stream so that parsing tokens out of either the original
747 /// or the fork does not advance the position of the other.
748 ///
749 /// # Performance
750 ///
751 /// Forking a parse stream is a cheap fixed amount of work and does not
752 /// involve copying token buffers. Where you might hit performance problems
753 /// is if your macro ends up parsing a large amount of content more than
754 /// once.
755 ///
756 /// ```
757 /// # use syn::Expr;
758 /// # use syn::parse::{ParseStream, Result};
759 /// #
760 /// # fn bad(input: ParseStream) -> Result<Expr> {
761 /// // Do not do this.
762 /// if input.fork().parse::<Expr>().is_ok() {
763 /// return input.parse::<Expr>();
764 /// }
765 /// # unimplemented!()
766 /// # }
767 /// ```
768 ///
769 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
770 /// parse stream. Only use a fork when the amount of work performed against
771 /// the fork is small and bounded.
772 ///
David Tolnayec149b02018-09-01 14:17:28 -0700773 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700774 /// speculative parsing, consider using [`ParseStream::step`] instead.
775 ///
776 /// [`ParseStream::step`]: #method.step
David Tolnayec149b02018-09-01 14:17:28 -0700777 ///
778 /// # Example
779 ///
780 /// The parse implementation shown here parses possibly restricted `pub`
781 /// visibilities.
782 ///
783 /// - `pub`
784 /// - `pub(crate)`
785 /// - `pub(self)`
786 /// - `pub(super)`
787 /// - `pub(in some::path)`
788 ///
789 /// To handle the case of visibilities inside of tuple structs, the parser
790 /// needs to distinguish parentheses that specify visibility restrictions
791 /// from parentheses that form part of a tuple type.
792 ///
793 /// ```
794 /// # struct A;
795 /// # struct B;
796 /// # struct C;
797 /// #
798 /// struct S(pub(crate) A, pub (B, C));
799 /// ```
800 ///
801 /// In this example input the first tuple struct element of `S` has
802 /// `pub(crate)` visibility while the second tuple struct element has `pub`
803 /// visibility; the parentheses around `(B, C)` are part of the type rather
804 /// than part of a visibility restriction.
805 ///
806 /// The parser uses a forked parse stream to check the first token inside of
807 /// parentheses after the `pub` keyword. This is a small bounded amount of
808 /// work performed against the forked parse stream.
809 ///
810 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700811 /// #[macro_use]
812 /// extern crate syn;
813 ///
814 /// use syn::{token, Ident, Path};
David Tolnayec149b02018-09-01 14:17:28 -0700815 /// use syn::ext::IdentExt;
816 /// use syn::parse::{Parse, ParseStream, Result};
817 ///
818 /// struct PubVisibility {
819 /// pub_token: Token![pub],
820 /// restricted: Option<Restricted>,
821 /// }
822 ///
823 /// struct Restricted {
824 /// paren_token: token::Paren,
825 /// in_token: Option<Token![in]>,
826 /// path: Path,
827 /// }
828 ///
829 /// impl Parse for PubVisibility {
830 /// fn parse(input: ParseStream) -> Result<Self> {
831 /// let pub_token: Token![pub] = input.parse()?;
832 ///
833 /// if input.peek(token::Paren) {
834 /// let ahead = input.fork();
835 /// let mut content;
836 /// parenthesized!(content in ahead);
837 ///
838 /// if content.peek(Token![crate])
839 /// || content.peek(Token![self])
840 /// || content.peek(Token![super])
841 /// {
842 /// return Ok(PubVisibility {
843 /// pub_token: pub_token,
844 /// restricted: Some(Restricted {
845 /// paren_token: parenthesized!(content in input),
846 /// in_token: None,
847 /// path: Path::from(content.call(Ident::parse_any)?),
848 /// }),
849 /// });
850 /// } else if content.peek(Token![in]) {
851 /// return Ok(PubVisibility {
852 /// pub_token: pub_token,
853 /// restricted: Some(Restricted {
854 /// paren_token: parenthesized!(content in input),
855 /// in_token: Some(content.parse()?),
856 /// path: content.call(Path::parse_mod_style)?,
857 /// }),
858 /// });
859 /// }
860 /// }
861 ///
862 /// Ok(PubVisibility {
863 /// pub_token: pub_token,
864 /// restricted: None,
865 /// })
866 /// }
867 /// }
868 /// #
869 /// # fn main() {}
870 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400871 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400872 ParseBuffer {
873 scope: self.scope,
874 cell: self.cell.clone(),
875 marker: PhantomData,
876 // Not the parent's unexpected. Nothing cares whether the clone
877 // parses all the way.
878 unexpected: Rc::new(Cell::new(None)),
879 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400880 }
881
David Tolnay725e1c62018-09-01 12:07:25 -0700882 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700883 ///
884 /// # Example
885 ///
886 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700887 /// #[macro_use]
888 /// extern crate syn;
889 ///
890 /// use syn::Expr;
David Tolnay23fce0b2018-09-01 13:50:31 -0700891 /// use syn::parse::{Parse, ParseStream, Result};
892 ///
893 /// // Some kind of loop: `while` or `for` or `loop`.
894 /// struct Loop {
895 /// expr: Expr,
896 /// }
897 ///
898 /// impl Parse for Loop {
899 /// fn parse(input: ParseStream) -> Result<Self> {
900 /// if input.peek(Token![while])
901 /// || input.peek(Token![for])
902 /// || input.peek(Token![loop])
903 /// {
904 /// Ok(Loop {
905 /// expr: input.parse()?,
906 /// })
907 /// } else {
908 /// Err(input.error("expected some kind of loop"))
909 /// }
910 /// }
911 /// }
David Tolnaya1c98072018-09-06 08:58:10 -0700912 /// #
913 /// # fn main() {}
David Tolnay23fce0b2018-09-01 13:50:31 -0700914 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400915 pub fn error<T: Display>(&self, message: T) -> Error {
916 error::new_at(self.scope, self.cursor(), message)
917 }
918
David Tolnay725e1c62018-09-01 12:07:25 -0700919 /// Speculatively parses tokens from this parse stream, advancing the
920 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700921 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700922 /// This is a powerful low-level API used for defining the `Parse` impls of
923 /// the basic built-in token types. It is not something that will be used
924 /// widely outside of the Syn codebase.
925 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700926 /// # Example
927 ///
928 /// ```
929 /// # extern crate proc_macro2;
930 /// # extern crate syn;
931 /// #
932 /// use proc_macro2::TokenTree;
933 /// use syn::parse::{ParseStream, Result};
934 ///
935 /// // This function advances the stream past the next occurrence of `@`. If
936 /// // no `@` is present in the stream, the stream position is unchanged and
937 /// // an error is returned.
938 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
939 /// input.step(|cursor| {
940 /// let mut rest = *cursor;
David Tolnaydb312582018-11-06 20:42:05 -0800941 /// while let Some((tt, next)) = rest.token_tree() {
David Tolnay9bd34392018-09-01 13:19:53 -0700942 /// match tt {
943 /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
944 /// return Ok(((), next));
945 /// }
946 /// _ => rest = next,
947 /// }
948 /// }
949 /// Err(cursor.error("no `@` was found after this point"))
950 /// })
951 /// }
952 /// #
David Tolnaydb312582018-11-06 20:42:05 -0800953 /// # fn remainder_after_skipping_past_next_at(
954 /// # input: ParseStream,
955 /// # ) -> Result<proc_macro2::TokenStream> {
956 /// # skip_past_next_at(input)?;
957 /// # input.parse()
958 /// # }
959 /// #
960 /// # fn main() {
961 /// # use syn::parse::Parser;
962 /// # let remainder = remainder_after_skipping_past_next_at
963 /// # .parse_str("a @ b c")
964 /// # .unwrap();
965 /// # assert_eq!(remainder.to_string(), "b c");
966 /// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700967 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700968 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400969 where
970 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
971 {
David Tolnayc142b092018-09-02 08:52:52 -0700972 // Since the user's function is required to work for any 'c, we know
973 // that the Cursor<'c> they return is either derived from the input
974 // StepCursor<'c, 'a> or from a Cursor<'static>.
975 //
976 // It would not be legal to write this function without the invariant
977 // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
978 // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
979 // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
980 // `step` on their ParseBuffer<'short> with a closure that returns
981 // Cursor<'short>, and we would wrongly write that Cursor<'short> into
982 // the Cell intended to hold Cursor<'a>.
983 //
984 // In some cases it may be necessary for R to contain a Cursor<'a>.
985 // Within Syn we solve this using `private::advance_step_cursor` which
986 // uses the existence of a StepCursor<'c, 'a> as proof that it is safe
987 // to cast from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it
988 // would be safe to expose that API as a method on StepCursor.
David Tolnay6b65f852018-09-01 11:56:25 -0700989 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -0400990 scope: self.scope,
991 cursor: self.cell.get(),
992 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700993 })?;
994 self.cell.set(rest);
995 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -0400996 }
David Tolnayeafc8052018-08-25 16:33:53 -0400997
David Tolnay725e1c62018-09-01 12:07:25 -0700998 /// Provides low-level access to the token representation underlying this
999 /// parse stream.
1000 ///
1001 /// Cursors are immutable so no operations you perform against the cursor
1002 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -07001003 pub fn cursor(&self) -> Cursor<'a> {
1004 self.cell.get()
1005 }
1006
David Tolnay94f06632018-08-31 10:17:17 -07001007 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -04001008 match self.unexpected.get() {
1009 Some(span) => Err(Error::new(span, "unexpected token")),
1010 None => Ok(()),
1011 }
1012 }
David Tolnay18c754c2018-08-21 23:26:58 -04001013}
1014
David Tolnaya7d69fc2018-08-26 13:30:24 -04001015impl<T: Parse> Parse for Box<T> {
1016 fn parse(input: ParseStream) -> Result<Self> {
1017 input.parse().map(Box::new)
1018 }
1019}
1020
David Tolnay4fb71232018-08-25 23:14:50 -04001021impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -04001022 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -07001023 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -04001024 Ok(Some(input.parse()?))
1025 } else {
1026 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -04001027 }
David Tolnay18c754c2018-08-21 23:26:58 -04001028 }
1029}
David Tolnay4ac232d2018-08-31 10:18:03 -07001030
David Tolnay80a914f2018-08-30 23:49:53 -07001031impl Parse for TokenStream {
1032 fn parse(input: ParseStream) -> Result<Self> {
1033 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
1034 }
1035}
1036
1037impl Parse for TokenTree {
1038 fn parse(input: ParseStream) -> Result<Self> {
1039 input.step(|cursor| match cursor.token_tree() {
1040 Some((tt, rest)) => Ok((tt, rest)),
1041 None => Err(cursor.error("expected token tree")),
1042 })
1043 }
1044}
1045
1046impl Parse for Group {
1047 fn parse(input: ParseStream) -> Result<Self> {
1048 input.step(|cursor| {
1049 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
1050 if let Some((inside, span, rest)) = cursor.group(*delim) {
1051 let mut group = Group::new(*delim, inside.token_stream());
1052 group.set_span(span);
1053 return Ok((group, rest));
1054 }
1055 }
1056 Err(cursor.error("expected group token"))
1057 })
1058 }
1059}
1060
1061impl Parse for Punct {
1062 fn parse(input: ParseStream) -> Result<Self> {
1063 input.step(|cursor| match cursor.punct() {
1064 Some((punct, rest)) => Ok((punct, rest)),
1065 None => Err(cursor.error("expected punctuation token")),
1066 })
1067 }
1068}
1069
1070impl Parse for Literal {
1071 fn parse(input: ParseStream) -> Result<Self> {
1072 input.step(|cursor| match cursor.literal() {
1073 Some((literal, rest)) => Ok((literal, rest)),
1074 None => Err(cursor.error("expected literal token")),
1075 })
1076 }
1077}
1078
1079/// Parser that can parse Rust tokens into a particular syntax tree node.
1080///
1081/// Refer to the [module documentation] for details about parsing in Syn.
1082///
1083/// [module documentation]: index.html
1084///
1085/// *This trait is available if Syn is built with the `"parsing"` feature.*
1086pub trait Parser: Sized {
1087 type Output;
1088
1089 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
1090 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1091
1092 /// Parse tokens of source code into the chosen syntax tree node.
1093 ///
1094 /// *This method is available if Syn is built with both the `"parsing"` and
1095 /// `"proc-macro"` features.*
1096 #[cfg(all(
1097 not(all(target_arch = "wasm32", target_os = "unknown")),
1098 feature = "proc-macro"
1099 ))]
1100 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1101 self.parse2(proc_macro2::TokenStream::from(tokens))
1102 }
1103
1104 /// Parse a string of Rust code into the chosen syntax tree node.
1105 ///
1106 /// # Hygiene
1107 ///
1108 /// Every span in the resulting syntax tree will be set to resolve at the
1109 /// macro call site.
1110 fn parse_str(self, s: &str) -> Result<Self::Output> {
1111 self.parse2(proc_macro2::TokenStream::from_str(s)?)
1112 }
1113}
1114
David Tolnay7b07aa12018-09-01 11:41:12 -07001115fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1116 let scope = Span::call_site();
1117 let cursor = tokens.begin();
1118 let unexpected = Rc::new(Cell::new(None));
1119 private::new_parse_buffer(scope, cursor, unexpected)
1120}
1121
David Tolnay80a914f2018-08-30 23:49:53 -07001122impl<F, T> Parser for F
1123where
1124 F: FnOnce(ParseStream) -> Result<T>,
1125{
1126 type Output = T;
1127
1128 fn parse2(self, tokens: TokenStream) -> Result<T> {
1129 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -07001130 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -07001131 let node = self(&state)?;
1132 state.check_unexpected()?;
1133 if state.is_empty() {
1134 Ok(node)
1135 } else {
1136 Err(state.error("unexpected token"))
1137 }
1138 }
1139}