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};
14 use ext::base::ExtCtxt;
15 use ext::build::AstBuilder;
16 use ext::deriving::generic::*;
17 use parse::token::InternedString;
19 pub fn expand_deriving_default(cx: &mut ExtCtxt,
24 let inline = cx.meta_word(span, InternedString::new("inline"));
25 let attrs = vec!(cx.attribute(attr::mk_attr_id(), span, inline));
26 let trait_def = TraitDef {
28 attributes: Vec::new(),
29 path: Path::new(vec!("std", "default", "Default")),
30 additional_bounds: Vec::new(),
31 generics: LifetimeBounds::empty(),
35 generics: LifetimeBounds::empty(),
40 const_nonmatching: false,
41 combine_substructure: combine_substructure(|a, b, c| {
42 default_substructure(a, b, c)
46 trait_def.expand(cx, mitem, item, push)
49 fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> @Expr {
50 let default_ident = vec!(
52 cx.ident_of("default"),
53 cx.ident_of("Default"),
54 cx.ident_of("default")
56 let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
58 return match *substr.fields {
59 StaticStruct(_, ref summary) => {
61 Unnamed(ref fields) => {
62 if fields.is_empty() {
63 cx.expr_ident(trait_span, substr.type_ident)
65 let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
66 cx.expr_call_ident(trait_span, substr.type_ident, exprs)
69 Named(ref fields) => {
70 let default_fields = fields.iter().map(|&(ident, span)| {
71 cx.field_imm(span, ident, default_call(span))
73 cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
78 cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs");
79 // let compilation continue
80 cx.expr_uint(trait_span, 0)
82 _ => cx.span_bug(trait_span, "Non-static method in `deriving(Default)`")