Skip to main content

rustc_builtin_macros/deriving/
hash.rs

1use rustc_ast::Mutability;
2use rustc_expand::base::ExtCtxt;
3use rustc_span::{Ident, Span, kw, sym};
4use thin_vec::{ThinVec, thin_vec};
5
6use crate::deriving::generic::*;
7use crate::deriving::{call_discriminant_value, path_std};
8
9pub(crate) fn expand_deriving_hash(
10    cx: &ExtCtxt<'_>,
11    span: Span,
12    item: &ast::Item,
13    push: &mut dyn FnMut(Box<ast::Item>),
14    is_const: bool,
15) {
16    let path = cx.std_path(span, { &[sym::hash, sym::Hash] })path_std!(cx, span, hash::Hash);
17
18    let arg = cx.ty_name(span, sym::__H);
19
20    let param = {
21        let path = cx.std_path(span, { &[sym::hash, sym::Hasher] })path_std!(cx, span, hash::Hasher);
22        cx.typaram(Ident::new(sym::__H, span), {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(cx.trait_bound(path, false));
    vec
}thin_vec![cx.trait_bound(path, false)], None)
23    };
24
25    let generics = ast::Generics {
26        params: {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(param);
    vec
}thin_vec![param],
27        where_clause: ast::WhereClause { has_where_token: false, predicates: ThinVec::new(), span },
28        span,
29    };
30
31    let hash_trait_def = TraitDef {
32        span,
33        path,
34        needs_copy_as_bound_if_packed: true,
35        additional_bounds: SmallVec::new(),
36        supports_unions: false,
37        methods: {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(MethodDef {
                name: sym::hash,
                generics,
                explicit_self: true,
                nonself_args: {
                    let count = 0usize + 1usize;
                    let mut vec = ::smallvec::SmallVec::new();
                    if count <= vec.inline_size() {
                        vec.push((cx.ty_ref(span, arg, None, 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(),
                                    [(cx.ty_ref(span, arg, None, Mutability::Mut),
                                                sym::state)])))
                    }
                },
                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
                },
                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,
                                explicit_self: true,
                                nonself_args: {
                                    let count = 0usize + 1usize;
                                    let mut vec = ::smallvec::SmallVec::new();
                                    if count <= vec.inline_size() {
                                        vec.push((cx.ty_ref(span, arg, None, 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(),
                                                    [(cx.ty_ref(span, arg, None, Mutability::Mut),
                                                                sym::state)])))
                                    }
                                },
                                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
                                },
                                fieldless_variants_strategy: FieldlessVariantsStrategy::Unify,
                                combine_substructure: combine_substructure(hash_substructure),
                            }])))
    }
}smallvec![MethodDef {
38            name: sym::hash,
39            generics,
40            explicit_self: true,
41            nonself_args: smallvec![(cx.ty_ref(span, arg, None, Mutability::Mut), sym::state)],
42            has_other_selflike_arg: false,
43            ret_ty: cx.ty_unit(span),
44            attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)],
45            fieldless_variants_strategy: FieldlessVariantsStrategy::Unify,
46            combine_substructure: combine_substructure(hash_substructure),
47        }],
48        is_const,
49        ..
50    };
51
52    hash_trait_def.expand(cx, item, push);
53}
54
55fn hash_substructure(cx: &ExtCtxt<'_>, span: Span, substr: Substructure<'_>) -> BlockOrExpr {
56    let call_hash = |span, expr| {
57        let strs = cx.std_path(span, &[sym::hash, sym::Hash, sym::hash]);
58        let hash_path = cx.expr_path(strs);
59        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(cx.expr_name(span, sym::state));
    vec
}thin_vec![expr, cx.expr_name(span, sym::state)]);
60        cx.stmt_expr(expr)
61    };
62
63    let (stmts, match_expr) = match substr {
64        Struct(_, fields) | EnumMatching(.., fields) => {
65            let stmts =
66                fields.into_iter().map(|field| call_hash(field.span, field.self_expr)).collect();
67            (stmts, None)
68        }
69        EnumDiscr(match_expr) => {
70            let stmts = {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(call_hash(span,
            cx.expr_addr_of(span,
                call_discriminant_value(cx, span, kw::SelfLower))));
    vec
}thin_vec![call_hash(
71                span,
72                cx.expr_addr_of(span, call_discriminant_value(cx, span, kw::SelfLower))
73            )];
74            (stmts, match_expr)
75        }
76        _ => cx.dcx().span_bug(span, "unexpected substructure in `derive(Hash)`"),
77    };
78
79    BlockOrExpr::new_mixed(stmts, match_expr)
80}