blob: 90b3d3efc6387313c797ea76e7f27476bd9cb07a [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 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700335 /// # Syntax
336 ///
337 /// Note that this method does not use turbofish syntax. Pass the peek type
338 /// inside of parentheses.
339 ///
340 /// - `input.peek(Token![struct])`
341 /// - `input.peek(Token![==])`
342 /// - `input.peek(Ident)`
343 /// - `input.peek(Lifetime)`
344 /// - `input.peek(token::Brace)`
345 ///
David Tolnayddebc3e2018-09-01 16:29:20 -0700346 /// # Example
347 ///
348 /// In this example we finish parsing the list of supertraits when the next
349 /// token in the input is either `where` or an opening curly brace.
350 ///
351 /// ```
352 /// # extern crate syn;
353 /// #
354 /// use syn::{braced, token, Generics, Ident, Token, TypeParamBound};
355 /// use syn::parse::{Parse, ParseStream, Result};
356 /// use syn::punctuated::Punctuated;
357 ///
358 /// // Parses a trait definition containing no associated items.
359 /// //
360 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
361 /// struct MarkerTrait {
362 /// trait_token: Token![trait],
363 /// ident: Ident,
364 /// generics: Generics,
365 /// colon_token: Option<Token![:]>,
366 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
367 /// brace_token: token::Brace,
368 /// }
369 ///
370 /// impl Parse for MarkerTrait {
371 /// fn parse(input: ParseStream) -> Result<Self> {
372 /// let trait_token: Token![trait] = input.parse()?;
373 /// let ident: Ident = input.parse()?;
374 /// let mut generics: Generics = input.parse()?;
375 /// let colon_token: Option<Token![:]> = input.parse()?;
376 ///
377 /// let mut supertraits = Punctuated::new();
378 /// if colon_token.is_some() {
379 /// loop {
380 /// supertraits.push_value(input.parse()?);
381 /// if input.peek(Token![where]) || input.peek(token::Brace) {
382 /// break;
383 /// }
384 /// supertraits.push_punct(input.parse()?);
385 /// }
386 /// }
387 ///
388 /// generics.where_clause = input.parse()?;
389 /// let content;
390 /// let empty_brace_token = braced!(content in input);
391 ///
392 /// Ok(MarkerTrait {
393 /// trait_token: trait_token,
394 /// ident: ident,
395 /// generics: generics,
396 /// colon_token: colon_token,
397 /// supertraits: supertraits,
398 /// brace_token: empty_brace_token,
399 /// })
400 /// }
401 /// }
402 /// #
403 /// # fn main() {}
404 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400405 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700406 let _ = token;
407 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400408 }
409
David Tolnay725e1c62018-09-01 12:07:25 -0700410 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700411 ///
412 /// This is commonly useful as a way to implement contextual keywords.
413 ///
414 /// # Example
415 ///
416 /// This example needs to use `peek2` because the symbol `union` is not a
417 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
418 /// the very next token is `union`, because someone is free to write a `mod
419 /// union` and a macro invocation that looks like `union::some_macro! { ...
420 /// }`. In other words `union` is a contextual keyword.
421 ///
422 /// ```
423 /// # extern crate syn;
424 /// #
425 /// use syn::{Ident, ItemUnion, Macro, Token};
426 /// use syn::parse::{Parse, ParseStream, Result};
427 ///
428 /// // Parses either a union or a macro invocation.
429 /// enum UnionOrMacro {
430 /// // union MaybeUninit<T> { uninit: (), value: T }
431 /// Union(ItemUnion),
432 /// // lazy_static! { ... }
433 /// Macro(Macro),
434 /// }
435 ///
436 /// impl Parse for UnionOrMacro {
437 /// fn parse(input: ParseStream) -> Result<Self> {
438 /// if input.peek(Token![union]) && input.peek2(Ident) {
439 /// input.parse().map(UnionOrMacro::Union)
440 /// } else {
441 /// input.parse().map(UnionOrMacro::Macro)
442 /// }
443 /// }
444 /// }
445 /// #
446 /// # fn main() {}
447 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400448 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400449 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700450 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400451 }
452
David Tolnay725e1c62018-09-01 12:07:25 -0700453 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400454 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400455 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700456 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400457 }
458
David Tolnay725e1c62018-09-01 12:07:25 -0700459 /// Parses zero or more occurrences of `T` separated by punctuation of type
460 /// `P`, with optional trailing punctuation.
461 ///
462 /// Parsing continues until the end of this parse stream. The entire content
463 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700464 ///
465 /// # Example
466 ///
467 /// ```rust
468 /// # extern crate quote;
469 /// # extern crate syn;
470 /// #
471 /// # use quote::quote;
472 /// #
473 /// use syn::{parenthesized, token, Ident, Token, Type};
474 /// use syn::parse::{Parse, ParseStream, Result};
475 /// use syn::punctuated::Punctuated;
476 ///
477 /// // Parse a simplified tuple struct syntax like:
478 /// //
479 /// // struct S(A, B);
480 /// struct TupleStruct {
481 /// struct_token: Token![struct],
482 /// ident: Ident,
483 /// paren_token: token::Paren,
484 /// fields: Punctuated<Type, Token![,]>,
485 /// semi_token: Token![;],
486 /// }
487 ///
488 /// impl Parse for TupleStruct {
489 /// fn parse(input: ParseStream) -> Result<Self> {
490 /// let content;
491 /// Ok(TupleStruct {
492 /// struct_token: input.parse()?,
493 /// ident: input.parse()?,
494 /// paren_token: parenthesized!(content in input),
495 /// fields: content.parse_terminated(Type::parse)?,
496 /// semi_token: input.parse()?,
497 /// })
498 /// }
499 /// }
500 /// #
501 /// # fn main() {
502 /// # let input = quote! {
503 /// # struct S(A, B);
504 /// # };
505 /// # syn::parse2::<TupleStruct>(input).unwrap();
506 /// # }
507 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400508 pub fn parse_terminated<T, P: Parse>(
509 &self,
510 parser: fn(ParseStream) -> Result<T>,
511 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700512 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400513 }
514
David Tolnay725e1c62018-09-01 12:07:25 -0700515 /// Returns whether there are tokens remaining in this stream.
516 ///
517 /// This method returns true at the end of the content of a set of
518 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700519 ///
520 /// # Example
521 ///
522 /// ```rust
523 /// # extern crate syn;
524 /// #
525 /// use syn::{braced, token, Ident, Item, Token};
526 /// use syn::parse::{Parse, ParseStream, Result};
527 ///
528 /// // Parses a Rust `mod m { ... }` containing zero or more items.
529 /// struct Mod {
530 /// mod_token: Token![mod],
531 /// name: Ident,
532 /// brace_token: token::Brace,
533 /// items: Vec<Item>,
534 /// }
535 ///
536 /// impl Parse for Mod {
537 /// fn parse(input: ParseStream) -> Result<Self> {
538 /// let content;
539 /// Ok(Mod {
540 /// mod_token: input.parse()?,
541 /// name: input.parse()?,
542 /// brace_token: braced!(content in input),
543 /// items: {
544 /// let mut items = Vec::new();
545 /// while !content.is_empty() {
546 /// items.push(content.parse()?);
547 /// }
548 /// items
549 /// },
550 /// })
551 /// }
552 /// }
553 /// #
554 /// # fn main() {}
David Tolnayf5d30452018-09-01 02:29:04 -0700555 pub fn is_empty(&self) -> bool {
556 self.cursor().eof()
557 }
558
David Tolnay725e1c62018-09-01 12:07:25 -0700559 /// Constructs a helper for peeking at the next token in this stream and
560 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700561 ///
562 /// # Example
563 ///
564 /// ```
565 /// # extern crate syn;
566 /// #
567 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Token, TypeParam};
568 /// use syn::parse::{Parse, ParseStream, Result};
569 ///
570 /// // A generic parameter, a single one of the comma-separated elements inside
571 /// // angle brackets in:
572 /// //
573 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
574 /// //
575 /// // On invalid input, lookahead gives us a reasonable error message.
576 /// //
577 /// // error: expected one of: identifier, lifetime, `const`
578 /// // |
579 /// // 5 | fn f<!Sized>() {}
580 /// // | ^
581 /// enum GenericParam {
582 /// Type(TypeParam),
583 /// Lifetime(LifetimeDef),
584 /// Const(ConstParam),
585 /// }
586 ///
587 /// impl Parse for GenericParam {
588 /// fn parse(input: ParseStream) -> Result<Self> {
589 /// let lookahead = input.lookahead1();
590 /// if lookahead.peek(Ident) {
591 /// input.parse().map(GenericParam::Type)
592 /// } else if lookahead.peek(Lifetime) {
593 /// input.parse().map(GenericParam::Lifetime)
594 /// } else if lookahead.peek(Token![const]) {
595 /// input.parse().map(GenericParam::Const)
596 /// } else {
597 /// Err(lookahead.error())
598 /// }
599 /// }
600 /// }
601 /// #
602 /// # fn main() {}
603 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700604 pub fn lookahead1(&self) -> Lookahead1<'a> {
605 lookahead::new(self.scope, self.cursor())
606 }
607
David Tolnay725e1c62018-09-01 12:07:25 -0700608 /// Forks a parse stream so that parsing tokens out of either the original
609 /// or the fork does not advance the position of the other.
610 ///
611 /// # Performance
612 ///
613 /// Forking a parse stream is a cheap fixed amount of work and does not
614 /// involve copying token buffers. Where you might hit performance problems
615 /// is if your macro ends up parsing a large amount of content more than
616 /// once.
617 ///
618 /// ```
619 /// # use syn::Expr;
620 /// # use syn::parse::{ParseStream, Result};
621 /// #
622 /// # fn bad(input: ParseStream) -> Result<Expr> {
623 /// // Do not do this.
624 /// if input.fork().parse::<Expr>().is_ok() {
625 /// return input.parse::<Expr>();
626 /// }
627 /// # unimplemented!()
628 /// # }
629 /// ```
630 ///
631 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
632 /// parse stream. Only use a fork when the amount of work performed against
633 /// the fork is small and bounded.
634 ///
David Tolnayec149b02018-09-01 14:17:28 -0700635 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700636 /// speculative parsing, consider using [`ParseStream::step`] instead.
637 ///
638 /// [`ParseStream::step`]: #method.step
David Tolnayec149b02018-09-01 14:17:28 -0700639 ///
640 /// # Example
641 ///
642 /// The parse implementation shown here parses possibly restricted `pub`
643 /// visibilities.
644 ///
645 /// - `pub`
646 /// - `pub(crate)`
647 /// - `pub(self)`
648 /// - `pub(super)`
649 /// - `pub(in some::path)`
650 ///
651 /// To handle the case of visibilities inside of tuple structs, the parser
652 /// needs to distinguish parentheses that specify visibility restrictions
653 /// from parentheses that form part of a tuple type.
654 ///
655 /// ```
656 /// # struct A;
657 /// # struct B;
658 /// # struct C;
659 /// #
660 /// struct S(pub(crate) A, pub (B, C));
661 /// ```
662 ///
663 /// In this example input the first tuple struct element of `S` has
664 /// `pub(crate)` visibility while the second tuple struct element has `pub`
665 /// visibility; the parentheses around `(B, C)` are part of the type rather
666 /// than part of a visibility restriction.
667 ///
668 /// The parser uses a forked parse stream to check the first token inside of
669 /// parentheses after the `pub` keyword. This is a small bounded amount of
670 /// work performed against the forked parse stream.
671 ///
672 /// ```
673 /// # extern crate syn;
674 /// #
675 /// use syn::{parenthesized, token, Ident, Path, Token};
676 /// use syn::ext::IdentExt;
677 /// use syn::parse::{Parse, ParseStream, Result};
678 ///
679 /// struct PubVisibility {
680 /// pub_token: Token![pub],
681 /// restricted: Option<Restricted>,
682 /// }
683 ///
684 /// struct Restricted {
685 /// paren_token: token::Paren,
686 /// in_token: Option<Token![in]>,
687 /// path: Path,
688 /// }
689 ///
690 /// impl Parse for PubVisibility {
691 /// fn parse(input: ParseStream) -> Result<Self> {
692 /// let pub_token: Token![pub] = input.parse()?;
693 ///
694 /// if input.peek(token::Paren) {
695 /// let ahead = input.fork();
696 /// let mut content;
697 /// parenthesized!(content in ahead);
698 ///
699 /// if content.peek(Token![crate])
700 /// || content.peek(Token![self])
701 /// || content.peek(Token![super])
702 /// {
703 /// return Ok(PubVisibility {
704 /// pub_token: pub_token,
705 /// restricted: Some(Restricted {
706 /// paren_token: parenthesized!(content in input),
707 /// in_token: None,
708 /// path: Path::from(content.call(Ident::parse_any)?),
709 /// }),
710 /// });
711 /// } else if content.peek(Token![in]) {
712 /// return Ok(PubVisibility {
713 /// pub_token: pub_token,
714 /// restricted: Some(Restricted {
715 /// paren_token: parenthesized!(content in input),
716 /// in_token: Some(content.parse()?),
717 /// path: content.call(Path::parse_mod_style)?,
718 /// }),
719 /// });
720 /// }
721 /// }
722 ///
723 /// Ok(PubVisibility {
724 /// pub_token: pub_token,
725 /// restricted: None,
726 /// })
727 /// }
728 /// }
729 /// #
730 /// # fn main() {}
731 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400732 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400733 ParseBuffer {
734 scope: self.scope,
735 cell: self.cell.clone(),
736 marker: PhantomData,
737 // Not the parent's unexpected. Nothing cares whether the clone
738 // parses all the way.
739 unexpected: Rc::new(Cell::new(None)),
740 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400741 }
742
David Tolnay725e1c62018-09-01 12:07:25 -0700743 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700744 ///
745 /// # Example
746 ///
747 /// ```
748 /// # extern crate syn;
749 /// #
750 /// use syn::{Expr, Token};
751 /// use syn::parse::{Parse, ParseStream, Result};
752 ///
753 /// // Some kind of loop: `while` or `for` or `loop`.
754 /// struct Loop {
755 /// expr: Expr,
756 /// }
757 ///
758 /// impl Parse for Loop {
759 /// fn parse(input: ParseStream) -> Result<Self> {
760 /// if input.peek(Token![while])
761 /// || input.peek(Token![for])
762 /// || input.peek(Token![loop])
763 /// {
764 /// Ok(Loop {
765 /// expr: input.parse()?,
766 /// })
767 /// } else {
768 /// Err(input.error("expected some kind of loop"))
769 /// }
770 /// }
771 /// }
772 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400773 pub fn error<T: Display>(&self, message: T) -> Error {
774 error::new_at(self.scope, self.cursor(), message)
775 }
776
David Tolnay725e1c62018-09-01 12:07:25 -0700777 /// Speculatively parses tokens from this parse stream, advancing the
778 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700779 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700780 /// This is a powerful low-level API used for defining the `Parse` impls of
781 /// the basic built-in token types. It is not something that will be used
782 /// widely outside of the Syn codebase.
783 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700784 /// # Example
785 ///
786 /// ```
787 /// # extern crate proc_macro2;
788 /// # extern crate syn;
789 /// #
790 /// use proc_macro2::TokenTree;
791 /// use syn::parse::{ParseStream, Result};
792 ///
793 /// // This function advances the stream past the next occurrence of `@`. If
794 /// // no `@` is present in the stream, the stream position is unchanged and
795 /// // an error is returned.
796 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
797 /// input.step(|cursor| {
798 /// let mut rest = *cursor;
799 /// while let Some((tt, next)) = cursor.token_tree() {
800 /// match tt {
801 /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
802 /// return Ok(((), next));
803 /// }
804 /// _ => rest = next,
805 /// }
806 /// }
807 /// Err(cursor.error("no `@` was found after this point"))
808 /// })
809 /// }
810 /// #
811 /// # fn main() {}
812 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700813 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400814 where
815 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
816 {
David Tolnay6b65f852018-09-01 11:56:25 -0700817 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -0400818 scope: self.scope,
819 cursor: self.cell.get(),
820 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700821 })?;
822 self.cell.set(rest);
823 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -0400824 }
David Tolnayeafc8052018-08-25 16:33:53 -0400825
David Tolnay725e1c62018-09-01 12:07:25 -0700826 /// Provides low-level access to the token representation underlying this
827 /// parse stream.
828 ///
829 /// Cursors are immutable so no operations you perform against the cursor
830 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -0700831 pub fn cursor(&self) -> Cursor<'a> {
832 self.cell.get()
833 }
834
David Tolnay94f06632018-08-31 10:17:17 -0700835 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -0400836 match self.unexpected.get() {
837 Some(span) => Err(Error::new(span, "unexpected token")),
838 None => Ok(()),
839 }
840 }
David Tolnay18c754c2018-08-21 23:26:58 -0400841}
842
David Tolnaya7d69fc2018-08-26 13:30:24 -0400843impl<T: Parse> Parse for Box<T> {
844 fn parse(input: ParseStream) -> Result<Self> {
845 input.parse().map(Box::new)
846 }
847}
848
David Tolnay4fb71232018-08-25 23:14:50 -0400849impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400850 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -0700851 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -0400852 Ok(Some(input.parse()?))
853 } else {
854 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400855 }
David Tolnay18c754c2018-08-21 23:26:58 -0400856 }
857}
David Tolnay4ac232d2018-08-31 10:18:03 -0700858
David Tolnay80a914f2018-08-30 23:49:53 -0700859impl Parse for TokenStream {
860 fn parse(input: ParseStream) -> Result<Self> {
861 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
862 }
863}
864
865impl Parse for TokenTree {
866 fn parse(input: ParseStream) -> Result<Self> {
867 input.step(|cursor| match cursor.token_tree() {
868 Some((tt, rest)) => Ok((tt, rest)),
869 None => Err(cursor.error("expected token tree")),
870 })
871 }
872}
873
874impl Parse for Group {
875 fn parse(input: ParseStream) -> Result<Self> {
876 input.step(|cursor| {
877 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
878 if let Some((inside, span, rest)) = cursor.group(*delim) {
879 let mut group = Group::new(*delim, inside.token_stream());
880 group.set_span(span);
881 return Ok((group, rest));
882 }
883 }
884 Err(cursor.error("expected group token"))
885 })
886 }
887}
888
889impl Parse for Punct {
890 fn parse(input: ParseStream) -> Result<Self> {
891 input.step(|cursor| match cursor.punct() {
892 Some((punct, rest)) => Ok((punct, rest)),
893 None => Err(cursor.error("expected punctuation token")),
894 })
895 }
896}
897
898impl Parse for Literal {
899 fn parse(input: ParseStream) -> Result<Self> {
900 input.step(|cursor| match cursor.literal() {
901 Some((literal, rest)) => Ok((literal, rest)),
902 None => Err(cursor.error("expected literal token")),
903 })
904 }
905}
906
907/// Parser that can parse Rust tokens into a particular syntax tree node.
908///
909/// Refer to the [module documentation] for details about parsing in Syn.
910///
911/// [module documentation]: index.html
912///
913/// *This trait is available if Syn is built with the `"parsing"` feature.*
914pub trait Parser: Sized {
915 type Output;
916
917 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
918 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
919
920 /// Parse tokens of source code into the chosen syntax tree node.
921 ///
922 /// *This method is available if Syn is built with both the `"parsing"` and
923 /// `"proc-macro"` features.*
924 #[cfg(all(
925 not(all(target_arch = "wasm32", target_os = "unknown")),
926 feature = "proc-macro"
927 ))]
928 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
929 self.parse2(proc_macro2::TokenStream::from(tokens))
930 }
931
932 /// Parse a string of Rust code into the chosen syntax tree node.
933 ///
934 /// # Hygiene
935 ///
936 /// Every span in the resulting syntax tree will be set to resolve at the
937 /// macro call site.
938 fn parse_str(self, s: &str) -> Result<Self::Output> {
939 self.parse2(proc_macro2::TokenStream::from_str(s)?)
940 }
941}
942
David Tolnay7b07aa12018-09-01 11:41:12 -0700943fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
944 let scope = Span::call_site();
945 let cursor = tokens.begin();
946 let unexpected = Rc::new(Cell::new(None));
947 private::new_parse_buffer(scope, cursor, unexpected)
948}
949
David Tolnay80a914f2018-08-30 23:49:53 -0700950impl<F, T> Parser for F
951where
952 F: FnOnce(ParseStream) -> Result<T>,
953{
954 type Output = T;
955
956 fn parse2(self, tokens: TokenStream) -> Result<T> {
957 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -0700958 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -0700959 let node = self(&state)?;
960 state.check_unexpected()?;
961 if state.is_empty() {
962 Ok(node)
963 } else {
964 Err(state.error("unexpected token"))
965 }
966 }
967}