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_default(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", "default", "Default")),
29 additional_bounds: Vec::new(),
30 generics: LifetimeBounds::empty(),
34 generics: LifetimeBounds::empty(),
39 const_nonmatching: false,
40 combine_substructure: default_substructure
43 trait_def.expand(cx, mitem, item, push)
46 fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> @Expr {
47 let default_ident = vec!(
49 cx.ident_of("default"),
50 cx.ident_of("Default"),
51 cx.ident_of("default")
53 let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
55 return match *substr.fields {
56 StaticStruct(_, ref summary) => {
58 Unnamed(ref fields) => {
59 if fields.is_empty() {
60 cx.expr_ident(trait_span, substr.type_ident)
62 let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
63 cx.expr_call_ident(trait_span, substr.type_ident, exprs)
66 Named(ref fields) => {
67 let default_fields = fields.iter().map(|&(ident, span)| {
68 cx.field_imm(span, ident, default_call(span))
70 cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
75 cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs");
76 // let compilation continue
77 cx.expr_uint(trait_span, 0)
79 _ => cx.span_bug(trait_span, "Non-static method in `deriving(Default)`")