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.
11 use ast::{MetaItem, Item, Expr, MutMutable};
13 use ext::base::ExtCtxt;
14 use ext::build::AstBuilder;
15 use ext::deriving::generic::*;
16 use ext::deriving::generic::ty::*;
17 use parse::token::InternedString;
20 pub fn expand_deriving_hash<F>(cx: &mut ExtCtxt,
28 let (path, generics, args) = if cx.ecfg.deriving_hash_type_parameter {
29 (Path::new_(vec!("std", "hash", "Hash"), None,
30 vec!(box Literal(Path::new_local("__S"))), true),
32 lifetimes: Vec::new(),
34 vec!(Path::new(vec!("std", "hash", "Writer"))))),
36 Path::new_local("__S"))
38 (Path::new(vec!("std", "hash", "Hash")),
39 LifetimeBounds::empty(),
40 Path::new(vec!("std", "hash", "sip", "SipState")))
42 let inline = cx.meta_word(span, InternedString::new("inline"));
43 let attrs = vec!(cx.attribute(span, inline));
44 let hash_trait_def = TraitDef {
46 attributes: Vec::new(),
48 additional_bounds: Vec::new(),
53 generics: LifetimeBounds::empty(),
54 explicit_self: borrowed_explicit_self(),
55 args: vec!(Ptr(box Literal(args), Borrowed(None, MutMutable))),
58 combine_substructure: combine_substructure(|a, b, c| {
59 hash_substructure(a, b, c)
65 hash_trait_def.expand(cx, mitem, item, push);
68 fn hash_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
69 let state_expr = match substr.nonself_args {
70 [ref state_expr] => state_expr,
71 _ => cx.span_bug(trait_span, "incorrect number of arguments in `deriving(Hash)`")
73 let hash_ident = substr.method_ident;
74 let call_hash = |&: span, thing_expr| {
75 let expr = cx.expr_method_call(span, thing_expr, hash_ident, vec!(state_expr.clone()));
78 let mut stmts = Vec::new();
80 let fields = match *substr.fields {
82 EnumMatching(index, variant, ref fs) => {
83 // Determine the discriminant. We will feed this value to the byte
84 // iteration function.
85 let discriminant = match variant.node.disr_expr {
86 Some(ref d) => d.clone(),
87 None => cx.expr_uint(trait_span, index)
90 stmts.push(call_hash(trait_span, discriminant));
94 _ => cx.span_bug(trait_span, "impossible substructure in `deriving(Hash)`")
97 for &FieldInfo { ref self_, span, .. } in fields.iter() {
98 stmts.push(call_hash(span, self_.clone()));
101 if stmts.len() == 0 {
102 cx.span_bug(trait_span, "#[deriving(Hash)] needs at least one field");
105 cx.expr_block(cx.block(trait_span, stmts, None))