1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use syn::*;

pub fn str_value_of_meta_item(item: &Meta, name: &str) -> String {
    match *item {
        Meta::NameValue(MetaNameValue {
            lit: Lit::Str(ref value),
            ..
        }) => value.value(),
        _ => panic!(
            r#"`{}` must be in the form `#[{}="something"]`"#,
            name, name
        ),
    }
}

pub fn get_options_from_input(
    name: &Path,
    attrs: &[Attribute],
    on_bug: fn() -> !,
) -> Option<Vec<Meta>> {
    let options = attrs
        .iter()
        .find(|a| &a.path == name)
        .map(|a| a.parse_meta());
    match options {
        Some(Ok(Meta::List(MetaList { ref nested, .. }))) => Some(
            nested
                .iter()
                .map(|o| match *o {
                    NestedMeta::Meta(ref m) => m.clone(),
                    _ => on_bug(),
                })
                .collect(),
        ),
        Some(_) => on_bug(),
        None => None,
    }
}

pub fn get_option(options: &[Meta], option_name: &str, on_bug: fn() -> !) -> String {
    get_optional_option(options, option_name).unwrap_or_else(|| on_bug())
}

pub fn get_optional_option(options: &[Meta], option_name: &str) -> Option<String> {
    options
        .iter()
        .find(|a| a.path().is_ident(option_name))
        .map(|a| str_value_of_meta_item(a, option_name))
}