rustc_builtin_macros/deriving/cmp/
eq.rs
1use rustc_ast::{self as ast, MetaItem};
2use rustc_data_structures::fx::FxHashSet;
3use rustc_expand::base::{Annotatable, ExtCtxt};
4use rustc_span::{Span, sym};
5use thin_vec::{ThinVec, thin_vec};
6
7use crate::deriving::generic::ty::*;
8use crate::deriving::generic::*;
9use crate::deriving::path_std;
10
11pub(crate) fn expand_deriving_eq(
12 cx: &ExtCtxt<'_>,
13 span: Span,
14 mitem: &MetaItem,
15 item: &Annotatable,
16 push: &mut dyn FnMut(Annotatable),
17 is_const: bool,
18) {
19 let span = cx.with_def_site_ctxt(span);
20
21 let trait_def = TraitDef {
22 span,
23 path: path_std!(cmp::Eq),
24 skip_path_as_bound: false,
25 needs_copy_as_bound_if_packed: true,
26 additional_bounds: Vec::new(),
27 supports_unions: true,
28 methods: vec![MethodDef {
29 name: sym::assert_receiver_is_total_eq,
30 generics: Bounds::empty(),
31 explicit_self: true,
32 nonself_args: vec![],
33 ret_ty: Unit,
34 attributes: thin_vec![
35 cx.attr_word(sym::inline, span),
36 cx.attr_nested_word(sym::doc, sym::hidden, span),
37 cx.attr_nested_word(sym::coverage, sym::off, span)
38 ],
39 fieldless_variants_strategy: FieldlessVariantsStrategy::Unify,
40 combine_substructure: combine_substructure(Box::new(|a, b, c| {
41 cs_total_eq_assert(a, b, c)
42 })),
43 }],
44 associated_types: Vec::new(),
45 is_const,
46 };
47 trait_def.expand_ext(cx, mitem, item, push, true)
48}
49
50fn cs_total_eq_assert(
51 cx: &ExtCtxt<'_>,
52 trait_span: Span,
53 substr: &Substructure<'_>,
54) -> BlockOrExpr {
55 let mut stmts = ThinVec::new();
56 let mut seen_type_names = FxHashSet::default();
57 let mut process_variant = |variant: &ast::VariantData| {
58 for field in variant.fields() {
59 if let Some(name) = field.ty.kind.is_simple_path()
63 && !seen_type_names.insert(name)
64 {
65 } else {
67 super::assert_ty_bounds(
69 cx,
70 &mut stmts,
71 field.ty.clone(),
72 field.span,
73 &[sym::cmp, sym::AssertParamIsEq],
74 );
75 }
76 }
77 };
78
79 match *substr.fields {
80 StaticStruct(vdata, ..) => {
81 process_variant(vdata);
82 }
83 StaticEnum(enum_def, ..) => {
84 for variant in &enum_def.variants {
85 process_variant(&variant.data);
86 }
87 }
88 _ => cx.dcx().span_bug(trait_span, "unexpected substructure in `derive(Eq)`"),
89 }
90 BlockOrExpr::new_stmts(stmts)
91}