| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 1 | use crate::syntax::{Derive, Doc}; |
| 2 | use proc_macro2::Ident; |
| 3 | use syn::parse::{ParseStream, Parser}; |
| 4 | use syn::{Attribute, Error, LitStr, Path, Result, Token}; |
| 5 | |
| 6 | pub(super) fn parse_doc(attrs: &[Attribute]) -> Result<Doc> { |
| 7 | let mut doc = Doc::new(); |
| 8 | let derives = None; |
| 9 | parse(attrs, &mut doc, derives)?; |
| 10 | Ok(doc) |
| 11 | } |
| 12 | |
| 13 | pub(super) fn parse( |
| 14 | attrs: &[Attribute], |
| 15 | doc: &mut Doc, |
| David Tolnay | e86b9cf | 2020-05-10 14:24:29 -0700 | [diff] [blame^] | 16 | mut derives: Option<&mut Vec<Derive>>, |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 17 | ) -> Result<()> { |
| 18 | for attr in attrs { |
| 19 | if attr.path.is_ident("doc") { |
| 20 | let lit = parse_doc_attribute.parse2(attr.tokens.clone())?; |
| 21 | doc.push(lit); |
| 22 | continue; |
| 23 | } else if attr.path.is_ident("derive") { |
| 24 | if let Some(derives) = &mut derives { |
| 25 | derives.extend(attr.parse_args_with(parse_derive_attribute)?); |
| 26 | continue; |
| 27 | } |
| 28 | } |
| 29 | return Err(Error::new_spanned(attr, "unsupported attribute")); |
| 30 | } |
| 31 | Ok(()) |
| 32 | } |
| 33 | |
| 34 | fn parse_doc_attribute(input: ParseStream) -> Result<LitStr> { |
| 35 | input.parse::<Token![=]>()?; |
| 36 | let lit: LitStr = input.parse()?; |
| 37 | Ok(lit) |
| 38 | } |
| 39 | |
| David Tolnay | e86b9cf | 2020-05-10 14:24:29 -0700 | [diff] [blame^] | 40 | fn parse_derive_attribute(input: ParseStream) -> Result<Vec<Derive>> { |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 41 | input |
| 42 | .parse_terminated::<Path, Token![,]>(Path::parse_mod_style)? |
| 43 | .into_iter() |
| David Tolnay | e86b9cf | 2020-05-10 14:24:29 -0700 | [diff] [blame^] | 44 | .map(|path| { |
| 45 | if let Some(ident) = path.get_ident() { |
| 46 | if let Some(derive) = Derive::from(ident) { |
| 47 | return Ok(derive); |
| 48 | } |
| 49 | } |
| 50 | Err(Error::new_spanned(path, "unsupported derive")) |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 51 | }) |
| 52 | .collect() |
| 53 | } |
| 54 | |
| 55 | impl Derive { |
| 56 | pub fn from(ident: &Ident) -> Option<Self> { |
| 57 | match ident.to_string().as_str() { |
| 58 | "Clone" => Some(Derive::Clone), |
| 59 | "Copy" => Some(Derive::Copy), |
| 60 | _ => None, |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | impl AsRef<str> for Derive { |
| 66 | fn as_ref(&self) -> &str { |
| 67 | match self { |
| 68 | Derive::Clone => "Clone", |
| 69 | Derive::Copy => "Copy", |
| 70 | } |
| 71 | } |
| 72 | } |