blob: 1b7e947bb2511735455a05ec8eb5c726d38e9e1b [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 Tolnay95989db2019-01-01 15:05:57 -050028//! ```edition2018
David Tolnaya1c98072018-09-06 08:58:10 -070029//! extern crate proc_macro;
30//!
David Tolnay88d9f622018-09-01 17:52:33 -070031//! use proc_macro::TokenStream;
David Tolnayfd5b1172018-12-31 17:54:36 -050032//! use syn::{braced, parse_macro_input, token, Field, Ident, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -080033//! use syn::parse::{Parse, ParseStream};
David Tolnay43984452018-09-01 17:43:56 -070034//! use syn::punctuated::Punctuated;
35//!
36//! enum Item {
37//! Struct(ItemStruct),
38//! Enum(ItemEnum),
39//! }
40//!
41//! struct ItemStruct {
42//! struct_token: Token![struct],
43//! ident: Ident,
44//! brace_token: token::Brace,
45//! fields: Punctuated<Field, Token![,]>,
46//! }
47//! #
48//! # enum ItemEnum {}
49//!
50//! impl Parse for Item {
51//! fn parse(input: ParseStream) -> Result<Self> {
52//! let lookahead = input.lookahead1();
53//! if lookahead.peek(Token![struct]) {
54//! input.parse().map(Item::Struct)
55//! } else if lookahead.peek(Token![enum]) {
56//! input.parse().map(Item::Enum)
57//! } else {
58//! Err(lookahead.error())
59//! }
60//! }
61//! }
62//!
63//! impl Parse for ItemStruct {
64//! fn parse(input: ParseStream) -> Result<Self> {
65//! let content;
66//! Ok(ItemStruct {
67//! struct_token: input.parse()?,
68//! ident: input.parse()?,
69//! brace_token: braced!(content in input),
70//! fields: content.parse_terminated(Field::parse_named)?,
71//! })
72//! }
73//! }
74//! #
75//! # impl Parse for ItemEnum {
76//! # fn parse(input: ParseStream) -> Result<Self> {
77//! # unimplemented!()
78//! # }
79//! # }
David Tolnay88d9f622018-09-01 17:52:33 -070080//!
81//! # const IGNORE: &str = stringify! {
82//! #[proc_macro]
83//! # };
84//! pub fn my_macro(tokens: TokenStream) -> TokenStream {
85//! let input = parse_macro_input!(tokens as Item);
86//!
87//! /* ... */
88//! # "".parse().unwrap()
89//! }
David Tolnay43984452018-09-01 17:43:56 -070090//! ```
91//!
92//! # The `syn::parse*` functions
David Tolnay80a914f2018-08-30 23:49:53 -070093//!
94//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
95//! as an entry point for parsing syntax tree nodes that can be parsed in an
96//! obvious default way. These functions can return any syntax tree node that
David Tolnay8aacee12018-08-31 09:15:15 -070097//! implements the [`Parse`] trait, which includes most types in Syn.
David Tolnay80a914f2018-08-30 23:49:53 -070098//!
99//! [`syn::parse`]: ../fn.parse.html
100//! [`syn::parse2`]: ../fn.parse2.html
101//! [`syn::parse_str`]: ../fn.parse_str.html
David Tolnay8aacee12018-08-31 09:15:15 -0700102//! [`Parse`]: trait.Parse.html
David Tolnay80a914f2018-08-30 23:49:53 -0700103//!
David Tolnay95989db2019-01-01 15:05:57 -0500104//! ```edition2018
David Tolnay80a914f2018-08-30 23:49:53 -0700105//! use syn::Type;
106//!
David Tolnay67fea042018-11-24 14:50:20 -0800107//! # fn run_parser() -> syn::Result<()> {
David Tolnay80a914f2018-08-30 23:49:53 -0700108//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
109//! # Ok(())
110//! # }
111//! #
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//!
David Tolnay43984452018-09-01 17:43:56 -0700121//! # The `Parser` trait
David Tolnay80a914f2018-08-30 23:49:53 -0700122//!
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//!
David Tolnaye0c51762018-08-31 11:05:22 -0700132//! The `Parse` trait is not implemented in these cases because there is no good
David Tolnay80a914f2018-08-30 23:49:53 -0700133//! behavior to consider the default.
134//!
David Tolnay95989db2019-01-01 15:05:57 -0500135//! ```edition2018,compile_fail
David Tolnay2b45fd42018-11-06 21:16:55 -0800136//! # extern crate proc_macro;
David Tolnay2b45fd42018-11-06 21:16:55 -0800137//! #
David Tolnay2b45fd42018-11-06 21:16:55 -0800138//! # use syn::punctuated::Punctuated;
David Tolnay67fea042018-11-24 14:50:20 -0800139//! # use syn::{PathSegment, Result, Token};
David Tolnay2b45fd42018-11-06 21:16:55 -0800140//! #
141//! # fn f(tokens: proc_macro::TokenStream) -> Result<()> {
142//! #
David Tolnay80a914f2018-08-30 23:49:53 -0700143//! // 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)?;
David Tolnay2b45fd42018-11-06 21:16:55 -0800146//! #
147//! # Ok(())
148//! # }
David Tolnay80a914f2018-08-30 23:49:53 -0700149//! ```
150//!
151//! In these cases the types provide a choice of parser functions rather than a
David Tolnaye0c51762018-08-31 11:05:22 -0700152//! single `Parse` implementation, and those parser functions can be invoked
David Tolnay80a914f2018-08-30 23:49:53 -0700153//! through the [`Parser`] trait.
154//!
155//! [`Parser`]: trait.Parser.html
156//!
David Tolnay95989db2019-01-01 15:05:57 -0500157//! ```edition2018
David Tolnay66a23602018-12-31 17:59:21 -0500158//! extern crate proc_macro;
159//!
160//! use proc_macro::TokenStream;
David Tolnay3e3f7752018-08-31 09:33:59 -0700161//! use syn::parse::Parser;
David Tolnay80a914f2018-08-30 23:49:53 -0700162//! use syn::punctuated::Punctuated;
David Tolnay66a23602018-12-31 17:59:21 -0500163//! use syn::{Attribute, Expr, PathSegment, Result, Token};
David Tolnay80a914f2018-08-30 23:49:53 -0700164//!
David Tolnay66a23602018-12-31 17:59:21 -0500165//! 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)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700171//!
David Tolnay66a23602018-12-31 17:59:21 -0500172//! // 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)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700177//!
David Tolnay66a23602018-12-31 17:59:21 -0500178//! // 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//! }
David Tolnay80a914f2018-08-30 23:49:53 -0700185//! ```
186//!
David Tolnaye0c51762018-08-31 11:05:22 -0700187//! ---
David Tolnay80a914f2018-08-30 23:49:53 -0700188//!
189//! *This module is available if Syn is built with the `"parsing"` feature.*
David Tolnay18c754c2018-08-21 23:26:58 -0400190
191use std::cell::Cell;
Diggory Hardy1c522e12018-11-02 10:10:02 +0000192use std::fmt::{self, Debug, Display};
David Tolnay18c754c2018-08-21 23:26:58 -0400193use std::marker::PhantomData;
194use std::mem;
195use std::ops::Deref;
David Tolnayeafc8052018-08-25 16:33:53 -0400196use std::rc::Rc;
David Tolnay80a914f2018-08-30 23:49:53 -0700197use std::str::FromStr;
David Tolnayeafc8052018-08-25 16:33:53 -0400198
David Tolnay80a914f2018-08-30 23:49:53 -0700199#[cfg(all(
200 not(all(target_arch = "wasm32", target_os = "unknown")),
201 feature = "proc-macro"
202))]
203use proc_macro;
David Tolnayf07b3342018-09-01 11:58:11 -0700204use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
David Tolnay18c754c2018-08-21 23:26:58 -0400205
David Tolnay80a914f2018-08-30 23:49:53 -0700206use buffer::{Cursor, TokenBuffer};
David Tolnayb6254182018-08-25 08:44:54 -0400207use error;
David Tolnay94f06632018-08-31 10:17:17 -0700208use lookahead;
209use private;
David Tolnay577d0332018-08-25 21:45:24 -0400210use punctuated::Punctuated;
David Tolnay4fb71232018-08-25 23:14:50 -0400211use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -0400212
David Tolnayb6254182018-08-25 08:44:54 -0400213pub use error::{Error, Result};
214pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -0400215
216/// Parsing interface implemented by all types that can be parsed in a default
217/// way from a token stream.
218pub trait Parse: Sized {
219 fn parse(input: ParseStream) -> Result<Self>;
220}
221
222/// Input to a Syn parser function.
David Tolnaya0daa482018-09-01 02:09:40 -0700223///
224/// See the methods of this type under the documentation of [`ParseBuffer`]. For
225/// an overview of parsing in Syn, refer to the [module documentation].
226///
227/// [module documentation]: index.html
David Tolnay18c754c2018-08-21 23:26:58 -0400228pub type ParseStream<'a> = &'a ParseBuffer<'a>;
229
230/// Cursor position within a buffered token stream.
David Tolnay20d29a12018-09-01 15:15:33 -0700231///
232/// This type is more commonly used through the type alias [`ParseStream`] which
233/// is an alias for `&ParseBuffer`.
234///
235/// `ParseStream` is the input type for all parser functions in Syn. They have
236/// the signature `fn(ParseStream) -> Result<T>`.
David Tolnay028a7d72018-12-31 17:11:02 -0500237///
238/// ## Calling a parser function
239///
240/// There is no public way to construct a `ParseBuffer`. Instead, if you are
241/// looking to invoke a parser function that requires `ParseStream` as input,
242/// you will need to go through one of the public parsing entry points.
243///
244/// - The [`parse_macro_input!`] macro if parsing input of a procedural macro;
245/// - One of [the `syn::parse*` functions][syn-parse]; or
246/// - A method of the [`Parser`] trait.
247///
248/// [`parse_macro_input!`]: ../macro.parse_macro_input.html
249/// [syn-parse]: index.html#the-synparse-functions
David Tolnay18c754c2018-08-21 23:26:58 -0400250pub struct ParseBuffer<'a> {
251 scope: Span,
David Tolnay5d7f2252018-09-02 08:21:40 -0700252 // 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.
David Tolnay18c754c2018-08-21 23:26:58 -0400263 cell: Cell<Cursor<'static>>,
264 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400265 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 }
David Tolnay18c754c2018-08-21 23:26:58 -0400274}
275
Diggory Hardy1c522e12018-11-02 10:10:02 +0000276impl<'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
David Tolnay642832f2018-09-01 13:08:10 -0700288/// 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
David Tolnay9bd34392018-09-01 13:19:53 -0700293///
294/// # Example
295///
David Tolnay95989db2019-01-01 15:05:57 -0500296/// ```edition2018
David Tolnay9bd34392018-09-01 13:19:53 -0700297/// # extern crate proc_macro2;
David Tolnay9bd34392018-09-01 13:19:53 -0700298/// #
299/// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800300/// use syn::Result;
301/// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700302///
303/// // This function advances the stream past the next occurrence of `@`. If
304/// // no `@` is present in the stream, the stream position is unchanged and
305/// // an error is returned.
306/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
307/// input.step(|cursor| {
308/// let mut rest = *cursor;
Sharad Chande1df40a2018-09-08 15:25:52 +0545309/// while let Some((tt, next)) = rest.token_tree() {
David Tolnay9bd34392018-09-01 13:19:53 -0700310/// match tt {
311/// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
312/// return Ok(((), next));
313/// }
314/// _ => rest = next,
315/// }
316/// }
317/// Err(cursor.error("no `@` was found after this point"))
318/// })
319/// }
320/// #
David Tolnaydb312582018-11-06 20:42:05 -0800321/// # fn remainder_after_skipping_past_next_at(
322/// # input: ParseStream,
323/// # ) -> Result<proc_macro2::TokenStream> {
324/// # skip_past_next_at(input)?;
325/// # input.parse()
326/// # }
327/// #
328/// # fn main() {
329/// # use syn::parse::Parser;
330/// # let remainder = remainder_after_skipping_past_next_at
331/// # .parse_str("a @ b c")
332/// # .unwrap();
333/// # assert_eq!(remainder.to_string(), "b c");
334/// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700335/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400336#[derive(Copy, Clone)]
337pub struct StepCursor<'c, 'a> {
338 scope: Span,
David Tolnay56924f42018-09-02 08:24:58 -0700339 // This field is covariant in 'c.
David Tolnay18c754c2018-08-21 23:26:58 -0400340 cursor: Cursor<'c>,
David Tolnay56924f42018-09-02 08:24:58 -0700341 // This field is contravariant in 'c. Together these make StepCursor
342 // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
343 // different lifetime but can upcast into a StepCursor with a shorter
344 // lifetime 'a.
345 //
346 // As long as we only ever construct a StepCursor for which 'c outlives 'a,
347 // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
348 // outlives 'a.
David Tolnay18c754c2018-08-21 23:26:58 -0400349 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
350}
351
352impl<'c, 'a> Deref for StepCursor<'c, 'a> {
353 type Target = Cursor<'c>;
354
355 fn deref(&self) -> &Self::Target {
356 &self.cursor
357 }
358}
359
360impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700361 /// Triggers an error at the current position of the parse stream.
362 ///
363 /// The `ParseStream::step` invocation will return this same error without
364 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400365 pub fn error<T: Display>(self, message: T) -> Error {
366 error::new_at(self.scope, self.cursor, message)
367 }
368}
369
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700370impl private {
371 pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
David Tolnay56924f42018-09-02 08:24:58 -0700372 // Refer to the comments within the StepCursor definition. We use the
373 // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
374 // Cursor is covariant in its lifetime parameter so we can cast a
375 // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700376 let _ = proof;
377 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
378 }
379}
380
David Tolnay66cb0c42018-08-31 09:01:30 -0700381fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700382 input
383 .step(|cursor| {
384 if let Some((_lifetime, rest)) = cursor.lifetime() {
385 Ok((true, rest))
386 } else if let Some((_token, rest)) = cursor.token_tree() {
387 Ok((true, rest))
388 } else {
389 Ok((false, *cursor))
390 }
David Tolnayfb84fc02018-10-02 21:01:30 -0700391 })
392 .unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700393}
394
David Tolnay10951d52018-08-31 10:27:39 -0700395impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700396 pub fn new_parse_buffer(
397 scope: Span,
398 cursor: Cursor,
399 unexpected: Rc<Cell<Option<Span>>>,
400 ) -> ParseBuffer {
David Tolnay18c754c2018-08-21 23:26:58 -0400401 ParseBuffer {
402 scope: scope,
David Tolnay5d7f2252018-09-02 08:21:40 -0700403 // See comment on `cell` in the struct definition.
404 cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
David Tolnay18c754c2018-08-21 23:26:58 -0400405 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400406 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400407 }
408 }
409
David Tolnay94f06632018-08-31 10:17:17 -0700410 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
411 buffer.unexpected.clone()
412 }
413}
414
415impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700416 /// Parses a syntax tree node of type `T`, advancing the position of our
417 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400418 pub fn parse<T: Parse>(&self) -> Result<T> {
419 T::parse(self)
420 }
421
David Tolnay725e1c62018-09-01 12:07:25 -0700422 /// Calls the given parser function to parse a syntax tree node of type `T`
423 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700424 ///
425 /// # Example
426 ///
427 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
428 /// zero or more outer attributes.
429 ///
430 /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
431 ///
David Tolnay95989db2019-01-01 15:05:57 -0500432 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500433 /// use syn::{Attribute, Ident, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800434 /// use syn::parse::{Parse, ParseStream};
David Tolnay21ce84c2018-09-01 15:37:51 -0700435 ///
436 /// // Parses a unit struct with attributes.
437 /// //
438 /// // #[path = "s.tmpl"]
439 /// // struct S;
440 /// struct UnitStruct {
441 /// attrs: Vec<Attribute>,
442 /// struct_token: Token![struct],
443 /// name: Ident,
444 /// semi_token: Token![;],
445 /// }
446 ///
447 /// impl Parse for UnitStruct {
448 /// fn parse(input: ParseStream) -> Result<Self> {
449 /// Ok(UnitStruct {
450 /// attrs: input.call(Attribute::parse_outer)?,
451 /// struct_token: input.parse()?,
452 /// name: input.parse()?,
453 /// semi_token: input.parse()?,
454 /// })
455 /// }
456 /// }
David Tolnay21ce84c2018-09-01 15:37:51 -0700457 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400458 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
459 function(self)
460 }
461
David Tolnay725e1c62018-09-01 12:07:25 -0700462 /// Looks at the next token in the parse stream to determine whether it
463 /// matches the requested type of token.
464 ///
465 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700466 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700467 /// # Syntax
468 ///
469 /// Note that this method does not use turbofish syntax. Pass the peek type
470 /// inside of parentheses.
471 ///
472 /// - `input.peek(Token![struct])`
473 /// - `input.peek(Token![==])`
474 /// - `input.peek(Ident)`
475 /// - `input.peek(Lifetime)`
476 /// - `input.peek(token::Brace)`
477 ///
David Tolnayddebc3e2018-09-01 16:29:20 -0700478 /// # Example
479 ///
480 /// In this example we finish parsing the list of supertraits when the next
481 /// token in the input is either `where` or an opening curly brace.
482 ///
David Tolnay95989db2019-01-01 15:05:57 -0500483 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500484 /// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
David Tolnay67fea042018-11-24 14:50:20 -0800485 /// use syn::parse::{Parse, ParseStream};
David Tolnayddebc3e2018-09-01 16:29:20 -0700486 /// use syn::punctuated::Punctuated;
487 ///
488 /// // Parses a trait definition containing no associated items.
489 /// //
490 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
491 /// struct MarkerTrait {
492 /// trait_token: Token![trait],
493 /// ident: Ident,
494 /// generics: Generics,
495 /// colon_token: Option<Token![:]>,
496 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
497 /// brace_token: token::Brace,
498 /// }
499 ///
500 /// impl Parse for MarkerTrait {
501 /// fn parse(input: ParseStream) -> Result<Self> {
502 /// let trait_token: Token![trait] = input.parse()?;
503 /// let ident: Ident = input.parse()?;
504 /// let mut generics: Generics = input.parse()?;
505 /// let colon_token: Option<Token![:]> = input.parse()?;
506 ///
507 /// let mut supertraits = Punctuated::new();
508 /// if colon_token.is_some() {
509 /// loop {
510 /// supertraits.push_value(input.parse()?);
511 /// if input.peek(Token![where]) || input.peek(token::Brace) {
512 /// break;
513 /// }
514 /// supertraits.push_punct(input.parse()?);
515 /// }
516 /// }
517 ///
518 /// generics.where_clause = input.parse()?;
519 /// let content;
520 /// let empty_brace_token = braced!(content in input);
521 ///
522 /// Ok(MarkerTrait {
523 /// trait_token: trait_token,
524 /// ident: ident,
525 /// generics: generics,
526 /// colon_token: colon_token,
527 /// supertraits: supertraits,
528 /// brace_token: empty_brace_token,
529 /// })
530 /// }
531 /// }
David Tolnayddebc3e2018-09-01 16:29:20 -0700532 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400533 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700534 let _ = token;
535 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400536 }
537
David Tolnay725e1c62018-09-01 12:07:25 -0700538 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700539 ///
540 /// This is commonly useful as a way to implement contextual keywords.
541 ///
542 /// # Example
543 ///
544 /// This example needs to use `peek2` because the symbol `union` is not a
545 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
546 /// the very next token is `union`, because someone is free to write a `mod
547 /// union` and a macro invocation that looks like `union::some_macro! { ...
548 /// }`. In other words `union` is a contextual keyword.
549 ///
David Tolnay95989db2019-01-01 15:05:57 -0500550 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500551 /// use syn::{Ident, ItemUnion, Macro, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800552 /// use syn::parse::{Parse, ParseStream};
David Tolnaye334b872018-09-01 16:38:10 -0700553 ///
554 /// // Parses either a union or a macro invocation.
555 /// enum UnionOrMacro {
556 /// // union MaybeUninit<T> { uninit: (), value: T }
557 /// Union(ItemUnion),
558 /// // lazy_static! { ... }
559 /// Macro(Macro),
560 /// }
561 ///
562 /// impl Parse for UnionOrMacro {
563 /// fn parse(input: ParseStream) -> Result<Self> {
564 /// if input.peek(Token![union]) && input.peek2(Ident) {
565 /// input.parse().map(UnionOrMacro::Union)
566 /// } else {
567 /// input.parse().map(UnionOrMacro::Macro)
568 /// }
569 /// }
570 /// }
David Tolnaye334b872018-09-01 16:38:10 -0700571 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400572 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400573 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700574 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400575 }
576
David Tolnay725e1c62018-09-01 12:07:25 -0700577 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400578 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400579 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700580 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400581 }
582
David Tolnay725e1c62018-09-01 12:07:25 -0700583 /// Parses zero or more occurrences of `T` separated by punctuation of type
584 /// `P`, with optional trailing punctuation.
585 ///
586 /// Parsing continues until the end of this parse stream. The entire content
587 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700588 ///
589 /// # Example
590 ///
David Tolnay95989db2019-01-01 15:05:57 -0500591 /// ```edition2018
David Tolnay0abe65b2018-09-01 14:31:43 -0700592 /// # extern crate quote;
David Tolnayfd5b1172018-12-31 17:54:36 -0500593 /// # use quote::quote;
David Tolnay0abe65b2018-09-01 14:31:43 -0700594 /// #
David Tolnayfd5b1172018-12-31 17:54:36 -0500595 /// use syn::{parenthesized, token, Ident, Result, Token, Type};
David Tolnay67fea042018-11-24 14:50:20 -0800596 /// use syn::parse::{Parse, ParseStream};
David Tolnay0abe65b2018-09-01 14:31:43 -0700597 /// use syn::punctuated::Punctuated;
598 ///
599 /// // Parse a simplified tuple struct syntax like:
600 /// //
601 /// // struct S(A, B);
602 /// struct TupleStruct {
603 /// struct_token: Token![struct],
604 /// ident: Ident,
605 /// paren_token: token::Paren,
606 /// fields: Punctuated<Type, Token![,]>,
607 /// semi_token: Token![;],
608 /// }
609 ///
610 /// impl Parse for TupleStruct {
611 /// fn parse(input: ParseStream) -> Result<Self> {
612 /// let content;
613 /// Ok(TupleStruct {
614 /// struct_token: input.parse()?,
615 /// ident: input.parse()?,
616 /// paren_token: parenthesized!(content in input),
617 /// fields: content.parse_terminated(Type::parse)?,
618 /// semi_token: input.parse()?,
619 /// })
620 /// }
621 /// }
622 /// #
623 /// # fn main() {
624 /// # let input = quote! {
625 /// # struct S(A, B);
626 /// # };
627 /// # syn::parse2::<TupleStruct>(input).unwrap();
628 /// # }
629 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400630 pub fn parse_terminated<T, P: Parse>(
631 &self,
632 parser: fn(ParseStream) -> Result<T>,
633 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700634 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400635 }
636
David Tolnay725e1c62018-09-01 12:07:25 -0700637 /// Returns whether there are tokens remaining in this stream.
638 ///
639 /// This method returns true at the end of the content of a set of
640 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700641 ///
642 /// # Example
643 ///
David Tolnay95989db2019-01-01 15:05:57 -0500644 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500645 /// use syn::{braced, token, Ident, Item, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800646 /// use syn::parse::{Parse, ParseStream};
David Tolnaycce6b5f2018-09-01 14:24:46 -0700647 ///
648 /// // Parses a Rust `mod m { ... }` containing zero or more items.
649 /// struct Mod {
650 /// mod_token: Token![mod],
651 /// name: Ident,
652 /// brace_token: token::Brace,
653 /// items: Vec<Item>,
654 /// }
655 ///
656 /// impl Parse for Mod {
657 /// fn parse(input: ParseStream) -> Result<Self> {
658 /// let content;
659 /// Ok(Mod {
660 /// mod_token: input.parse()?,
661 /// name: input.parse()?,
662 /// brace_token: braced!(content in input),
663 /// items: {
664 /// let mut items = Vec::new();
665 /// while !content.is_empty() {
666 /// items.push(content.parse()?);
667 /// }
668 /// items
669 /// },
670 /// })
671 /// }
672 /// }
David Tolnayf2b78602018-11-06 20:42:37 -0800673 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700674 pub fn is_empty(&self) -> bool {
675 self.cursor().eof()
676 }
677
David Tolnay725e1c62018-09-01 12:07:25 -0700678 /// Constructs a helper for peeking at the next token in this stream and
679 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700680 ///
681 /// # Example
682 ///
David Tolnay95989db2019-01-01 15:05:57 -0500683 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500684 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, Token, TypeParam};
David Tolnay67fea042018-11-24 14:50:20 -0800685 /// use syn::parse::{Parse, ParseStream};
David Tolnay2c77e772018-09-01 14:18:46 -0700686 ///
687 /// // A generic parameter, a single one of the comma-separated elements inside
688 /// // angle brackets in:
689 /// //
690 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
691 /// //
692 /// // On invalid input, lookahead gives us a reasonable error message.
693 /// //
694 /// // error: expected one of: identifier, lifetime, `const`
695 /// // |
696 /// // 5 | fn f<!Sized>() {}
697 /// // | ^
698 /// enum GenericParam {
699 /// Type(TypeParam),
700 /// Lifetime(LifetimeDef),
701 /// Const(ConstParam),
702 /// }
703 ///
704 /// impl Parse for GenericParam {
705 /// fn parse(input: ParseStream) -> Result<Self> {
706 /// let lookahead = input.lookahead1();
707 /// if lookahead.peek(Ident) {
708 /// input.parse().map(GenericParam::Type)
709 /// } else if lookahead.peek(Lifetime) {
710 /// input.parse().map(GenericParam::Lifetime)
711 /// } else if lookahead.peek(Token![const]) {
712 /// input.parse().map(GenericParam::Const)
713 /// } else {
714 /// Err(lookahead.error())
715 /// }
716 /// }
717 /// }
David Tolnay2c77e772018-09-01 14:18:46 -0700718 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700719 pub fn lookahead1(&self) -> Lookahead1<'a> {
720 lookahead::new(self.scope, self.cursor())
721 }
722
David Tolnay725e1c62018-09-01 12:07:25 -0700723 /// Forks a parse stream so that parsing tokens out of either the original
724 /// or the fork does not advance the position of the other.
725 ///
726 /// # Performance
727 ///
728 /// Forking a parse stream is a cheap fixed amount of work and does not
729 /// involve copying token buffers. Where you might hit performance problems
730 /// is if your macro ends up parsing a large amount of content more than
731 /// once.
732 ///
David Tolnay95989db2019-01-01 15:05:57 -0500733 /// ```edition2018
David Tolnay67fea042018-11-24 14:50:20 -0800734 /// # use syn::{Expr, Result};
735 /// # use syn::parse::ParseStream;
David Tolnay725e1c62018-09-01 12:07:25 -0700736 /// #
737 /// # fn bad(input: ParseStream) -> Result<Expr> {
738 /// // Do not do this.
739 /// if input.fork().parse::<Expr>().is_ok() {
740 /// return input.parse::<Expr>();
741 /// }
742 /// # unimplemented!()
743 /// # }
744 /// ```
745 ///
746 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
747 /// parse stream. Only use a fork when the amount of work performed against
748 /// the fork is small and bounded.
749 ///
David Tolnayec149b02018-09-01 14:17:28 -0700750 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700751 /// speculative parsing, consider using [`ParseStream::step`] instead.
752 ///
753 /// [`ParseStream::step`]: #method.step
David Tolnayec149b02018-09-01 14:17:28 -0700754 ///
755 /// # Example
756 ///
757 /// The parse implementation shown here parses possibly restricted `pub`
758 /// visibilities.
759 ///
760 /// - `pub`
761 /// - `pub(crate)`
762 /// - `pub(self)`
763 /// - `pub(super)`
764 /// - `pub(in some::path)`
765 ///
766 /// To handle the case of visibilities inside of tuple structs, the parser
767 /// needs to distinguish parentheses that specify visibility restrictions
768 /// from parentheses that form part of a tuple type.
769 ///
David Tolnay95989db2019-01-01 15:05:57 -0500770 /// ```edition2018
David Tolnayec149b02018-09-01 14:17:28 -0700771 /// # struct A;
772 /// # struct B;
773 /// # struct C;
774 /// #
775 /// struct S(pub(crate) A, pub (B, C));
776 /// ```
777 ///
778 /// In this example input the first tuple struct element of `S` has
779 /// `pub(crate)` visibility while the second tuple struct element has `pub`
780 /// visibility; the parentheses around `(B, C)` are part of the type rather
781 /// than part of a visibility restriction.
782 ///
783 /// The parser uses a forked parse stream to check the first token inside of
784 /// parentheses after the `pub` keyword. This is a small bounded amount of
785 /// work performed against the forked parse stream.
786 ///
David Tolnay95989db2019-01-01 15:05:57 -0500787 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500788 /// use syn::{parenthesized, token, Ident, Path, Result, Token};
David Tolnayec149b02018-09-01 14:17:28 -0700789 /// use syn::ext::IdentExt;
David Tolnay67fea042018-11-24 14:50:20 -0800790 /// use syn::parse::{Parse, ParseStream};
David Tolnayec149b02018-09-01 14:17:28 -0700791 ///
792 /// struct PubVisibility {
793 /// pub_token: Token![pub],
794 /// restricted: Option<Restricted>,
795 /// }
796 ///
797 /// struct Restricted {
798 /// paren_token: token::Paren,
799 /// in_token: Option<Token![in]>,
800 /// path: Path,
801 /// }
802 ///
803 /// impl Parse for PubVisibility {
804 /// fn parse(input: ParseStream) -> Result<Self> {
805 /// let pub_token: Token![pub] = input.parse()?;
806 ///
807 /// if input.peek(token::Paren) {
808 /// let ahead = input.fork();
809 /// let mut content;
810 /// parenthesized!(content in ahead);
811 ///
812 /// if content.peek(Token![crate])
813 /// || content.peek(Token![self])
814 /// || content.peek(Token![super])
815 /// {
816 /// return Ok(PubVisibility {
817 /// pub_token: pub_token,
818 /// restricted: Some(Restricted {
819 /// paren_token: parenthesized!(content in input),
820 /// in_token: None,
821 /// path: Path::from(content.call(Ident::parse_any)?),
822 /// }),
823 /// });
824 /// } else if content.peek(Token![in]) {
825 /// return Ok(PubVisibility {
826 /// pub_token: pub_token,
827 /// restricted: Some(Restricted {
828 /// paren_token: parenthesized!(content in input),
829 /// in_token: Some(content.parse()?),
830 /// path: content.call(Path::parse_mod_style)?,
831 /// }),
832 /// });
833 /// }
834 /// }
835 ///
836 /// Ok(PubVisibility {
837 /// pub_token: pub_token,
838 /// restricted: None,
839 /// })
840 /// }
841 /// }
David Tolnayec149b02018-09-01 14:17:28 -0700842 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400843 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400844 ParseBuffer {
845 scope: self.scope,
846 cell: self.cell.clone(),
847 marker: PhantomData,
848 // Not the parent's unexpected. Nothing cares whether the clone
849 // parses all the way.
850 unexpected: Rc::new(Cell::new(None)),
851 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400852 }
853
David Tolnay725e1c62018-09-01 12:07:25 -0700854 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700855 ///
856 /// # Example
857 ///
David Tolnay95989db2019-01-01 15:05:57 -0500858 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -0500859 /// use syn::{Expr, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -0800860 /// use syn::parse::{Parse, ParseStream};
David Tolnay23fce0b2018-09-01 13:50:31 -0700861 ///
862 /// // Some kind of loop: `while` or `for` or `loop`.
863 /// struct Loop {
864 /// expr: Expr,
865 /// }
866 ///
867 /// impl Parse for Loop {
868 /// fn parse(input: ParseStream) -> Result<Self> {
869 /// if input.peek(Token![while])
870 /// || input.peek(Token![for])
871 /// || input.peek(Token![loop])
872 /// {
873 /// Ok(Loop {
874 /// expr: input.parse()?,
875 /// })
876 /// } else {
877 /// Err(input.error("expected some kind of loop"))
878 /// }
879 /// }
880 /// }
881 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400882 pub fn error<T: Display>(&self, message: T) -> Error {
883 error::new_at(self.scope, self.cursor(), message)
884 }
885
David Tolnay725e1c62018-09-01 12:07:25 -0700886 /// Speculatively parses tokens from this parse stream, advancing the
887 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700888 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700889 /// This is a powerful low-level API used for defining the `Parse` impls of
890 /// the basic built-in token types. It is not something that will be used
891 /// widely outside of the Syn codebase.
892 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700893 /// # Example
894 ///
David Tolnay95989db2019-01-01 15:05:57 -0500895 /// ```edition2018
David Tolnay9bd34392018-09-01 13:19:53 -0700896 /// # extern crate proc_macro2;
David Tolnay9bd34392018-09-01 13:19:53 -0700897 /// #
898 /// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800899 /// use syn::Result;
900 /// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700901 ///
902 /// // This function advances the stream past the next occurrence of `@`. If
903 /// // no `@` is present in the stream, the stream position is unchanged and
904 /// // an error is returned.
905 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
906 /// input.step(|cursor| {
907 /// let mut rest = *cursor;
David Tolnaydb312582018-11-06 20:42:05 -0800908 /// while let Some((tt, next)) = rest.token_tree() {
David Tolnay9bd34392018-09-01 13:19:53 -0700909 /// match tt {
910 /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
911 /// return Ok(((), next));
912 /// }
913 /// _ => rest = next,
914 /// }
915 /// }
916 /// Err(cursor.error("no `@` was found after this point"))
917 /// })
918 /// }
919 /// #
David Tolnaydb312582018-11-06 20:42:05 -0800920 /// # fn remainder_after_skipping_past_next_at(
921 /// # input: ParseStream,
922 /// # ) -> Result<proc_macro2::TokenStream> {
923 /// # skip_past_next_at(input)?;
924 /// # input.parse()
925 /// # }
926 /// #
927 /// # fn main() {
928 /// # use syn::parse::Parser;
929 /// # let remainder = remainder_after_skipping_past_next_at
930 /// # .parse_str("a @ b c")
931 /// # .unwrap();
932 /// # assert_eq!(remainder.to_string(), "b c");
933 /// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700934 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700935 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400936 where
937 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
938 {
David Tolnayc142b092018-09-02 08:52:52 -0700939 // Since the user's function is required to work for any 'c, we know
940 // that the Cursor<'c> they return is either derived from the input
941 // StepCursor<'c, 'a> or from a Cursor<'static>.
942 //
943 // It would not be legal to write this function without the invariant
944 // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
945 // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
946 // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
947 // `step` on their ParseBuffer<'short> with a closure that returns
948 // Cursor<'short>, and we would wrongly write that Cursor<'short> into
949 // the Cell intended to hold Cursor<'a>.
950 //
951 // In some cases it may be necessary for R to contain a Cursor<'a>.
952 // Within Syn we solve this using `private::advance_step_cursor` which
953 // uses the existence of a StepCursor<'c, 'a> as proof that it is safe
954 // to cast from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it
955 // would be safe to expose that API as a method on StepCursor.
David Tolnay6b65f852018-09-01 11:56:25 -0700956 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -0400957 scope: self.scope,
958 cursor: self.cell.get(),
959 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700960 })?;
961 self.cell.set(rest);
962 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -0400963 }
David Tolnayeafc8052018-08-25 16:33:53 -0400964
David Tolnay725e1c62018-09-01 12:07:25 -0700965 /// Provides low-level access to the token representation underlying this
966 /// parse stream.
967 ///
968 /// Cursors are immutable so no operations you perform against the cursor
969 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -0700970 pub fn cursor(&self) -> Cursor<'a> {
971 self.cell.get()
972 }
973
David Tolnay94f06632018-08-31 10:17:17 -0700974 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -0400975 match self.unexpected.get() {
976 Some(span) => Err(Error::new(span, "unexpected token")),
977 None => Ok(()),
978 }
979 }
David Tolnay18c754c2018-08-21 23:26:58 -0400980}
981
David Tolnaya7d69fc2018-08-26 13:30:24 -0400982impl<T: Parse> Parse for Box<T> {
983 fn parse(input: ParseStream) -> Result<Self> {
984 input.parse().map(Box::new)
985 }
986}
987
David Tolnay4fb71232018-08-25 23:14:50 -0400988impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400989 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -0700990 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -0400991 Ok(Some(input.parse()?))
992 } else {
993 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400994 }
David Tolnay18c754c2018-08-21 23:26:58 -0400995 }
996}
David Tolnay4ac232d2018-08-31 10:18:03 -0700997
David Tolnay80a914f2018-08-30 23:49:53 -0700998impl Parse for TokenStream {
999 fn parse(input: ParseStream) -> Result<Self> {
1000 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
1001 }
1002}
1003
1004impl Parse for TokenTree {
1005 fn parse(input: ParseStream) -> Result<Self> {
1006 input.step(|cursor| match cursor.token_tree() {
1007 Some((tt, rest)) => Ok((tt, rest)),
1008 None => Err(cursor.error("expected token tree")),
1009 })
1010 }
1011}
1012
1013impl Parse for Group {
1014 fn parse(input: ParseStream) -> Result<Self> {
1015 input.step(|cursor| {
1016 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
1017 if let Some((inside, span, rest)) = cursor.group(*delim) {
1018 let mut group = Group::new(*delim, inside.token_stream());
1019 group.set_span(span);
1020 return Ok((group, rest));
1021 }
1022 }
1023 Err(cursor.error("expected group token"))
1024 })
1025 }
1026}
1027
1028impl Parse for Punct {
1029 fn parse(input: ParseStream) -> Result<Self> {
1030 input.step(|cursor| match cursor.punct() {
1031 Some((punct, rest)) => Ok((punct, rest)),
1032 None => Err(cursor.error("expected punctuation token")),
1033 })
1034 }
1035}
1036
1037impl Parse for Literal {
1038 fn parse(input: ParseStream) -> Result<Self> {
1039 input.step(|cursor| match cursor.literal() {
1040 Some((literal, rest)) => Ok((literal, rest)),
1041 None => Err(cursor.error("expected literal token")),
1042 })
1043 }
1044}
1045
1046/// Parser that can parse Rust tokens into a particular syntax tree node.
1047///
1048/// Refer to the [module documentation] for details about parsing in Syn.
1049///
1050/// [module documentation]: index.html
1051///
1052/// *This trait is available if Syn is built with the `"parsing"` feature.*
1053pub trait Parser: Sized {
1054 type Output;
1055
1056 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
Jethro Beekman33c22332018-12-31 11:16:25 +05301057 ///
1058 /// This function will check that the input is fully parsed. If there are
1059 /// any unparsed tokens at the end of the stream, an error is returned.
David Tolnay80a914f2018-08-30 23:49:53 -07001060 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1061
1062 /// Parse tokens of source code into the chosen syntax tree node.
1063 ///
Jethro Beekman33c22332018-12-31 11:16:25 +05301064 /// This function will check that the input is fully parsed. If there are
1065 /// any unparsed tokens at the end of the stream, an error is returned.
1066 ///
David Tolnay80a914f2018-08-30 23:49:53 -07001067 /// *This method is available if Syn is built with both the `"parsing"` and
1068 /// `"proc-macro"` features.*
1069 #[cfg(all(
1070 not(all(target_arch = "wasm32", target_os = "unknown")),
1071 feature = "proc-macro"
1072 ))]
1073 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1074 self.parse2(proc_macro2::TokenStream::from(tokens))
1075 }
1076
1077 /// Parse a string of Rust code into the chosen syntax tree node.
1078 ///
Jethro Beekman33c22332018-12-31 11:16:25 +05301079 /// This function will check that the input is fully parsed. If there are
1080 /// any unparsed tokens at the end of the string, an error is returned.
1081 ///
David Tolnay80a914f2018-08-30 23:49:53 -07001082 /// # Hygiene
1083 ///
1084 /// Every span in the resulting syntax tree will be set to resolve at the
1085 /// macro call site.
1086 fn parse_str(self, s: &str) -> Result<Self::Output> {
1087 self.parse2(proc_macro2::TokenStream::from_str(s)?)
1088 }
1089}
1090
David Tolnay7b07aa12018-09-01 11:41:12 -07001091fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1092 let scope = Span::call_site();
1093 let cursor = tokens.begin();
1094 let unexpected = Rc::new(Cell::new(None));
1095 private::new_parse_buffer(scope, cursor, unexpected)
1096}
1097
David Tolnay80a914f2018-08-30 23:49:53 -07001098impl<F, T> Parser for F
1099where
1100 F: FnOnce(ParseStream) -> Result<T>,
1101{
1102 type Output = T;
1103
1104 fn parse2(self, tokens: TokenStream) -> Result<T> {
1105 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -07001106 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -07001107 let node = self(&state)?;
1108 state.check_unexpected()?;
1109 if state.is_empty() {
1110 Ok(node)
1111 } else {
1112 Err(state.error("unexpected token"))
1113 }
1114 }
1115}