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 ext::deriving::generic::ty::*;
17 use parse::token::InternedString;
20 pub fn expand_deriving_zero<F>(cx: &mut ExtCtxt,
27 let inline = cx.meta_word(span, InternedString::new("inline"));
28 let attrs = vec!(cx.attribute(span, inline));
29 let trait_def = TraitDef {
31 attributes: Vec::new(),
32 path: Path::new(vec!("std", "num", "Zero")),
33 additional_bounds: Vec::new(),
34 generics: LifetimeBounds::empty(),
38 generics: LifetimeBounds::empty(),
42 attributes: attrs.clone(),
43 combine_substructure: combine_substructure(|a, b, c| {
44 zero_substructure(a, b, c)
49 generics: LifetimeBounds::empty(),
50 explicit_self: borrowed_explicit_self(),
52 ret_ty: Literal(Path::new(vec!("bool"))),
54 combine_substructure: combine_substructure(|cx, span, substr| {
55 cs_and(|cx, span, _, _| cx.span_bug(span,
64 trait_def.expand(cx, mitem, item, push)
67 fn zero_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
68 let zero_ident = vec!(
74 let zero_call = |&: span| cx.expr_call_global(span, zero_ident.clone(), Vec::new());
76 return match *substr.fields {
77 StaticStruct(_, ref summary) => {
79 Unnamed(ref fields) => {
80 if fields.is_empty() {
81 cx.expr_ident(trait_span, substr.type_ident)
83 let exprs = fields.iter().map(|sp| zero_call(*sp)).collect();
84 cx.expr_call_ident(trait_span, substr.type_ident, exprs)
87 Named(ref fields) => {
88 let zero_fields = fields.iter().map(|&(ident, span)| {
89 cx.field_imm(span, ident, zero_call(span))
91 cx.expr_struct_ident(trait_span, substr.type_ident, zero_fields)
96 cx.span_err(trait_span, "`Zero` cannot be derived for enums, only structs");
97 // let compilation continue
98 cx.expr_uint(trait_span, 0)
100 _ => cx.bug("Non-static method in `deriving(Zero)`")