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};
8 use syntax::symbol::{sym, Symbol};
11 pub fn expand_deriving_eq(cx: &mut ExtCtxt<'_>,
15 push: &mut dyn FnMut(Annotatable)) {
16 let inline = cx.meta_word(span, sym::inline);
17 let hidden = cx.meta_list_item_word(span, sym::hidden);
18 let doc = cx.meta_list(span, sym::doc, vec![hidden]);
19 let attrs = vec![cx.attribute(inline), cx.attribute(doc)];
20 let trait_def = TraitDef {
22 attributes: Vec::new(),
23 path: path_std!(cx, cmp::Eq),
24 additional_bounds: Vec::new(),
25 generics: LifetimeBounds::empty(),
27 supports_unions: true,
28 methods: vec![MethodDef {
29 name: "assert_receiver_is_total_eq",
30 generics: LifetimeBounds::empty(),
31 explicit_self: borrowed_explicit_self(),
36 unify_fieldless_variants: true,
37 combine_substructure: combine_substructure(Box::new(|a, b, c| {
38 cs_total_eq_assert(a, b, c)
41 associated_types: Vec::new(),
43 trait_def.expand_ext(cx, mitem, item, push, true)
46 fn cs_total_eq_assert(cx: &mut ExtCtxt<'_>,
48 substr: &Substructure<'_>)
50 fn assert_ty_bounds(cx: &mut ExtCtxt<'_>, stmts: &mut Vec<ast::Stmt>,
51 ty: P<ast::Ty>, span: Span, helper_name: &str) {
52 // Generate statement `let _: helper_name<ty>;`,
53 // set the expn ID so we can use the unstable struct.
54 let span = span.with_ctxt(cx.backtrace());
55 let assert_path = cx.path_all(span, true,
56 cx.std_path(&[sym::cmp, Symbol::intern(helper_name)]),
57 vec![GenericArg::Type(ty)], vec![]);
58 stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path)));
60 fn process_variant(cx: &mut ExtCtxt<'_>,
61 stmts: &mut Vec<ast::Stmt>,
62 variant: &ast::VariantData) {
63 for field in variant.fields() {
64 // let _: AssertParamIsEq<FieldTy>;
65 assert_ty_bounds(cx, stmts, field.ty.clone(), field.span, "AssertParamIsEq");
69 let mut stmts = Vec::new();
70 match *substr.fields {
71 StaticStruct(vdata, ..) => {
72 process_variant(cx, &mut stmts, vdata);
74 StaticEnum(enum_def, ..) => {
75 for variant in &enum_def.variants {
76 process_variant(cx, &mut stmts, &variant.node.data);
79 _ => cx.span_bug(trait_span, "unexpected substructure in `derive(Eq)`")
81 cx.expr_block(cx.block(trait_span, stmts))