1 // Copyright 2013 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.
4 //
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.
10
11 use ast::{MetaItem, Item, Expr};
12 use codemap::Span;
13 use ext::base::ExtCtxt;
14 use ext::build::AstBuilder;
15 use ext::deriving::generic::*;
16 use parse::token::InternedString;
17
18 pub fn expand_deriving_eq(cx: &mut ExtCtxt,
19 span: Span,
20 mitem: @MetaItem,
21 item: @Item,
22 push: |@Item|) {
23 // structures are equal if all fields are equal, and non equal, if
24 // any fields are not equal or if the enum variants are different
25 fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
26 cs_and(|cx, span, _, _| cx.expr_bool(span, false),
27 cx, span, substr)
28 }
29 fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
30 cs_or(|cx, span, _, _| cx.expr_bool(span, true),
31 cx, span, substr)
32 }
33
34 macro_rules! md (
35 ($name:expr, $f:ident) => { {
36 let inline = cx.meta_word(span, InternedString::new("inline"));
37 let attrs = vec!(cx.attribute(span, inline));
38 MethodDef {
39 name: $name,
40 generics: LifetimeBounds::empty(),
41 explicit_self: borrowed_explicit_self(),
42 args: vec!(borrowed_self()),
43 ret_ty: Literal(Path::new(vec!("bool"))),
44 attributes: attrs,
45 const_nonmatching: true,
46 combine_substructure: combine_substructure(|a, b, c| {
47 $f(a, b, c)
48 })
49 }
50 } }
51 );
52
53 let trait_def = TraitDef {
54 span: span,
55 attributes: Vec::new(),
56 path: Path::new(vec!("std", "cmp", "Eq")),
57 additional_bounds: Vec::new(),
58 generics: LifetimeBounds::empty(),
59 methods: vec!(
60 md!("eq", cs_eq),
61 md!("ne", cs_ne)
62 )
63 };
64 trait_def.expand(cx, mitem, item, push)
65 }