syn_pub_items/
parse.rs

1//! Parsing interface for parsing a token stream into a syntax tree node.
2//!
3//! 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.
8//!
9//! [`ParseStream`]: type.ParseStream.html
10//! [`Result<T>`]: type.Result.html
11//! [`Cursor`]: ../buffer/index.html
12//!
13//! # Example
14//!
15//! 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//!
20//! Once `Parse` impls have been defined, they can be called conveniently from a
21//! 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
27//!
28//! ```edition2018
29//! extern crate proc_macro;
30//!
31//! use proc_macro::TokenStream;
32//! use syn::{braced, parse_macro_input, token, Field, Ident, Result, Token};
33//! use syn::parse::{Parse, ParseStream};
34//! use syn::punctuated::Punctuated;
35//!
36//! enum Item {
37//!     Struct(ItemStruct),
38//!     Enum(ItemEnum),
39//! }
40//!
41//! struct ItemStruct {
42//!     struct_token: Token![struct],
43//!     ident: Ident,
44//!     brace_token: token::Brace,
45//!     fields: Punctuated<Field, Token![,]>,
46//! }
47//! #
48//! # enum ItemEnum {}
49//!
50//! impl Parse for Item {
51//!     fn parse(input: ParseStream) -> Result<Self> {
52//!         let lookahead = input.lookahead1();
53//!         if lookahead.peek(Token![struct]) {
54//!             input.parse().map(Item::Struct)
55//!         } else if lookahead.peek(Token![enum]) {
56//!             input.parse().map(Item::Enum)
57//!         } else {
58//!             Err(lookahead.error())
59//!         }
60//!     }
61//! }
62//!
63//! impl Parse for ItemStruct {
64//!     fn parse(input: ParseStream) -> Result<Self> {
65//!         let content;
66//!         Ok(ItemStruct {
67//!             struct_token: input.parse()?,
68//!             ident: input.parse()?,
69//!             brace_token: braced!(content in input),
70//!             fields: content.parse_terminated(Field::parse_named)?,
71//!         })
72//!     }
73//! }
74//! #
75//! # impl Parse for ItemEnum {
76//! #     fn parse(input: ParseStream) -> Result<Self> {
77//! #         unimplemented!()
78//! #     }
79//! # }
80//!
81//! # const IGNORE: &str = stringify! {
82//! #[proc_macro]
83//! # };
84//! pub fn my_macro(tokens: TokenStream) -> TokenStream {
85//!     let input = parse_macro_input!(tokens as Item);
86//!
87//!     /* ... */
88//! #   "".parse().unwrap()
89//! }
90//! ```
91//!
92//! # The `syn::parse*` functions
93//!
94//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
95//! as an entry point for parsing syntax tree nodes that can be parsed in an
96//! obvious default way. These functions can return any syntax tree node that
97//! implements the [`Parse`] trait, which includes most types in Syn.
98//!
99//! [`syn::parse`]: ../fn.parse.html
100//! [`syn::parse2`]: ../fn.parse2.html
101//! [`syn::parse_str`]: ../fn.parse_str.html
102//! [`Parse`]: trait.Parse.html
103//!
104//! ```edition2018
105//! use syn::Type;
106//!
107//! # fn run_parser() -> syn::Result<()> {
108//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
109//! #     Ok(())
110//! # }
111//! #
112//! # fn main() {
113//! #     run_parser().unwrap();
114//! # }
115//! ```
116//!
117//! The [`parse_quote!`] macro also uses this approach.
118//!
119//! [`parse_quote!`]: ../macro.parse_quote.html
120//!
121//! # The `Parser` trait
122//!
123//! Some types can be parsed in several ways depending on context. For example
124//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
125//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
126//! may or may not allow trailing punctuation, and parsing it the wrong way
127//! would either reject valid input or accept invalid input.
128//!
129//! [`Attribute`]: ../struct.Attribute.html
130//! [`Punctuated`]: ../punctuated/index.html
131//!
132//! The `Parse` trait is not implemented in these cases because there is no good
133//! behavior to consider the default.
134//!
135//! ```edition2018,compile_fail
136//! # extern crate proc_macro;
137//! #
138//! # use syn::punctuated::Punctuated;
139//! # use syn::{PathSegment, Result, Token};
140//! #
141//! # fn f(tokens: proc_macro::TokenStream) -> Result<()> {
142//! #
143//! // Can't parse `Punctuated` without knowing whether trailing punctuation
144//! // should be allowed in this context.
145//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
146//! #
147//! #     Ok(())
148//! # }
149//! ```
150//!
151//! In these cases the types provide a choice of parser functions rather than a
152//! single `Parse` implementation, and those parser functions can be invoked
153//! through the [`Parser`] trait.
154//!
155//! [`Parser`]: trait.Parser.html
156//!
157//! ```edition2018
158//! extern crate proc_macro;
159//!
160//! use proc_macro::TokenStream;
161//! use syn::parse::Parser;
162//! use syn::punctuated::Punctuated;
163//! use syn::{Attribute, Expr, PathSegment, Result, Token};
164//!
165//! fn call_some_parser_methods(input: TokenStream) -> Result<()> {
166//!     // Parse a nonempty sequence of path segments separated by `::` punctuation
167//!     // with no trailing punctuation.
168//!     let tokens = input.clone();
169//!     let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
170//!     let _path = parser.parse(tokens)?;
171//!
172//!     // Parse a possibly empty sequence of expressions terminated by commas with
173//!     // an optional trailing punctuation.
174//!     let tokens = input.clone();
175//!     let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
176//!     let _args = parser.parse(tokens)?;
177//!
178//!     // Parse zero or more outer attributes but not inner attributes.
179//!     let tokens = input.clone();
180//!     let parser = Attribute::parse_outer;
181//!     let _attrs = parser.parse(tokens)?;
182//!
183//!     Ok(())
184//! }
185//! ```
186//!
187//! ---
188//!
189//! *This module is available if Syn is built with the `"parsing"` feature.*
190
191use std::cell::Cell;
192use std::fmt::{self, Debug, Display};
193use std::marker::PhantomData;
194use std::mem;
195use std::ops::Deref;
196use std::rc::Rc;
197use std::str::FromStr;
198
199#[cfg(all(
200    not(all(target_arch = "wasm32", target_os = "unknown")),
201    feature = "proc-macro"
202))]
203use proc_macro;
204use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
205
206use buffer::{Cursor, TokenBuffer};
207use error;
208use lookahead;
209use private;
210use punctuated::Punctuated;
211use token::Token;
212
213pub use error::{Error, Result};
214pub use lookahead::{Lookahead1, Peek};
215
216/// Parsing interface implemented by all types that can be parsed in a default
217/// way from a token stream.
218pub trait Parse: Sized {
219    fn parse(input: ParseStream) -> Result<Self>;
220}
221
222/// Input to a Syn parser function.
223///
224/// See the methods of this type under the documentation of [`ParseBuffer`]. For
225/// an overview of parsing in Syn, refer to the [module documentation].
226///
227/// [module documentation]: index.html
228pub type ParseStream<'a> = &'a ParseBuffer<'a>;
229
230/// Cursor position within a buffered token stream.
231///
232/// This type is more commonly used through the type alias [`ParseStream`] which
233/// is an alias for `&ParseBuffer`.
234///
235/// `ParseStream` is the input type for all parser functions in Syn. They have
236/// the signature `fn(ParseStream) -> Result<T>`.
237///
238/// ## Calling a parser function
239///
240/// There is no public way to construct a `ParseBuffer`. Instead, if you are
241/// looking to invoke a parser function that requires `ParseStream` as input,
242/// you will need to go through one of the public parsing entry points.
243///
244/// - The [`parse_macro_input!`] macro if parsing input of a procedural macro;
245/// - One of [the `syn::parse*` functions][syn-parse]; or
246/// - A method of the [`Parser`] trait.
247///
248/// [`parse_macro_input!`]: ../macro.parse_macro_input.html
249/// [syn-parse]: index.html#the-synparse-functions
250pub struct ParseBuffer<'a> {
251    scope: Span,
252    // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
253    // The rest of the code in this module needs to be careful that only a
254    // cursor derived from this `cell` is ever assigned to this `cell`.
255    //
256    // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
257    // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
258    // than 'a, and then assign a Cursor<'short> into the Cell.
259    //
260    // By extension, it would not be safe to expose an API that accepts a
261    // Cursor<'a> and trusts that it lives as long as the cursor currently in
262    // the cell.
263    cell: Cell<Cursor<'static>>,
264    marker: PhantomData<Cursor<'a>>,
265    unexpected: Rc<Cell<Option<Span>>>,
266}
267
268impl<'a> Drop for ParseBuffer<'a> {
269    fn drop(&mut self) {
270        if !self.is_empty() && self.unexpected.get().is_none() {
271            self.unexpected.set(Some(self.cursor().span()));
272        }
273    }
274}
275
276impl<'a> Display for ParseBuffer<'a> {
277    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
278        Display::fmt(&self.cursor().token_stream(), f)
279    }
280}
281
282impl<'a> Debug for ParseBuffer<'a> {
283    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
284        Debug::fmt(&self.cursor().token_stream(), f)
285    }
286}
287
288/// Cursor state associated with speculative parsing.
289///
290/// This type is the input of the closure provided to [`ParseStream::step`].
291///
292/// [`ParseStream::step`]: struct.ParseBuffer.html#method.step
293///
294/// # Example
295///
296/// ```edition2018
297/// use proc_macro2::TokenTree;
298/// use syn::Result;
299/// use syn::parse::ParseStream;
300///
301/// // This function advances the stream past the next occurrence of `@`. If
302/// // no `@` is present in the stream, the stream position is unchanged and
303/// // an error is returned.
304/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
305///     input.step(|cursor| {
306///         let mut rest = *cursor;
307///         while let Some((tt, next)) = rest.token_tree() {
308///             match tt {
309///                 TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
310///                     return Ok(((), next));
311///                 }
312///                 _ => rest = next,
313///             }
314///         }
315///         Err(cursor.error("no `@` was found after this point"))
316///     })
317/// }
318/// #
319/// # fn remainder_after_skipping_past_next_at(
320/// #     input: ParseStream,
321/// # ) -> Result<proc_macro2::TokenStream> {
322/// #     skip_past_next_at(input)?;
323/// #     input.parse()
324/// # }
325/// #
326/// # fn main() {
327/// #     use syn::parse::Parser;
328/// #     let remainder = remainder_after_skipping_past_next_at
329/// #         .parse_str("a @ b c")
330/// #         .unwrap();
331/// #     assert_eq!(remainder.to_string(), "b c");
332/// # }
333/// ```
334#[derive(Copy, Clone)]
335pub struct StepCursor<'c, 'a> {
336    scope: Span,
337    // This field is covariant in 'c.
338    cursor: Cursor<'c>,
339    // This field is contravariant in 'c. Together these make StepCursor
340    // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
341    // different lifetime but can upcast into a StepCursor with a shorter
342    // lifetime 'a.
343    //
344    // As long as we only ever construct a StepCursor for which 'c outlives 'a,
345    // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
346    // outlives 'a.
347    marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
348}
349
350impl<'c, 'a> Deref for StepCursor<'c, 'a> {
351    type Target = Cursor<'c>;
352
353    fn deref(&self) -> &Self::Target {
354        &self.cursor
355    }
356}
357
358impl<'c, 'a> StepCursor<'c, 'a> {
359    /// Triggers an error at the current position of the parse stream.
360    ///
361    /// The `ParseStream::step` invocation will return this same error without
362    /// advancing the stream state.
363    pub fn error<T: Display>(self, message: T) -> Error {
364        error::new_at(self.scope, self.cursor, message)
365    }
366}
367
368impl private {
369    pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
370        // Refer to the comments within the StepCursor definition. We use the
371        // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
372        // Cursor is covariant in its lifetime parameter so we can cast a
373        // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
374        let _ = proof;
375        unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
376    }
377}
378
379fn skip(input: ParseStream) -> bool {
380    input
381        .step(|cursor| {
382            if let Some((_lifetime, rest)) = cursor.lifetime() {
383                Ok((true, rest))
384            } else if let Some((_token, rest)) = cursor.token_tree() {
385                Ok((true, rest))
386            } else {
387                Ok((false, *cursor))
388            }
389        })
390        .unwrap()
391}
392
393impl private {
394    pub fn new_parse_buffer(
395        scope: Span,
396        cursor: Cursor,
397        unexpected: Rc<Cell<Option<Span>>>,
398    ) -> ParseBuffer {
399        ParseBuffer {
400            scope: scope,
401            // See comment on `cell` in the struct definition.
402            cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
403            marker: PhantomData,
404            unexpected: unexpected,
405        }
406    }
407
408    pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
409        buffer.unexpected.clone()
410    }
411}
412
413impl<'a> ParseBuffer<'a> {
414    /// Parses a syntax tree node of type `T`, advancing the position of our
415    /// parse stream past it.
416    pub fn parse<T: Parse>(&self) -> Result<T> {
417        T::parse(self)
418    }
419
420    /// Calls the given parser function to parse a syntax tree node of type `T`
421    /// from this stream.
422    ///
423    /// # Example
424    ///
425    /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
426    /// zero or more outer attributes.
427    ///
428    /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
429    ///
430    /// ```edition2018
431    /// use syn::{Attribute, Ident, Result, Token};
432    /// use syn::parse::{Parse, ParseStream};
433    ///
434    /// // Parses a unit struct with attributes.
435    /// //
436    /// //     #[path = "s.tmpl"]
437    /// //     struct S;
438    /// struct UnitStruct {
439    ///     attrs: Vec<Attribute>,
440    ///     struct_token: Token![struct],
441    ///     name: Ident,
442    ///     semi_token: Token![;],
443    /// }
444    ///
445    /// impl Parse for UnitStruct {
446    ///     fn parse(input: ParseStream) -> Result<Self> {
447    ///         Ok(UnitStruct {
448    ///             attrs: input.call(Attribute::parse_outer)?,
449    ///             struct_token: input.parse()?,
450    ///             name: input.parse()?,
451    ///             semi_token: input.parse()?,
452    ///         })
453    ///     }
454    /// }
455    /// ```
456    pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
457        function(self)
458    }
459
460    /// Looks at the next token in the parse stream to determine whether it
461    /// matches the requested type of token.
462    ///
463    /// Does not advance the position of the parse stream.
464    ///
465    /// # Syntax
466    ///
467    /// Note that this method does not use turbofish syntax. Pass the peek type
468    /// inside of parentheses.
469    ///
470    /// - `input.peek(Token![struct])`
471    /// - `input.peek(Token![==])`
472    /// - `input.peek(Ident)`
473    /// - `input.peek(Lifetime)`
474    /// - `input.peek(token::Brace)`
475    ///
476    /// # Example
477    ///
478    /// In this example we finish parsing the list of supertraits when the next
479    /// token in the input is either `where` or an opening curly brace.
480    ///
481    /// ```edition2018
482    /// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
483    /// use syn::parse::{Parse, ParseStream};
484    /// use syn::punctuated::Punctuated;
485    ///
486    /// // Parses a trait definition containing no associated items.
487    /// //
488    /// //     trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
489    /// struct MarkerTrait {
490    ///     trait_token: Token![trait],
491    ///     ident: Ident,
492    ///     generics: Generics,
493    ///     colon_token: Option<Token![:]>,
494    ///     supertraits: Punctuated<TypeParamBound, Token![+]>,
495    ///     brace_token: token::Brace,
496    /// }
497    ///
498    /// impl Parse for MarkerTrait {
499    ///     fn parse(input: ParseStream) -> Result<Self> {
500    ///         let trait_token: Token![trait] = input.parse()?;
501    ///         let ident: Ident = input.parse()?;
502    ///         let mut generics: Generics = input.parse()?;
503    ///         let colon_token: Option<Token![:]> = input.parse()?;
504    ///
505    ///         let mut supertraits = Punctuated::new();
506    ///         if colon_token.is_some() {
507    ///             loop {
508    ///                 supertraits.push_value(input.parse()?);
509    ///                 if input.peek(Token![where]) || input.peek(token::Brace) {
510    ///                     break;
511    ///                 }
512    ///                 supertraits.push_punct(input.parse()?);
513    ///             }
514    ///         }
515    ///
516    ///         generics.where_clause = input.parse()?;
517    ///         let content;
518    ///         let empty_brace_token = braced!(content in input);
519    ///
520    ///         Ok(MarkerTrait {
521    ///             trait_token: trait_token,
522    ///             ident: ident,
523    ///             generics: generics,
524    ///             colon_token: colon_token,
525    ///             supertraits: supertraits,
526    ///             brace_token: empty_brace_token,
527    ///         })
528    ///     }
529    /// }
530    /// ```
531    pub fn peek<T: Peek>(&self, token: T) -> bool {
532        let _ = token;
533        T::Token::peek(self.cursor())
534    }
535
536    /// Looks at the second-next token in the parse stream.
537    ///
538    /// This is commonly useful as a way to implement contextual keywords.
539    ///
540    /// # Example
541    ///
542    /// This example needs to use `peek2` because the symbol `union` is not a
543    /// keyword in Rust. We can't use just `peek` and decide to parse a union if
544    /// the very next token is `union`, because someone is free to write a `mod
545    /// union` and a macro invocation that looks like `union::some_macro! { ...
546    /// }`. In other words `union` is a contextual keyword.
547    ///
548    /// ```edition2018
549    /// use syn::{Ident, ItemUnion, Macro, Result, Token};
550    /// use syn::parse::{Parse, ParseStream};
551    ///
552    /// // Parses either a union or a macro invocation.
553    /// enum UnionOrMacro {
554    ///     // union MaybeUninit<T> { uninit: (), value: T }
555    ///     Union(ItemUnion),
556    ///     // lazy_static! { ... }
557    ///     Macro(Macro),
558    /// }
559    ///
560    /// impl Parse for UnionOrMacro {
561    ///     fn parse(input: ParseStream) -> Result<Self> {
562    ///         if input.peek(Token![union]) && input.peek2(Ident) {
563    ///             input.parse().map(UnionOrMacro::Union)
564    ///         } else {
565    ///             input.parse().map(UnionOrMacro::Macro)
566    ///         }
567    ///     }
568    /// }
569    /// ```
570    pub fn peek2<T: Peek>(&self, token: T) -> bool {
571        let ahead = self.fork();
572        skip(&ahead) && ahead.peek(token)
573    }
574
575    /// Looks at the third-next token in the parse stream.
576    pub fn peek3<T: Peek>(&self, token: T) -> bool {
577        let ahead = self.fork();
578        skip(&ahead) && skip(&ahead) && ahead.peek(token)
579    }
580
581    /// Parses zero or more occurrences of `T` separated by punctuation of type
582    /// `P`, with optional trailing punctuation.
583    ///
584    /// Parsing continues until the end of this parse stream. The entire content
585    /// of this parse stream must consist of `T` and `P`.
586    ///
587    /// # Example
588    ///
589    /// ```edition2018
590    /// # use quote::quote;
591    /// #
592    /// use syn::{parenthesized, token, Ident, Result, Token, Type};
593    /// use syn::parse::{Parse, ParseStream};
594    /// use syn::punctuated::Punctuated;
595    ///
596    /// // Parse a simplified tuple struct syntax like:
597    /// //
598    /// //     struct S(A, B);
599    /// struct TupleStruct {
600    ///     struct_token: Token![struct],
601    ///     ident: Ident,
602    ///     paren_token: token::Paren,
603    ///     fields: Punctuated<Type, Token![,]>,
604    ///     semi_token: Token![;],
605    /// }
606    ///
607    /// impl Parse for TupleStruct {
608    ///     fn parse(input: ParseStream) -> Result<Self> {
609    ///         let content;
610    ///         Ok(TupleStruct {
611    ///             struct_token: input.parse()?,
612    ///             ident: input.parse()?,
613    ///             paren_token: parenthesized!(content in input),
614    ///             fields: content.parse_terminated(Type::parse)?,
615    ///             semi_token: input.parse()?,
616    ///         })
617    ///     }
618    /// }
619    /// #
620    /// # fn main() {
621    /// #     let input = quote! {
622    /// #         struct S(A, B);
623    /// #     };
624    /// #     syn::parse2::<TupleStruct>(input).unwrap();
625    /// # }
626    /// ```
627    pub fn parse_terminated<T, P: Parse>(
628        &self,
629        parser: fn(ParseStream) -> Result<T>,
630    ) -> Result<Punctuated<T, P>> {
631        Punctuated::parse_terminated_with(self, parser)
632    }
633
634    /// Returns whether there are tokens remaining in this stream.
635    ///
636    /// This method returns true at the end of the content of a set of
637    /// delimiters, as well as at the very end of the complete macro input.
638    ///
639    /// # Example
640    ///
641    /// ```edition2018
642    /// use syn::{braced, token, Ident, Item, Result, Token};
643    /// use syn::parse::{Parse, ParseStream};
644    ///
645    /// // Parses a Rust `mod m { ... }` containing zero or more items.
646    /// struct Mod {
647    ///     mod_token: Token![mod],
648    ///     name: Ident,
649    ///     brace_token: token::Brace,
650    ///     items: Vec<Item>,
651    /// }
652    ///
653    /// impl Parse for Mod {
654    ///     fn parse(input: ParseStream) -> Result<Self> {
655    ///         let content;
656    ///         Ok(Mod {
657    ///             mod_token: input.parse()?,
658    ///             name: input.parse()?,
659    ///             brace_token: braced!(content in input),
660    ///             items: {
661    ///                 let mut items = Vec::new();
662    ///                 while !content.is_empty() {
663    ///                     items.push(content.parse()?);
664    ///                 }
665    ///                 items
666    ///             },
667    ///         })
668    ///     }
669    /// }
670    /// ```
671    pub fn is_empty(&self) -> bool {
672        self.cursor().eof()
673    }
674
675    /// Constructs a helper for peeking at the next token in this stream and
676    /// building an error message if it is not one of a set of expected tokens.
677    ///
678    /// # Example
679    ///
680    /// ```edition2018
681    /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, Token, TypeParam};
682    /// use syn::parse::{Parse, ParseStream};
683    ///
684    /// // A generic parameter, a single one of the comma-separated elements inside
685    /// // angle brackets in:
686    /// //
687    /// //     fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
688    /// //
689    /// // On invalid input, lookahead gives us a reasonable error message.
690    /// //
691    /// //     error: expected one of: identifier, lifetime, `const`
692    /// //       |
693    /// //     5 |     fn f<!Sized>() {}
694    /// //       |          ^
695    /// enum GenericParam {
696    ///     Type(TypeParam),
697    ///     Lifetime(LifetimeDef),
698    ///     Const(ConstParam),
699    /// }
700    ///
701    /// impl Parse for GenericParam {
702    ///     fn parse(input: ParseStream) -> Result<Self> {
703    ///         let lookahead = input.lookahead1();
704    ///         if lookahead.peek(Ident) {
705    ///             input.parse().map(GenericParam::Type)
706    ///         } else if lookahead.peek(Lifetime) {
707    ///             input.parse().map(GenericParam::Lifetime)
708    ///         } else if lookahead.peek(Token![const]) {
709    ///             input.parse().map(GenericParam::Const)
710    ///         } else {
711    ///             Err(lookahead.error())
712    ///         }
713    ///     }
714    /// }
715    /// ```
716    pub fn lookahead1(&self) -> Lookahead1<'a> {
717        lookahead::new(self.scope, self.cursor())
718    }
719
720    /// Forks a parse stream so that parsing tokens out of either the original
721    /// or the fork does not advance the position of the other.
722    ///
723    /// # Performance
724    ///
725    /// Forking a parse stream is a cheap fixed amount of work and does not
726    /// involve copying token buffers. Where you might hit performance problems
727    /// is if your macro ends up parsing a large amount of content more than
728    /// once.
729    ///
730    /// ```edition2018
731    /// # use syn::{Expr, Result};
732    /// # use syn::parse::ParseStream;
733    /// #
734    /// # fn bad(input: ParseStream) -> Result<Expr> {
735    /// // Do not do this.
736    /// if input.fork().parse::<Expr>().is_ok() {
737    ///     return input.parse::<Expr>();
738    /// }
739    /// # unimplemented!()
740    /// # }
741    /// ```
742    ///
743    /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
744    /// parse stream. Only use a fork when the amount of work performed against
745    /// the fork is small and bounded.
746    ///
747    /// For a lower level but occasionally more performant way to perform
748    /// speculative parsing, consider using [`ParseStream::step`] instead.
749    ///
750    /// [`ParseStream::step`]: #method.step
751    ///
752    /// # Example
753    ///
754    /// The parse implementation shown here parses possibly restricted `pub`
755    /// visibilities.
756    ///
757    /// - `pub`
758    /// - `pub(crate)`
759    /// - `pub(self)`
760    /// - `pub(super)`
761    /// - `pub(in some::path)`
762    ///
763    /// To handle the case of visibilities inside of tuple structs, the parser
764    /// needs to distinguish parentheses that specify visibility restrictions
765    /// from parentheses that form part of a tuple type.
766    ///
767    /// ```edition2018
768    /// # struct A;
769    /// # struct B;
770    /// # struct C;
771    /// #
772    /// struct S(pub(crate) A, pub (B, C));
773    /// ```
774    ///
775    /// In this example input the first tuple struct element of `S` has
776    /// `pub(crate)` visibility while the second tuple struct element has `pub`
777    /// visibility; the parentheses around `(B, C)` are part of the type rather
778    /// than part of a visibility restriction.
779    ///
780    /// The parser uses a forked parse stream to check the first token inside of
781    /// parentheses after the `pub` keyword. This is a small bounded amount of
782    /// work performed against the forked parse stream.
783    ///
784    /// ```edition2018
785    /// use syn::{parenthesized, token, Ident, Path, Result, Token};
786    /// use syn::ext::IdentExt;
787    /// use syn::parse::{Parse, ParseStream};
788    ///
789    /// struct PubVisibility {
790    ///     pub_token: Token![pub],
791    ///     restricted: Option<Restricted>,
792    /// }
793    ///
794    /// struct Restricted {
795    ///     paren_token: token::Paren,
796    ///     in_token: Option<Token![in]>,
797    ///     path: Path,
798    /// }
799    ///
800    /// impl Parse for PubVisibility {
801    ///     fn parse(input: ParseStream) -> Result<Self> {
802    ///         let pub_token: Token![pub] = input.parse()?;
803    ///
804    ///         if input.peek(token::Paren) {
805    ///             let ahead = input.fork();
806    ///             let mut content;
807    ///             parenthesized!(content in ahead);
808    ///
809    ///             if content.peek(Token![crate])
810    ///                 || content.peek(Token![self])
811    ///                 || content.peek(Token![super])
812    ///             {
813    ///                 return Ok(PubVisibility {
814    ///                     pub_token: pub_token,
815    ///                     restricted: Some(Restricted {
816    ///                         paren_token: parenthesized!(content in input),
817    ///                         in_token: None,
818    ///                         path: Path::from(content.call(Ident::parse_any)?),
819    ///                     }),
820    ///                 });
821    ///             } else if content.peek(Token![in]) {
822    ///                 return Ok(PubVisibility {
823    ///                     pub_token: pub_token,
824    ///                     restricted: Some(Restricted {
825    ///                         paren_token: parenthesized!(content in input),
826    ///                         in_token: Some(content.parse()?),
827    ///                         path: content.call(Path::parse_mod_style)?,
828    ///                     }),
829    ///                 });
830    ///             }
831    ///         }
832    ///
833    ///         Ok(PubVisibility {
834    ///             pub_token: pub_token,
835    ///             restricted: None,
836    ///         })
837    ///     }
838    /// }
839    /// ```
840    pub fn fork(&self) -> Self {
841        ParseBuffer {
842            scope: self.scope,
843            cell: self.cell.clone(),
844            marker: PhantomData,
845            // Not the parent's unexpected. Nothing cares whether the clone
846            // parses all the way.
847            unexpected: Rc::new(Cell::new(None)),
848        }
849    }
850
851    /// Triggers an error at the current position of the parse stream.
852    ///
853    /// # Example
854    ///
855    /// ```edition2018
856    /// use syn::{Expr, Result, Token};
857    /// use syn::parse::{Parse, ParseStream};
858    ///
859    /// // Some kind of loop: `while` or `for` or `loop`.
860    /// struct Loop {
861    ///     expr: Expr,
862    /// }
863    ///
864    /// impl Parse for Loop {
865    ///     fn parse(input: ParseStream) -> Result<Self> {
866    ///         if input.peek(Token![while])
867    ///             || input.peek(Token![for])
868    ///             || input.peek(Token![loop])
869    ///         {
870    ///             Ok(Loop {
871    ///                 expr: input.parse()?,
872    ///             })
873    ///         } else {
874    ///             Err(input.error("expected some kind of loop"))
875    ///         }
876    ///     }
877    /// }
878    /// ```
879    pub fn error<T: Display>(&self, message: T) -> Error {
880        error::new_at(self.scope, self.cursor(), message)
881    }
882
883    /// Speculatively parses tokens from this parse stream, advancing the
884    /// position of this stream only if parsing succeeds.
885    ///
886    /// This is a powerful low-level API used for defining the `Parse` impls of
887    /// the basic built-in token types. It is not something that will be used
888    /// widely outside of the Syn codebase.
889    ///
890    /// # Example
891    ///
892    /// ```edition2018
893    /// use proc_macro2::TokenTree;
894    /// use syn::Result;
895    /// use syn::parse::ParseStream;
896    ///
897    /// // This function advances the stream past the next occurrence of `@`. If
898    /// // no `@` is present in the stream, the stream position is unchanged and
899    /// // an error is returned.
900    /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
901    ///     input.step(|cursor| {
902    ///         let mut rest = *cursor;
903    ///         while let Some((tt, next)) = rest.token_tree() {
904    ///             match tt {
905    ///                 TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
906    ///                     return Ok(((), next));
907    ///                 }
908    ///                 _ => rest = next,
909    ///             }
910    ///         }
911    ///         Err(cursor.error("no `@` was found after this point"))
912    ///     })
913    /// }
914    /// #
915    /// # fn remainder_after_skipping_past_next_at(
916    /// #     input: ParseStream,
917    /// # ) -> Result<proc_macro2::TokenStream> {
918    /// #     skip_past_next_at(input)?;
919    /// #     input.parse()
920    /// # }
921    /// #
922    /// # fn main() {
923    /// #     use syn::parse::Parser;
924    /// #     let remainder = remainder_after_skipping_past_next_at
925    /// #         .parse_str("a @ b c")
926    /// #         .unwrap();
927    /// #     assert_eq!(remainder.to_string(), "b c");
928    /// # }
929    /// ```
930    pub fn step<F, R>(&self, function: F) -> Result<R>
931    where
932        F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
933    {
934        // Since the user's function is required to work for any 'c, we know
935        // that the Cursor<'c> they return is either derived from the input
936        // StepCursor<'c, 'a> or from a Cursor<'static>.
937        //
938        // It would not be legal to write this function without the invariant
939        // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
940        // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
941        // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
942        // `step` on their ParseBuffer<'short> with a closure that returns
943        // Cursor<'short>, and we would wrongly write that Cursor<'short> into
944        // the Cell intended to hold Cursor<'a>.
945        //
946        // In some cases it may be necessary for R to contain a Cursor<'a>.
947        // Within Syn we solve this using `private::advance_step_cursor` which
948        // uses the existence of a StepCursor<'c, 'a> as proof that it is safe
949        // to cast from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it
950        // would be safe to expose that API as a method on StepCursor.
951        let (node, rest) = function(StepCursor {
952            scope: self.scope,
953            cursor: self.cell.get(),
954            marker: PhantomData,
955        })?;
956        self.cell.set(rest);
957        Ok(node)
958    }
959
960    /// Provides low-level access to the token representation underlying this
961    /// parse stream.
962    ///
963    /// Cursors are immutable so no operations you perform against the cursor
964    /// will affect the state of this parse stream.
965    pub fn cursor(&self) -> Cursor<'a> {
966        self.cell.get()
967    }
968
969    fn check_unexpected(&self) -> Result<()> {
970        match self.unexpected.get() {
971            Some(span) => Err(Error::new(span, "unexpected token")),
972            None => Ok(()),
973        }
974    }
975}
976
977impl<T: Parse> Parse for Box<T> {
978    fn parse(input: ParseStream) -> Result<Self> {
979        input.parse().map(Box::new)
980    }
981}
982
983impl<T: Parse + Token> Parse for Option<T> {
984    fn parse(input: ParseStream) -> Result<Self> {
985        if T::peek(input.cursor()) {
986            Ok(Some(input.parse()?))
987        } else {
988            Ok(None)
989        }
990    }
991}
992
993impl Parse for TokenStream {
994    fn parse(input: ParseStream) -> Result<Self> {
995        input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
996    }
997}
998
999impl Parse for TokenTree {
1000    fn parse(input: ParseStream) -> Result<Self> {
1001        input.step(|cursor| match cursor.token_tree() {
1002            Some((tt, rest)) => Ok((tt, rest)),
1003            None => Err(cursor.error("expected token tree")),
1004        })
1005    }
1006}
1007
1008impl Parse for Group {
1009    fn parse(input: ParseStream) -> Result<Self> {
1010        input.step(|cursor| {
1011            for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
1012                if let Some((inside, span, rest)) = cursor.group(*delim) {
1013                    let mut group = Group::new(*delim, inside.token_stream());
1014                    group.set_span(span);
1015                    return Ok((group, rest));
1016                }
1017            }
1018            Err(cursor.error("expected group token"))
1019        })
1020    }
1021}
1022
1023impl Parse for Punct {
1024    fn parse(input: ParseStream) -> Result<Self> {
1025        input.step(|cursor| match cursor.punct() {
1026            Some((punct, rest)) => Ok((punct, rest)),
1027            None => Err(cursor.error("expected punctuation token")),
1028        })
1029    }
1030}
1031
1032impl Parse for Literal {
1033    fn parse(input: ParseStream) -> Result<Self> {
1034        input.step(|cursor| match cursor.literal() {
1035            Some((literal, rest)) => Ok((literal, rest)),
1036            None => Err(cursor.error("expected literal token")),
1037        })
1038    }
1039}
1040
1041/// Parser that can parse Rust tokens into a particular syntax tree node.
1042///
1043/// Refer to the [module documentation] for details about parsing in Syn.
1044///
1045/// [module documentation]: index.html
1046///
1047/// *This trait is available if Syn is built with the `"parsing"` feature.*
1048pub trait Parser: Sized {
1049    type Output;
1050
1051    /// Parse a proc-macro2 token stream into the chosen syntax tree node.
1052    ///
1053    /// This function will check that the input is fully parsed. If there are
1054    /// any unparsed tokens at the end of the stream, an error is returned.
1055    fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1056
1057    /// Parse tokens of source code into the chosen syntax tree node.
1058    ///
1059    /// This function will check that the input is fully parsed. If there are
1060    /// any unparsed tokens at the end of the stream, an error is returned.
1061    ///
1062    /// *This method is available if Syn is built with both the `"parsing"` and
1063    /// `"proc-macro"` features.*
1064    #[cfg(all(
1065        not(all(target_arch = "wasm32", target_os = "unknown")),
1066        feature = "proc-macro"
1067    ))]
1068    fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1069        self.parse2(proc_macro2::TokenStream::from(tokens))
1070    }
1071
1072    /// Parse a string of Rust code into the chosen syntax tree node.
1073    ///
1074    /// This function will check that the input is fully parsed. If there are
1075    /// any unparsed tokens at the end of the string, an error is returned.
1076    ///
1077    /// # Hygiene
1078    ///
1079    /// Every span in the resulting syntax tree will be set to resolve at the
1080    /// macro call site.
1081    fn parse_str(self, s: &str) -> Result<Self::Output> {
1082        self.parse2(proc_macro2::TokenStream::from_str(s)?)
1083    }
1084}
1085
1086fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1087    let scope = Span::call_site();
1088    let cursor = tokens.begin();
1089    let unexpected = Rc::new(Cell::new(None));
1090    private::new_parse_buffer(scope, cursor, unexpected)
1091}
1092
1093impl<F, T> Parser for F
1094where
1095    F: FnOnce(ParseStream) -> Result<T>,
1096{
1097    type Output = T;
1098
1099    fn parse2(self, tokens: TokenStream) -> Result<T> {
1100        let buf = TokenBuffer::new2(tokens);
1101        let state = tokens_to_parse_buffer(&buf);
1102        let node = self(&state)?;
1103        state.check_unexpected()?;
1104        if state.is_empty() {
1105            Ok(node)
1106        } else {
1107            Err(state.error("unexpected token"))
1108        }
1109    }
1110}