1 use crate::deriving::generic::ty::*;
2 use crate::deriving::generic::*;
3 use crate::deriving::{self, path_std, pathvec_std};
6 use rustc_ast::{Expr, MetaItem, Mutability};
7 use rustc_expand::base::{Annotatable, ExtCtxt};
8 use rustc_span::symbol::sym;
11 pub fn expand_deriving_hash(
16 push: &mut dyn FnMut(Annotatable),
18 let path = Path::new_(pathvec_std!(hash::Hash), vec![], PathKind::Std);
20 let typaram = sym::__H;
22 let arg = Path::new_local(typaram);
23 let hash_trait_def = TraitDef {
25 attributes: Vec::new(),
27 additional_bounds: Vec::new(),
28 generics: Bounds::empty(),
29 supports_unions: false,
30 methods: vec![MethodDef {
32 generics: Bounds { bounds: vec![(typaram, vec![path_std!(hash::Hasher)])] },
34 args: vec![(Ref(Box::new(Literal(arg)), Mutability::Mut), sym::state)],
37 unify_fieldless_variants: true,
38 combine_substructure: combine_substructure(Box::new(|a, b, c| {
39 hash_substructure(a, b, c)
42 associated_types: Vec::new(),
45 hash_trait_def.expand(cx, mitem, item, push);
48 fn hash_substructure(cx: &mut ExtCtxt<'_>, trait_span: Span, substr: &Substructure<'_>) -> P<Expr> {
49 let [state_expr] = substr.nonself_args else {
50 cx.span_bug(trait_span, "incorrect number of arguments in `derive(Hash)`");
52 let call_hash = |span, thing_expr| {
54 let strs = cx.std_path(&[sym::hash, sym::Hash, sym::hash]);
56 cx.expr_path(cx.path_global(span, strs))
58 let ref_thing = cx.expr_addr_of(span, thing_expr);
59 let expr = cx.expr_call(span, hash_path, vec![ref_thing, state_expr.clone()]);
62 let mut stmts = Vec::new();
64 let fields = match substr.fields {
65 Struct(_, fs) | EnumMatching(_, 1, .., fs) => fs,
66 EnumMatching(.., fs) => {
67 let variant_value = deriving::call_intrinsic(
70 sym::discriminant_value,
71 vec![cx.expr_self(trait_span)],
74 stmts.push(call_hash(trait_span, variant_value));
78 _ => cx.span_bug(trait_span, "impossible substructure in `derive(Hash)`"),
82 fields.iter().map(|FieldInfo { ref self_, span, .. }| call_hash(*span, self_.clone())),
85 cx.expr_block(cx.block(trait_span, stmts))