Skip to main content

autophagy_macro/
utility.rs

1use crate::attribute_list::AttributeList;
2use std::error::Error;
3use syn::{parse::Parse, parse_str, Expr, ExprLit, Lit, Meta, Path};
4
5const DEFAULT_CRATE_NAME: &str = "autophagy";
6
7pub fn parse_crate_path(attributes: &AttributeList) -> Result<Path, Box<dyn Error>> {
8    Ok(parse_string_attribute(attributes, "crate")?.unwrap_or(parse_str(DEFAULT_CRATE_NAME)?))
9}
10
11fn parse_string_attribute<T: Parse>(
12    attributes: &AttributeList,
13    key: &str,
14) -> Result<Option<T>, Box<dyn Error>> {
15    Ok(attributes
16        .variables()
17        .find_map(|meta| match meta {
18            Meta::NameValue(name_value) => {
19                if name_value.path.is_ident(key) {
20                    if let Expr::Lit(ExprLit {
21                        lit: Lit::Str(string),
22                        ..
23                    }) = &name_value.value
24                    {
25                        Some(string.value())
26                    } else {
27                        None
28                    }
29                } else {
30                    None
31                }
32            }
33            _ => None,
34        })
35        .map(|string| parse_str(&string))
36        .transpose()?)
37}