]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_builtin_macros/src/deriving/hash.rs
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / compiler / rustc_builtin_macros / src / deriving / hash.rs
1 use crate::deriving::generic::ty::*;
2 use crate::deriving::generic::*;
3 use crate::deriving::{self, path_std, pathvec_std};
4
5 use rustc_ast::ptr::P;
6 use rustc_ast::{Expr, MetaItem, Mutability};
7 use rustc_expand::base::{Annotatable, ExtCtxt};
8 use rustc_span::symbol::sym;
9 use rustc_span::Span;
10
11 pub fn expand_deriving_hash(
12 cx: &mut ExtCtxt<'_>,
13 span: Span,
14 mitem: &MetaItem,
15 item: &Annotatable,
16 push: &mut dyn FnMut(Annotatable),
17 ) {
18 let path = Path::new_(pathvec_std!(hash::Hash), None, vec![], PathKind::Std);
19
20 let typaram = sym::__H;
21
22 let arg = Path::new_local(typaram);
23 let hash_trait_def = TraitDef {
24 span,
25 attributes: Vec::new(),
26 path,
27 additional_bounds: Vec::new(),
28 generics: Bounds::empty(),
29 is_unsafe: false,
30 supports_unions: false,
31 methods: vec![MethodDef {
32 name: sym::hash,
33 generics: Bounds { bounds: vec![(typaram, vec![path_std!(hash::Hasher)])] },
34 explicit_self: borrowed_explicit_self(),
35 args: vec![(Ptr(Box::new(Literal(arg)), Borrowed(None, Mutability::Mut)), sym::state)],
36 ret_ty: nil_ty(),
37 attributes: vec![],
38 is_unsafe: false,
39 unify_fieldless_variants: true,
40 combine_substructure: combine_substructure(Box::new(|a, b, c| {
41 hash_substructure(a, b, c)
42 })),
43 }],
44 associated_types: Vec::new(),
45 };
46
47 hash_trait_def.expand(cx, mitem, item, push);
48 }
49
50 fn hash_substructure(cx: &mut ExtCtxt<'_>, trait_span: Span, substr: &Substructure<'_>) -> P<Expr> {
51 let state_expr = match &substr.nonself_args {
52 &[o_f] => o_f,
53 _ => cx.span_bug(trait_span, "incorrect number of arguments in `derive(Hash)`"),
54 };
55 let call_hash = |span, thing_expr| {
56 let hash_path = {
57 let strs = cx.std_path(&[sym::hash, sym::Hash, sym::hash]);
58
59 cx.expr_path(cx.path_global(span, strs))
60 };
61 let ref_thing = cx.expr_addr_of(span, thing_expr);
62 let expr = cx.expr_call(span, hash_path, vec![ref_thing, state_expr.clone()]);
63 cx.stmt_expr(expr)
64 };
65 let mut stmts = Vec::new();
66
67 let fields = match *substr.fields {
68 Struct(_, ref fs) | EnumMatching(_, 1, .., ref fs) => fs,
69 EnumMatching(.., ref fs) => {
70 let variant_value = deriving::call_intrinsic(
71 cx,
72 trait_span,
73 sym::discriminant_value,
74 vec![cx.expr_self(trait_span)],
75 );
76
77 stmts.push(call_hash(trait_span, variant_value));
78
79 fs
80 }
81 _ => cx.span_bug(trait_span, "impossible substructure in `derive(Hash)`"),
82 };
83
84 stmts.extend(
85 fields.iter().map(|FieldInfo { ref self_, span, .. }| call_hash(*span, self_.clone())),
86 );
87
88 cx.expr_block(cx.block(trait_span, stmts))
89 }