1 use crate::deriving::path_std;
2 use crate::deriving::generic::*;
3 use crate::deriving::generic::ty::*;
5 use syntax::ast::{self, Expr, MetaItem, GenericArg};
6 use syntax::ext::base::{Annotatable, ExtCtxt};
7 use syntax::ext::build::AstBuilder;
9 use syntax::symbol::{sym, Symbol};
12 pub fn expand_deriving_eq(cx: &mut ExtCtxt<'_>,
16 push: &mut dyn FnMut(Annotatable)) {
17 let inline = cx.meta_word(span, sym::inline);
18 let hidden = cx.meta_list_item_word(span, sym::hidden);
19 let doc = cx.meta_list(span, sym::doc, vec![hidden]);
20 let attrs = vec![cx.attribute(inline), cx.attribute(doc)];
21 let trait_def = TraitDef {
23 attributes: Vec::new(),
24 path: path_std!(cx, cmp::Eq),
25 additional_bounds: Vec::new(),
26 generics: LifetimeBounds::empty(),
28 supports_unions: true,
29 methods: vec![MethodDef {
30 name: "assert_receiver_is_total_eq",
31 generics: LifetimeBounds::empty(),
32 explicit_self: borrowed_explicit_self(),
37 unify_fieldless_variants: true,
38 combine_substructure: combine_substructure(Box::new(|a, b, c| {
39 cs_total_eq_assert(a, b, c)
42 associated_types: Vec::new(),
44 trait_def.expand_ext(cx, mitem, item, push, true)
47 fn cs_total_eq_assert(cx: &mut ExtCtxt<'_>,
49 substr: &Substructure<'_>)
51 fn assert_ty_bounds(cx: &mut ExtCtxt<'_>, stmts: &mut Vec<ast::Stmt>,
52 ty: P<ast::Ty>, span: Span, helper_name: &str) {
53 // Generate statement `let _: helper_name<ty>;`,
54 // set the expn ID so we can use the unstable struct.
55 let span = span.with_ctxt(cx.backtrace());
56 let assert_path = cx.path_all(span, true,
57 cx.std_path(&[sym::cmp, Symbol::intern(helper_name)]),
58 vec![GenericArg::Type(ty)], vec![]);
59 stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path)));
61 fn process_variant(cx: &mut ExtCtxt<'_>,
62 stmts: &mut Vec<ast::Stmt>,
63 variant: &ast::VariantData) {
64 for field in variant.fields() {
65 // let _: AssertParamIsEq<FieldTy>;
66 assert_ty_bounds(cx, stmts, field.ty.clone(), field.span, "AssertParamIsEq");
70 let mut stmts = Vec::new();
71 match *substr.fields {
72 StaticStruct(vdata, ..) => {
73 process_variant(cx, &mut stmts, vdata);
75 StaticEnum(enum_def, ..) => {
76 for variant in &enum_def.variants {
77 process_variant(cx, &mut stmts, &variant.node.data);
80 _ => cx.span_bug(trait_span, "unexpected substructure in `derive(Eq)`")
82 cx.expr_block(cx.block(trait_span, stmts))