style: Introduce css(skip_if) to conditionally skip serialization of a field.

This commit is contained in:
Emilio Cobos Álvarez 2018-03-07 03:12:12 +01:00
parent ada45f4968
commit 6da1b2fff5
No known key found for this signature in database
GPG key ID: 056B727BB9C1027C

View file

@ -5,7 +5,7 @@
use cg::{self, WhereClause};
use darling::util::Override;
use quote::{ToTokens, Tokens};
use syn::{self, Data};
use syn::{self, Data, Ident};
use synstructure::{BindingInfo, Structure, VariantInfo};
pub fn derive(input: syn::DeriveInput) -> Tokens {
@ -128,7 +128,15 @@ fn derive_variant_fields_expr(
if !attrs.ignore_bound {
where_clause.add_trait_bound(&first.ast().ty);
}
return quote! { ::style_traits::ToCss::to_css(#first, dest) };
let mut expr = quote! { ::style_traits::ToCss::to_css(#first, dest) };
if let Some(condition) = attrs.skip_if {
expr = quote! {
if !#first.#condition() {
#expr
}
}
}
return expr;
}
let mut expr = derive_single_field_expr(first, attrs, where_clause);
@ -148,7 +156,7 @@ fn derive_single_field_expr(
attrs: CssFieldAttrs,
where_clause: &mut WhereClause,
) -> Tokens {
if attrs.iterable {
let mut expr = if attrs.iterable {
if let Some(if_empty) = attrs.if_empty {
return quote! {
{
@ -173,7 +181,17 @@ fn derive_single_field_expr(
where_clause.add_trait_bound(&field.ast().ty);
}
quote! { writer.item(#field)?; }
};
if let Some(condition) = attrs.skip_if {
expr = quote! {
if !#field.#condition() {
#expr
}
}
}
expr
}
#[darling(attributes(css), default)]
@ -203,4 +221,5 @@ struct CssFieldAttrs {
ignore_bound: bool,
iterable: bool,
skip: bool,
skip_if: Option<Ident>,
}