blob: 1ce65fbde1d795ec008395b59162fc06c67fbda7 [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 Tolnay67fea042018-11-24 14:50:20 -080043//! use syn::{token, Field, Ident, Result};
44//! use syn::parse::{Parse, ParseStream};
David Tolnay43984452018-09-01 17:43:56 -070045//! 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 Tolnay67fea042018-11-24 14:50:20 -0800120//! # fn run_parser() -> syn::Result<()> {
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//!
David Tolnay2b45fd42018-11-06 21:16:55 -0800148//! ```compile_fail
149//! # extern crate proc_macro;
150//! # extern crate syn;
151//! #
David Tolnay2b45fd42018-11-06 21:16:55 -0800152//! # use syn::punctuated::Punctuated;
David Tolnay67fea042018-11-24 14:50:20 -0800153//! # use syn::{PathSegment, Result, Token};
David Tolnay2b45fd42018-11-06 21:16:55 -0800154//! #
155//! # fn f(tokens: proc_macro::TokenStream) -> Result<()> {
156//! #
David Tolnay80a914f2018-08-30 23:49:53 -0700157//! // Can't parse `Punctuated` without knowing whether trailing punctuation
158//! // should be allowed in this context.
159//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
David Tolnay2b45fd42018-11-06 21:16:55 -0800160//! #
161//! # Ok(())
162//! # }
David Tolnay80a914f2018-08-30 23:49:53 -0700163//! ```
164//!
165//! In these cases the types provide a choice of parser functions rather than a
David Tolnaye0c51762018-08-31 11:05:22 -0700166//! single `Parse` implementation, and those parser functions can be invoked
David Tolnay80a914f2018-08-30 23:49:53 -0700167//! through the [`Parser`] trait.
168//!
169//! [`Parser`]: trait.Parser.html
170//!
171//! ```
David Tolnaya1c98072018-09-06 08:58:10 -0700172//! #[macro_use]
173//! extern crate syn;
174//!
175//! extern crate proc_macro2;
176//!
177//! use proc_macro2::TokenStream;
David Tolnay3e3f7752018-08-31 09:33:59 -0700178//! use syn::parse::Parser;
David Tolnay80a914f2018-08-30 23:49:53 -0700179//! use syn::punctuated::Punctuated;
David Tolnaya1c98072018-09-06 08:58:10 -0700180//! use syn::{Attribute, Expr, PathSegment};
David Tolnay80a914f2018-08-30 23:49:53 -0700181//!
David Tolnay67fea042018-11-24 14:50:20 -0800182//! # fn run_parsers() -> syn::Result<()> {
David Tolnay80a914f2018-08-30 23:49:53 -0700183//! # let tokens = TokenStream::new().into();
184//! // Parse a nonempty sequence of path segments separated by `::` punctuation
185//! // with no trailing punctuation.
186//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
187//! let path = parser.parse(tokens)?;
188//!
189//! # let tokens = TokenStream::new().into();
190//! // Parse a possibly empty sequence of expressions terminated by commas with
191//! // an optional trailing punctuation.
192//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
193//! let args = parser.parse(tokens)?;
194//!
195//! # let tokens = TokenStream::new().into();
196//! // Parse zero or more outer attributes but not inner attributes.
David Tolnay3e3f7752018-08-31 09:33:59 -0700197//! let parser = Attribute::parse_outer;
198//! let attrs = parser.parse(tokens)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700199//! #
200//! # Ok(())
201//! # }
202//! #
203//! # fn main() {}
204//! ```
205//!
David Tolnaye0c51762018-08-31 11:05:22 -0700206//! ---
David Tolnay80a914f2018-08-30 23:49:53 -0700207//!
208//! *This module is available if Syn is built with the `"parsing"` feature.*
David Tolnay18c754c2018-08-21 23:26:58 -0400209
210use std::cell::Cell;
Diggory Hardy1c522e12018-11-02 10:10:02 +0000211use std::fmt::{self, Debug, Display};
David Tolnay18c754c2018-08-21 23:26:58 -0400212use std::marker::PhantomData;
213use std::mem;
214use std::ops::Deref;
David Tolnayeafc8052018-08-25 16:33:53 -0400215use std::rc::Rc;
David Tolnay80a914f2018-08-30 23:49:53 -0700216use std::str::FromStr;
David Tolnayeafc8052018-08-25 16:33:53 -0400217
David Tolnay80a914f2018-08-30 23:49:53 -0700218#[cfg(all(
219 not(all(target_arch = "wasm32", target_os = "unknown")),
220 feature = "proc-macro"
221))]
222use proc_macro;
David Tolnayf07b3342018-09-01 11:58:11 -0700223use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
David Tolnay18c754c2018-08-21 23:26:58 -0400224
David Tolnay80a914f2018-08-30 23:49:53 -0700225use buffer::{Cursor, TokenBuffer};
David Tolnayb6254182018-08-25 08:44:54 -0400226use error;
David Tolnay94f06632018-08-31 10:17:17 -0700227use lookahead;
228use private;
David Tolnay577d0332018-08-25 21:45:24 -0400229use punctuated::Punctuated;
David Tolnay4fb71232018-08-25 23:14:50 -0400230use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -0400231
David Tolnayb6254182018-08-25 08:44:54 -0400232pub use error::{Error, Result};
233pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -0400234
235/// Parsing interface implemented by all types that can be parsed in a default
236/// way from a token stream.
237pub trait Parse: Sized {
238 fn parse(input: ParseStream) -> Result<Self>;
239}
240
241/// Input to a Syn parser function.
David Tolnaya0daa482018-09-01 02:09:40 -0700242///
243/// See the methods of this type under the documentation of [`ParseBuffer`]. For
244/// an overview of parsing in Syn, refer to the [module documentation].
245///
246/// [module documentation]: index.html
David Tolnay18c754c2018-08-21 23:26:58 -0400247pub type ParseStream<'a> = &'a ParseBuffer<'a>;
248
249/// Cursor position within a buffered token stream.
David Tolnay20d29a12018-09-01 15:15:33 -0700250///
251/// This type is more commonly used through the type alias [`ParseStream`] which
252/// is an alias for `&ParseBuffer`.
253///
254/// `ParseStream` is the input type for all parser functions in Syn. They have
255/// the signature `fn(ParseStream) -> Result<T>`.
David Tolnay18c754c2018-08-21 23:26:58 -0400256pub struct ParseBuffer<'a> {
257 scope: Span,
David Tolnay5d7f2252018-09-02 08:21:40 -0700258 // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
259 // The rest of the code in this module needs to be careful that only a
260 // cursor derived from this `cell` is ever assigned to this `cell`.
261 //
262 // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
263 // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
264 // than 'a, and then assign a Cursor<'short> into the Cell.
265 //
266 // By extension, it would not be safe to expose an API that accepts a
267 // Cursor<'a> and trusts that it lives as long as the cursor currently in
268 // the cell.
David Tolnay18c754c2018-08-21 23:26:58 -0400269 cell: Cell<Cursor<'static>>,
270 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400271 unexpected: Rc<Cell<Option<Span>>>,
272}
273
274impl<'a> Drop for ParseBuffer<'a> {
275 fn drop(&mut self) {
276 if !self.is_empty() && self.unexpected.get().is_none() {
277 self.unexpected.set(Some(self.cursor().span()));
278 }
279 }
David Tolnay18c754c2018-08-21 23:26:58 -0400280}
281
Diggory Hardy1c522e12018-11-02 10:10:02 +0000282impl<'a> Display for ParseBuffer<'a> {
283 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
284 Display::fmt(&self.cursor().token_stream(), f)
285 }
286}
287
288impl<'a> Debug for ParseBuffer<'a> {
289 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
290 Debug::fmt(&self.cursor().token_stream(), f)
291 }
292}
293
David Tolnay642832f2018-09-01 13:08:10 -0700294/// Cursor state associated with speculative parsing.
295///
296/// This type is the input of the closure provided to [`ParseStream::step`].
297///
298/// [`ParseStream::step`]: struct.ParseBuffer.html#method.step
David Tolnay9bd34392018-09-01 13:19:53 -0700299///
300/// # Example
301///
302/// ```
303/// # extern crate proc_macro2;
304/// # extern crate syn;
305/// #
306/// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800307/// use syn::Result;
308/// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700309///
310/// // This function advances the stream past the next occurrence of `@`. If
311/// // no `@` is present in the stream, the stream position is unchanged and
312/// // an error is returned.
313/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
314/// input.step(|cursor| {
315/// let mut rest = *cursor;
Sharad Chande1df40a2018-09-08 15:25:52 +0545316/// while let Some((tt, next)) = rest.token_tree() {
David Tolnay9bd34392018-09-01 13:19:53 -0700317/// match tt {
318/// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
319/// return Ok(((), next));
320/// }
321/// _ => rest = next,
322/// }
323/// }
324/// Err(cursor.error("no `@` was found after this point"))
325/// })
326/// }
327/// #
David Tolnaydb312582018-11-06 20:42:05 -0800328/// #
329/// # fn remainder_after_skipping_past_next_at(
330/// # input: ParseStream,
331/// # ) -> Result<proc_macro2::TokenStream> {
332/// # skip_past_next_at(input)?;
333/// # input.parse()
334/// # }
335/// #
336/// # fn main() {
337/// # use syn::parse::Parser;
338/// # let remainder = remainder_after_skipping_past_next_at
339/// # .parse_str("a @ b c")
340/// # .unwrap();
341/// # assert_eq!(remainder.to_string(), "b c");
342/// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700343/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400344#[derive(Copy, Clone)]
345pub struct StepCursor<'c, 'a> {
346 scope: Span,
David Tolnay56924f42018-09-02 08:24:58 -0700347 // This field is covariant in 'c.
David Tolnay18c754c2018-08-21 23:26:58 -0400348 cursor: Cursor<'c>,
David Tolnay56924f42018-09-02 08:24:58 -0700349 // This field is contravariant in 'c. Together these make StepCursor
350 // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
351 // different lifetime but can upcast into a StepCursor with a shorter
352 // lifetime 'a.
353 //
354 // As long as we only ever construct a StepCursor for which 'c outlives 'a,
355 // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
356 // outlives 'a.
David Tolnay18c754c2018-08-21 23:26:58 -0400357 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
358}
359
360impl<'c, 'a> Deref for StepCursor<'c, 'a> {
361 type Target = Cursor<'c>;
362
363 fn deref(&self) -> &Self::Target {
364 &self.cursor
365 }
366}
367
368impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700369 /// Triggers an error at the current position of the parse stream.
370 ///
371 /// The `ParseStream::step` invocation will return this same error without
372 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400373 pub fn error<T: Display>(self, message: T) -> Error {
374 error::new_at(self.scope, self.cursor, message)
375 }
376}
377
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700378impl private {
379 pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
David Tolnay56924f42018-09-02 08:24:58 -0700380 // Refer to the comments within the StepCursor definition. We use the
381 // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
382 // Cursor is covariant in its lifetime parameter so we can cast a
383 // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700384 let _ = proof;
385 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
386 }
387}
388
David Tolnay66cb0c42018-08-31 09:01:30 -0700389fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700390 input
391 .step(|cursor| {
392 if let Some((_lifetime, rest)) = cursor.lifetime() {
393 Ok((true, rest))
394 } else if let Some((_token, rest)) = cursor.token_tree() {
395 Ok((true, rest))
396 } else {
397 Ok((false, *cursor))
398 }
David Tolnayfb84fc02018-10-02 21:01:30 -0700399 })
400 .unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700401}
402
David Tolnay10951d52018-08-31 10:27:39 -0700403impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700404 pub fn new_parse_buffer(
405 scope: Span,
406 cursor: Cursor,
407 unexpected: Rc<Cell<Option<Span>>>,
408 ) -> ParseBuffer {
David Tolnay18c754c2018-08-21 23:26:58 -0400409 ParseBuffer {
410 scope: scope,
David Tolnay5d7f2252018-09-02 08:21:40 -0700411 // See comment on `cell` in the struct definition.
412 cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
David Tolnay18c754c2018-08-21 23:26:58 -0400413 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400414 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400415 }
416 }
417
David Tolnay94f06632018-08-31 10:17:17 -0700418 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
419 buffer.unexpected.clone()
420 }
421}
422
423impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700424 /// Parses a syntax tree node of type `T`, advancing the position of our
425 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400426 pub fn parse<T: Parse>(&self) -> Result<T> {
427 T::parse(self)
428 }
429
David Tolnay725e1c62018-09-01 12:07:25 -0700430 /// Calls the given parser function to parse a syntax tree node of type `T`
431 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700432 ///
433 /// # Example
434 ///
435 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
436 /// zero or more outer attributes.
437 ///
438 /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
439 ///
440 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700441 /// #[macro_use]
442 /// extern crate syn;
443 ///
David Tolnay67fea042018-11-24 14:50:20 -0800444 /// use syn::{Attribute, Ident, Result};
445 /// use syn::parse::{Parse, ParseStream};
David Tolnay21ce84c2018-09-01 15:37:51 -0700446 ///
447 /// // Parses a unit struct with attributes.
448 /// //
449 /// // #[path = "s.tmpl"]
450 /// // struct S;
451 /// struct UnitStruct {
452 /// attrs: Vec<Attribute>,
453 /// struct_token: Token![struct],
454 /// name: Ident,
455 /// semi_token: Token![;],
456 /// }
457 ///
458 /// impl Parse for UnitStruct {
459 /// fn parse(input: ParseStream) -> Result<Self> {
460 /// Ok(UnitStruct {
461 /// attrs: input.call(Attribute::parse_outer)?,
462 /// struct_token: input.parse()?,
463 /// name: input.parse()?,
464 /// semi_token: input.parse()?,
465 /// })
466 /// }
467 /// }
468 /// #
469 /// # fn main() {}
470 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400471 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
472 function(self)
473 }
474
David Tolnay725e1c62018-09-01 12:07:25 -0700475 /// Looks at the next token in the parse stream to determine whether it
476 /// matches the requested type of token.
477 ///
478 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700479 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700480 /// # Syntax
481 ///
482 /// Note that this method does not use turbofish syntax. Pass the peek type
483 /// inside of parentheses.
484 ///
485 /// - `input.peek(Token![struct])`
486 /// - `input.peek(Token![==])`
487 /// - `input.peek(Ident)`
488 /// - `input.peek(Lifetime)`
489 /// - `input.peek(token::Brace)`
490 ///
David Tolnayddebc3e2018-09-01 16:29:20 -0700491 /// # Example
492 ///
493 /// In this example we finish parsing the list of supertraits when the next
494 /// token in the input is either `where` or an opening curly brace.
495 ///
496 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700497 /// #[macro_use]
498 /// extern crate syn;
499 ///
David Tolnay67fea042018-11-24 14:50:20 -0800500 /// use syn::{token, Generics, Ident, Result, TypeParamBound};
501 /// use syn::parse::{Parse, ParseStream};
David Tolnayddebc3e2018-09-01 16:29:20 -0700502 /// use syn::punctuated::Punctuated;
503 ///
504 /// // Parses a trait definition containing no associated items.
505 /// //
506 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
507 /// struct MarkerTrait {
508 /// trait_token: Token![trait],
509 /// ident: Ident,
510 /// generics: Generics,
511 /// colon_token: Option<Token![:]>,
512 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
513 /// brace_token: token::Brace,
514 /// }
515 ///
516 /// impl Parse for MarkerTrait {
517 /// fn parse(input: ParseStream) -> Result<Self> {
518 /// let trait_token: Token![trait] = input.parse()?;
519 /// let ident: Ident = input.parse()?;
520 /// let mut generics: Generics = input.parse()?;
521 /// let colon_token: Option<Token![:]> = input.parse()?;
522 ///
523 /// let mut supertraits = Punctuated::new();
524 /// if colon_token.is_some() {
525 /// loop {
526 /// supertraits.push_value(input.parse()?);
527 /// if input.peek(Token![where]) || input.peek(token::Brace) {
528 /// break;
529 /// }
530 /// supertraits.push_punct(input.parse()?);
531 /// }
532 /// }
533 ///
534 /// generics.where_clause = input.parse()?;
535 /// let content;
536 /// let empty_brace_token = braced!(content in input);
537 ///
538 /// Ok(MarkerTrait {
539 /// trait_token: trait_token,
540 /// ident: ident,
541 /// generics: generics,
542 /// colon_token: colon_token,
543 /// supertraits: supertraits,
544 /// brace_token: empty_brace_token,
545 /// })
546 /// }
547 /// }
548 /// #
549 /// # fn main() {}
550 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400551 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700552 let _ = token;
553 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400554 }
555
David Tolnay725e1c62018-09-01 12:07:25 -0700556 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700557 ///
558 /// This is commonly useful as a way to implement contextual keywords.
559 ///
560 /// # Example
561 ///
562 /// This example needs to use `peek2` because the symbol `union` is not a
563 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
564 /// the very next token is `union`, because someone is free to write a `mod
565 /// union` and a macro invocation that looks like `union::some_macro! { ...
566 /// }`. In other words `union` is a contextual keyword.
567 ///
568 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700569 /// #[macro_use]
570 /// extern crate syn;
571 ///
David Tolnay67fea042018-11-24 14:50:20 -0800572 /// use syn::{Ident, ItemUnion, Macro, Result};
573 /// use syn::parse::{Parse, ParseStream};
David Tolnaye334b872018-09-01 16:38:10 -0700574 ///
575 /// // Parses either a union or a macro invocation.
576 /// enum UnionOrMacro {
577 /// // union MaybeUninit<T> { uninit: (), value: T }
578 /// Union(ItemUnion),
579 /// // lazy_static! { ... }
580 /// Macro(Macro),
581 /// }
582 ///
583 /// impl Parse for UnionOrMacro {
584 /// fn parse(input: ParseStream) -> Result<Self> {
585 /// if input.peek(Token![union]) && input.peek2(Ident) {
586 /// input.parse().map(UnionOrMacro::Union)
587 /// } else {
588 /// input.parse().map(UnionOrMacro::Macro)
589 /// }
590 /// }
591 /// }
592 /// #
593 /// # fn main() {}
594 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400595 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400596 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700597 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400598 }
599
David Tolnay725e1c62018-09-01 12:07:25 -0700600 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400601 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400602 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700603 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400604 }
605
David Tolnay725e1c62018-09-01 12:07:25 -0700606 /// Parses zero or more occurrences of `T` separated by punctuation of type
607 /// `P`, with optional trailing punctuation.
608 ///
609 /// Parsing continues until the end of this parse stream. The entire content
610 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700611 ///
612 /// # Example
613 ///
614 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700615 /// # #[macro_use]
David Tolnay0abe65b2018-09-01 14:31:43 -0700616 /// # extern crate quote;
David Tolnay0abe65b2018-09-01 14:31:43 -0700617 /// #
David Tolnaya1c98072018-09-06 08:58:10 -0700618 /// #[macro_use]
619 /// extern crate syn;
620 ///
David Tolnay67fea042018-11-24 14:50:20 -0800621 /// use syn::{token, Ident, Result, Type};
622 /// use syn::parse::{Parse, ParseStream};
David Tolnay0abe65b2018-09-01 14:31:43 -0700623 /// use syn::punctuated::Punctuated;
624 ///
625 /// // Parse a simplified tuple struct syntax like:
626 /// //
627 /// // struct S(A, B);
628 /// struct TupleStruct {
629 /// struct_token: Token![struct],
630 /// ident: Ident,
631 /// paren_token: token::Paren,
632 /// fields: Punctuated<Type, Token![,]>,
633 /// semi_token: Token![;],
634 /// }
635 ///
636 /// impl Parse for TupleStruct {
637 /// fn parse(input: ParseStream) -> Result<Self> {
638 /// let content;
639 /// Ok(TupleStruct {
640 /// struct_token: input.parse()?,
641 /// ident: input.parse()?,
642 /// paren_token: parenthesized!(content in input),
643 /// fields: content.parse_terminated(Type::parse)?,
644 /// semi_token: input.parse()?,
645 /// })
646 /// }
647 /// }
648 /// #
649 /// # fn main() {
650 /// # let input = quote! {
651 /// # struct S(A, B);
652 /// # };
653 /// # syn::parse2::<TupleStruct>(input).unwrap();
654 /// # }
655 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400656 pub fn parse_terminated<T, P: Parse>(
657 &self,
658 parser: fn(ParseStream) -> Result<T>,
659 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700660 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400661 }
662
David Tolnay725e1c62018-09-01 12:07:25 -0700663 /// Returns whether there are tokens remaining in this stream.
664 ///
665 /// This method returns true at the end of the content of a set of
666 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700667 ///
668 /// # Example
669 ///
670 /// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700671 /// #[macro_use]
672 /// extern crate syn;
673 ///
David Tolnay67fea042018-11-24 14:50:20 -0800674 /// use syn::{token, Ident, Item, Result};
675 /// use syn::parse::{Parse, ParseStream};
David Tolnaycce6b5f2018-09-01 14:24:46 -0700676 ///
677 /// // Parses a Rust `mod m { ... }` containing zero or more items.
678 /// struct Mod {
679 /// mod_token: Token![mod],
680 /// name: Ident,
681 /// brace_token: token::Brace,
682 /// items: Vec<Item>,
683 /// }
684 ///
685 /// impl Parse for Mod {
686 /// fn parse(input: ParseStream) -> Result<Self> {
687 /// let content;
688 /// Ok(Mod {
689 /// mod_token: input.parse()?,
690 /// name: input.parse()?,
691 /// brace_token: braced!(content in input),
692 /// items: {
693 /// let mut items = Vec::new();
694 /// while !content.is_empty() {
695 /// items.push(content.parse()?);
696 /// }
697 /// items
698 /// },
699 /// })
700 /// }
701 /// }
702 /// #
703 /// # fn main() {}
David Tolnayf2b78602018-11-06 20:42:37 -0800704 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700705 pub fn is_empty(&self) -> bool {
706 self.cursor().eof()
707 }
708
David Tolnay725e1c62018-09-01 12:07:25 -0700709 /// Constructs a helper for peeking at the next token in this stream and
710 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700711 ///
712 /// # Example
713 ///
714 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700715 /// #[macro_use]
716 /// extern crate syn;
717 ///
David Tolnay67fea042018-11-24 14:50:20 -0800718 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, TypeParam};
719 /// use syn::parse::{Parse, ParseStream};
David Tolnay2c77e772018-09-01 14:18:46 -0700720 ///
721 /// // A generic parameter, a single one of the comma-separated elements inside
722 /// // angle brackets in:
723 /// //
724 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
725 /// //
726 /// // On invalid input, lookahead gives us a reasonable error message.
727 /// //
728 /// // error: expected one of: identifier, lifetime, `const`
729 /// // |
730 /// // 5 | fn f<!Sized>() {}
731 /// // | ^
732 /// enum GenericParam {
733 /// Type(TypeParam),
734 /// Lifetime(LifetimeDef),
735 /// Const(ConstParam),
736 /// }
737 ///
738 /// impl Parse for GenericParam {
739 /// fn parse(input: ParseStream) -> Result<Self> {
740 /// let lookahead = input.lookahead1();
741 /// if lookahead.peek(Ident) {
742 /// input.parse().map(GenericParam::Type)
743 /// } else if lookahead.peek(Lifetime) {
744 /// input.parse().map(GenericParam::Lifetime)
745 /// } else if lookahead.peek(Token![const]) {
746 /// input.parse().map(GenericParam::Const)
747 /// } else {
748 /// Err(lookahead.error())
749 /// }
750 /// }
751 /// }
752 /// #
753 /// # fn main() {}
754 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700755 pub fn lookahead1(&self) -> Lookahead1<'a> {
756 lookahead::new(self.scope, self.cursor())
757 }
758
David Tolnay725e1c62018-09-01 12:07:25 -0700759 /// Forks a parse stream so that parsing tokens out of either the original
760 /// or the fork does not advance the position of the other.
761 ///
762 /// # Performance
763 ///
764 /// Forking a parse stream is a cheap fixed amount of work and does not
765 /// involve copying token buffers. Where you might hit performance problems
766 /// is if your macro ends up parsing a large amount of content more than
767 /// once.
768 ///
769 /// ```
David Tolnay67fea042018-11-24 14:50:20 -0800770 /// # use syn::{Expr, Result};
771 /// # use syn::parse::ParseStream;
David Tolnay725e1c62018-09-01 12:07:25 -0700772 /// #
773 /// # fn bad(input: ParseStream) -> Result<Expr> {
774 /// // Do not do this.
775 /// if input.fork().parse::<Expr>().is_ok() {
776 /// return input.parse::<Expr>();
777 /// }
778 /// # unimplemented!()
779 /// # }
780 /// ```
781 ///
782 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
783 /// parse stream. Only use a fork when the amount of work performed against
784 /// the fork is small and bounded.
785 ///
David Tolnayec149b02018-09-01 14:17:28 -0700786 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700787 /// speculative parsing, consider using [`ParseStream::step`] instead.
788 ///
789 /// [`ParseStream::step`]: #method.step
David Tolnayec149b02018-09-01 14:17:28 -0700790 ///
791 /// # Example
792 ///
793 /// The parse implementation shown here parses possibly restricted `pub`
794 /// visibilities.
795 ///
796 /// - `pub`
797 /// - `pub(crate)`
798 /// - `pub(self)`
799 /// - `pub(super)`
800 /// - `pub(in some::path)`
801 ///
802 /// To handle the case of visibilities inside of tuple structs, the parser
803 /// needs to distinguish parentheses that specify visibility restrictions
804 /// from parentheses that form part of a tuple type.
805 ///
806 /// ```
807 /// # struct A;
808 /// # struct B;
809 /// # struct C;
810 /// #
811 /// struct S(pub(crate) A, pub (B, C));
812 /// ```
813 ///
814 /// In this example input the first tuple struct element of `S` has
815 /// `pub(crate)` visibility while the second tuple struct element has `pub`
816 /// visibility; the parentheses around `(B, C)` are part of the type rather
817 /// than part of a visibility restriction.
818 ///
819 /// The parser uses a forked parse stream to check the first token inside of
820 /// parentheses after the `pub` keyword. This is a small bounded amount of
821 /// work performed against the forked parse stream.
822 ///
823 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700824 /// #[macro_use]
825 /// extern crate syn;
826 ///
David Tolnay67fea042018-11-24 14:50:20 -0800827 /// use syn::{token, Ident, Path, Result};
David Tolnayec149b02018-09-01 14:17:28 -0700828 /// use syn::ext::IdentExt;
David Tolnay67fea042018-11-24 14:50:20 -0800829 /// use syn::parse::{Parse, ParseStream};
David Tolnayec149b02018-09-01 14:17:28 -0700830 ///
831 /// struct PubVisibility {
832 /// pub_token: Token![pub],
833 /// restricted: Option<Restricted>,
834 /// }
835 ///
836 /// struct Restricted {
837 /// paren_token: token::Paren,
838 /// in_token: Option<Token![in]>,
839 /// path: Path,
840 /// }
841 ///
842 /// impl Parse for PubVisibility {
843 /// fn parse(input: ParseStream) -> Result<Self> {
844 /// let pub_token: Token![pub] = input.parse()?;
845 ///
846 /// if input.peek(token::Paren) {
847 /// let ahead = input.fork();
848 /// let mut content;
849 /// parenthesized!(content in ahead);
850 ///
851 /// if content.peek(Token![crate])
852 /// || content.peek(Token![self])
853 /// || content.peek(Token![super])
854 /// {
855 /// return Ok(PubVisibility {
856 /// pub_token: pub_token,
857 /// restricted: Some(Restricted {
858 /// paren_token: parenthesized!(content in input),
859 /// in_token: None,
860 /// path: Path::from(content.call(Ident::parse_any)?),
861 /// }),
862 /// });
863 /// } else if content.peek(Token![in]) {
864 /// return Ok(PubVisibility {
865 /// pub_token: pub_token,
866 /// restricted: Some(Restricted {
867 /// paren_token: parenthesized!(content in input),
868 /// in_token: Some(content.parse()?),
869 /// path: content.call(Path::parse_mod_style)?,
870 /// }),
871 /// });
872 /// }
873 /// }
874 ///
875 /// Ok(PubVisibility {
876 /// pub_token: pub_token,
877 /// restricted: None,
878 /// })
879 /// }
880 /// }
881 /// #
882 /// # fn main() {}
883 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400884 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400885 ParseBuffer {
886 scope: self.scope,
887 cell: self.cell.clone(),
888 marker: PhantomData,
889 // Not the parent's unexpected. Nothing cares whether the clone
890 // parses all the way.
891 unexpected: Rc::new(Cell::new(None)),
892 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400893 }
894
David Tolnay725e1c62018-09-01 12:07:25 -0700895 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700896 ///
897 /// # Example
898 ///
899 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -0700900 /// #[macro_use]
901 /// extern crate syn;
902 ///
David Tolnay67fea042018-11-24 14:50:20 -0800903 /// use syn::{Expr, Result};
904 /// use syn::parse::{Parse, ParseStream};
David Tolnay23fce0b2018-09-01 13:50:31 -0700905 ///
906 /// // Some kind of loop: `while` or `for` or `loop`.
907 /// struct Loop {
908 /// expr: Expr,
909 /// }
910 ///
911 /// impl Parse for Loop {
912 /// fn parse(input: ParseStream) -> Result<Self> {
913 /// if input.peek(Token![while])
914 /// || input.peek(Token![for])
915 /// || input.peek(Token![loop])
916 /// {
917 /// Ok(Loop {
918 /// expr: input.parse()?,
919 /// })
920 /// } else {
921 /// Err(input.error("expected some kind of loop"))
922 /// }
923 /// }
924 /// }
David Tolnaya1c98072018-09-06 08:58:10 -0700925 /// #
926 /// # fn main() {}
David Tolnay23fce0b2018-09-01 13:50:31 -0700927 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400928 pub fn error<T: Display>(&self, message: T) -> Error {
929 error::new_at(self.scope, self.cursor(), message)
930 }
931
David Tolnay725e1c62018-09-01 12:07:25 -0700932 /// Speculatively parses tokens from this parse stream, advancing the
933 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700934 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700935 /// This is a powerful low-level API used for defining the `Parse` impls of
936 /// the basic built-in token types. It is not something that will be used
937 /// widely outside of the Syn codebase.
938 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700939 /// # Example
940 ///
941 /// ```
942 /// # extern crate proc_macro2;
943 /// # extern crate syn;
944 /// #
945 /// use proc_macro2::TokenTree;
David Tolnay67fea042018-11-24 14:50:20 -0800946 /// use syn::Result;
947 /// use syn::parse::ParseStream;
David Tolnay9bd34392018-09-01 13:19:53 -0700948 ///
949 /// // This function advances the stream past the next occurrence of `@`. If
950 /// // no `@` is present in the stream, the stream position is unchanged and
951 /// // an error is returned.
952 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
953 /// input.step(|cursor| {
954 /// let mut rest = *cursor;
David Tolnaydb312582018-11-06 20:42:05 -0800955 /// while let Some((tt, next)) = rest.token_tree() {
David Tolnay9bd34392018-09-01 13:19:53 -0700956 /// match tt {
957 /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
958 /// return Ok(((), next));
959 /// }
960 /// _ => rest = next,
961 /// }
962 /// }
963 /// Err(cursor.error("no `@` was found after this point"))
964 /// })
965 /// }
966 /// #
David Tolnaydb312582018-11-06 20:42:05 -0800967 /// # fn remainder_after_skipping_past_next_at(
968 /// # input: ParseStream,
969 /// # ) -> Result<proc_macro2::TokenStream> {
970 /// # skip_past_next_at(input)?;
971 /// # input.parse()
972 /// # }
973 /// #
974 /// # fn main() {
975 /// # use syn::parse::Parser;
976 /// # let remainder = remainder_after_skipping_past_next_at
977 /// # .parse_str("a @ b c")
978 /// # .unwrap();
979 /// # assert_eq!(remainder.to_string(), "b c");
980 /// # }
David Tolnay9bd34392018-09-01 13:19:53 -0700981 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700982 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400983 where
984 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
985 {
David Tolnayc142b092018-09-02 08:52:52 -0700986 // Since the user's function is required to work for any 'c, we know
987 // that the Cursor<'c> they return is either derived from the input
988 // StepCursor<'c, 'a> or from a Cursor<'static>.
989 //
990 // It would not be legal to write this function without the invariant
991 // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
992 // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
993 // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
994 // `step` on their ParseBuffer<'short> with a closure that returns
995 // Cursor<'short>, and we would wrongly write that Cursor<'short> into
996 // the Cell intended to hold Cursor<'a>.
997 //
998 // In some cases it may be necessary for R to contain a Cursor<'a>.
999 // Within Syn we solve this using `private::advance_step_cursor` which
1000 // uses the existence of a StepCursor<'c, 'a> as proof that it is safe
1001 // to cast from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it
1002 // would be safe to expose that API as a method on StepCursor.
David Tolnay6b65f852018-09-01 11:56:25 -07001003 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -04001004 scope: self.scope,
1005 cursor: self.cell.get(),
1006 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -07001007 })?;
1008 self.cell.set(rest);
1009 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -04001010 }
David Tolnayeafc8052018-08-25 16:33:53 -04001011
David Tolnay725e1c62018-09-01 12:07:25 -07001012 /// Provides low-level access to the token representation underlying this
1013 /// parse stream.
1014 ///
1015 /// Cursors are immutable so no operations you perform against the cursor
1016 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -07001017 pub fn cursor(&self) -> Cursor<'a> {
1018 self.cell.get()
1019 }
1020
David Tolnay94f06632018-08-31 10:17:17 -07001021 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -04001022 match self.unexpected.get() {
1023 Some(span) => Err(Error::new(span, "unexpected token")),
1024 None => Ok(()),
1025 }
1026 }
David Tolnay18c754c2018-08-21 23:26:58 -04001027}
1028
David Tolnaya7d69fc2018-08-26 13:30:24 -04001029impl<T: Parse> Parse for Box<T> {
1030 fn parse(input: ParseStream) -> Result<Self> {
1031 input.parse().map(Box::new)
1032 }
1033}
1034
David Tolnay4fb71232018-08-25 23:14:50 -04001035impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -04001036 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -07001037 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -04001038 Ok(Some(input.parse()?))
1039 } else {
1040 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -04001041 }
David Tolnay18c754c2018-08-21 23:26:58 -04001042 }
1043}
David Tolnay4ac232d2018-08-31 10:18:03 -07001044
David Tolnay80a914f2018-08-30 23:49:53 -07001045impl Parse for TokenStream {
1046 fn parse(input: ParseStream) -> Result<Self> {
1047 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
1048 }
1049}
1050
1051impl Parse for TokenTree {
1052 fn parse(input: ParseStream) -> Result<Self> {
1053 input.step(|cursor| match cursor.token_tree() {
1054 Some((tt, rest)) => Ok((tt, rest)),
1055 None => Err(cursor.error("expected token tree")),
1056 })
1057 }
1058}
1059
1060impl Parse for Group {
1061 fn parse(input: ParseStream) -> Result<Self> {
1062 input.step(|cursor| {
1063 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
1064 if let Some((inside, span, rest)) = cursor.group(*delim) {
1065 let mut group = Group::new(*delim, inside.token_stream());
1066 group.set_span(span);
1067 return Ok((group, rest));
1068 }
1069 }
1070 Err(cursor.error("expected group token"))
1071 })
1072 }
1073}
1074
1075impl Parse for Punct {
1076 fn parse(input: ParseStream) -> Result<Self> {
1077 input.step(|cursor| match cursor.punct() {
1078 Some((punct, rest)) => Ok((punct, rest)),
1079 None => Err(cursor.error("expected punctuation token")),
1080 })
1081 }
1082}
1083
1084impl Parse for Literal {
1085 fn parse(input: ParseStream) -> Result<Self> {
1086 input.step(|cursor| match cursor.literal() {
1087 Some((literal, rest)) => Ok((literal, rest)),
1088 None => Err(cursor.error("expected literal token")),
1089 })
1090 }
1091}
1092
1093/// Parser that can parse Rust tokens into a particular syntax tree node.
1094///
1095/// Refer to the [module documentation] for details about parsing in Syn.
1096///
1097/// [module documentation]: index.html
1098///
1099/// *This trait is available if Syn is built with the `"parsing"` feature.*
1100pub trait Parser: Sized {
1101 type Output;
1102
1103 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
1104 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1105
1106 /// Parse tokens of source code into the chosen syntax tree node.
1107 ///
1108 /// *This method is available if Syn is built with both the `"parsing"` and
1109 /// `"proc-macro"` features.*
1110 #[cfg(all(
1111 not(all(target_arch = "wasm32", target_os = "unknown")),
1112 feature = "proc-macro"
1113 ))]
1114 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1115 self.parse2(proc_macro2::TokenStream::from(tokens))
1116 }
1117
1118 /// Parse a string of Rust code into the chosen syntax tree node.
1119 ///
1120 /// # Hygiene
1121 ///
1122 /// Every span in the resulting syntax tree will be set to resolve at the
1123 /// macro call site.
1124 fn parse_str(self, s: &str) -> Result<Self::Output> {
1125 self.parse2(proc_macro2::TokenStream::from_str(s)?)
1126 }
1127}
1128
David Tolnay7b07aa12018-09-01 11:41:12 -07001129fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1130 let scope = Span::call_site();
1131 let cursor = tokens.begin();
1132 let unexpected = Rc::new(Cell::new(None));
1133 private::new_parse_buffer(scope, cursor, unexpected)
1134}
1135
David Tolnay80a914f2018-08-30 23:49:53 -07001136impl<F, T> Parser for F
1137where
1138 F: FnOnce(ParseStream) -> Result<T>,
1139{
1140 type Output = T;
1141
1142 fn parse2(self, tokens: TokenStream) -> Result<T> {
1143 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -07001144 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -07001145 let node = self(&state)?;
1146 state.check_unexpected()?;
1147 if state.is_empty() {
1148 Ok(node)
1149 } else {
1150 Err(state.error("unexpected token"))
1151 }
1152 }
1153}