Debian Codegraph @

src/attribute.rs

raw symbols SCIP
1 use syn::parse::Parse;
2 use syn::punctuated::Punctuated;
3 use syn::{token, Attribute, Expr, Ident, LitStr, Token};
4
5 pub(crate) enum AttributeValue {
6 /// `#[lofty(attribute_name)]`
7 Path(Ident),
8 /// `#[lofty(attribute_name = "value")]`
9 NameValue(Ident, LitStr),
10 #[allow(dead_code)]
11 /// `#[lofty(attribute_name(value1, value2, value3))]`
12 SingleList(Ident, Punctuated<Expr, Token![,]>),
13 }
14
15 impl AttributeValue {
16 pub(crate) fn from_attribute(
17 expected_path: &str,
18 attribute: &Attribute,
19 ) -> syn::Result<Option<Self>> {
20 if !attribute.path().is_ident(expected_path) {
21 return Ok(None);
22 }
23
24 let mut value = None;
25 attribute.parse_nested_meta(|meta| {
26 // `#[lofty(attribute_name)]`
27 if meta.input.is_empty() {
28 value = Some(AttributeValue::Path(meta.path.get_ident().unwrap().clone()));
29 return Ok(());
30 }
31
32 // `#[lofty(attribute_name = "value")]`
33 if meta.input.peek(token::Eq) {
34 let val = meta.value()?;
35 let str_value: LitStr = val.parse()?;
36
37 value = Some(AttributeValue::NameValue(
38 meta.path.get_ident().unwrap().clone(),
39 str_value,
40 ));
41 return Ok(());
42 }
43
44 // `#[lofty(attribute_name(value1, value2, value3))]`
45 if meta.input.peek(token::Paren) {
46 return meta.parse_nested_meta(|meta| {
47 let list = meta.input.parse_terminated(syn::Expr::parse, Token![,])?;
48 value = Some(AttributeValue::SingleList(
49 meta.path.get_ident().unwrap().clone(),
50 list,
51 ));
52
53 Ok(())
54 });
55 }
56
57 Err(meta.error("Unrecognized attribute format"))
58 })?;
59
60 Ok(value)
61 }
62 }