1 // Copyright 2012-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.
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};
13 use ext::base::ExtCtxt;
14 use ext::build::AstBuilder;
15 use ext::deriving::generic::*;
16 use parse::token::InternedString;
18 pub fn expand_deriving_zero(cx: &mut ExtCtxt,
23 let inline = cx.meta_word(span, InternedString::new("inline"));
24 let attrs = vec!(cx.attribute(span, inline));
25 let trait_def = TraitDef {
27 attributes: Vec::new(),
28 path: Path::new(vec!("std", "num", "Zero")),
29 additional_bounds: Vec::new(),
30 generics: LifetimeBounds::empty(),
34 generics: LifetimeBounds::empty(),
38 attributes: attrs.clone(),
39 const_nonmatching: false,
40 combine_substructure: combine_substructure(|a, b, c| {
41 zero_substructure(a, b, c)
46 generics: LifetimeBounds::empty(),
47 explicit_self: borrowed_explicit_self(),
49 ret_ty: Literal(Path::new(vec!("bool"))),
51 const_nonmatching: false,
52 combine_substructure: combine_substructure(|cx, span, substr| {
53 cs_and(|cx, span, _, _| cx.span_bug(span,
62 trait_def.expand(cx, mitem, item, push)
65 fn zero_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> @Expr {
66 let zero_ident = vec!(
72 let zero_call = |span| cx.expr_call_global(span, zero_ident.clone(), Vec::new());
74 return match *substr.fields {
75 StaticStruct(_, ref summary) => {
77 Unnamed(ref fields) => {
78 if fields.is_empty() {
79 cx.expr_ident(trait_span, substr.type_ident)
81 let exprs = fields.iter().map(|sp| zero_call(*sp)).collect();
82 cx.expr_call_ident(trait_span, substr.type_ident, exprs)
85 Named(ref fields) => {
86 let zero_fields = fields.iter().map(|&(ident, span)| {
87 cx.field_imm(span, ident, zero_call(span))
89 cx.expr_struct_ident(trait_span, substr.type_ident, zero_fields)
94 cx.span_err(trait_span, "`Zero` cannot be derived for enums, only structs");
95 // let compilation continue
96 cx.expr_uint(trait_span, 0)
98 _ => cx.bug("Non-static method in `deriving(Zero)`")