Skip to main content

rustc_builtin_macros/deriving/
hash.rs

1use rustc_ast::{MetaItem, Mutability, Safety};
2use rustc_expand::base::{Annotatable, ExtCtxt};
3use rustc_span::{Span, sym};
4use thin_vec::thin_vec;
5
6use crate::deriving::generic::ty::*;
7use crate::deriving::generic::*;
8use crate::deriving::path_std;
9
10pub(crate) fn expand_deriving_hash(
11    cx: &ExtCtxt<'_>,
12    span: Span,
13    mitem: &MetaItem,
14    item: &Annotatable,
15    push: &mut dyn FnMut(Annotatable),
16    is_const: bool,
17) {
18    let path = generic::ty::Path::new({
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [sym::hash, sym::Hash]))
    })path_std!(hash::Hash);
19
20    let typaram = sym::__H;
21
22    let arg = Path::new_local(typaram);
23    let hash_trait_def = TraitDef {
24        span,
25        path,
26        skip_path_as_bound: false,
27        needs_copy_as_bound_if_packed: true,
28        additional_bounds: SmallVec::new(),
29        supports_unions: false,
30        methods: {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(MethodDef {
                name: sym::hash,
                generics: Bounds {
                    bounds: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                            [(typaram,
                                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [generic::ty::Path::new({
                                                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                                        [sym::hash, sym::Hasher]))
                                                            })])))])),
                },
                explicit_self: true,
                nonself_args: {
                    let count = 0usize + 1usize;
                    let mut vec = ::smallvec::SmallVec::new();
                    if count <= vec.inline_size() {
                        vec.push((Ref(Box::new(Path(arg)), Mutability::Mut),
                                sym::state));
                        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(),
                                    [(Ref(Box::new(Path(arg)), Mutability::Mut), sym::state)])))
                    }
                },
                ret_ty: Unit,
                attributes: {
                    let len = [()].len();
                    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                    vec.push(cx.attr_word(sym::inline, span));
                    vec
                },
                fieldless_variants_strategy: FieldlessVariantsStrategy::Unify,
                combine_substructure: combine_substructure(hash_substructure),
            });
        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::hash,
                                generics: Bounds {
                                    bounds: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                            [(typaram,
                                                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                                [generic::ty::Path::new({
                                                                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                                                        [sym::hash, sym::Hasher]))
                                                                            })])))])),
                                },
                                explicit_self: true,
                                nonself_args: {
                                    let count = 0usize + 1usize;
                                    let mut vec = ::smallvec::SmallVec::new();
                                    if count <= vec.inline_size() {
                                        vec.push((Ref(Box::new(Path(arg)), Mutability::Mut),
                                                sym::state));
                                        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(),
                                                    [(Ref(Box::new(Path(arg)), Mutability::Mut), sym::state)])))
                                    }
                                },
                                ret_ty: Unit,
                                attributes: {
                                    let len = [()].len();
                                    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                                    vec.push(cx.attr_word(sym::inline, span));
                                    vec
                                },
                                fieldless_variants_strategy: FieldlessVariantsStrategy::Unify,
                                combine_substructure: combine_substructure(hash_substructure),
                            }])))
    }
}smallvec![MethodDef {
31            name: sym::hash,
32            generics: Bounds { bounds: vec![(typaram, vec![path_std!(hash::Hasher)])] },
33            explicit_self: true,
34            nonself_args: smallvec![(Ref(Box::new(Path(arg)), Mutability::Mut), sym::state)],
35            ret_ty: Unit,
36            attributes: thin_vec![cx.attr_word(sym::inline, span)],
37            fieldless_variants_strategy: FieldlessVariantsStrategy::Unify,
38            combine_substructure: combine_substructure(hash_substructure),
39        }],
40        associated_types: SmallVec::new(),
41        is_const,
42        safety: Safety::Default,
43        document: true,
44    };
45
46    hash_trait_def.expand(cx, mitem, item, push);
47}
48
49fn hash_substructure(cx: &ExtCtxt<'_>, trait_span: Span, substr: &Substructure<'_>) -> BlockOrExpr {
50    let [state_expr] = substr.nonselflike_args else {
51        cx.dcx().span_bug(trait_span, "incorrect number of arguments in `derive(Hash)`");
52    };
53    let call_hash = |span, expr| {
54        let strs = cx.std_path(&[sym::hash, sym::Hash, sym::hash]);
55        let hash_path = cx.expr_path(cx.path_global(span, strs));
56        let expr = cx.expr_call(span, hash_path, {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(expr);
    vec.push(state_expr.clone());
    vec
}thin_vec![expr, state_expr.clone()]);
57        cx.stmt_expr(expr)
58    };
59
60    let (stmts, match_expr) = match substr.fields {
61        Struct(_, fields) | EnumMatching(.., fields) => {
62            let stmts =
63                fields.iter().map(|field| call_hash(field.span, field.self_expr.clone())).collect();
64            (stmts, None)
65        }
66        EnumDiscr(discr_field, match_expr) => {
67            if !discr_field.other_selflike_exprs.is_empty() {
    ::core::panicking::panic("assertion failed: discr_field.other_selflike_exprs.is_empty()")
};assert!(discr_field.other_selflike_exprs.is_empty());
68            let stmts = {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(call_hash(discr_field.span, discr_field.self_expr.clone()));
    vec
}thin_vec![call_hash(discr_field.span, discr_field.self_expr.clone())];
69            (stmts, match_expr.clone())
70        }
71        _ => cx.dcx().span_bug(trait_span, "impossible substructure in `derive(Hash)`"),
72    };
73
74    BlockOrExpr::new_mixed(stmts, match_expr)
75}