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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use darling::util::Override;
use crate::cg;
use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, TokenStreamExt};
use syn::{self, Data, Ident, Path, WhereClause};
use synstructure::{BindingInfo, Structure, VariantInfo};

fn derive_bitflags(input: &syn::DeriveInput, bitflags: &CssBitflagAttrs) -> TokenStream {
    let name = &input.ident;
    let mut body = TokenStream::new();
    for (rust_name, css_name) in bitflags.single_flags() {
        let rust_ident = Ident::new(&rust_name, Span::call_site());
        body.append_all(quote! {
            if *self == Self::#rust_ident {
                return dest.write_str(#css_name);
            }
        });
    }

    body.append_all(quote! {
        let mut has_any = false;
    });

    if bitflags.overlapping_bits {
        body.append_all(quote! {
            let mut serialized = Self::empty();
        });
    }

    for (rust_name, css_name) in bitflags.mixed_flags() {
        let rust_ident = Ident::new(&rust_name, Span::call_site());
        let serialize = quote! {
            if has_any {
                dest.write_char(' ')?;
            }
            has_any = true;
            dest.write_str(#css_name)?;
        };
        if bitflags.overlapping_bits {
            body.append_all(quote! {
                if self.contains(Self::#rust_ident) && !serialized.intersects(Self::#rust_ident) {
                    #serialize
                    serialized.insert(Self::#rust_ident);
                }
            });
        } else {
            body.append_all(quote! {
                if self.intersects(Self::#rust_ident) {
                    #serialize
                }
            });
        }
    }

    body.append_all(quote! {
        Ok(())
    });

    quote! {
        impl style_traits::ToCss for #name {
            #[allow(unused_variables)]
            #[inline]
            fn to_css<W>(
                &self,
                dest: &mut style_traits::CssWriter<W>,
            ) -> std::fmt::Result
            where
                W: std::fmt::Write,
            {
                #body
            }
        }
    }
}

pub fn derive(mut input: syn::DeriveInput) -> TokenStream {
    let mut where_clause = input.generics.where_clause.take();
    for param in input.generics.type_params() {
        cg::add_predicate(&mut where_clause, parse_quote!(#param: style_traits::ToCss));
    }

    let input_attrs = cg::parse_input_attrs::<CssInputAttrs>(&input);
    if matches!(input.data, Data::Enum(..)) || input_attrs.bitflags.is_some() {
        assert!(
            input_attrs.function.is_none(),
            "#[css(function)] is not allowed on enums or bitflags"
        );
        assert!(
            !input_attrs.comma,
            "#[css(comma)] is not allowed on enums or bitflags"
        );
    }

    if let Some(ref bitflags) = input_attrs.bitflags {
        assert!(
            !input_attrs.derive_debug,
            "Bitflags can derive debug on their own"
        );
        assert!(where_clause.is_none(), "Generic bitflags?");
        return derive_bitflags(&input, bitflags);
    }

    let match_body = {
        let s = Structure::new(&input);
        s.each_variant(|variant| derive_variant_arm(variant, &mut where_clause))
    };
    input.generics.where_clause = where_clause;

    let name = &input.ident;
    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

    let mut impls = quote! {
        impl #impl_generics style_traits::ToCss for #name #ty_generics #where_clause {
            #[allow(unused_variables)]
            #[inline]
            fn to_css<W>(
                &self,
                dest: &mut style_traits::CssWriter<W>,
            ) -> std::fmt::Result
            where
                W: std::fmt::Write,
            {
                match *self {
                    #match_body
                }
            }
        }
    };

    if input_attrs.derive_debug {
        impls.append_all(quote! {
            impl #impl_generics std::fmt::Debug for #name #ty_generics #where_clause {
                fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                    style_traits::ToCss::to_css(
                        self,
                        &mut style_traits::CssWriter::new(f),
                    )
                }
            }
        });
    }

    impls
}

