blob: c4329675cb6d6aa083077ba2db4adfd07483978a [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
29//! procedural macro as shown at the bottom of the snippet. If the caller
30//! provides syntactically invalid input to the procedural macro, they will
31//! receive a helpful compiler error message pointing out the exact token that
32//! triggered the failure to parse.
33//!
David Tolnay43984452018-09-01 17:43:56 -070034//! ```
David Tolnay88d9f622018-09-01 17:52:33 -070035//! # extern crate proc_macro;
David Tolnay43984452018-09-01 17:43:56 -070036//! # extern crate syn;
37//! #
David Tolnay88d9f622018-09-01 17:52:33 -070038//! use proc_macro::TokenStream;
39//! use syn::{braced, parse_macro_input, token, Field, Ident, Token};
David Tolnay43984452018-09-01 17:43:56 -070040//! use syn::parse::{Parse, ParseStream, Result};
41//! use syn::punctuated::Punctuated;
42//!
43//! enum Item {
44//! Struct(ItemStruct),
45//! Enum(ItemEnum),
46//! }
47//!
48//! struct ItemStruct {
49//! struct_token: Token![struct],
50//! ident: Ident,
51//! brace_token: token::Brace,
52//! fields: Punctuated<Field, Token![,]>,
53//! }
54//! #
55//! # enum ItemEnum {}
56//!
57//! impl Parse for Item {
58//! fn parse(input: ParseStream) -> Result<Self> {
59//! let lookahead = input.lookahead1();
60//! if lookahead.peek(Token![struct]) {
61//! input.parse().map(Item::Struct)
62//! } else if lookahead.peek(Token![enum]) {
63//! input.parse().map(Item::Enum)
64//! } else {
65//! Err(lookahead.error())
66//! }
67//! }
68//! }
69//!
70//! impl Parse for ItemStruct {
71//! fn parse(input: ParseStream) -> Result<Self> {
72//! let content;
73//! Ok(ItemStruct {
74//! struct_token: input.parse()?,
75//! ident: input.parse()?,
76//! brace_token: braced!(content in input),
77//! fields: content.parse_terminated(Field::parse_named)?,
78//! })
79//! }
80//! }
81//! #
82//! # impl Parse for ItemEnum {
83//! # fn parse(input: ParseStream) -> Result<Self> {
84//! # unimplemented!()
85//! # }
86//! # }
David Tolnay88d9f622018-09-01 17:52:33 -070087//!
88//! # const IGNORE: &str = stringify! {
89//! #[proc_macro]
90//! # };
91//! pub fn my_macro(tokens: TokenStream) -> TokenStream {
92//! let input = parse_macro_input!(tokens as Item);
93//!
94//! /* ... */
95//! # "".parse().unwrap()
96//! }
97//! #
98//! # fn main() {}
David Tolnay43984452018-09-01 17:43:56 -070099//! ```
100//!
101//! # The `syn::parse*` functions
David Tolnay80a914f2018-08-30 23:49:53 -0700102//!
103//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
104//! as an entry point for parsing syntax tree nodes that can be parsed in an
105//! obvious default way. These functions can return any syntax tree node that
David Tolnay8aacee12018-08-31 09:15:15 -0700106//! implements the [`Parse`] trait, which includes most types in Syn.
David Tolnay80a914f2018-08-30 23:49:53 -0700107//!
108//! [`syn::parse`]: ../fn.parse.html
109//! [`syn::parse2`]: ../fn.parse2.html
110//! [`syn::parse_str`]: ../fn.parse_str.html
David Tolnay8aacee12018-08-31 09:15:15 -0700111//! [`Parse`]: trait.Parse.html
David Tolnay80a914f2018-08-30 23:49:53 -0700112//!
113//! ```
114//! use syn::Type;
115//!
David Tolnay8aacee12018-08-31 09:15:15 -0700116//! # fn run_parser() -> Result<(), syn::parse::Error> {
David Tolnay80a914f2018-08-30 23:49:53 -0700117//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
118//! # Ok(())
119//! # }
120//! #
121//! # fn main() {
122//! # run_parser().unwrap();
123//! # }
124//! ```
125//!
126//! The [`parse_quote!`] macro also uses this approach.
127//!
128//! [`parse_quote!`]: ../macro.parse_quote.html
129//!
David Tolnay43984452018-09-01 17:43:56 -0700130//! # The `Parser` trait
David Tolnay80a914f2018-08-30 23:49:53 -0700131//!
132//! Some types can be parsed in several ways depending on context. For example
133//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
134//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
135//! may or may not allow trailing punctuation, and parsing it the wrong way
136//! would either reject valid input or accept invalid input.
137//!
138//! [`Attribute`]: ../struct.Attribute.html
139//! [`Punctuated`]: ../punctuated/index.html
140//!
David Tolnaye0c51762018-08-31 11:05:22 -0700141//! The `Parse` trait is not implemented in these cases because there is no good
David Tolnay80a914f2018-08-30 23:49:53 -0700142//! behavior to consider the default.
143//!
144//! ```ignore
145//! // Can't parse `Punctuated` without knowing whether trailing punctuation
146//! // should be allowed in this context.
147//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
148//! ```
149//!
150//! In these cases the types provide a choice of parser functions rather than a
David Tolnaye0c51762018-08-31 11:05:22 -0700151//! single `Parse` implementation, and those parser functions can be invoked
David Tolnay80a914f2018-08-30 23:49:53 -0700152//! through the [`Parser`] trait.
153//!
154//! [`Parser`]: trait.Parser.html
155//!
156//! ```
David Tolnay80a914f2018-08-30 23:49:53 -0700157//! # extern crate syn;
158//! #
159//! # extern crate proc_macro2;
160//! # use proc_macro2::TokenStream;
161//! #
David Tolnay3e3f7752018-08-31 09:33:59 -0700162//! use syn::parse::Parser;
David Tolnay80a914f2018-08-30 23:49:53 -0700163//! use syn::punctuated::Punctuated;
David Tolnay9b00f652018-09-01 10:31:02 -0700164//! use syn::{Attribute, Expr, PathSegment, Token};
David Tolnay80a914f2018-08-30 23:49:53 -0700165//!
David Tolnay3e3f7752018-08-31 09:33:59 -0700166//! # fn run_parsers() -> Result<(), syn::parse::Error> {
David Tolnay80a914f2018-08-30 23:49:53 -0700167//! # let tokens = TokenStream::new().into();
168//! // Parse a nonempty sequence of path segments separated by `::` punctuation
169//! // with no trailing punctuation.
170//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
171//! let path = parser.parse(tokens)?;
172//!
173//! # let tokens = TokenStream::new().into();
174//! // Parse a possibly empty sequence of expressions terminated by commas with
175//! // an optional trailing punctuation.
176//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
177//! let args = parser.parse(tokens)?;
178//!
179//! # let tokens = TokenStream::new().into();
180//! // Parse zero or more outer attributes but not inner attributes.
David Tolnay3e3f7752018-08-31 09:33:59 -0700181//! let parser = Attribute::parse_outer;
182//! let attrs = parser.parse(tokens)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700183//! #
184//! # Ok(())
185//! # }
186//! #
187//! # fn main() {}
188//! ```
189//!
David Tolnaye0c51762018-08-31 11:05:22 -0700190//! ---
David Tolnay80a914f2018-08-30 23:49:53 -0700191//!
192//! *This module is available if Syn is built with the `"parsing"` feature.*
David Tolnay18c754c2018-08-21 23:26:58 -0400193
194use std::cell::Cell;
195use std::fmt::Display;
196use std::marker::PhantomData;
197use std::mem;
198use std::ops::Deref;
David Tolnayeafc8052018-08-25 16:33:53 -0400199use std::rc::Rc;
David Tolnay80a914f2018-08-30 23:49:53 -0700200use std::str::FromStr;
David Tolnayeafc8052018-08-25 16:33:53 -0400201
David Tolnay80a914f2018-08-30 23:49:53 -0700202#[cfg(all(
203 not(all(target_arch = "wasm32", target_os = "unknown")),
204 feature = "proc-macro"
205))]
206use proc_macro;
David Tolnayf07b3342018-09-01 11:58:11 -0700207use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
David Tolnay18c754c2018-08-21 23:26:58 -0400208
David Tolnay80a914f2018-08-30 23:49:53 -0700209use buffer::{Cursor, TokenBuffer};
David Tolnayb6254182018-08-25 08:44:54 -0400210use error;
David Tolnay94f06632018-08-31 10:17:17 -0700211use lookahead;
212use private;
David Tolnay577d0332018-08-25 21:45:24 -0400213use punctuated::Punctuated;
David Tolnay4fb71232018-08-25 23:14:50 -0400214use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -0400215
David Tolnayb6254182018-08-25 08:44:54 -0400216pub use error::{Error, Result};
217pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -0400218
219/// Parsing interface implemented by all types that can be parsed in a default
220/// way from a token stream.
221pub trait Parse: Sized {
222 fn parse(input: ParseStream) -> Result<Self>;
223}
224
225/// Input to a Syn parser function.
David Tolnaya0daa482018-09-01 02:09:40 -0700226///
227/// See the methods of this type under the documentation of [`ParseBuffer`]. For
228/// an overview of parsing in Syn, refer to the [module documentation].
229///
230/// [module documentation]: index.html
David Tolnay18c754c2018-08-21 23:26:58 -0400231pub type ParseStream<'a> = &'a ParseBuffer<'a>;
232
233/// Cursor position within a buffered token stream.
David Tolnay20d29a12018-09-01 15:15:33 -0700234///
235/// This type is more commonly used through the type alias [`ParseStream`] which
236/// is an alias for `&ParseBuffer`.
237///
238/// `ParseStream` is the input type for all parser functions in Syn. They have
239/// the signature `fn(ParseStream) -> Result<T>`.
David Tolnay18c754c2018-08-21 23:26:58 -0400240pub struct ParseBuffer<'a> {
241 scope: Span,
David Tolnay5d7f2252018-09-02 08:21:40 -0700242 // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
243 // The rest of the code in this module needs to be careful that only a
244 // cursor derived from this `cell` is ever assigned to this `cell`.
245 //
246 // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
247 // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
248 // than 'a, and then assign a Cursor<'short> into the Cell.
249 //
250 // By extension, it would not be safe to expose an API that accepts a
251 // Cursor<'a> and trusts that it lives as long as the cursor currently in
252 // the cell.
David Tolnay18c754c2018-08-21 23:26:58 -0400253 cell: Cell<Cursor<'static>>,
254 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400255 unexpected: Rc<Cell<Option<Span>>>,
256}
257
258impl<'a> Drop for ParseBuffer<'a> {
259 fn drop(&mut self) {
260 if !self.is_empty() && self.unexpected.get().is_none() {
261 self.unexpected.set(Some(self.cursor().span()));
262 }
263 }
David Tolnay18c754c2018-08-21 23:26:58 -0400264}
265
David Tolnay642832f2018-09-01 13:08:10 -0700266/// Cursor state associated with speculative parsing.
267///
268/// This type is the input of the closure provided to [`ParseStream::step`].
269///
270/// [`ParseStream::step`]: struct.ParseBuffer.html#method.step
David Tolnay9bd34392018-09-01 13:19:53 -0700271///
272/// # Example
273///
274/// ```
275/// # extern crate proc_macro2;
276/// # extern crate syn;
277/// #
278/// use proc_macro2::TokenTree;
279/// use syn::parse::{ParseStream, Result};
280///
281/// // This function advances the stream past the next occurrence of `@`. If
282/// // no `@` is present in the stream, the stream position is unchanged and
283/// // an error is returned.
284/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
285/// input.step(|cursor| {
286/// let mut rest = *cursor;
287/// while let Some((tt, next)) = cursor.token_tree() {
288/// match tt {
289/// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
290/// return Ok(((), next));
291/// }
292/// _ => rest = next,
293/// }
294/// }
295/// Err(cursor.error("no `@` was found after this point"))
296/// })
297/// }
298/// #
299/// # fn main() {}
300/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400301#[derive(Copy, Clone)]
302pub struct StepCursor<'c, 'a> {
303 scope: Span,
304 cursor: Cursor<'c>,
305 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
306}
307
308impl<'c, 'a> Deref for StepCursor<'c, 'a> {
309 type Target = Cursor<'c>;
310
311 fn deref(&self) -> &Self::Target {
312 &self.cursor
313 }
314}
315
316impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700317 /// Triggers an error at the current position of the parse stream.
318 ///
319 /// The `ParseStream::step` invocation will return this same error without
320 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400321 pub fn error<T: Display>(self, message: T) -> Error {
322 error::new_at(self.scope, self.cursor, message)
323 }
324}
325
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700326impl private {
327 pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
328 let _ = proof;
329 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
330 }
331}
332
David Tolnay66cb0c42018-08-31 09:01:30 -0700333fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700334 input
335 .step(|cursor| {
336 if let Some((_lifetime, rest)) = cursor.lifetime() {
337 Ok((true, rest))
338 } else if let Some((_token, rest)) = cursor.token_tree() {
339 Ok((true, rest))
340 } else {
341 Ok((false, *cursor))
342 }
343 }).unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700344}
345
David Tolnay10951d52018-08-31 10:27:39 -0700346impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700347 pub fn new_parse_buffer(
348 scope: Span,
349 cursor: Cursor,
350 unexpected: Rc<Cell<Option<Span>>>,
351 ) -> ParseBuffer {
David Tolnay18c754c2018-08-21 23:26:58 -0400352 ParseBuffer {
353 scope: scope,
David Tolnay5d7f2252018-09-02 08:21:40 -0700354 // See comment on `cell` in the struct definition.
355 cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
David Tolnay18c754c2018-08-21 23:26:58 -0400356 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400357 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400358 }
359 }
360
David Tolnay94f06632018-08-31 10:17:17 -0700361 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
362 buffer.unexpected.clone()
363 }
364}
365
366impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700367 /// Parses a syntax tree node of type `T`, advancing the position of our
368 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400369 pub fn parse<T: Parse>(&self) -> Result<T> {
370 T::parse(self)
371 }
372
David Tolnay725e1c62018-09-01 12:07:25 -0700373 /// Calls the given parser function to parse a syntax tree node of type `T`
374 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700375 ///
376 /// # Example
377 ///
378 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
379 /// zero or more outer attributes.
380 ///
381 /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
382 ///
383 /// ```
384 /// # extern crate syn;
385 /// #
386 /// use syn::{Attribute, Ident, Token};
387 /// use syn::parse::{Parse, ParseStream, Result};
388 ///
389 /// // Parses a unit struct with attributes.
390 /// //
391 /// // #[path = "s.tmpl"]
392 /// // struct S;
393 /// struct UnitStruct {
394 /// attrs: Vec<Attribute>,
395 /// struct_token: Token![struct],
396 /// name: Ident,
397 /// semi_token: Token![;],
398 /// }
399 ///
400 /// impl Parse for UnitStruct {
401 /// fn parse(input: ParseStream) -> Result<Self> {
402 /// Ok(UnitStruct {
403 /// attrs: input.call(Attribute::parse_outer)?,
404 /// struct_token: input.parse()?,
405 /// name: input.parse()?,
406 /// semi_token: input.parse()?,
407 /// })
408 /// }
409 /// }
410 /// #
411 /// # fn main() {}
412 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400413 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
414 function(self)
415 }
416
David Tolnay725e1c62018-09-01 12:07:25 -0700417 /// Looks at the next token in the parse stream to determine whether it
418 /// matches the requested type of token.
419 ///
420 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700421 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700422 /// # Syntax
423 ///
424 /// Note that this method does not use turbofish syntax. Pass the peek type
425 /// inside of parentheses.
426 ///
427 /// - `input.peek(Token![struct])`
428 /// - `input.peek(Token![==])`
429 /// - `input.peek(Ident)`
430 /// - `input.peek(Lifetime)`
431 /// - `input.peek(token::Brace)`
432 ///
David Tolnayddebc3e2018-09-01 16:29:20 -0700433 /// # Example
434 ///
435 /// In this example we finish parsing the list of supertraits when the next
436 /// token in the input is either `where` or an opening curly brace.
437 ///
438 /// ```
439 /// # extern crate syn;
440 /// #
441 /// use syn::{braced, token, Generics, Ident, Token, TypeParamBound};
442 /// use syn::parse::{Parse, ParseStream, Result};
443 /// use syn::punctuated::Punctuated;
444 ///
445 /// // Parses a trait definition containing no associated items.
446 /// //
447 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
448 /// struct MarkerTrait {
449 /// trait_token: Token![trait],
450 /// ident: Ident,
451 /// generics: Generics,
452 /// colon_token: Option<Token![:]>,
453 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
454 /// brace_token: token::Brace,
455 /// }
456 ///
457 /// impl Parse for MarkerTrait {
458 /// fn parse(input: ParseStream) -> Result<Self> {
459 /// let trait_token: Token![trait] = input.parse()?;
460 /// let ident: Ident = input.parse()?;
461 /// let mut generics: Generics = input.parse()?;
462 /// let colon_token: Option<Token![:]> = input.parse()?;
463 ///
464 /// let mut supertraits = Punctuated::new();
465 /// if colon_token.is_some() {
466 /// loop {
467 /// supertraits.push_value(input.parse()?);
468 /// if input.peek(Token![where]) || input.peek(token::Brace) {
469 /// break;
470 /// }
471 /// supertraits.push_punct(input.parse()?);
472 /// }
473 /// }
474 ///
475 /// generics.where_clause = input.parse()?;
476 /// let content;
477 /// let empty_brace_token = braced!(content in input);
478 ///
479 /// Ok(MarkerTrait {
480 /// trait_token: trait_token,
481 /// ident: ident,
482 /// generics: generics,
483 /// colon_token: colon_token,
484 /// supertraits: supertraits,
485 /// brace_token: empty_brace_token,
486 /// })
487 /// }
488 /// }
489 /// #
490 /// # fn main() {}
491 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400492 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700493 let _ = token;
494 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400495 }
496
David Tolnay725e1c62018-09-01 12:07:25 -0700497 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700498 ///
499 /// This is commonly useful as a way to implement contextual keywords.
500 ///
501 /// # Example
502 ///
503 /// This example needs to use `peek2` because the symbol `union` is not a
504 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
505 /// the very next token is `union`, because someone is free to write a `mod
506 /// union` and a macro invocation that looks like `union::some_macro! { ...
507 /// }`. In other words `union` is a contextual keyword.
508 ///
509 /// ```
510 /// # extern crate syn;
511 /// #
512 /// use syn::{Ident, ItemUnion, Macro, Token};
513 /// use syn::parse::{Parse, ParseStream, Result};
514 ///
515 /// // Parses either a union or a macro invocation.
516 /// enum UnionOrMacro {
517 /// // union MaybeUninit<T> { uninit: (), value: T }
518 /// Union(ItemUnion),
519 /// // lazy_static! { ... }
520 /// Macro(Macro),
521 /// }
522 ///
523 /// impl Parse for UnionOrMacro {
524 /// fn parse(input: ParseStream) -> Result<Self> {
525 /// if input.peek(Token![union]) && input.peek2(Ident) {
526 /// input.parse().map(UnionOrMacro::Union)
527 /// } else {
528 /// input.parse().map(UnionOrMacro::Macro)
529 /// }
530 /// }
531 /// }
532 /// #
533 /// # fn main() {}
534 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400535 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400536 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700537 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400538 }
539
David Tolnay725e1c62018-09-01 12:07:25 -0700540 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400541 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400542 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700543 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400544 }
545
David Tolnay725e1c62018-09-01 12:07:25 -0700546 /// Parses zero or more occurrences of `T` separated by punctuation of type
547 /// `P`, with optional trailing punctuation.
548 ///
549 /// Parsing continues until the end of this parse stream. The entire content
550 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700551 ///
552 /// # Example
553 ///
554 /// ```rust
555 /// # extern crate quote;
556 /// # extern crate syn;
557 /// #
558 /// # use quote::quote;
559 /// #
560 /// use syn::{parenthesized, token, Ident, Token, Type};
561 /// use syn::parse::{Parse, ParseStream, Result};
562 /// use syn::punctuated::Punctuated;
563 ///
564 /// // Parse a simplified tuple struct syntax like:
565 /// //
566 /// // struct S(A, B);
567 /// struct TupleStruct {
568 /// struct_token: Token![struct],
569 /// ident: Ident,
570 /// paren_token: token::Paren,
571 /// fields: Punctuated<Type, Token![,]>,
572 /// semi_token: Token![;],
573 /// }
574 ///
575 /// impl Parse for TupleStruct {
576 /// fn parse(input: ParseStream) -> Result<Self> {
577 /// let content;
578 /// Ok(TupleStruct {
579 /// struct_token: input.parse()?,
580 /// ident: input.parse()?,
581 /// paren_token: parenthesized!(content in input),
582 /// fields: content.parse_terminated(Type::parse)?,
583 /// semi_token: input.parse()?,
584 /// })
585 /// }
586 /// }
587 /// #
588 /// # fn main() {
589 /// # let input = quote! {
590 /// # struct S(A, B);
591 /// # };
592 /// # syn::parse2::<TupleStruct>(input).unwrap();
593 /// # }
594 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400595 pub fn parse_terminated<T, P: Parse>(
596 &self,
597 parser: fn(ParseStream) -> Result<T>,
598 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700599 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400600 }
601
David Tolnay725e1c62018-09-01 12:07:25 -0700602 /// Returns whether there are tokens remaining in this stream.
603 ///
604 /// This method returns true at the end of the content of a set of
605 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700606 ///
607 /// # Example
608 ///
609 /// ```rust
610 /// # extern crate syn;
611 /// #
612 /// use syn::{braced, token, Ident, Item, Token};
613 /// use syn::parse::{Parse, ParseStream, Result};
614 ///
615 /// // Parses a Rust `mod m { ... }` containing zero or more items.
616 /// struct Mod {
617 /// mod_token: Token![mod],
618 /// name: Ident,
619 /// brace_token: token::Brace,
620 /// items: Vec<Item>,
621 /// }
622 ///
623 /// impl Parse for Mod {
624 /// fn parse(input: ParseStream) -> Result<Self> {
625 /// let content;
626 /// Ok(Mod {
627 /// mod_token: input.parse()?,
628 /// name: input.parse()?,
629 /// brace_token: braced!(content in input),
630 /// items: {
631 /// let mut items = Vec::new();
632 /// while !content.is_empty() {
633 /// items.push(content.parse()?);
634 /// }
635 /// items
636 /// },
637 /// })
638 /// }
639 /// }
640 /// #
641 /// # fn main() {}
David Tolnayf5d30452018-09-01 02:29:04 -0700642 pub fn is_empty(&self) -> bool {
643 self.cursor().eof()
644 }
645
David Tolnay725e1c62018-09-01 12:07:25 -0700646 /// Constructs a helper for peeking at the next token in this stream and
647 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700648 ///
649 /// # Example
650 ///
651 /// ```
652 /// # extern crate syn;
653 /// #
654 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Token, TypeParam};
655 /// use syn::parse::{Parse, ParseStream, Result};
656 ///
657 /// // A generic parameter, a single one of the comma-separated elements inside
658 /// // angle brackets in:
659 /// //
660 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
661 /// //
662 /// // On invalid input, lookahead gives us a reasonable error message.
663 /// //
664 /// // error: expected one of: identifier, lifetime, `const`
665 /// // |
666 /// // 5 | fn f<!Sized>() {}
667 /// // | ^
668 /// enum GenericParam {
669 /// Type(TypeParam),
670 /// Lifetime(LifetimeDef),
671 /// Const(ConstParam),
672 /// }
673 ///
674 /// impl Parse for GenericParam {
675 /// fn parse(input: ParseStream) -> Result<Self> {
676 /// let lookahead = input.lookahead1();
677 /// if lookahead.peek(Ident) {
678 /// input.parse().map(GenericParam::Type)
679 /// } else if lookahead.peek(Lifetime) {
680 /// input.parse().map(GenericParam::Lifetime)
681 /// } else if lookahead.peek(Token![const]) {
682 /// input.parse().map(GenericParam::Const)
683 /// } else {
684 /// Err(lookahead.error())
685 /// }
686 /// }
687 /// }
688 /// #
689 /// # fn main() {}
690 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700691 pub fn lookahead1(&self) -> Lookahead1<'a> {
692 lookahead::new(self.scope, self.cursor())
693 }
694
David Tolnay725e1c62018-09-01 12:07:25 -0700695 /// Forks a parse stream so that parsing tokens out of either the original
696 /// or the fork does not advance the position of the other.
697 ///
698 /// # Performance
699 ///
700 /// Forking a parse stream is a cheap fixed amount of work and does not
701 /// involve copying token buffers. Where you might hit performance problems
702 /// is if your macro ends up parsing a large amount of content more than
703 /// once.
704 ///
705 /// ```
706 /// # use syn::Expr;
707 /// # use syn::parse::{ParseStream, Result};
708 /// #
709 /// # fn bad(input: ParseStream) -> Result<Expr> {
710 /// // Do not do this.
711 /// if input.fork().parse::<Expr>().is_ok() {
712 /// return input.parse::<Expr>();
713 /// }
714 /// # unimplemented!()
715 /// # }
716 /// ```
717 ///
718 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
719 /// parse stream. Only use a fork when the amount of work performed against
720 /// the fork is small and bounded.
721 ///
David Tolnayec149b02018-09-01 14:17:28 -0700722 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700723 /// speculative parsing, consider using [`ParseStream::step`] instead.
724 ///
725 /// [`ParseStream::step`]: #method.step
David Tolnayec149b02018-09-01 14:17:28 -0700726 ///
727 /// # Example
728 ///
729 /// The parse implementation shown here parses possibly restricted `pub`
730 /// visibilities.
731 ///
732 /// - `pub`
733 /// - `pub(crate)`
734 /// - `pub(self)`
735 /// - `pub(super)`
736 /// - `pub(in some::path)`
737 ///
738 /// To handle the case of visibilities inside of tuple structs, the parser
739 /// needs to distinguish parentheses that specify visibility restrictions
740 /// from parentheses that form part of a tuple type.
741 ///
742 /// ```
743 /// # struct A;
744 /// # struct B;
745 /// # struct C;
746 /// #
747 /// struct S(pub(crate) A, pub (B, C));
748 /// ```
749 ///
750 /// In this example input the first tuple struct element of `S` has
751 /// `pub(crate)` visibility while the second tuple struct element has `pub`
752 /// visibility; the parentheses around `(B, C)` are part of the type rather
753 /// than part of a visibility restriction.
754 ///
755 /// The parser uses a forked parse stream to check the first token inside of
756 /// parentheses after the `pub` keyword. This is a small bounded amount of
757 /// work performed against the forked parse stream.
758 ///
759 /// ```
760 /// # extern crate syn;
761 /// #
762 /// use syn::{parenthesized, token, Ident, Path, Token};
763 /// use syn::ext::IdentExt;
764 /// use syn::parse::{Parse, ParseStream, Result};
765 ///
766 /// struct PubVisibility {
767 /// pub_token: Token![pub],
768 /// restricted: Option<Restricted>,
769 /// }
770 ///
771 /// struct Restricted {
772 /// paren_token: token::Paren,
773 /// in_token: Option<Token![in]>,
774 /// path: Path,
775 /// }
776 ///
777 /// impl Parse for PubVisibility {
778 /// fn parse(input: ParseStream) -> Result<Self> {
779 /// let pub_token: Token![pub] = input.parse()?;
780 ///
781 /// if input.peek(token::Paren) {
782 /// let ahead = input.fork();
783 /// let mut content;
784 /// parenthesized!(content in ahead);
785 ///
786 /// if content.peek(Token![crate])
787 /// || content.peek(Token![self])
788 /// || content.peek(Token![super])
789 /// {
790 /// return Ok(PubVisibility {
791 /// pub_token: pub_token,
792 /// restricted: Some(Restricted {
793 /// paren_token: parenthesized!(content in input),
794 /// in_token: None,
795 /// path: Path::from(content.call(Ident::parse_any)?),
796 /// }),
797 /// });
798 /// } else if content.peek(Token![in]) {
799 /// return Ok(PubVisibility {
800 /// pub_token: pub_token,
801 /// restricted: Some(Restricted {
802 /// paren_token: parenthesized!(content in input),
803 /// in_token: Some(content.parse()?),
804 /// path: content.call(Path::parse_mod_style)?,
805 /// }),
806 /// });
807 /// }
808 /// }
809 ///
810 /// Ok(PubVisibility {
811 /// pub_token: pub_token,
812 /// restricted: None,
813 /// })
814 /// }
815 /// }
816 /// #
817 /// # fn main() {}
818 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400819 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400820 ParseBuffer {
821 scope: self.scope,
822 cell: self.cell.clone(),
823 marker: PhantomData,
824 // Not the parent's unexpected. Nothing cares whether the clone
825 // parses all the way.
826 unexpected: Rc::new(Cell::new(None)),
827 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400828 }
829
David Tolnay725e1c62018-09-01 12:07:25 -0700830 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700831 ///
832 /// # Example
833 ///
834 /// ```
835 /// # extern crate syn;
836 /// #
837 /// use syn::{Expr, Token};
838 /// use syn::parse::{Parse, ParseStream, Result};
839 ///
840 /// // Some kind of loop: `while` or `for` or `loop`.
841 /// struct Loop {
842 /// expr: Expr,
843 /// }
844 ///
845 /// impl Parse for Loop {
846 /// fn parse(input: ParseStream) -> Result<Self> {
847 /// if input.peek(Token![while])
848 /// || input.peek(Token![for])
849 /// || input.peek(Token![loop])
850 /// {
851 /// Ok(Loop {
852 /// expr: input.parse()?,
853 /// })
854 /// } else {
855 /// Err(input.error("expected some kind of loop"))
856 /// }
857 /// }
858 /// }
859 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400860 pub fn error<T: Display>(&self, message: T) -> Error {
861 error::new_at(self.scope, self.cursor(), message)
862 }
863
David Tolnay725e1c62018-09-01 12:07:25 -0700864 /// Speculatively parses tokens from this parse stream, advancing the
865 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700866 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700867 /// This is a powerful low-level API used for defining the `Parse` impls of
868 /// the basic built-in token types. It is not something that will be used
869 /// widely outside of the Syn codebase.
870 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700871 /// # Example
872 ///
873 /// ```
874 /// # extern crate proc_macro2;
875 /// # extern crate syn;
876 /// #
877 /// use proc_macro2::TokenTree;
878 /// use syn::parse::{ParseStream, Result};
879 ///
880 /// // This function advances the stream past the next occurrence of `@`. If
881 /// // no `@` is present in the stream, the stream position is unchanged and
882 /// // an error is returned.
883 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
884 /// input.step(|cursor| {
885 /// let mut rest = *cursor;
886 /// while let Some((tt, next)) = cursor.token_tree() {
887 /// match tt {
888 /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
889 /// return Ok(((), next));
890 /// }
891 /// _ => rest = next,
892 /// }
893 /// }
894 /// Err(cursor.error("no `@` was found after this point"))
895 /// })
896 /// }
897 /// #
898 /// # fn main() {}
899 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700900 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400901 where
902 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
903 {
David Tolnay6b65f852018-09-01 11:56:25 -0700904 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -0400905 scope: self.scope,
906 cursor: self.cell.get(),
907 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700908 })?;
909 self.cell.set(rest);
910 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -0400911 }
David Tolnayeafc8052018-08-25 16:33:53 -0400912
David Tolnay725e1c62018-09-01 12:07:25 -0700913 /// Provides low-level access to the token representation underlying this
914 /// parse stream.
915 ///
916 /// Cursors are immutable so no operations you perform against the cursor
917 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -0700918 pub fn cursor(&self) -> Cursor<'a> {
919 self.cell.get()
920 }
921
David Tolnay94f06632018-08-31 10:17:17 -0700922 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -0400923 match self.unexpected.get() {
924 Some(span) => Err(Error::new(span, "unexpected token")),
925 None => Ok(()),
926 }
927 }
David Tolnay18c754c2018-08-21 23:26:58 -0400928}
929
David Tolnaya7d69fc2018-08-26 13:30:24 -0400930impl<T: Parse> Parse for Box<T> {
931 fn parse(input: ParseStream) -> Result<Self> {
932 input.parse().map(Box::new)
933 }
934}
935
David Tolnay4fb71232018-08-25 23:14:50 -0400936impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400937 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -0700938 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -0400939 Ok(Some(input.parse()?))
940 } else {
941 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400942 }
David Tolnay18c754c2018-08-21 23:26:58 -0400943 }
944}
David Tolnay4ac232d2018-08-31 10:18:03 -0700945
David Tolnay80a914f2018-08-30 23:49:53 -0700946impl Parse for TokenStream {
947 fn parse(input: ParseStream) -> Result<Self> {
948 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
949 }
950}
951
952impl Parse for TokenTree {
953 fn parse(input: ParseStream) -> Result<Self> {
954 input.step(|cursor| match cursor.token_tree() {
955 Some((tt, rest)) => Ok((tt, rest)),
956 None => Err(cursor.error("expected token tree")),
957 })
958 }
959}
960
961impl Parse for Group {
962 fn parse(input: ParseStream) -> Result<Self> {
963 input.step(|cursor| {
964 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
965 if let Some((inside, span, rest)) = cursor.group(*delim) {
966 let mut group = Group::new(*delim, inside.token_stream());
967 group.set_span(span);
968 return Ok((group, rest));
969 }
970 }
971 Err(cursor.error("expected group token"))
972 })
973 }
974}
975
976impl Parse for Punct {
977 fn parse(input: ParseStream) -> Result<Self> {
978 input.step(|cursor| match cursor.punct() {
979 Some((punct, rest)) => Ok((punct, rest)),
980 None => Err(cursor.error("expected punctuation token")),
981 })
982 }
983}
984
985impl Parse for Literal {
986 fn parse(input: ParseStream) -> Result<Self> {
987 input.step(|cursor| match cursor.literal() {
988 Some((literal, rest)) => Ok((literal, rest)),
989 None => Err(cursor.error("expected literal token")),
990 })
991 }
992}
993
994/// Parser that can parse Rust tokens into a particular syntax tree node.
995///
996/// Refer to the [module documentation] for details about parsing in Syn.
997///
998/// [module documentation]: index.html
999///
1000/// *This trait is available if Syn is built with the `"parsing"` feature.*
1001pub trait Parser: Sized {
1002 type Output;
1003
1004 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
1005 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1006
1007 /// Parse tokens of source code into the chosen syntax tree node.
1008 ///
1009 /// *This method is available if Syn is built with both the `"parsing"` and
1010 /// `"proc-macro"` features.*
1011 #[cfg(all(
1012 not(all(target_arch = "wasm32", target_os = "unknown")),
1013 feature = "proc-macro"
1014 ))]
1015 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1016 self.parse2(proc_macro2::TokenStream::from(tokens))
1017 }
1018
1019 /// Parse a string of Rust code into the chosen syntax tree node.
1020 ///
1021 /// # Hygiene
1022 ///
1023 /// Every span in the resulting syntax tree will be set to resolve at the
1024 /// macro call site.
1025 fn parse_str(self, s: &str) -> Result<Self::Output> {
1026 self.parse2(proc_macro2::TokenStream::from_str(s)?)
1027 }
1028}
1029
David Tolnay7b07aa12018-09-01 11:41:12 -07001030fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1031 let scope = Span::call_site();
1032 let cursor = tokens.begin();
1033 let unexpected = Rc::new(Cell::new(None));
1034 private::new_parse_buffer(scope, cursor, unexpected)
1035}
1036
David Tolnay80a914f2018-08-30 23:49:53 -07001037impl<F, T> Parser for F
1038where
1039 F: FnOnce(ParseStream) -> Result<T>,
1040{
1041 type Output = T;
1042
1043 fn parse2(self, tokens: TokenStream) -> Result<T> {
1044 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -07001045 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -07001046 let node = self(&state)?;
1047 state.check_unexpected()?;
1048 if state.is_empty() {
1049 Ok(node)
1050 } else {
1051 Err(state.error("unexpected token"))
1052 }
1053 }
1054}