blob: 0a412e412c51cb77c215817c227d7aceb8299317 [file] [log] [blame]
David Tolnayac51b362018-08-30 23:59:52 -07001//! Extension traits to provide parsing methods on foreign types.
David Tolnay94d304f2018-08-30 23:43:53 -07002//!
3//! *This module is available if Syn is built with the `"parsing"` feature.*
4
5use proc_macro2::Ident;
6
7use parse::{ParseStream, Result};
8
9/// Additional parsing methods for `Ident`.
10///
11/// This trait is sealed and cannot be implemented for types outside of Syn.
12///
13/// *This trait is available if Syn is built with the `"parsing"` feature.*
14pub trait IdentExt: Sized + private::Sealed {
15 /// Parses any identifier including keywords.
16 ///
17 /// This is useful when parsing a DSL which allows Rust keywords as
18 /// identifiers.
19 ///
20 /// ```rust
David Tolnay9b00f652018-09-01 10:31:02 -070021 /// # extern crate syn;
22 /// #
23 /// use syn::{Ident, Token};
David Tolnayac51b362018-08-30 23:59:52 -070024 /// use syn::ext::IdentExt;
25 /// use syn::parse::{Error, ParseStream, Result};
David Tolnay94d304f2018-08-30 23:43:53 -070026 ///
27 /// // Parses input that looks like `name = NAME` where `NAME` can be
28 /// // any identifier.
29 /// //
30 /// // Examples:
31 /// //
32 /// // name = anything
33 /// // name = impl
David Tolnayac51b362018-08-30 23:59:52 -070034 /// fn parse_dsl(input: ParseStream) -> Result<Ident> {
35 /// let name_token: Ident = input.parse()?;
36 /// if name_token != "name" {
37 /// return Err(Error::new(name_token.span(), "expected `name`"));
38 /// }
39 /// input.parse::<Token![=]>()?;
40 /// let name = input.call(Ident::parse_any)?;
41 /// Ok(name)
42 /// }
David Tolnay94d304f2018-08-30 23:43:53 -070043 /// #
44 /// # fn main() {}
45 /// ```
46 fn parse_any(input: ParseStream) -> Result<Self>;
47}
48
49impl IdentExt for Ident {
50 fn parse_any(input: ParseStream) -> Result<Self> {
51 input.step(|cursor| match cursor.ident() {
52 Some((ident, rest)) => Ok((ident, rest)),
53 None => Err(cursor.error("expected ident")),
54 })
55 }
56}
57
58mod private {
59 use proc_macro2::Ident;
60
61 pub trait Sealed {}
62
63 impl Sealed for Ident {}
64}