blob: c063d4e5164c3761f2065ff4f6eda2e2fa2e0a9c [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,
242 cell: Cell<Cursor<'static>>,
243 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400244 unexpected: Rc<Cell<Option<Span>>>,
245}
246
247impl<'a> Drop for ParseBuffer<'a> {
248 fn drop(&mut self) {
249 if !self.is_empty() && self.unexpected.get().is_none() {
250 self.unexpected.set(Some(self.cursor().span()));
251 }
252 }
David Tolnay18c754c2018-08-21 23:26:58 -0400253}
254
David Tolnay642832f2018-09-01 13:08:10 -0700255/// Cursor state associated with speculative parsing.
256///
257/// This type is the input of the closure provided to [`ParseStream::step`].
258///
259/// [`ParseStream::step`]: struct.ParseBuffer.html#method.step
David Tolnay9bd34392018-09-01 13:19:53 -0700260///
261/// # Example
262///
263/// ```
264/// # extern crate proc_macro2;
265/// # extern crate syn;
266/// #
267/// use proc_macro2::TokenTree;
268/// use syn::parse::{ParseStream, Result};
269///
270/// // This function advances the stream past the next occurrence of `@`. If
271/// // no `@` is present in the stream, the stream position is unchanged and
272/// // an error is returned.
273/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
274/// input.step(|cursor| {
275/// let mut rest = *cursor;
276/// while let Some((tt, next)) = cursor.token_tree() {
277/// match tt {
278/// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
279/// return Ok(((), next));
280/// }
281/// _ => rest = next,
282/// }
283/// }
284/// Err(cursor.error("no `@` was found after this point"))
285/// })
286/// }
287/// #
288/// # fn main() {}
289/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400290#[derive(Copy, Clone)]
291pub struct StepCursor<'c, 'a> {
292 scope: Span,
293 cursor: Cursor<'c>,
294 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
295}
296
297impl<'c, 'a> Deref for StepCursor<'c, 'a> {
298 type Target = Cursor<'c>;
299
300 fn deref(&self) -> &Self::Target {
301 &self.cursor
302 }
303}
304
305impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700306 /// Triggers an error at the current position of the parse stream.
307 ///
308 /// The `ParseStream::step` invocation will return this same error without
309 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400310 pub fn error<T: Display>(self, message: T) -> Error {
311 error::new_at(self.scope, self.cursor, message)
312 }
313}
314
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700315impl private {
316 pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
317 let _ = proof;
318 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
319 }
320}
321
David Tolnay66cb0c42018-08-31 09:01:30 -0700322fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700323 input
324 .step(|cursor| {
325 if let Some((_lifetime, rest)) = cursor.lifetime() {
326 Ok((true, rest))
327 } else if let Some((_token, rest)) = cursor.token_tree() {
328 Ok((true, rest))
329 } else {
330 Ok((false, *cursor))
331 }
332 }).unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700333}
334
David Tolnay10951d52018-08-31 10:27:39 -0700335impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700336 pub fn new_parse_buffer(
337 scope: Span,
338 cursor: Cursor,
339 unexpected: Rc<Cell<Option<Span>>>,
340 ) -> ParseBuffer {
David Tolnay94f06632018-08-31 10:17:17 -0700341 let extend = unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) };
David Tolnay18c754c2018-08-21 23:26:58 -0400342 ParseBuffer {
343 scope: scope,
344 cell: Cell::new(extend),
345 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400346 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400347 }
348 }
349
David Tolnay94f06632018-08-31 10:17:17 -0700350 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
351 buffer.unexpected.clone()
352 }
353}
354
355impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700356 /// Parses a syntax tree node of type `T`, advancing the position of our
357 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400358 pub fn parse<T: Parse>(&self) -> Result<T> {
359 T::parse(self)
360 }
361
David Tolnay725e1c62018-09-01 12:07:25 -0700362 /// Calls the given parser function to parse a syntax tree node of type `T`
363 /// from this stream.
David Tolnay21ce84c2018-09-01 15:37:51 -0700364 ///
365 /// # Example
366 ///
367 /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
368 /// zero or more outer attributes.
369 ///
370 /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer
371 ///
372 /// ```
373 /// # extern crate syn;
374 /// #
375 /// use syn::{Attribute, Ident, Token};
376 /// use syn::parse::{Parse, ParseStream, Result};
377 ///
378 /// // Parses a unit struct with attributes.
379 /// //
380 /// // #[path = "s.tmpl"]
381 /// // struct S;
382 /// struct UnitStruct {
383 /// attrs: Vec<Attribute>,
384 /// struct_token: Token![struct],
385 /// name: Ident,
386 /// semi_token: Token![;],
387 /// }
388 ///
389 /// impl Parse for UnitStruct {
390 /// fn parse(input: ParseStream) -> Result<Self> {
391 /// Ok(UnitStruct {
392 /// attrs: input.call(Attribute::parse_outer)?,
393 /// struct_token: input.parse()?,
394 /// name: input.parse()?,
395 /// semi_token: input.parse()?,
396 /// })
397 /// }
398 /// }
399 /// #
400 /// # fn main() {}
401 /// ```
David Tolnay3a515a02018-08-25 21:08:27 -0400402 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
403 function(self)
404 }
405
David Tolnay725e1c62018-09-01 12:07:25 -0700406 /// Looks at the next token in the parse stream to determine whether it
407 /// matches the requested type of token.
408 ///
409 /// Does not advance the position of the parse stream.
David Tolnayddebc3e2018-09-01 16:29:20 -0700410 ///
David Tolnay7d229e82018-09-01 16:42:34 -0700411 /// # Syntax
412 ///
413 /// Note that this method does not use turbofish syntax. Pass the peek type
414 /// inside of parentheses.
415 ///
416 /// - `input.peek(Token![struct])`
417 /// - `input.peek(Token![==])`
418 /// - `input.peek(Ident)`
419 /// - `input.peek(Lifetime)`
420 /// - `input.peek(token::Brace)`
421 ///
David Tolnayddebc3e2018-09-01 16:29:20 -0700422 /// # Example
423 ///
424 /// In this example we finish parsing the list of supertraits when the next
425 /// token in the input is either `where` or an opening curly brace.
426 ///
427 /// ```
428 /// # extern crate syn;
429 /// #
430 /// use syn::{braced, token, Generics, Ident, Token, TypeParamBound};
431 /// use syn::parse::{Parse, ParseStream, Result};
432 /// use syn::punctuated::Punctuated;
433 ///
434 /// // Parses a trait definition containing no associated items.
435 /// //
436 /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
437 /// struct MarkerTrait {
438 /// trait_token: Token![trait],
439 /// ident: Ident,
440 /// generics: Generics,
441 /// colon_token: Option<Token![:]>,
442 /// supertraits: Punctuated<TypeParamBound, Token![+]>,
443 /// brace_token: token::Brace,
444 /// }
445 ///
446 /// impl Parse for MarkerTrait {
447 /// fn parse(input: ParseStream) -> Result<Self> {
448 /// let trait_token: Token![trait] = input.parse()?;
449 /// let ident: Ident = input.parse()?;
450 /// let mut generics: Generics = input.parse()?;
451 /// let colon_token: Option<Token![:]> = input.parse()?;
452 ///
453 /// let mut supertraits = Punctuated::new();
454 /// if colon_token.is_some() {
455 /// loop {
456 /// supertraits.push_value(input.parse()?);
457 /// if input.peek(Token![where]) || input.peek(token::Brace) {
458 /// break;
459 /// }
460 /// supertraits.push_punct(input.parse()?);
461 /// }
462 /// }
463 ///
464 /// generics.where_clause = input.parse()?;
465 /// let content;
466 /// let empty_brace_token = braced!(content in input);
467 ///
468 /// Ok(MarkerTrait {
469 /// trait_token: trait_token,
470 /// ident: ident,
471 /// generics: generics,
472 /// colon_token: colon_token,
473 /// supertraits: supertraits,
474 /// brace_token: empty_brace_token,
475 /// })
476 /// }
477 /// }
478 /// #
479 /// # fn main() {}
480 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400481 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700482 let _ = token;
483 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400484 }
485
David Tolnay725e1c62018-09-01 12:07:25 -0700486 /// Looks at the second-next token in the parse stream.
David Tolnaye334b872018-09-01 16:38:10 -0700487 ///
488 /// This is commonly useful as a way to implement contextual keywords.
489 ///
490 /// # Example
491 ///
492 /// This example needs to use `peek2` because the symbol `union` is not a
493 /// keyword in Rust. We can't use just `peek` and decide to parse a union if
494 /// the very next token is `union`, because someone is free to write a `mod
495 /// union` and a macro invocation that looks like `union::some_macro! { ...
496 /// }`. In other words `union` is a contextual keyword.
497 ///
498 /// ```
499 /// # extern crate syn;
500 /// #
501 /// use syn::{Ident, ItemUnion, Macro, Token};
502 /// use syn::parse::{Parse, ParseStream, Result};
503 ///
504 /// // Parses either a union or a macro invocation.
505 /// enum UnionOrMacro {
506 /// // union MaybeUninit<T> { uninit: (), value: T }
507 /// Union(ItemUnion),
508 /// // lazy_static! { ... }
509 /// Macro(Macro),
510 /// }
511 ///
512 /// impl Parse for UnionOrMacro {
513 /// fn parse(input: ParseStream) -> Result<Self> {
514 /// if input.peek(Token![union]) && input.peek2(Ident) {
515 /// input.parse().map(UnionOrMacro::Union)
516 /// } else {
517 /// input.parse().map(UnionOrMacro::Macro)
518 /// }
519 /// }
520 /// }
521 /// #
522 /// # fn main() {}
523 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400524 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400525 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700526 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400527 }
528
David Tolnay725e1c62018-09-01 12:07:25 -0700529 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400530 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400531 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700532 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400533 }
534
David Tolnay725e1c62018-09-01 12:07:25 -0700535 /// Parses zero or more occurrences of `T` separated by punctuation of type
536 /// `P`, with optional trailing punctuation.
537 ///
538 /// Parsing continues until the end of this parse stream. The entire content
539 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700540 ///
541 /// # Example
542 ///
543 /// ```rust
544 /// # extern crate quote;
545 /// # extern crate syn;
546 /// #
547 /// # use quote::quote;
548 /// #
549 /// use syn::{parenthesized, token, Ident, Token, Type};
550 /// use syn::parse::{Parse, ParseStream, Result};
551 /// use syn::punctuated::Punctuated;
552 ///
553 /// // Parse a simplified tuple struct syntax like:
554 /// //
555 /// // struct S(A, B);
556 /// struct TupleStruct {
557 /// struct_token: Token![struct],
558 /// ident: Ident,
559 /// paren_token: token::Paren,
560 /// fields: Punctuated<Type, Token![,]>,
561 /// semi_token: Token![;],
562 /// }
563 ///
564 /// impl Parse for TupleStruct {
565 /// fn parse(input: ParseStream) -> Result<Self> {
566 /// let content;
567 /// Ok(TupleStruct {
568 /// struct_token: input.parse()?,
569 /// ident: input.parse()?,
570 /// paren_token: parenthesized!(content in input),
571 /// fields: content.parse_terminated(Type::parse)?,
572 /// semi_token: input.parse()?,
573 /// })
574 /// }
575 /// }
576 /// #
577 /// # fn main() {
578 /// # let input = quote! {
579 /// # struct S(A, B);
580 /// # };
581 /// # syn::parse2::<TupleStruct>(input).unwrap();
582 /// # }
583 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400584 pub fn parse_terminated<T, P: Parse>(
585 &self,
586 parser: fn(ParseStream) -> Result<T>,
587 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700588 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400589 }
590
David Tolnay725e1c62018-09-01 12:07:25 -0700591 /// Returns whether there are tokens remaining in this stream.
592 ///
593 /// This method returns true at the end of the content of a set of
594 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700595 ///
596 /// # Example
597 ///
598 /// ```rust
599 /// # extern crate syn;
600 /// #
601 /// use syn::{braced, token, Ident, Item, Token};
602 /// use syn::parse::{Parse, ParseStream, Result};
603 ///
604 /// // Parses a Rust `mod m { ... }` containing zero or more items.
605 /// struct Mod {
606 /// mod_token: Token![mod],
607 /// name: Ident,
608 /// brace_token: token::Brace,
609 /// items: Vec<Item>,
610 /// }
611 ///
612 /// impl Parse for Mod {
613 /// fn parse(input: ParseStream) -> Result<Self> {
614 /// let content;
615 /// Ok(Mod {
616 /// mod_token: input.parse()?,
617 /// name: input.parse()?,
618 /// brace_token: braced!(content in input),
619 /// items: {
620 /// let mut items = Vec::new();
621 /// while !content.is_empty() {
622 /// items.push(content.parse()?);
623 /// }
624 /// items
625 /// },
626 /// })
627 /// }
628 /// }
629 /// #
630 /// # fn main() {}
David Tolnayf5d30452018-09-01 02:29:04 -0700631 pub fn is_empty(&self) -> bool {
632 self.cursor().eof()
633 }
634
David Tolnay725e1c62018-09-01 12:07:25 -0700635 /// Constructs a helper for peeking at the next token in this stream and
636 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700637 ///
638 /// # Example
639 ///
640 /// ```
641 /// # extern crate syn;
642 /// #
643 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Token, TypeParam};
644 /// use syn::parse::{Parse, ParseStream, Result};
645 ///
646 /// // A generic parameter, a single one of the comma-separated elements inside
647 /// // angle brackets in:
648 /// //
649 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
650 /// //
651 /// // On invalid input, lookahead gives us a reasonable error message.
652 /// //
653 /// // error: expected one of: identifier, lifetime, `const`
654 /// // |
655 /// // 5 | fn f<!Sized>() {}
656 /// // | ^
657 /// enum GenericParam {
658 /// Type(TypeParam),
659 /// Lifetime(LifetimeDef),
660 /// Const(ConstParam),
661 /// }
662 ///
663 /// impl Parse for GenericParam {
664 /// fn parse(input: ParseStream) -> Result<Self> {
665 /// let lookahead = input.lookahead1();
666 /// if lookahead.peek(Ident) {
667 /// input.parse().map(GenericParam::Type)
668 /// } else if lookahead.peek(Lifetime) {
669 /// input.parse().map(GenericParam::Lifetime)
670 /// } else if lookahead.peek(Token![const]) {
671 /// input.parse().map(GenericParam::Const)
672 /// } else {
673 /// Err(lookahead.error())
674 /// }
675 /// }
676 /// }
677 /// #
678 /// # fn main() {}
679 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700680 pub fn lookahead1(&self) -> Lookahead1<'a> {
681 lookahead::new(self.scope, self.cursor())
682 }
683
David Tolnay725e1c62018-09-01 12:07:25 -0700684 /// Forks a parse stream so that parsing tokens out of either the original
685 /// or the fork does not advance the position of the other.
686 ///
687 /// # Performance
688 ///
689 /// Forking a parse stream is a cheap fixed amount of work and does not
690 /// involve copying token buffers. Where you might hit performance problems
691 /// is if your macro ends up parsing a large amount of content more than
692 /// once.
693 ///
694 /// ```
695 /// # use syn::Expr;
696 /// # use syn::parse::{ParseStream, Result};
697 /// #
698 /// # fn bad(input: ParseStream) -> Result<Expr> {
699 /// // Do not do this.
700 /// if input.fork().parse::<Expr>().is_ok() {
701 /// return input.parse::<Expr>();
702 /// }
703 /// # unimplemented!()
704 /// # }
705 /// ```
706 ///
707 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
708 /// parse stream. Only use a fork when the amount of work performed against
709 /// the fork is small and bounded.
710 ///
David Tolnayec149b02018-09-01 14:17:28 -0700711 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700712 /// speculative parsing, consider using [`ParseStream::step`] instead.
713 ///
714 /// [`ParseStream::step`]: #method.step
David Tolnayec149b02018-09-01 14:17:28 -0700715 ///
716 /// # Example
717 ///
718 /// The parse implementation shown here parses possibly restricted `pub`
719 /// visibilities.
720 ///
721 /// - `pub`
722 /// - `pub(crate)`
723 /// - `pub(self)`
724 /// - `pub(super)`
725 /// - `pub(in some::path)`
726 ///
727 /// To handle the case of visibilities inside of tuple structs, the parser
728 /// needs to distinguish parentheses that specify visibility restrictions
729 /// from parentheses that form part of a tuple type.
730 ///
731 /// ```
732 /// # struct A;
733 /// # struct B;
734 /// # struct C;
735 /// #
736 /// struct S(pub(crate) A, pub (B, C));
737 /// ```
738 ///
739 /// In this example input the first tuple struct element of `S` has
740 /// `pub(crate)` visibility while the second tuple struct element has `pub`
741 /// visibility; the parentheses around `(B, C)` are part of the type rather
742 /// than part of a visibility restriction.
743 ///
744 /// The parser uses a forked parse stream to check the first token inside of
745 /// parentheses after the `pub` keyword. This is a small bounded amount of
746 /// work performed against the forked parse stream.
747 ///
748 /// ```
749 /// # extern crate syn;
750 /// #
751 /// use syn::{parenthesized, token, Ident, Path, Token};
752 /// use syn::ext::IdentExt;
753 /// use syn::parse::{Parse, ParseStream, Result};
754 ///
755 /// struct PubVisibility {
756 /// pub_token: Token![pub],
757 /// restricted: Option<Restricted>,
758 /// }
759 ///
760 /// struct Restricted {
761 /// paren_token: token::Paren,
762 /// in_token: Option<Token![in]>,
763 /// path: Path,
764 /// }
765 ///
766 /// impl Parse for PubVisibility {
767 /// fn parse(input: ParseStream) -> Result<Self> {
768 /// let pub_token: Token![pub] = input.parse()?;
769 ///
770 /// if input.peek(token::Paren) {
771 /// let ahead = input.fork();
772 /// let mut content;
773 /// parenthesized!(content in ahead);
774 ///
775 /// if content.peek(Token![crate])
776 /// || content.peek(Token![self])
777 /// || content.peek(Token![super])
778 /// {
779 /// return Ok(PubVisibility {
780 /// pub_token: pub_token,
781 /// restricted: Some(Restricted {
782 /// paren_token: parenthesized!(content in input),
783 /// in_token: None,
784 /// path: Path::from(content.call(Ident::parse_any)?),
785 /// }),
786 /// });
787 /// } else if content.peek(Token![in]) {
788 /// return Ok(PubVisibility {
789 /// pub_token: pub_token,
790 /// restricted: Some(Restricted {
791 /// paren_token: parenthesized!(content in input),
792 /// in_token: Some(content.parse()?),
793 /// path: content.call(Path::parse_mod_style)?,
794 /// }),
795 /// });
796 /// }
797 /// }
798 ///
799 /// Ok(PubVisibility {
800 /// pub_token: pub_token,
801 /// restricted: None,
802 /// })
803 /// }
804 /// }
805 /// #
806 /// # fn main() {}
807 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400808 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400809 ParseBuffer {
810 scope: self.scope,
811 cell: self.cell.clone(),
812 marker: PhantomData,
813 // Not the parent's unexpected. Nothing cares whether the clone
814 // parses all the way.
815 unexpected: Rc::new(Cell::new(None)),
816 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400817 }
818
David Tolnay725e1c62018-09-01 12:07:25 -0700819 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700820 ///
821 /// # Example
822 ///
823 /// ```
824 /// # extern crate syn;
825 /// #
826 /// use syn::{Expr, Token};
827 /// use syn::parse::{Parse, ParseStream, Result};
828 ///
829 /// // Some kind of loop: `while` or `for` or `loop`.
830 /// struct Loop {
831 /// expr: Expr,
832 /// }
833 ///
834 /// impl Parse for Loop {
835 /// fn parse(input: ParseStream) -> Result<Self> {
836 /// if input.peek(Token![while])
837 /// || input.peek(Token![for])
838 /// || input.peek(Token![loop])
839 /// {
840 /// Ok(Loop {
841 /// expr: input.parse()?,
842 /// })
843 /// } else {
844 /// Err(input.error("expected some kind of loop"))
845 /// }
846 /// }
847 /// }
848 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400849 pub fn error<T: Display>(&self, message: T) -> Error {
850 error::new_at(self.scope, self.cursor(), message)
851 }
852
David Tolnay725e1c62018-09-01 12:07:25 -0700853 /// Speculatively parses tokens from this parse stream, advancing the
854 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700855 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700856 /// This is a powerful low-level API used for defining the `Parse` impls of
857 /// the basic built-in token types. It is not something that will be used
858 /// widely outside of the Syn codebase.
859 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700860 /// # Example
861 ///
862 /// ```
863 /// # extern crate proc_macro2;
864 /// # extern crate syn;
865 /// #
866 /// use proc_macro2::TokenTree;
867 /// use syn::parse::{ParseStream, Result};
868 ///
869 /// // This function advances the stream past the next occurrence of `@`. If
870 /// // no `@` is present in the stream, the stream position is unchanged and
871 /// // an error is returned.
872 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
873 /// input.step(|cursor| {
874 /// let mut rest = *cursor;
875 /// while let Some((tt, next)) = cursor.token_tree() {
876 /// match tt {
877 /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
878 /// return Ok(((), next));
879 /// }
880 /// _ => rest = next,
881 /// }
882 /// }
883 /// Err(cursor.error("no `@` was found after this point"))
884 /// })
885 /// }
886 /// #
887 /// # fn main() {}
888 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700889 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400890 where
891 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
892 {
David Tolnay6b65f852018-09-01 11:56:25 -0700893 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -0400894 scope: self.scope,
895 cursor: self.cell.get(),
896 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700897 })?;
898 self.cell.set(rest);
899 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -0400900 }
David Tolnayeafc8052018-08-25 16:33:53 -0400901
David Tolnay725e1c62018-09-01 12:07:25 -0700902 /// Provides low-level access to the token representation underlying this
903 /// parse stream.
904 ///
905 /// Cursors are immutable so no operations you perform against the cursor
906 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -0700907 pub fn cursor(&self) -> Cursor<'a> {
908 self.cell.get()
909 }
910
David Tolnay94f06632018-08-31 10:17:17 -0700911 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -0400912 match self.unexpected.get() {
913 Some(span) => Err(Error::new(span, "unexpected token")),
914 None => Ok(()),
915 }
916 }
David Tolnay18c754c2018-08-21 23:26:58 -0400917}
918
David Tolnaya7d69fc2018-08-26 13:30:24 -0400919impl<T: Parse> Parse for Box<T> {
920 fn parse(input: ParseStream) -> Result<Self> {
921 input.parse().map(Box::new)
922 }
923}
924
David Tolnay4fb71232018-08-25 23:14:50 -0400925impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400926 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -0700927 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -0400928 Ok(Some(input.parse()?))
929 } else {
930 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400931 }
David Tolnay18c754c2018-08-21 23:26:58 -0400932 }
933}
David Tolnay4ac232d2018-08-31 10:18:03 -0700934
David Tolnay80a914f2018-08-30 23:49:53 -0700935impl Parse for TokenStream {
936 fn parse(input: ParseStream) -> Result<Self> {
937 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
938 }
939}
940
941impl Parse for TokenTree {
942 fn parse(input: ParseStream) -> Result<Self> {
943 input.step(|cursor| match cursor.token_tree() {
944 Some((tt, rest)) => Ok((tt, rest)),
945 None => Err(cursor.error("expected token tree")),
946 })
947 }
948}
949
950impl Parse for Group {
951 fn parse(input: ParseStream) -> Result<Self> {
952 input.step(|cursor| {
953 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
954 if let Some((inside, span, rest)) = cursor.group(*delim) {
955 let mut group = Group::new(*delim, inside.token_stream());
956 group.set_span(span);
957 return Ok((group, rest));
958 }
959 }
960 Err(cursor.error("expected group token"))
961 })
962 }
963}
964
965impl Parse for Punct {
966 fn parse(input: ParseStream) -> Result<Self> {
967 input.step(|cursor| match cursor.punct() {
968 Some((punct, rest)) => Ok((punct, rest)),
969 None => Err(cursor.error("expected punctuation token")),
970 })
971 }
972}
973
974impl Parse for Literal {
975 fn parse(input: ParseStream) -> Result<Self> {
976 input.step(|cursor| match cursor.literal() {
977 Some((literal, rest)) => Ok((literal, rest)),
978 None => Err(cursor.error("expected literal token")),
979 })
980 }
981}
982
983/// Parser that can parse Rust tokens into a particular syntax tree node.
984///
985/// Refer to the [module documentation] for details about parsing in Syn.
986///
987/// [module documentation]: index.html
988///
989/// *This trait is available if Syn is built with the `"parsing"` feature.*
990pub trait Parser: Sized {
991 type Output;
992
993 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
994 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
995
996 /// Parse tokens of source code into the chosen syntax tree node.
997 ///
998 /// *This method is available if Syn is built with both the `"parsing"` and
999 /// `"proc-macro"` features.*
1000 #[cfg(all(
1001 not(all(target_arch = "wasm32", target_os = "unknown")),
1002 feature = "proc-macro"
1003 ))]
1004 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1005 self.parse2(proc_macro2::TokenStream::from(tokens))
1006 }
1007
1008 /// Parse a string of Rust code into the chosen syntax tree node.
1009 ///
1010 /// # Hygiene
1011 ///
1012 /// Every span in the resulting syntax tree will be set to resolve at the
1013 /// macro call site.
1014 fn parse_str(self, s: &str) -> Result<Self::Output> {
1015 self.parse2(proc_macro2::TokenStream::from_str(s)?)
1016 }
1017}
1018
David Tolnay7b07aa12018-09-01 11:41:12 -07001019fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1020 let scope = Span::call_site();
1021 let cursor = tokens.begin();
1022 let unexpected = Rc::new(Cell::new(None));
1023 private::new_parse_buffer(scope, cursor, unexpected)
1024}
1025
David Tolnay80a914f2018-08-30 23:49:53 -07001026impl<F, T> Parser for F
1027where
1028 F: FnOnce(ParseStream) -> Result<T>,
1029{
1030 type Output = T;
1031
1032 fn parse2(self, tokens: TokenStream) -> Result<T> {
1033 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -07001034 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -07001035 let node = self(&state)?;
1036 state.check_unexpected()?;
1037 if state.is_empty() {
1038 Ok(node)
1039 } else {
1040 Err(state.error("unexpected token"))
1041 }
1042 }
1043}