fn derive_variant_arm(variant: &VariantInfo, generics: &mut Option<WhereClause>) -> TokenStream {
    let bindings = variant.bindings();
    let identifier = cg::to_css_identifier(&variant.ast().ident.to_string());
    let ast = variant.ast();
    let variant_attrs = cg::parse_variant_attrs_from_ast::<CssVariantAttrs>(&ast);
    let separator = if variant_attrs.comma { ", " } else { " " };

    if variant_attrs.skip {
        return quote!(Ok(()));
    }
    if variant_attrs.dimension {
        assert_eq!(bindings.len(), 1);
        assert!(
            variant_attrs.function.is_none() && variant_attrs.keyword.is_none(),
            "That makes no sense"
        );
    }

    let mut expr = if let Some(keyword) = variant_attrs.keyword {
        assert!(bindings.is_empty());
        quote! {
            std::fmt::Write::write_str(dest, #keyword)
        }
    } else if !bindings.is_empty() {
        derive_variant_fields_expr(bindings, generics, separator)
    } else {
        quote! {
            std::fmt::Write::write_str(dest, #identifier)
        }
    };

    if variant_attrs.dimension {
        expr = quote! {
            #expr?;
            std::fmt::Write::write_str(dest, #identifier)
        }
    } else if let Some(function) = variant_attrs.function {
        let mut identifier = function.explicit().map_or(identifier, |name| name);
        identifier.push('(');
        expr = quote! {
            std::fmt::Write::write_str(dest, #identifier)?;
            #expr?;
            std::fmt::Write::write_str(dest, ")")
        }
    }
    expr
}

fn derive_variant_fields_expr(
    bindings: &[BindingInfo],
    where_clause: &mut Option<WhereClause>,
    separator: &str,
) -> TokenStream {
    let mut iter = bindings
        .iter()
        .filter_map(|binding| {
            let attrs = cg::parse_field_attrs::<CssFieldAttrs>(&binding.ast());
            if attrs.skip {
                return None;
            }
            Some((binding, attrs))
        })
        .peekable();

    let (first, attrs) = match iter.next() {
        Some(pair) => pair,
        None => return quote! { Ok(()) },
    };
    if attrs.field_bound {
        let ty = &first.ast().ty;
        // TODO(emilio): IntoIterator might not be enough for every type of
        // iterable thing (like ArcSlice<> or what not). We might want to expose
        // an `item = "T"` attribute to handle that in the future.
        let predicate = if attrs.iterable {
            parse_quote!(<#ty as IntoIterator>::Item: style_traits::ToCss)
        } else {
            parse_quote!(#ty: style_traits::ToCss)
        };
        cg::add_predicate(where_clause, predicate);
    }
    if !attrs.iterable && iter.peek().is_none() {
        let mut expr = quote! { style_traits::ToCss::to_css(#first, dest) };
        if let Some(condition) = attrs.skip_if {
            expr = quote! {
                if !#condition(#first) {
                    #expr
                }
            }
        }

        if let Some(condition) = attrs.contextual_skip_if {
            expr = quote! {
                if !#condition(#(#bindings), *) {
                    #expr
                }
            }
        }
        return expr;
    }

    let mut expr = derive_single_field_expr(first, attrs, where_clause, bindings);
    for (binding, attrs) in iter {
        derive_single_field_expr(binding, attrs, where_clause, bindings).to_tokens(&mut expr)
    }

    quote! {{
        let mut writer = style_traits::values::SequenceWriter::new(dest, #separator);
        #expr
        Ok(())
    }}
}

fn derive_single_field_expr(
    field: &BindingInfo,
    attrs: CssFieldAttrs,
    where_clause: &mut Option<WhereClause>,
    bindings: &[BindingInfo],
) -> TokenStream {
    let mut expr = if attrs.iterable {
        if let Some(if_empty) = attrs.if_empty {
            return quote! {
                {
                    let mut iter = #field.iter().peekable();
                    if iter.peek().is_none() {
                        writer.raw_item(#if_empty)?;
                    } else {
                        for item in iter {
                            writer.item(&item)?;
                        }
                    }
                }
            };
        }
        quote! {
            for item in #field.iter() {
                writer.item(&item)?;
            }
        }
    } else if attrs.represents_keyword {
        let ident = field
            .ast()
            .ident
            .as_ref()
            .expect("Unnamed field with represents_keyword?");
        let ident = cg::to_css_identifier(&ident.to_string()).replace("_", "-");
        quote! {
            if *#field {
                writer.raw_item(#ident)?;
            }
        }
    } else {
        if attrs.field_bound {
            let ty = &field.ast().ty;
            cg::add_predicate(where_clause, parse_quote!(#ty: style_traits::ToCss));
        }
        quote! { writer.item(#field)?; }
    };

    if let Some(condition) = attrs.skip_if {
        expr = quote! {
            if !#condition(#field) {
                #expr
            }
        }
    }

    if let Some(condition) = attrs.contextual_skip_if {
        expr = quote! {
            if !#condition(#(#bindings), *) {
                #expr
            }
        }
    }

    expr
}

#[derive(Default, FromMeta)]
#[darling(default)]
pub struct CssBitflagAttrs {
    /// Flags that can only go on their own, comma-separated.
    pub single: Option<String>,
    /// Flags that can go mixed with each other, comma-separated.
    pub mixed: Option<String>,
    /// Extra validation of the resulting mixed flags.
    pub validate_mixed: Option<Path>,
    /// Whether there are overlapping bits we need to take care of when
    /// serializing.
    pub overlapping_bits: bool,
}

impl CssBitflagAttrs {
    /// Returns a vector of (rust_name, css_name) of a given flag list.
    fn names(s: &Option<String>) -> Vec<(String, String)> {
        let s = match s {
            Some(s) => s,
            None => return vec![],
        };
        s.split(',')
            .map(|css_name| (cg::to_scream_case(css_name), css_name.to_owned()))
            .collect()
    }

    pub fn single_flags(&self) -> Vec<(String, String)> {
        Self::names(&self.single)
    }

    pub fn mixed_flags(&self) -> Vec<(String, String)> {
        Self::names(&self.mixed)
    }
}

#[derive(Default, FromDeriveInput)]
#[darling(attributes(css), default)]
pub struct CssInputAttrs {
    pub derive_debug: bool,
    // Here because structs variants are also their whole type definition.
    pub function: Option<Override<String>>,
    // Here because structs variants are also their whole type definition.
    pub comma: bool,
    pub bitflags: Option<CssBitflagAttrs>,
}

#[derive(Default, FromVariant)]
#[darling(attributes(css), default)]
pub struct CssVariantAttrs {
    pub function: Option<Override<String>>,
    // Here because structs variants are also their whole type definition.
    pub derive_debug: bool,
    pub comma: bool,
    pub bitflags: Option<CssBitflagAttrs>,
    pub dimension: bool,
    pub keyword: Option<String>,
    pub skip: bool,
}

#[derive(Default, FromField)]
#[darling(attributes(css), default)]
pub struct CssFieldAttrs {
    pub if_empty: Option<String>,
    pub field_bound: bool,
    pub iterable: bool,
    pub skip: bool,
    pub represents_keyword: bool,
    pub contextual_skip_if: Option<Path>,
    pub skip_if: Option<Path>,
}