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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
use proc_macro2::{Span, TokenStream};
use quote::ToTokens;
use syn::punctuated::Punctuated;
use syn::synom::Synom;
use syn::token::{Comma, Eq};
use syn::{Attribute, Data, Field, Fields, Ident, Index, LitStr, Type};

pub fn parse_attributes<T: MetaParser>(attributes: Vec<Attribute>) -> T {
    let mut result = T::default();

    for attribute in attributes {
        let attribute_name = attribute
            .path
            .segments
            .first()
            .unwrap()
            .into_value()
            .ident
            .clone();
        let is_palette_attribute = attribute_name.to_string().starts_with("palette_");

        if attribute.path.segments.len() > 1 {
            if is_palette_attribute {
                panic!(
                    "expected `{}`, but found `{}`",
                    attribute_name,
                    attribute.path.into_token_stream()
                );
            } else {
                continue;
            }
        }

        if attribute_name == "palette_internal" {
            assert_empty_attribute(&attribute_name, attribute.tts);
            result.internal();
        } else {
            result.parse_attribute(attribute_name, attribute.tts);
        }
    }

    result
}

pub fn parse_data_attributes<T: DataMetaParser>(data: Data) -> T {
    let mut result = T::default();

    match data {
        Data::Struct(struct_item) => {
            let fields = match struct_item.fields {
                Fields::Named(fields) => fields.named,
                Fields::Unnamed(fields) => fields.unnamed,
                Fields::Unit => Default::default(),
            };

            parse_struct_field_attributes(&mut result, fields)
        }
        Data::Enum(_) => {}
        Data::Union(_) => {}
    }

    result
}

pub fn parse_struct_field_attributes<T: DataMetaParser>(
    parser: &mut T,
    fields: Punctuated<Field, Comma>,
) {
    for (index, field) in fields.into_iter().enumerate() {
        let identifier = field
            .ident
            .map(IdentOrIndex::Ident)
            .unwrap_or_else(|| IdentOrIndex::Index(index.into()));

        for attribute in field.attrs {
            let attribute_name = attribute
                .path
                .segments
                .first()
                .unwrap()
                .into_value()
                .ident
                .clone();
            if !attribute_name.to_string().starts_with("palette_") {
                continue;
            }

            if attribute.path.segments.len() > 1 {
                panic!(
                    "expected `{}`, but found `{}`",
                    attribute_name,
                    attribute.path.into_token_stream()
                );
            }

            parser.parse_struct_field_attribute(
                identifier.clone(),
                field.ty.clone(),
                attribute_name,
                attribute.tts,
            );
        }
    }
}

pub fn assert_empty_attribute(attribute_name: &Ident, tts: TokenStream) {
    if !tts.is_empty() {
        panic!(
            "expected the attribute to be on the form `#[{name}]`, but found `#[{name}{tts}]`",
            name = attribute_name,
            tts = tts
        );
    }
}

pub fn parse_tuple_attribute<T: Synom>(
    attribute_name: &Ident,
    tts: TokenStream,
) -> Punctuated<T, Comma> {
    struct GenericTuple<T>(Punctuated<T, Comma>);

    impl<T: Synom> Synom for GenericTuple<T> {
        named!(parse -> Self, do_parse!(
            tuple: parens!(call!(Punctuated::parse_separated_nonempty)) >>
            (GenericTuple(tuple.1))
        ));
    }

    match ::syn::parse2::<GenericTuple<T>>(tts.clone()) {
        Ok(elements) => elements.0,
        Err(_) => panic!(
            "expected the attribute to be on the form `#[{name}(A, B, ...)]`, but found #[{name}{tts}]",
            name = attribute_name,
            tts = tts
        ),
    }
}

pub fn parse_equal_attribute<T: Synom>(attribute_name: &Ident, tts: TokenStream) -> T {
    struct Paren<T>(T);

    impl<T: Synom> Synom for Paren<T> {
        named!(parse -> Self, do_parse!(
            _eq: syn!(Eq) >>
            content: syn!(StringOrValue<T>) >>
            result: switch!(value!(content),
                StringOrValue::Value(value) => value!(value) |
                StringOrValue::String(string) => call!(parse_string, string)
            ) >>
            (Paren(result))
        ));
    }

    enum StringOrValue<T> {
        String(String),
        Value(T),
    }

    impl<T: Synom> Synom for StringOrValue<T> {
        named!(parse -> Self, alt!(
            syn!(T) => {StringOrValue::Value} |
            syn!(LitStr) => {|lit| StringOrValue::String(lit.value())}
        ));
    }

    fn parse_string<T: Synom>(
        cursor: ::syn::buffer::Cursor,
        string: String,
    ) -> ::syn::synom::PResult<T> {
        ::syn::parse2(string.parse().unwrap()).map(|value| (value, cursor))
    }

    match ::syn::parse2::<Paren<T>>(tts.clone()) {
        Ok(assign) => assign.0,
        Err(_) => panic!(
            "expected the attribute to be on the form `#[{name} = A]` or `#[{name} = \"A\"]`, but found #[{name}{tts}]",
            name = attribute_name,
            tts = tts
        ),
    }
}

#[derive(PartialEq)]
pub struct KeyValuePair {
    pub key: Ident,
    pub value: Option<Ident>,
}

impl ::syn::synom::Synom for KeyValuePair {
    named!(parse -> Self, do_parse!(
        key: syn!(Ident) >>
        value: option!(do_parse!(
            _eq: syn!(Eq) >>
            value: syn!(LitStr) >>
            (Ident::new(&value.value(), Span::call_site()))
        )) >>
        (KeyValuePair {
            key,
            value
        })
    ));
}

impl PartialEq<str> for KeyValuePair {
    fn eq(&self, other: &str) -> bool {
        self.key == other
    }
}

#[derive(Clone)]
pub enum IdentOrIndex {
    Index(Index),
    Ident(Ident),
}

impl PartialEq for IdentOrIndex {
    fn eq(&self, other: &IdentOrIndex) -> bool {
        match (self, other) {
            (&IdentOrIndex::Index(ref this), &IdentOrIndex::Index(ref other)) => {
                this.index == other.index
            }
            (&IdentOrIndex::Ident(ref this), &IdentOrIndex::Ident(ref other)) => this == other,
            _ => false,
        }
    }
}

impl ::std::cmp::Eq for IdentOrIndex {}

impl ::std::hash::Hash for IdentOrIndex {
    fn hash<H: ::std::hash::Hasher>(&self, hasher: &mut H) {
        ::std::mem::discriminant(self).hash(hasher);

        match *self {
            IdentOrIndex::Index(ref index) => index.index.hash(hasher),
            IdentOrIndex::Ident(ref ident) => ident.hash(hasher),
        }
    }
}

impl ::quote::ToTokens for IdentOrIndex {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match *self {
            IdentOrIndex::Index(ref index) => index.to_tokens(tokens),
            IdentOrIndex::Ident(ref ident) => ident.to_tokens(tokens),
        }
    }
}

pub trait MetaParser: Default {
    fn internal(&mut self);
    fn parse_attribute(&mut self, attribute_name: Ident, attribute_tts: TokenStream);
}

pub trait DataMetaParser: Default {
    fn parse_struct_field_attribute(
        &mut self,
        field_name: IdentOrIndex,
        ty: Type,
        attribute_name: Ident,
        attribute_tts: TokenStream,
    );
}