aboutsummaryrefslogtreecommitdiff
path: root/derive-macro/src/attrs.rs
blob: c95e6edfcdb51d9dbc863b9cbd396297822968aa (plain)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use proc_macro2::TokenStream;
use proc_macro_error::{abort, ResultExt};
use quote::{quote, ToTokens};
use syn::{
    parenthesized,
    parse::{Parse, ParseStream},
    punctuated::Punctuated,
    spanned::Spanned,
    Attribute, Expr, Ident, LitStr, Token,
};

use crate::spanned::Sp;

#[derive(Clone)]
pub struct IniAttr {
    pub kind: Sp<AttrKind>,
    pub name: Ident,
    pub magic: Option<MagicAttrName>,
    pub value: Option<AttrValue>,
}

impl IniAttr {
    pub fn parse_all(all_attrs: &[Attribute]) -> Vec<Self> {
        all_attrs
            .iter()
            .filter_map(|attr| {
                let kind = if attr.path.is_ident("key") {
                    Some(Sp::new(AttrKind::Key, attr.path.span()))
                } else {
                    None
                };
                kind.map(|k| (k, attr))
            })
            .flat_map(|(k, attr)| {
                attr.parse_args_with(Punctuated::<IniAttr, Token![,]>::parse_terminated)
                    .unwrap_or_abort()
                    .into_iter()
                    .map(move |mut a| {
                        a.kind = k;
                        a
                    })
            })
            .collect()
    }

    pub fn value_or_abort(&self) -> &AttrValue {
        self.value
            .as_ref()
            .unwrap_or_else(|| abort!(self.name, "attribute `{}` requires a value", self.name))
    }

    pub fn lit_str_or_abort(&self) -> &LitStr {
        let value = self.value_or_abort();
        match value {
            AttrValue::LitStr(tokens) => tokens,
            AttrValue::Expr(_) | AttrValue::Call(_) => {
                abort!(
                    self.name,
                    "attribute `{}` can only accept string literals",
                    self.name
                )
            }
        }
    }
}

impl Parse for IniAttr {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let name: Ident = input.parse()?;
        let name_str = name.to_string();

        let magic = match name_str.as_str() {
            "name" => Some(MagicAttrName::Name),
            "default" => Some(MagicAttrName::Default),
            "parse_with" => Some(MagicAttrName::ParseWith),
            _ => None,
        };

        let value = if input.peek(Token![=]) {
            // `name = value` attributes.
            let assign_token = input.parse::<Token![=]>()?; // skip '='
            if input.peek(LitStr) {
                let lit: LitStr = input.parse()?;
                Some(AttrValue::LitStr(lit))
            } else {
                match input.parse::<Expr>() {
                    Ok(expr) => Some(AttrValue::Expr(expr)),

                    Err(_) => abort! {
                        assign_token,
                        "expected `string literal` or `expression` after `=`"
                    },
                }
            }
        } else if input.peek(syn::token::Paren) {
            // `name(...)` attributes.
            let nested;
            parenthesized!(nested in input);

            let method_args: Punctuated<_, Token![,]> = nested.parse_terminated(Expr::parse)?;
            Some(AttrValue::Call(Vec::from_iter(method_args)))
        } else {
            None
        };

        Ok(Self {
            kind: Sp::new(AttrKind::Ini, name.span()),
            name,
            magic,
            value,
        })
    }
}

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum MagicAttrName {
    Name,
    Default,
    ParseWith,
}

#[derive(Clone)]
#[allow(clippy::large_enum_variant)]
pub enum AttrValue {
    LitStr(LitStr),
    Expr(Expr),
    Call(Vec<Expr>),
}

impl ToTokens for AttrValue {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match self {
            Self::LitStr(t) => t.to_tokens(tokens),
            Self::Expr(t) => t.to_tokens(tokens),
            Self::Call(t) => {
                let t = quote!(#(#t),*);
                t.to_tokens(tokens)
            }
        }
    }
}

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum AttrKind {
    Key,
}

impl AttrKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Key => "key",
        }
    }
}