blob: b24382780535d0d0e9335fb6e3128bc3315a626b [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 Tolnaye0c51762018-08-31 11:05:22 -070021//! The `ParseStream`-based interface is convenient for parser implementations,
22//! but not necessarily when you just have some tokens that you want to parse.
23//! For that we expose the following two entry points.
David Tolnay80a914f2018-08-30 23:49:53 -070024//!
25//! ## The `syn::parse*` functions
26//!
27//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
28//! as an entry point for parsing syntax tree nodes that can be parsed in an
29//! obvious default way. These functions can return any syntax tree node that
David Tolnay8aacee12018-08-31 09:15:15 -070030//! implements the [`Parse`] trait, which includes most types in Syn.
David Tolnay80a914f2018-08-30 23:49:53 -070031//!
32//! [`syn::parse`]: ../fn.parse.html
33//! [`syn::parse2`]: ../fn.parse2.html
34//! [`syn::parse_str`]: ../fn.parse_str.html
David Tolnay8aacee12018-08-31 09:15:15 -070035//! [`Parse`]: trait.Parse.html
David Tolnay80a914f2018-08-30 23:49:53 -070036//!
37//! ```
38//! use syn::Type;
39//!
David Tolnay8aacee12018-08-31 09:15:15 -070040//! # fn run_parser() -> Result<(), syn::parse::Error> {
David Tolnay80a914f2018-08-30 23:49:53 -070041//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
42//! # Ok(())
43//! # }
44//! #
45//! # fn main() {
46//! # run_parser().unwrap();
47//! # }
48//! ```
49//!
50//! The [`parse_quote!`] macro also uses this approach.
51//!
52//! [`parse_quote!`]: ../macro.parse_quote.html
53//!
54//! ## The `Parser` trait
55//!
56//! Some types can be parsed in several ways depending on context. For example
57//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
58//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
59//! may or may not allow trailing punctuation, and parsing it the wrong way
60//! would either reject valid input or accept invalid input.
61//!
62//! [`Attribute`]: ../struct.Attribute.html
63//! [`Punctuated`]: ../punctuated/index.html
64//!
David Tolnaye0c51762018-08-31 11:05:22 -070065//! The `Parse` trait is not implemented in these cases because there is no good
David Tolnay80a914f2018-08-30 23:49:53 -070066//! behavior to consider the default.
67//!
68//! ```ignore
69//! // Can't parse `Punctuated` without knowing whether trailing punctuation
70//! // should be allowed in this context.
71//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
72//! ```
73//!
74//! In these cases the types provide a choice of parser functions rather than a
David Tolnaye0c51762018-08-31 11:05:22 -070075//! single `Parse` implementation, and those parser functions can be invoked
David Tolnay80a914f2018-08-30 23:49:53 -070076//! through the [`Parser`] trait.
77//!
78//! [`Parser`]: trait.Parser.html
79//!
80//! ```
David Tolnay80a914f2018-08-30 23:49:53 -070081//! # extern crate syn;
82//! #
83//! # extern crate proc_macro2;
84//! # use proc_macro2::TokenStream;
85//! #
David Tolnay3e3f7752018-08-31 09:33:59 -070086//! use syn::parse::Parser;
David Tolnay80a914f2018-08-30 23:49:53 -070087//! use syn::punctuated::Punctuated;
David Tolnay9b00f652018-09-01 10:31:02 -070088//! use syn::{Attribute, Expr, PathSegment, Token};
David Tolnay80a914f2018-08-30 23:49:53 -070089//!
David Tolnay3e3f7752018-08-31 09:33:59 -070090//! # fn run_parsers() -> Result<(), syn::parse::Error> {
David Tolnay80a914f2018-08-30 23:49:53 -070091//! # let tokens = TokenStream::new().into();
92//! // Parse a nonempty sequence of path segments separated by `::` punctuation
93//! // with no trailing punctuation.
94//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
95//! let path = parser.parse(tokens)?;
96//!
97//! # let tokens = TokenStream::new().into();
98//! // Parse a possibly empty sequence of expressions terminated by commas with
99//! // an optional trailing punctuation.
100//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
101//! let args = parser.parse(tokens)?;
102//!
103//! # let tokens = TokenStream::new().into();
104//! // Parse zero or more outer attributes but not inner attributes.
David Tolnay3e3f7752018-08-31 09:33:59 -0700105//! let parser = Attribute::parse_outer;
106//! let attrs = parser.parse(tokens)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700107//! #
108//! # Ok(())
109//! # }
110//! #
111//! # fn main() {}
112//! ```
113//!
David Tolnaye0c51762018-08-31 11:05:22 -0700114//! ---
David Tolnay80a914f2018-08-30 23:49:53 -0700115//!
116//! *This module is available if Syn is built with the `"parsing"` feature.*
David Tolnay18c754c2018-08-21 23:26:58 -0400117
118use std::cell::Cell;
119use std::fmt::Display;
120use std::marker::PhantomData;
121use std::mem;
122use std::ops::Deref;
David Tolnayeafc8052018-08-25 16:33:53 -0400123use std::rc::Rc;
David Tolnay80a914f2018-08-30 23:49:53 -0700124use std::str::FromStr;
David Tolnayeafc8052018-08-25 16:33:53 -0400125
David Tolnay80a914f2018-08-30 23:49:53 -0700126#[cfg(all(
127 not(all(target_arch = "wasm32", target_os = "unknown")),
128 feature = "proc-macro"
129))]
130use proc_macro;
David Tolnayf07b3342018-09-01 11:58:11 -0700131use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
David Tolnay18c754c2018-08-21 23:26:58 -0400132
David Tolnay80a914f2018-08-30 23:49:53 -0700133use buffer::{Cursor, TokenBuffer};
David Tolnayb6254182018-08-25 08:44:54 -0400134use error;
David Tolnay94f06632018-08-31 10:17:17 -0700135use lookahead;
136use private;
David Tolnay577d0332018-08-25 21:45:24 -0400137use punctuated::Punctuated;
David Tolnay4fb71232018-08-25 23:14:50 -0400138use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -0400139
David Tolnayb6254182018-08-25 08:44:54 -0400140pub use error::{Error, Result};
141pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -0400142
143/// Parsing interface implemented by all types that can be parsed in a default
144/// way from a token stream.
145pub trait Parse: Sized {
146 fn parse(input: ParseStream) -> Result<Self>;
147}
148
149/// Input to a Syn parser function.
David Tolnaya0daa482018-09-01 02:09:40 -0700150///
151/// See the methods of this type under the documentation of [`ParseBuffer`]. For
152/// an overview of parsing in Syn, refer to the [module documentation].
153///
154/// [module documentation]: index.html
David Tolnay18c754c2018-08-21 23:26:58 -0400155pub type ParseStream<'a> = &'a ParseBuffer<'a>;
156
157/// Cursor position within a buffered token stream.
David Tolnay20d29a12018-09-01 15:15:33 -0700158///
159/// This type is more commonly used through the type alias [`ParseStream`] which
160/// is an alias for `&ParseBuffer`.
161///
162/// `ParseStream` is the input type for all parser functions in Syn. They have
163/// the signature `fn(ParseStream) -> Result<T>`.
David Tolnay18c754c2018-08-21 23:26:58 -0400164pub struct ParseBuffer<'a> {
165 scope: Span,
166 cell: Cell<Cursor<'static>>,
167 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400168 unexpected: Rc<Cell<Option<Span>>>,
169}
170
171impl<'a> Drop for ParseBuffer<'a> {
172 fn drop(&mut self) {
173 if !self.is_empty() && self.unexpected.get().is_none() {
174 self.unexpected.set(Some(self.cursor().span()));
175 }
176 }
David Tolnay18c754c2018-08-21 23:26:58 -0400177}
178
David Tolnay642832f2018-09-01 13:08:10 -0700179/// Cursor state associated with speculative parsing.
180///
181/// This type is the input of the closure provided to [`ParseStream::step`].
182///
183/// [`ParseStream::step`]: struct.ParseBuffer.html#method.step
David Tolnay9bd34392018-09-01 13:19:53 -0700184///
185/// # Example
186///
187/// ```
188/// # extern crate proc_macro2;
189/// # extern crate syn;
190/// #
191/// use proc_macro2::TokenTree;
192/// use syn::parse::{ParseStream, Result};
193///
194/// // This function advances the stream past the next occurrence of `@`. If
195/// // no `@` is present in the stream, the stream position is unchanged and
196/// // an error is returned.
197/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
198/// input.step(|cursor| {
199/// let mut rest = *cursor;
200/// while let Some((tt, next)) = cursor.token_tree() {
201/// match tt {
202/// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
203/// return Ok(((), next));
204/// }
205/// _ => rest = next,
206/// }
207/// }
208/// Err(cursor.error("no `@` was found after this point"))
209/// })
210/// }
211/// #
212/// # fn main() {}
213/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400214#[derive(Copy, Clone)]
215pub struct StepCursor<'c, 'a> {
216 scope: Span,
217 cursor: Cursor<'c>,
218 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
219}
220
221impl<'c, 'a> Deref for StepCursor<'c, 'a> {
222 type Target = Cursor<'c>;
223
224 fn deref(&self) -> &Self::Target {
225 &self.cursor
226 }
227}
228
229impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700230 /// Triggers an error at the current position of the parse stream.
231 ///
232 /// The `ParseStream::step` invocation will return this same error without
233 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400234 pub fn error<T: Display>(self, message: T) -> Error {
235 error::new_at(self.scope, self.cursor, message)
236 }
237}
238
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700239impl private {
240 pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
241 let _ = proof;
242 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
243 }
244}
245
David Tolnay66cb0c42018-08-31 09:01:30 -0700246fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700247 input
248 .step(|cursor| {
249 if let Some((_lifetime, rest)) = cursor.lifetime() {
250 Ok((true, rest))
251 } else if let Some((_token, rest)) = cursor.token_tree() {
252 Ok((true, rest))
253 } else {
254 Ok((false, *cursor))
255 }
256 }).unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700257}
258
David Tolnay10951d52018-08-31 10:27:39 -0700259impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700260 pub fn new_parse_buffer(
261 scope: Span,
262 cursor: Cursor,
263 unexpected: Rc<Cell<Option<Span>>>,
264 ) -> ParseBuffer {
David Tolnay94f06632018-08-31 10:17:17 -0700265 let extend = unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) };
David Tolnay18c754c2018-08-21 23:26:58 -0400266 ParseBuffer {
267 scope: scope,
268 cell: Cell::new(extend),
269 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400270 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400271 }
272 }
273
David Tolnay94f06632018-08-31 10:17:17 -0700274 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
275 buffer.unexpected.clone()
276 }
277}
278
279impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700280 /// Parses a syntax tree node of type `T`, advancing the position of our
281 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400282 pub fn parse<T: Parse>(&self) -> Result<T> {
283 T::parse(self)
284 }
285
David Tolnay725e1c62018-09-01 12:07:25 -0700286 /// Calls the given parser function to parse a syntax tree node of type `T`
287 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700288 ///
289 /// # Example
290 ///
291 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
292 /// zero or more outer attributes.
293 ///
294 /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
295 ///
296 /// ```
297 /// # extern crate syn;
298 /// #
299 /// use syn::{Attribute, Ident, Token};
300 /// use syn::parse::{Parse, ParseStream, Result};
301 ///
302 /// // Parses a unit struct with attributes.
303 /// //
304 /// // #[path = "s.tmpl"]
305 /// // struct S;
306 /// struct UnitStruct {
307 /// attrs: Vec<Attribute>,
308 /// struct_token: Token![struct],
309 /// name: Ident,
310 /// semi_token: Token![;],
311 /// }
312 ///
313 /// impl Parse for UnitStruct {
314 /// fn parse(input: ParseStream) -> Result<Self> {
315 /// Ok(UnitStruct {
316 /// attrs: input.call(Attribute::parse_outer)?,
317 /// struct_token: input.parse()?,
318 /// name: input.parse()?,
319 /// semi_token: input.parse()?,
320 /// })
321 /// }
322 /// }
323 /// #
324 /// # fn main() {}
325 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400326 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
327 function(self)
328 }
329
David Tolnay725e1c62018-09-01 12:07:25 -0700330 /// Looks at the next token in the parse stream to determine whether it
331 /// matches the requested type of token.
332 ///
333 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700334 ///
335 /// # Example
336 ///
337 /// In this example we finish parsing the list of supertraits when the next
338 /// token in the input is either `where` or an opening curly brace.
339 ///
340 /// ```
341 /// # extern crate syn;
342 /// #
343 /// use syn::{braced, token, Generics, Ident, Token, TypeParamBound};
344 /// use syn::parse::{Parse, ParseStream, Result};
345 /// use syn::punctuated::Punctuated;
346 ///
347 /// // Parses a trait definition containing no associated items.
348 /// //
349 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
350 /// struct MarkerTrait {
351 /// trait_token: Token![trait],
352 /// ident: Ident,
353 /// generics: Generics,
354 /// colon_token: Option<Token![:]>,
355 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
356 /// brace_token: token::Brace,
357 /// }
358 ///
359 /// impl Parse for MarkerTrait {
360 /// fn parse(input: ParseStream) -> Result<Self> {
361 /// let trait_token: Token![trait] = input.parse()?;
362 /// let ident: Ident = input.parse()?;
363 /// let mut generics: Generics = input.parse()?;
364 /// let colon_token: Option<Token![:]> = input.parse()?;
365 ///
366 /// let mut supertraits = Punctuated::new();
367 /// if colon_token.is_some() {
368 /// loop {
369 /// supertraits.push_value(input.parse()?);
370 /// if input.peek(Token![where]) || input.peek(token::Brace) {
371 /// break;
372 /// }
373 /// supertraits.push_punct(input.parse()?);
374 /// }
375 /// }
376 ///
377 /// generics.where_clause = input.parse()?;
378 /// let content;
379 /// let empty_brace_token = braced!(content in input);
380 ///
381 /// Ok(MarkerTrait {
382 /// trait_token: trait_token,
383 /// ident: ident,
384 /// generics: generics,
385 /// colon_token: colon_token,
386 /// supertraits: supertraits,
387 /// brace_token: empty_brace_token,
388 /// })
389 /// }
390 /// }
391 /// #
392 /// # fn main() {}
393 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400394 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700395 let _ = token;
396 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400397 }
398
David Tolnay725e1c62018-09-01 12:07:25 -0700399 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700400 ///
401 /// This is commonly useful as a way to implement contextual keywords.
402 ///
403 /// # Example
404 ///
405 /// This example needs to use `peek2` because the symbol `union` is not a
406 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
407 /// the very next token is `union`, because someone is free to write a `mod
408 /// union` and a macro invocation that looks like `union::some_macro! { ...
409 /// }`. In other words `union` is a contextual keyword.
410 ///
411 /// ```
412 /// # extern crate syn;
413 /// #
414 /// use syn::{Ident, ItemUnion, Macro, Token};
415 /// use syn::parse::{Parse, ParseStream, Result};
416 ///
417 /// // Parses either a union or a macro invocation.
418 /// enum UnionOrMacro {
419 /// // union MaybeUninit<T> { uninit: (), value: T }
420 /// Union(ItemUnion),
421 /// // lazy_static! { ... }
422 /// Macro(Macro),
423 /// }
424 ///
425 /// impl Parse for UnionOrMacro {
426 /// fn parse(input: ParseStream) -> Result<Self> {
427 /// if input.peek(Token![union]) && input.peek2(Ident) {
428 /// input.parse().map(UnionOrMacro::Union)
429 /// } else {
430 /// input.parse().map(UnionOrMacro::Macro)
431 /// }
432 /// }
433 /// }
434 /// #
435 /// # fn main() {}
436 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400437 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400438 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700439 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400440 }
441
David Tolnay725e1c62018-09-01 12:07:25 -0700442 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400443 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400444 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700445 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400446 }
447
David Tolnay725e1c62018-09-01 12:07:25 -0700448 /// Parses zero or more occurrences of `T` separated by punctuation of type
449 /// `P`, with optional trailing punctuation.
450 ///
451 /// Parsing continues until the end of this parse stream. The entire content
452 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700453 ///
454 /// # Example
455 ///
456 /// ```rust
457 /// # extern crate quote;
458 /// # extern crate syn;
459 /// #
460 /// # use quote::quote;
461 /// #
462 /// use syn::{parenthesized, token, Ident, Token, Type};
463 /// use syn::parse::{Parse, ParseStream, Result};
464 /// use syn::punctuated::Punctuated;
465 ///
466 /// // Parse a simplified tuple struct syntax like:
467 /// //
468 /// // struct S(A, B);
469 /// struct TupleStruct {
470 /// struct_token: Token![struct],
471 /// ident: Ident,
472 /// paren_token: token::Paren,
473 /// fields: Punctuated<Type, Token![,]>,
474 /// semi_token: Token![;],
475 /// }
476 ///
477 /// impl Parse for TupleStruct {
478 /// fn parse(input: ParseStream) -> Result<Self> {
479 /// let content;
480 /// Ok(TupleStruct {
481 /// struct_token: input.parse()?,
482 /// ident: input.parse()?,
483 /// paren_token: parenthesized!(content in input),
484 /// fields: content.parse_terminated(Type::parse)?,
485 /// semi_token: input.parse()?,
486 /// })
487 /// }
488 /// }
489 /// #
490 /// # fn main() {
491 /// # let input = quote! {
492 /// # struct S(A, B);
493 /// # };
494 /// # syn::parse2::<TupleStruct>(input).unwrap();
495 /// # }
496 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400497 pub fn parse_terminated<T, P: Parse>(
498 &self,
499 parser: fn(ParseStream) -> Result<T>,
500 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700501 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400502 }
503
David Tolnay725e1c62018-09-01 12:07:25 -0700504 /// Returns whether there are tokens remaining in this stream.
505 ///
506 /// This method returns true at the end of the content of a set of
507 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700508 ///
509 /// # Example
510 ///
511 /// ```rust
512 /// # extern crate syn;
513 /// #
514 /// use syn::{braced, token, Ident, Item, Token};
515 /// use syn::parse::{Parse, ParseStream, Result};
516 ///
517 /// // Parses a Rust `mod m { ... }` containing zero or more items.
518 /// struct Mod {
519 /// mod_token: Token![mod],
520 /// name: Ident,
521 /// brace_token: token::Brace,
522 /// items: Vec<Item>,
523 /// }
524 ///
525 /// impl Parse for Mod {
526 /// fn parse(input: ParseStream) -> Result<Self> {
527 /// let content;
528 /// Ok(Mod {
529 /// mod_token: input.parse()?,
530 /// name: input.parse()?,
531 /// brace_token: braced!(content in input),
532 /// items: {
533 /// let mut items = Vec::new();
534 /// while !content.is_empty() {
535 /// items.push(content.parse()?);
536 /// }
537 /// items
538 /// },
539 /// })
540 /// }
541 /// }
542 /// #
543 /// # fn main() {}
David Tolnayf5d30452018-09-01 02:29:04 -0700544 pub fn is_empty(&self) -> bool {
545 self.cursor().eof()
546 }
547
David Tolnay725e1c62018-09-01 12:07:25 -0700548 /// Constructs a helper for peeking at the next token in this stream and
549 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700550 ///
551 /// # Example
552 ///
553 /// ```
554 /// # extern crate syn;
555 /// #
556 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Token, TypeParam};
557 /// use syn::parse::{Parse, ParseStream, Result};
558 ///
559 /// // A generic parameter, a single one of the comma-separated elements inside
560 /// // angle brackets in:
561 /// //
562 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
563 /// //
564 /// // On invalid input, lookahead gives us a reasonable error message.
565 /// //
566 /// // error: expected one of: identifier, lifetime, `const`
567 /// // |
568 /// // 5 | fn f<!Sized>() {}
569 /// // | ^
570 /// enum GenericParam {
571 /// Type(TypeParam),
572 /// Lifetime(LifetimeDef),
573 /// Const(ConstParam),
574 /// }
575 ///
576 /// impl Parse for GenericParam {
577 /// fn parse(input: ParseStream) -> Result<Self> {
578 /// let lookahead = input.lookahead1();
579 /// if lookahead.peek(Ident) {
580 /// input.parse().map(GenericParam::Type)
581 /// } else if lookahead.peek(Lifetime) {
582 /// input.parse().map(GenericParam::Lifetime)
583 /// } else if lookahead.peek(Token![const]) {
584 /// input.parse().map(GenericParam::Const)
585 /// } else {
586 /// Err(lookahead.error())
587 /// }
588 /// }
589 /// }
590 /// #
591 /// # fn main() {}
592 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700593 pub fn lookahead1(&self) -> Lookahead1<'a> {
594 lookahead::new(self.scope, self.cursor())
595 }
596
David Tolnay725e1c62018-09-01 12:07:25 -0700597 /// Forks a parse stream so that parsing tokens out of either the original
598 /// or the fork does not advance the position of the other.
599 ///
600 /// # Performance
601 ///
602 /// Forking a parse stream is a cheap fixed amount of work and does not
603 /// involve copying token buffers. Where you might hit performance problems
604 /// is if your macro ends up parsing a large amount of content more than
605 /// once.
606 ///
607 /// ```
608 /// # use syn::Expr;
609 /// # use syn::parse::{ParseStream, Result};
610 /// #
611 /// # fn bad(input: ParseStream) -> Result<Expr> {
612 /// // Do not do this.
613 /// if input.fork().parse::<Expr>().is_ok() {
614 /// return input.parse::<Expr>();
615 /// }
616 /// # unimplemented!()
617 /// # }
618 /// ```
619 ///
620 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
621 /// parse stream. Only use a fork when the amount of work performed against
622 /// the fork is small and bounded.
623 ///
David Tolnayec149b02018-09-01 14:17:28 -0700624 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700625 /// speculative parsing, consider using [`ParseStream::step`] instead.
626 ///
627 /// [`ParseStream::step`]: #method.step
David Tolnayec149b02018-09-01 14:17:28 -0700628 ///
629 /// # Example
630 ///
631 /// The parse implementation shown here parses possibly restricted `pub`
632 /// visibilities.
633 ///
634 /// - `pub`
635 /// - `pub(crate)`
636 /// - `pub(self)`
637 /// - `pub(super)`
638 /// - `pub(in some::path)`
639 ///
640 /// To handle the case of visibilities inside of tuple structs, the parser
641 /// needs to distinguish parentheses that specify visibility restrictions
642 /// from parentheses that form part of a tuple type.
643 ///
644 /// ```
645 /// # struct A;
646 /// # struct B;
647 /// # struct C;
648 /// #
649 /// struct S(pub(crate) A, pub (B, C));
650 /// ```
651 ///
652 /// In this example input the first tuple struct element of `S` has
653 /// `pub(crate)` visibility while the second tuple struct element has `pub`
654 /// visibility; the parentheses around `(B, C)` are part of the type rather
655 /// than part of a visibility restriction.
656 ///
657 /// The parser uses a forked parse stream to check the first token inside of
658 /// parentheses after the `pub` keyword. This is a small bounded amount of
659 /// work performed against the forked parse stream.
660 ///
661 /// ```
662 /// # extern crate syn;
663 /// #
664 /// use syn::{parenthesized, token, Ident, Path, Token};
665 /// use syn::ext::IdentExt;
666 /// use syn::parse::{Parse, ParseStream, Result};
667 ///
668 /// struct PubVisibility {
669 /// pub_token: Token![pub],
670 /// restricted: Option<Restricted>,
671 /// }
672 ///
673 /// struct Restricted {
674 /// paren_token: token::Paren,
675 /// in_token: Option<Token![in]>,
676 /// path: Path,
677 /// }
678 ///
679 /// impl Parse for PubVisibility {
680 /// fn parse(input: ParseStream) -> Result<Self> {
681 /// let pub_token: Token![pub] = input.parse()?;
682 ///
683 /// if input.peek(token::Paren) {
684 /// let ahead = input.fork();
685 /// let mut content;
686 /// parenthesized!(content in ahead);
687 ///
688 /// if content.peek(Token![crate])
689 /// || content.peek(Token![self])
690 /// || content.peek(Token![super])
691 /// {
692 /// return Ok(PubVisibility {
693 /// pub_token: pub_token,
694 /// restricted: Some(Restricted {
695 /// paren_token: parenthesized!(content in input),
696 /// in_token: None,
697 /// path: Path::from(content.call(Ident::parse_any)?),
698 /// }),
699 /// });
700 /// } else if content.peek(Token![in]) {
701 /// return Ok(PubVisibility {
702 /// pub_token: pub_token,
703 /// restricted: Some(Restricted {
704 /// paren_token: parenthesized!(content in input),
705 /// in_token: Some(content.parse()?),
706 /// path: content.call(Path::parse_mod_style)?,
707 /// }),
708 /// });
709 /// }
710 /// }
711 ///
712 /// Ok(PubVisibility {
713 /// pub_token: pub_token,
714 /// restricted: None,
715 /// })
716 /// }
717 /// }
718 /// #
719 /// # fn main() {}
720 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400721 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400722 ParseBuffer {
723 scope: self.scope,
724 cell: self.cell.clone(),
725 marker: PhantomData,
726 // Not the parent's unexpected. Nothing cares whether the clone
727 // parses all the way.
728 unexpected: Rc::new(Cell::new(None)),
729 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400730 }
731
David Tolnay725e1c62018-09-01 12:07:25 -0700732 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700733 ///
734 /// # Example
735 ///
736 /// ```
737 /// # extern crate syn;
738 /// #
739 /// use syn::{Expr, Token};
740 /// use syn::parse::{Parse, ParseStream, Result};
741 ///
742 /// // Some kind of loop: `while` or `for` or `loop`.
743 /// struct Loop {
744 /// expr: Expr,
745 /// }
746 ///
747 /// impl Parse for Loop {
748 /// fn parse(input: ParseStream) -> Result<Self> {
749 /// if input.peek(Token![while])
750 /// || input.peek(Token![for])
751 /// || input.peek(Token![loop])
752 /// {
753 /// Ok(Loop {
754 /// expr: input.parse()?,
755 /// })
756 /// } else {
757 /// Err(input.error("expected some kind of loop"))
758 /// }
759 /// }
760 /// }
761 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400762 pub fn error<T: Display>(&self, message: T) -> Error {
763 error::new_at(self.scope, self.cursor(), message)
764 }
765
David Tolnay725e1c62018-09-01 12:07:25 -0700766 /// Speculatively parses tokens from this parse stream, advancing the
767 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700768 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700769 /// This is a powerful low-level API used for defining the `Parse` impls of
770 /// the basic built-in token types. It is not something that will be used
771 /// widely outside of the Syn codebase.
772 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700773 /// # Example
774 ///
775 /// ```
776 /// # extern crate proc_macro2;
777 /// # extern crate syn;
778 /// #
779 /// use proc_macro2::TokenTree;
780 /// use syn::parse::{ParseStream, Result};
781 ///
782 /// // This function advances the stream past the next occurrence of `@`. If
783 /// // no `@` is present in the stream, the stream position is unchanged and
784 /// // an error is returned.
785 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
786 /// input.step(|cursor| {
787 /// let mut rest = *cursor;
788 /// while let Some((tt, next)) = cursor.token_tree() {
789 /// match tt {
790 /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
791 /// return Ok(((), next));
792 /// }
793 /// _ => rest = next,
794 /// }
795 /// }
796 /// Err(cursor.error("no `@` was found after this point"))
797 /// })
798 /// }
799 /// #
800 /// # fn main() {}
801 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700802 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400803 where
804 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
805 {
David Tolnay6b65f852018-09-01 11:56:25 -0700806 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -0400807 scope: self.scope,
808 cursor: self.cell.get(),
809 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700810 })?;
811 self.cell.set(rest);
812 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -0400813 }
David Tolnayeafc8052018-08-25 16:33:53 -0400814
David Tolnay725e1c62018-09-01 12:07:25 -0700815 /// Provides low-level access to the token representation underlying this
816 /// parse stream.
817 ///
818 /// Cursors are immutable so no operations you perform against the cursor
819 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -0700820 pub fn cursor(&self) -> Cursor<'a> {
821 self.cell.get()
822 }
823
David Tolnay94f06632018-08-31 10:17:17 -0700824 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -0400825 match self.unexpected.get() {
826 Some(span) => Err(Error::new(span, "unexpected token")),
827 None => Ok(()),
828 }
829 }
David Tolnay18c754c2018-08-21 23:26:58 -0400830}
831
David Tolnaya7d69fc2018-08-26 13:30:24 -0400832impl<T: Parse> Parse for Box<T> {
833 fn parse(input: ParseStream) -> Result<Self> {
834 input.parse().map(Box::new)
835 }
836}
837
David Tolnay4fb71232018-08-25 23:14:50 -0400838impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400839 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -0700840 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -0400841 Ok(Some(input.parse()?))
842 } else {
843 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400844 }
David Tolnay18c754c2018-08-21 23:26:58 -0400845 }
846}
David Tolnay4ac232d2018-08-31 10:18:03 -0700847
David Tolnay80a914f2018-08-30 23:49:53 -0700848impl Parse for TokenStream {
849 fn parse(input: ParseStream) -> Result<Self> {
850 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
851 }
852}
853
854impl Parse for TokenTree {
855 fn parse(input: ParseStream) -> Result<Self> {
856 input.step(|cursor| match cursor.token_tree() {
857 Some((tt, rest)) => Ok((tt, rest)),
858 None => Err(cursor.error("expected token tree")),
859 })
860 }
861}
862
863impl Parse for Group {
864 fn parse(input: ParseStream) -> Result<Self> {
865 input.step(|cursor| {
866 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
867 if let Some((inside, span, rest)) = cursor.group(*delim) {
868 let mut group = Group::new(*delim, inside.token_stream());
869 group.set_span(span);
870 return Ok((group, rest));
871 }
872 }
873 Err(cursor.error("expected group token"))
874 })
875 }
876}
877
878impl Parse for Punct {
879 fn parse(input: ParseStream) -> Result<Self> {
880 input.step(|cursor| match cursor.punct() {
881 Some((punct, rest)) => Ok((punct, rest)),
882 None => Err(cursor.error("expected punctuation token")),
883 })
884 }
885}
886
887impl Parse for Literal {
888 fn parse(input: ParseStream) -> Result<Self> {
889 input.step(|cursor| match cursor.literal() {
890 Some((literal, rest)) => Ok((literal, rest)),
891 None => Err(cursor.error("expected literal token")),
892 })
893 }
894}
895
896/// Parser that can parse Rust tokens into a particular syntax tree node.
897///
898/// Refer to the [module documentation] for details about parsing in Syn.
899///
900/// [module documentation]: index.html
901///
902/// *This trait is available if Syn is built with the `"parsing"` feature.*
903pub trait Parser: Sized {
904 type Output;
905
906 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
907 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
908
909 /// Parse tokens of source code into the chosen syntax tree node.
910 ///
911 /// *This method is available if Syn is built with both the `"parsing"` and
912 /// `"proc-macro"` features.*
913 #[cfg(all(
914 not(all(target_arch = "wasm32", target_os = "unknown")),
915 feature = "proc-macro"
916 ))]
917 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
918 self.parse2(proc_macro2::TokenStream::from(tokens))
919 }
920
921 /// Parse a string of Rust code into the chosen syntax tree node.
922 ///
923 /// # Hygiene
924 ///
925 /// Every span in the resulting syntax tree will be set to resolve at the
926 /// macro call site.
927 fn parse_str(self, s: &str) -> Result<Self::Output> {
928 self.parse2(proc_macro2::TokenStream::from_str(s)?)
929 }
930}
931
David Tolnay7b07aa12018-09-01 11:41:12 -0700932fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
933 let scope = Span::call_site();
934 let cursor = tokens.begin();
935 let unexpected = Rc::new(Cell::new(None));
936 private::new_parse_buffer(scope, cursor, unexpected)
937}
938
David Tolnay80a914f2018-08-30 23:49:53 -0700939impl<F, T> Parser for F
940where
941 F: FnOnce(ParseStream) -> Result<T>,
942{
943 type Output = T;
944
945 fn parse2(self, tokens: TokenStream) -> Result<T> {
946 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -0700947 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -0700948 let node = self(&state)?;
949 state.check_unexpected()?;
950 if state.is_empty() {
951 Ok(node)
952 } else {
953 Err(state.error("unexpected token"))
954 }
955 }
956}