1 use crate::deriving::generic::ty::*;
2 use crate::deriving::generic::*;
3 use crate::deriving::{self, path_std, pathvec_std};
5 use rustc_ast::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!(cx, hash::Hash), None, vec![], PathKind::Std);
22 let arg = Path::new_local(typaram);
23 let hash_trait_def = TraitDef {
25 attributes: Vec::new(),
27 additional_bounds: Vec::new(),
28 generics: LifetimeBounds::empty(),
30 supports_unions: false,
31 methods: vec![MethodDef {
33 generics: LifetimeBounds {
34 lifetimes: Vec::new(),
35 bounds: vec![(typaram, vec![path_std!(cx, hash::Hasher)])],
37 explicit_self: borrowed_explicit_self(),
38 args: vec![(Ptr(Box::new(Literal(arg)), Borrowed(None, Mutability::Mut)), "state")],
42 unify_fieldless_variants: true,
43 combine_substructure: combine_substructure(Box::new(|a, b, c| {
44 hash_substructure(a, b, c)
47 associated_types: Vec::new(),
50 hash_trait_def.expand(cx, mitem, item, push);
53 fn hash_substructure(cx: &mut ExtCtxt<'_>, trait_span: Span, substr: &Substructure<'_>) -> P<Expr> {
54 let state_expr = match &substr.nonself_args {
56 _ => cx.span_bug(trait_span, "incorrect number of arguments in `derive(Hash)`"),
58 let call_hash = |span, thing_expr| {
60 let strs = cx.std_path(&[sym::hash, sym::Hash, sym::hash]);
62 cx.expr_path(cx.path_global(span, strs))
64 let ref_thing = cx.expr_addr_of(span, thing_expr);
65 let expr = cx.expr_call(span, hash_path, vec![ref_thing, state_expr.clone()]);
68 let mut stmts = Vec::new();
70 let fields = match *substr.fields {
71 Struct(_, ref fs) | EnumMatching(_, 1, .., ref fs) => fs,
72 EnumMatching(.., ref fs) => {
73 let variant_value = deriving::call_intrinsic(
77 vec![cx.expr_self(trait_span)],
80 stmts.push(call_hash(trait_span, variant_value));
84 _ => cx.span_bug(trait_span, "impossible substructure in `derive(Hash)`"),
88 fields.iter().map(|FieldInfo { ref self_, span, .. }| call_hash(*span, self_.clone())),
91 cx.expr_block(cx.block(trait_span, stmts))