1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
5 use darling::util::Override;
7 use proc_macro2::{Span, TokenStream};
8 use quote::{ToTokens, TokenStreamExt};
9 use syn::{self, Data, Ident, Path, WhereClause};
10 use synstructure::{BindingInfo, Structure, VariantInfo};
12 fn derive_bitflags(input: &syn::DeriveInput, bitflags: &CssBitflagAttrs) -> TokenStream {
13 let name = &input.ident;
14 let mut body = TokenStream::new();
15 for (rust_name, css_name) in bitflags.single_flags() {
16 let rust_ident = Ident::new(&rust_name, Span::call_site());
17 body.append_all(quote! {
18 if *self == Self::#rust_ident {
19 return dest.write_str(#css_name);
24 body.append_all(quote! {
25 let mut has_any = false;
28 if bitflags.overlapping_bits {
29 body.append_all(quote! {
30 let mut serialized = Self::empty();
34 for (rust_name, css_name) in bitflags.mixed_flags() {
35 let rust_ident = Ident::new(&rust_name, Span::call_site());
36 let serialize = quote! {
38 dest.write_char(' ')?;
41 dest.write_str(#css_name)?;
43 if bitflags.overlapping_bits {
44 body.append_all(quote! {
45 if self.contains(Self::#rust_ident) && !serialized.intersects(Self::#rust_ident) {
47 serialized.insert(Self::#rust_ident);
51 body.append_all(quote! {
52 if self.intersects(Self::#rust_ident) {
59 body.append_all(quote! {
64 impl style_traits::ToCss for #name {
65 #[allow(unused_variables)]
69 dest: &mut style_traits::CssWriter<W>,
80 pub fn derive(mut input: syn::DeriveInput) -> TokenStream {
81 let mut where_clause = input.generics.where_clause.take();
82 for param in input.generics.type_params() {
83 cg::add_predicate(&mut where_clause, parse_quote!(#param: style_traits::ToCss));
86 let input_attrs = cg::parse_input_attrs::<CssInputAttrs>(&input);
87 if matches!(input.data, Data::Enum(..)) || input_attrs.bitflags.is_some() {
89 input_attrs.function.is_none(),
90 "#[css(function)] is not allowed on enums or bitflags"
94 "#[css(comma)] is not allowed on enums or bitflags"
98 if let Some(ref bitflags) = input_attrs.bitflags {
100 !input_attrs.derive_debug,
101 "Bitflags can derive debug on their own"
103 assert!(where_clause.is_none(), "Generic bitflags?");
104 return derive_bitflags(&input, bitflags);
108 let s = Structure::new(&input);
109 s.each_variant(|variant| derive_variant_arm(variant, &mut where_clause))
111 input.generics.where_clause = where_clause;
113 let name = &input.ident;
114 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
116 let mut impls = quote! {
117 impl #impl_generics style_traits::ToCss for #name #ty_generics #where_clause {
118 #[allow(unused_variables)]
122 dest: &mut style_traits::CssWriter<W>,
123 ) -> std::fmt::Result
134 if input_attrs.derive_debug {
135 impls.append_all(quote! {
136 impl #impl_generics std::fmt::Debug for #name #ty_generics #where_clause {
137 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
138 style_traits::ToCss::to_css(
140 &mut style_traits::CssWriter::new(f),
150 fn derive_variant_arm(variant: &VariantInfo, generics: &mut Option<WhereClause>) -> TokenStream {
151 let bindings = variant.bindings();
152 let identifier = cg::to_css_identifier(&variant.ast().ident.to_string());
153 let ast = variant.ast();
154 let variant_attrs = cg::parse_variant_attrs_from_ast::<CssVariantAttrs>(&ast);
155 let separator = if variant_attrs.comma { ", " } else { " " };
157 if variant_attrs.skip {
158 return quote!(Ok(()));
160 if variant_attrs.dimension {
161 assert_eq!(bindings.len(), 1);
163 variant_attrs.function.is_none() && variant_attrs.keyword.is_none(),
164 "That makes no sense"
168 let mut expr = if let Some(keyword) = variant_attrs.keyword {
169 assert!(bindings.is_empty());
171 std::fmt::Write::write_str(dest, #keyword)
173 } else if !bindings.is_empty() {
174 derive_variant_fields_expr(bindings, generics, separator)
177 std::fmt::Write::write_str(dest, #identifier)
181 if variant_attrs.dimension {
184 std::fmt::Write::write_str(dest, #identifier)
186 } else if let Some(function) = variant_attrs.function {
187 let mut identifier = function.explicit().map_or(identifier, |name| name);
188 identifier.push('(');
190 std::fmt::Write::write_str(dest, #identifier)?;
192 std::fmt::Write::write_str(dest, ")")
198 fn derive_variant_fields_expr(
199 bindings: &[BindingInfo],
200 where_clause: &mut Option<WhereClause>,
203 let mut iter = bindings
205 .filter_map(|binding| {
206 let attrs = cg::parse_field_attrs::<CssFieldAttrs>(&binding.ast());
210 Some((binding, attrs))
214 let (first, attrs) = match iter.next() {
216 None => return quote! { Ok(()) },
218 if attrs.field_bound {
219 let ty = &first.ast().ty;
220 // TODO(emilio): IntoIterator might not be enough for every type of
221 // iterable thing (like ArcSlice<> or what not). We might want to expose
222 // an `item = "T"` attribute to handle that in the future.
223 let predicate = if attrs.iterable {
224 parse_quote!(<#ty as IntoIterator>::Item: style_traits::ToCss)
226 parse_quote!(#ty: style_traits::ToCss)
228 cg::add_predicate(where_clause, predicate);
230 if !attrs.iterable && iter.peek().is_none() {
231 let mut expr = quote! { style_traits::ToCss::to_css(#first, dest) };
232 if let Some(condition) = attrs.skip_if {
234 if !#condition(#first) {
240 if let Some(condition) = attrs.contextual_skip_if {
242 if !#condition(#(#bindings), *) {
250 let mut expr = derive_single_field_expr(first, attrs, where_clause, bindings);
251 for (binding, attrs) in iter {
252 derive_single_field_expr(binding, attrs, where_clause, bindings).to_tokens(&mut expr)
256 let mut writer = style_traits::values::SequenceWriter::new(dest, #separator);
262 fn derive_single_field_expr(
264 attrs: CssFieldAttrs,
265 where_clause: &mut Option<WhereClause>,
266 bindings: &[BindingInfo],
268 let mut expr = if attrs.iterable {
269 if let Some(if_empty) = attrs.if_empty {
272 let mut iter = #field.iter().peekable();
273 if iter.peek().is_none() {
274 writer.raw_item(#if_empty)?;
284 for item in #field.iter() {
288 } else if attrs.represents_keyword {
293 .expect("Unnamed field with represents_keyword?");
294 let ident = cg::to_css_identifier(&ident.to_string()).replace("_", "-");
297 writer.raw_item(#ident)?;
301 if attrs.field_bound {
302 let ty = &field.ast().ty;
303 cg::add_predicate(where_clause, parse_quote!(#ty: style_traits::ToCss));
305 quote! { writer.item(#field)?; }
308 if let Some(condition) = attrs.skip_if {
310 if !#condition(#field) {
316 if let Some(condition) = attrs.contextual_skip_if {
318 if !#condition(#(#bindings), *) {
327 #[derive(Default, FromMeta)]
329 pub struct CssBitflagAttrs {
330 /// Flags that can only go on their own, comma-separated.
331 pub single: Option<String>,
332 /// Flags that can go mixed with each other, comma-separated.
333 pub mixed: Option<String>,
334 /// Extra validation of the resulting mixed flags.
335 pub validate_mixed: Option<Path>,
336 /// Whether there are overlapping bits we need to take care of when
338 pub overlapping_bits: bool,
341 impl CssBitflagAttrs {
342 /// Returns a vector of (rust_name, css_name) of a given flag list.
343 fn names(s: &Option<String>) -> Vec<(String, String)> {
346 None => return vec![],
349 .map(|css_name| (cg::to_scream_case(css_name), css_name.to_owned()))
353 pub fn single_flags(&self) -> Vec<(String, String)> {
354 Self::names(&self.single)
357 pub fn mixed_flags(&self) -> Vec<(String, String)> {
358 Self::names(&self.mixed)
362 #[derive(Default, FromDeriveInput)]
363 #[darling(attributes(css), default)]
364 pub struct CssInputAttrs {
365 pub derive_debug: bool,
366 // Here because structs variants are also their whole type definition.
367 pub function: Option<Override<String>>,
368 // Here because structs variants are also their whole type definition.
370 pub bitflags: Option<CssBitflagAttrs>,
373 #[derive(Default, FromVariant)]
374 #[darling(attributes(css), default)]
375 pub struct CssVariantAttrs {
376 pub function: Option<Override<String>>,
377 // Here because structs variants are also their whole type definition.
378 pub derive_debug: bool,
380 pub bitflags: Option<CssBitflagAttrs>,
382 pub keyword: Option<String>,
386 #[derive(Default, FromField)]
387 #[darling(attributes(css), default)]
388 pub struct CssFieldAttrs {
389 pub if_empty: Option<String>,
390 pub field_bound: bool,
393 pub represents_keyword: bool,
394 pub contextual_skip_if: Option<Path>,
395 pub skip_if: Option<Path>,