1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use deriving::generic::*;
13 use deriving::generic::ty::*;
15 use syntax::ast::{MetaItem, Expr, Mutability};
16 use syntax::ext::base::{ExtCtxt, Annotatable};
17 use syntax::ext::build::AstBuilder;
21 pub fn expand_deriving_hash(cx: &mut ExtCtxt,
25 push: &mut FnMut(Annotatable))
28 let path = Path::new_(pathvec_std!(cx, core::hash::Hash), None,
31 let typaram = &*deriving::hygienic_type_parameter(item, "__H");
33 let arg = Path::new_local(typaram);
34 let hash_trait_def = TraitDef {
36 attributes: Vec::new(),
38 additional_bounds: Vec::new(),
39 generics: LifetimeBounds::empty(),
44 generics: LifetimeBounds {
45 lifetimes: Vec::new(),
46 bounds: vec![(typaram,
47 vec![path_std!(cx, core::hash::Hasher)])],
49 explicit_self: borrowed_explicit_self(),
50 args: vec!(Ptr(Box::new(Literal(arg)), Borrowed(None, Mutability::Mutable))),
54 unify_fieldless_variants: true,
55 combine_substructure: combine_substructure(Box::new(|a, b, c| {
56 hash_substructure(a, b, c)
60 associated_types: Vec::new(),
63 hash_trait_def.expand(cx, mitem, item, push);
66 fn hash_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
67 let state_expr = match (substr.nonself_args.len(), substr.nonself_args.get(0)) {
68 (1, Some(o_f)) => o_f,
69 _ => cx.span_bug(trait_span, "incorrect number of arguments in `derive(Hash)`")
71 let call_hash = |span, thing_expr| {
73 let strs = cx.std_path(&["hash", "Hash", "hash"]);
75 cx.expr_path(cx.path_global(span, strs))
77 let ref_thing = cx.expr_addr_of(span, thing_expr);
78 let expr = cx.expr_call(span, hash_path, vec!(ref_thing, state_expr.clone()));
81 let mut stmts = Vec::new();
83 let fields = match *substr.fields {
84 Struct(_, ref fs) => fs,
85 EnumMatching(_, _, ref fs) => {
86 let variant_value = deriving::call_intrinsic(cx,
89 vec![cx.expr_self(trait_span)]);
91 stmts.push(call_hash(trait_span, variant_value));
95 _ => cx.span_bug(trait_span, "impossible substructure in `derive(Hash)`")
98 for &FieldInfo { ref self_, span, .. } in fields {
99 stmts.push(call_hash(span, self_.clone()));
102 cx.expr_block(cx.block(trait_span, stmts))