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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use syn::{parse_macro_input, DeriveInput, Generics, Ident, Type};

use meta::{self, DataMetaParser, IdentOrIndex, KeyValuePair, MetaParser};
use util;
use COLOR_TYPES;

use super::shared::{self, ConvertDirection};

pub fn derive(tokens: TokenStream) -> TokenStream {
    let DeriveInput {
        ident,
        attrs,
        generics: original_generics,
        data,
        ..
    } = parse_macro_input!(tokens);
    let mut generics = original_generics.clone();

    let mut meta: IntoColorMeta = meta::parse_attributes(attrs);
    let item_meta: IntoColorItemMeta = meta::parse_data_attributes(data);

    let (generic_component, generic_white_point) = shared::find_in_generics(
        meta.component.as_ref(),
        meta.white_point.as_ref(),
        &original_generics,
    );

    let white_point = shared::white_point_type(meta.white_point.clone(), meta.internal);
    let component = shared::component_type(meta.component.clone());

    let (alpha_property, alpha_type) = item_meta
        .alpha_property
        .map(|(property, ty)| (Some(property), ty))
        .unwrap_or_else(|| (None, component.clone()));

    if generic_component {
        shared::add_component_where_clause(&component, &mut generics, meta.internal);
    }

    if generic_white_point {
        shared::add_white_point_where_clause(&white_point, &mut generics, meta.internal);
    }

    let (impl_generics, type_generics, where_clause) = generics.split_for_impl();

    // Assume conversion into Xyz by default
    if meta.manual_implementations.is_empty() {
        meta.manual_implementations.push(KeyValuePair {
            key: Ident::new("Xyz", Span::call_site()),
            value: None,
        });
    }

    let methods = shared::generate_methods(
        &ident,
        ConvertDirection::Into,
        &meta.manual_implementations,
        &component,
        &white_point,
        &shared::rgb_space_type(meta.rgb_space.clone(), &white_point, meta.internal),
        &type_generics.as_turbofish(),
        meta.internal,
    );

    let trait_path = util::path(&["IntoColor"], meta.internal);
    let into_color_impl = quote!{
        #[automatically_derived]
        impl #impl_generics #trait_path<#white_point, #component> for #ident #type_generics #where_clause {
            #(#methods)*
        }
    };

    let into_impls = COLOR_TYPES.into_iter().map(|&color| {
        let skip_regular_into = (meta.internal && ident == color)
            || meta
                .manual_implementations
                .iter()
                .any(|color_impl| color_impl.key == color && color_impl.value.is_none());

        let regular_into = if skip_regular_into {
            None
        } else {
            Some(impl_into(
                &ident,
                color,
                &meta,
                &original_generics,
                generic_component,
            ))
        };

        let with_alpha = impl_into_alpha(
            &ident,
            color,
            &meta,
            &original_generics,
            generic_component,
            alpha_property.as_ref(),
            &alpha_type,
        );

        quote! {
            #regular_into
            #with_alpha
        }
    });

    let result = util::bundle_impl(
        "IntoColor",
        ident.clone(),
        meta.internal,
        quote! {
            #into_color_impl
            #(#into_impls)*
        },
    );

    result.into()
}

fn impl_into(
    ident: &Ident,
    color: &str,
    meta: &IntoColorMeta,
    generics: &Generics,
    generic_component: bool,
) -> TokenStream2 {
    let (_, type_generics, _) = generics.split_for_impl();

    let IntoImplParameters {
        generics,
        trait_path,
        color_ty,
        method_call,
        ..
    } = prepare_into_impl(ident, color, meta, generics, generic_component);

    let (impl_generics, _, where_clause) = generics.split_for_impl();

    quote!{
        #[automatically_derived]
        impl #impl_generics Into<#color_ty> for #ident #type_generics #where_clause {
            fn into(self) -> #color_ty {
                use #trait_path;
                let color = self;
                #method_call
            }
        }
    }
}

