1use crate::{util::SpannedValue, Error, Result};
2use std::fmt;
3use syn::{punctuated::Pair, spanned::Spanned, token, Attribute, Meta, MetaList, Path};
4
5/// Try to parse an attribute into a meta list. Path-type meta values are accepted and returned
6/// as empty lists with their passed-in path. Name-value meta values and non-meta attributes
7/// will cause errors to be returned.
8pub fn parse_attribute_to_meta_list(attr: &Attribute) -> Result<MetaList> {
9 match attr.parse_meta() {
10 Ok(Meta::List(list: MetaList)) => Ok(list),
11 Ok(Meta::NameValue(nv: MetaNameValue)) => Err(Error::custom(format!(
12 "Name-value arguments are not supported. Use #[{}(...)]",
13 DisplayPath(&nv.path)
14 ))
15 .with_span(&nv)),
16 Ok(Meta::Path(path: Path)) => Ok(MetaList {
17 path,
18 paren_token: token::Paren(attr.span()),
19 nested: Default::default(),
20 }),
21 Err(e: Error) => Err(Error::custom(format!("Unable to parse attribute: {}", e))
22 .with_span(&SpannedValue::new((), e.span()))),
23 }
24}
25
26struct DisplayPath<'a>(&'a Path);
27
28impl fmt::Display for DisplayPath<'_> {
29 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
30 let path: &Path = self.0;
31 if path.leading_colon.is_some() {
32 write!(f, "::")?;
33 }
34 for segment: Pair<&PathSegment, &Colon2> in path.segments.pairs() {
35 match segment {
36 Pair::Punctuated(segment: &PathSegment, _) => write!(f, "{}::", segment.ident)?,
37 Pair::End(segment: &PathSegment) => segment.ident.fmt(f)?,
38 }
39 }
40
41 Ok(())
42 }
43}
44
45#[cfg(test)]
46mod tests {
47 use super::parse_attribute_to_meta_list;
48 use syn::{parse_quote, spanned::Spanned, Ident};
49
50 #[test]
51 fn parse_list() {
52 let meta = parse_attribute_to_meta_list(&parse_quote!(#[bar(baz = 4)])).unwrap();
53 assert_eq!(meta.nested.len(), 1);
54 }
55
56 #[test]
57 fn parse_path_returns_empty_list() {
58 let meta = parse_attribute_to_meta_list(&parse_quote!(#[bar])).unwrap();
59 assert!(meta.path.is_ident(&Ident::new("bar", meta.path.span())));
60 assert!(meta.nested.is_empty());
61 }
62
63 #[test]
64 fn parse_name_value_returns_error() {
65 parse_attribute_to_meta_list(&parse_quote!(#[bar = 4])).unwrap_err();
66 }
67
68 #[test]
69 fn parse_name_value_error_includes_example() {
70 let err = parse_attribute_to_meta_list(&parse_quote!(#[bar = 4])).unwrap_err();
71 assert!(err.to_string().contains("#[bar(...)]"));
72 }
73}
74