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_derive_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,
                args: {
                    let len = [(), ()].len();
                    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                    vec.push(cx.param_self_ref(span));
                    vec.push(cx.param(span, sym::state,
                            cx.ty_ref(span, arg, None, Mutability::Mut)));
                    vec
                },
                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
                },
                body: MethodBody::SubstructureFunc {
                    body_func: Box::new(hash_body),
                    strategy: FieldlessVariantsStrategy::Unify,
                    has_other_selflike_arg: false,
                },
            });
        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,
                                args: {
                                    let len = [(), ()].len();
                                    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                                    vec.push(cx.param_self_ref(span));
                                    vec.push(cx.param(span, sym::state,
                                            cx.ty_ref(span, arg, None, Mutability::Mut)));
                                    vec
                                },
                                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
                                },
                                body: MethodBody::SubstructureFunc {
                                    body_func: Box::new(hash_body),
                                    strategy: FieldlessVariantsStrategy::Unify,
                                    has_other_selflike_arg: false,
                                },
                            }])))
    }
}smallvec![MethodDef {
38            name: sym::hash,
39            generics,
40            args: thin_vec![
41                cx.param_self_ref(span),
42                cx.param(span, sym::state, cx.ty_ref(span, arg, None, Mutability::Mut))
43            ],
44            ret_ty: cx.ty_unit(span),
45            attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)],
46            body: MethodBody::SubstructureFunc {
47                body_func: Box::new(hash_body),
48                strategy: FieldlessVariantsStrategy::Unify,
49                has_other_selflike_arg: false,
50            },
51        }],
52        is_const,
53        ..
54    };
55
56    hash_trait_def.expand(cx, item, push);
57}
58
59fn hash_body(cx: &ExtCtxt<'_>, span: Span, substr: Substructure<'_>) -> BlockOrExpr {
60    let call_hash = |span, expr| {
61        let path = cx.expr_path(cx.std_path(span, &[sym::hash, sym::Hash, sym::hash]));
62        let expr = cx.expr_call(span, 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)]);
63        cx.stmt_expr(expr)
64    };
65
66    match substr {
67        Struct(_, fields) | EnumMatching(.., fields) => {
68            let stmts =
69                fields.into_iter().map(|field| call_hash(field.span, field.self_expr)).collect();
70            BlockOrExpr::new_stmts(stmts)
71        }
72        EnumDiscr(match_expr) => {
73            let stmts = {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(call_hash(span,
            cx.expr_ref(span,
                call_discriminant_value(cx, span, kw::SelfLower))));
    vec
}thin_vec![call_hash(
74                span,
75                cx.expr_ref(span, call_discriminant_value(cx, span, kw::SelfLower))
76            )];
77            BlockOrExpr::new_mixed(stmts, match_expr)
78        }
79    }
80}