Skip to content

Commit

Permalink
Simplify code generated for simple enumerations
Browse files Browse the repository at this point in the history
  • Loading branch information
mcarton committed Mar 25, 2020
1 parent 842be23 commit 486045f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
15 changes: 15 additions & 0 deletions src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ impl<'a> Input<'a> {
span: item.span(),
})
}

/// Checks whether this type is an enum with only unit variants.
pub fn is_trivial_enum(&self) -> bool {
match &self.body {
Body::Enum(e) => e.iter().all(|v| v.is_unit()),
Body::Struct(..) => false,
}
}
}

impl<'a> Body<'a> {
Expand All @@ -78,6 +86,13 @@ impl<'a> Body<'a> {
}
}

impl<'a> Variant<'a> {
/// Checks whether this variant is a unit variant.
pub fn is_unit(&self) -> bool {
self.fields.is_empty()
}
}

fn enum_from_ast<'a>(
variants: &'a syn::punctuated::Punctuated<syn::Variant, syn::token::Comma>,
) -> Result<Vec<Variant<'a>>, String> {
Expand Down
16 changes: 12 additions & 4 deletions src/cmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,22 @@ pub fn derive_partial_eq(input: &ast::Input) -> Result<proc_macro2::TokenStream,
);
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

let match_fields = if input.is_trivial_enum() {
quote!(true)
} else {
quote! {
match (&*self, &*other) {
#body
_ => unreachable!(),
}
}
};

Ok(quote! {
#[allow(unused_qualifications)]
impl #impl_generics #partial_eq_trait_path for #name #ty_generics #where_clause {
fn eq(&self, other: &Self) -> bool {
#discriminant_cmp && match (&*self, &*other) {
#body
_ => unreachable!(),
}
#discriminant_cmp && #match_fields
}
}
})
Expand Down

0 comments on commit 486045f

Please sign in to comment.