fn impl_into_alpha(
    ident: &Ident,
    color: &str,
    meta: &IntoColorMeta,
    generics: &Generics,
    generic_component: bool,
    alpha_property: Option<&IdentOrIndex>,
    alpha_type: &Type,
) -> TokenStream2 {
    let (_, type_generics, _) = generics.split_for_impl();

    let IntoImplParameters {
        generics,
        alpha_path,
        trait_path,
        color_ty,
        method_call,
        ..
    } = prepare_into_impl(ident, color, meta, generics, generic_component);

    let (impl_generics, _, where_clause) = generics.split_for_impl();

    if let Some(alpha_property) = alpha_property {
        quote!{
            #[automatically_derived]
            impl #impl_generics Into<#alpha_path<#color_ty, #alpha_type>> for #ident #type_generics #where_clause {
                fn into(self) -> #alpha_path<#color_ty, #alpha_type> {
                    use #trait_path;
                    let color = self;
                    #alpha_path {
                        alpha: color.#alpha_property.clone(),
                        color: #method_call,
                    }
                }
            }
        }
    } else {
        quote!{
            #[automatically_derived]
            impl #impl_generics Into<#alpha_path<#color_ty, #alpha_type>> for #ident #type_generics #where_clause {
                fn into(self) -> #alpha_path<#color_ty, #alpha_type> {
                    use #trait_path;
                    let color = self;
                    #method_call.into()
                }
            }
        }
    }
}

fn prepare_into_impl(
    ident: &Ident,
    color: &str,
    meta: &IntoColorMeta,
    generics: &Generics,
    generic_component: bool,
) -> IntoImplParameters {
    let (_, type_generics, _) = generics.split_for_impl();
    let turbofish_generics = type_generics.as_turbofish();
    let mut generics = generics.clone();

    let method_name = Ident::new(&format!("into_{}", color.to_lowercase()), Span::call_site());

    let trait_path = util::path(&["IntoColor"], meta.internal);
    let alpha_path = util::path(&["Alpha"], meta.internal);

    let white_point = shared::white_point_type(meta.white_point.clone(), meta.internal);
    let component = shared::component_type(meta.component.clone());

    if generic_component {
        shared::add_component_where_clause(&component, &mut generics, meta.internal)
    }

    let color_ty = shared::get_convert_color_type(
        color,
        &white_point,
        &component,
        meta.rgb_space.as_ref(),
        &mut generics,
        meta.internal,
    );

    let method_call = match color {
        "Rgb" | "Luma" => quote! {
            #ident #turbofish_generics::#method_name(color).into_encoding()
        },
        _ => quote! {
            #ident #turbofish_generics::#method_name(color)
        },
    };

    IntoImplParameters {
        generics,
        alpha_path,
        trait_path,
        color_ty,
        method_call,
    }
}

struct IntoImplParameters {
    generics: Generics,
    alpha_path: TokenStream2,
    trait_path: TokenStream2,
    color_ty: Type,
    method_call: TokenStream2,
}

#[derive(Default)]
struct IntoColorMeta {
    manual_implementations: Vec<KeyValuePair>,
    internal: bool,
    component: Option<Type>,
    white_point: Option<Type>,
    rgb_space: Option<Type>,
}

impl MetaParser for IntoColorMeta {
    fn internal(&mut self) {
        self.internal = true;
    }

    fn parse_attribute(&mut self, attribute_name: Ident, attribute_tts: TokenStream2) {
        match &*attribute_name.to_string() {
            "palette_manual_into" => {
                let impls =
                    meta::parse_tuple_attribute::<KeyValuePair>(&attribute_name, attribute_tts);
                self.manual_implementations.extend(impls)
            }
            "palette_component" => {
                if self.component.is_none() {
                    let component = meta::parse_equal_attribute(&attribute_name, attribute_tts);
                    self.component = Some(component);
                }
            }
            "palette_white_point" => {
                if self.white_point.is_none() {
                    let white_point = meta::parse_equal_attribute(&attribute_name, attribute_tts);
                    self.white_point = Some(white_point);
                }
            }
            "palette_rgb_space" => {
                if self.rgb_space.is_none() {
                    let rgb_space = meta::parse_equal_attribute(&attribute_name, attribute_tts);
                    self.rgb_space = Some(rgb_space);
                }
            }
            _ => {}
        }
    }
}

#[derive(Default)]
struct IntoColorItemMeta {
    alpha_property: Option<(IdentOrIndex, Type)>,
}

impl DataMetaParser for IntoColorItemMeta {
    fn parse_struct_field_attribute(
        &mut self,
        field_name: IdentOrIndex,
        ty: Type,
        attribute_name: Ident,
        attribute_tts: TokenStream2,
    ) {
        match &*attribute_name.to_string() {
            "palette_alpha" => {
                meta::assert_empty_attribute(&attribute_name, attribute_tts);
                self.alpha_property = Some((field_name, ty));
            }
            _ => {}
        }
    }
}