Skip to main content

rustc_builtin_macros/deriving/
eq.rs

1use rustc_ast::{self as ast};
2use rustc_data_structures::fx::FxHashSet;
3use rustc_expand::base::ExtCtxt;
4use rustc_span::{Span, sym};
5use thin_vec::{ThinVec, thin_vec};
6
7use crate::deriving::generic::*;
8use crate::deriving::path_std;
9
10pub(crate) fn expand_deriving_eq(
11    cx: &ExtCtxt<'_>,
12    span: Span,
13    item: &ast::Item,
14    push: &mut dyn FnMut(Box<ast::Item>),
15    is_const: bool,
16) {
17    let span = cx.with_def_site_ctxt(span);
18
19    let trait_def = TraitDef {
20        span,
21        path: cx.std_path(span, { &[sym::cmp, sym::Eq] })path_std!(cx, span, cmp::Eq),
22        needs_copy_as_bound_if_packed: true,
23        additional_bounds: SmallVec::new(),
24        supports_unions: true,
25        methods: {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(MethodDef {
                name: sym::assert_fields_are_eq,
                generics: cx.empty_generics(span),
                explicit_self: true,
                nonself_args: ::smallvec::SmallVec::new(),
                has_other_selflike_arg: false,
                ret_ty: cx.ty_unit(span),
                attributes: {
                    let len = [(), (), ()].len();
                    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                    vec.push(cx.generated_attr(span,
                            ast::GeneratedAttr::Inline));
                    vec.push(cx.generated_attr(span,
                            ast::GeneratedAttr::DocHidden));
                    vec.push(cx.generated_attr(span,
                            ast::GeneratedAttr::CoverageOff));
                    vec
                },
                fieldless_variants_strategy: FieldlessVariantsStrategy::Unify,
                combine_substructure: combine_substructure(cs_total_eq_assert),
            });
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [MethodDef {
                                name: sym::assert_fields_are_eq,
                                generics: cx.empty_generics(span),
                                explicit_self: true,
                                nonself_args: ::smallvec::SmallVec::new(),
                                has_other_selflike_arg: false,
                                ret_ty: cx.ty_unit(span),
                                attributes: {
                                    let len = [(), (), ()].len();
                                    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                                    vec.push(cx.generated_attr(span,
                                            ast::GeneratedAttr::Inline));
                                    vec.push(cx.generated_attr(span,
                                            ast::GeneratedAttr::DocHidden));
                                    vec.push(cx.generated_attr(span,
                                            ast::GeneratedAttr::CoverageOff));
                                    vec
                                },
                                fieldless_variants_strategy: FieldlessVariantsStrategy::Unify,
                                combine_substructure: combine_substructure(cs_total_eq_assert),
                            }])))
    }
}smallvec![MethodDef {
26            name: sym::assert_fields_are_eq,
27            generics: cx.empty_generics(span),
28            explicit_self: true,
29            nonself_args: smallvec![],
30            has_other_selflike_arg: false,
31            ret_ty: cx.ty_unit(span),
32            attributes: thin_vec![
33                // This method will never be called, so doing codegen etc. for it is unnecessary.
34                // We prevent this by adding `#[inline]`, which improves compile-time.
35                cx.generated_attr(span, ast::GeneratedAttr::Inline),
36                cx.generated_attr(span, ast::GeneratedAttr::DocHidden),
37                cx.generated_attr(span, ast::GeneratedAttr::CoverageOff),
38            ],
39            fieldless_variants_strategy: FieldlessVariantsStrategy::Unify,
40            combine_substructure: combine_substructure(cs_total_eq_assert),
41        }],
42        is_const,
43        ..
44    };
45    trait_def.expand_ext(cx, item, push, true)
46}
47
48fn cs_total_eq_assert(cx: &ExtCtxt<'_>, trait_span: Span, substr: Substructure<'_>) -> BlockOrExpr {
49    let mut stmts = ThinVec::new();
50    let mut seen_type_names = FxHashSet::default();
51    let mut process_variant = |variant: &ast::VariantData| {
52        for field in variant.fields() {
53            // This basic redundancy checking only prevents duplication of
54            // assertions like `AssertParamIsEq<Foo>` where the type is a
55            // simple name. That's enough to get a lot of cases, though.
56            if let Some(name) = field.ty.kind.is_simple_path()
57                && !seen_type_names.insert(name)
58            {
59                // Already produced an assertion for this type.
60            } else {
61                // let _: AssertParamIsEq<FieldTy>;
62                super::assert_ty_bounds(
63                    cx,
64                    &mut stmts,
65                    field.ty.clone(),
66                    field.span,
67                    &[sym::cmp, sym::AssertParamIsEq],
68                );
69            }
70        }
71    };
72
73    match substr {
74        StaticStruct(vdata, ..) => {
75            process_variant(vdata);
76        }
77        StaticEnum(enum_def, ..) => {
78            for variant in &enum_def.variants {
79                process_variant(&variant.data);
80            }
81        }
82        _ => cx.dcx().span_bug(trait_span, "unexpected substructure in `derive(Eq)`"),
83    }
84    BlockOrExpr::new_stmts(stmts)
85}