1 use crate::deriving::generic::ty::*;
2 use crate::deriving::generic::*;
3 use crate::deriving::{path_std, pathvec_std};
5 use rustc_ast::{AttrVec, MetaItem, Mutability};
6 use rustc_expand::base::{Annotatable, ExtCtxt};
7 use rustc_span::symbol::sym;
10 pub fn expand_deriving_hash(
15 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 {
26 skip_path_as_bound: false,
27 needs_copy_as_bound_if_packed: true,
28 additional_bounds: Vec::new(),
29 supports_unions: false,
30 methods: vec![MethodDef {
32 generics: Bounds { bounds: vec![(typaram, vec![path_std!(hash::Hasher)])] },
34 nonself_args: vec![(Ref(Box::new(Path(arg)), Mutability::Mut), sym::state)],
36 attributes: AttrVec::new(),
37 fieldless_variants_strategy: FieldlessVariantsStrategy::Unify,
38 combine_substructure: combine_substructure(Box::new(|a, b, c| {
39 hash_substructure(a, b, c)
42 associated_types: Vec::new(),
46 hash_trait_def.expand(cx, mitem, item, push);
52 substr: &Substructure<'_>,
54 let [state_expr] = substr.nonselflike_args else {
55 cx.span_bug(trait_span, "incorrect number of arguments in `derive(Hash)`");
57 let call_hash = |span, expr| {
59 let strs = cx.std_path(&[sym::hash, sym::Hash, sym::hash]);
61 cx.expr_path(cx.path_global(span, strs))
63 let expr = cx.expr_call(span, hash_path, vec![expr, state_expr.clone()]);
67 let (stmts, match_expr) = match substr.fields {
68 Struct(_, fields) | EnumMatching(.., fields) => {
70 fields.iter().map(|field| call_hash(field.span, field.self_expr.clone())).collect();
73 EnumTag(tag_field, match_expr) => {
74 assert!(tag_field.other_selflike_exprs.is_empty());
75 let stmts = vec![call_hash(tag_field.span, tag_field.self_expr.clone())];
76 (stmts, match_expr.clone())
78 _ => cx.span_bug(trait_span, "impossible substructure in `derive(Hash)`"),
81 BlockOrExpr::new_mixed(stmts, match_expr)