Skip to content

Commit

Permalink
derive: Skip PartialEq::ne for any zero-field enum or struct
Browse files Browse the repository at this point in the history
Also detect unit structs and enums with zero field struct variants.
  • Loading branch information
bluss committed Feb 29, 2016
1 parent 190af51 commit 57e0a7e
Showing 1 changed file with 15 additions and 17 deletions.
32 changes: 15 additions & 17 deletions src/libsyntax_ext/deriving/cmp/partial_eq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,30 +11,26 @@
use deriving::generic::*;
use deriving::generic::ty::*;

use syntax::ast::{MetaItem, Expr, BinOpKind, ItemKind, VariantData};
use syntax::ast::{MetaItem, Expr, BinOpKind, ItemKind};
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax::parse::token::InternedString;
use syntax::ptr::P;

fn is_clike_enum(item: &Annotatable) -> bool {
match *item {
Annotatable::Item(ref item) => {
match item.node {
ItemKind::Enum(ref enum_def, _) => {
enum_def.variants.iter().all(|v|
if let VariantData::Unit(..) = v.node.data {
true
} else {
false
}
)
}
_ => false,
fn is_type_without_fields(item: &Annotatable) -> bool {
if let Annotatable::Item(ref item) = *item {
match item.node {
ItemKind::Enum(ref enum_def, _) => {
enum_def.variants.iter().all(|v| v.node.data.fields().is_empty())
}
ItemKind::Struct(ref variant_data, _) => {
variant_data.fields().is_empty()
}
_ => false
}
_ => false,
} else {
false
}
}

Expand Down Expand Up @@ -101,8 +97,10 @@ pub fn expand_deriving_partial_eq(cx: &mut ExtCtxt,
}

// avoid defining `ne` if we can
// c-like enums, enums without any fields and structs without fields
// can safely define only `eq`.
let mut methods = vec![md!("eq", cs_eq)];
if !is_clike_enum(item) {
if !is_type_without_fields(item) {
methods.push(md!("ne", cs_ne));
}

Expand Down

0 comments on commit 57e0a7e

Please sign in to comment.