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::*;
17 pub fn expand_deriving_hash(cx: &mut ExtCtxt,
23 let hash_trait_def = TraitDef {
25 attributes: Vec::new(),
26 path: Path::new(vec!("std", "hash", "Hash")),
27 additional_bounds: Vec::new(),
28 generics: LifetimeBounds::empty(),
32 generics: LifetimeBounds::empty(),
33 explicit_self: borrowed_explicit_self(),
34 args: vec!(Ptr(~Literal(Path::new(vec!("std", "hash", "sip", "SipState"))),
35 Borrowed(None, MutMutable))),
38 const_nonmatching: false,
39 combine_substructure: hash_substructure
44 hash_trait_def.expand(cx, mitem, item, push);
47 fn hash_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> @Expr {
48 let state_expr = match substr.nonself_args {
49 [state_expr] => state_expr,
50 _ => cx.span_bug(trait_span, "incorrect number of arguments in `deriving(Hash)`")
52 let hash_ident = substr.method_ident;
53 let call_hash = |span, thing_expr| {
54 let expr = cx.expr_method_call(span, thing_expr, hash_ident, vec!(state_expr));
57 let mut stmts = Vec::new();
59 let fields = match *substr.fields {
61 EnumMatching(index, variant, ref fs) => {
62 // Determine the discriminant. We will feed this value to the byte
63 // iteration function.
64 let discriminant = match variant.node.disr_expr {
66 None => cx.expr_uint(trait_span, index)
69 stmts.push(call_hash(trait_span, discriminant));
73 _ => cx.span_bug(trait_span, "impossible substructure in `deriving(Hash)`")
76 for &FieldInfo { self_, span, .. } in fields.iter() {
77 stmts.push(call_hash(span, self_));
81 cx.span_bug(trait_span, "#[deriving(Hash)] needs at least one field");
84 cx.expr_block(cx.block(trait_span, stmts, None))