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_default<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", "default", "Default")),
33 additional_bounds: Vec::new(),
34 generics: LifetimeBounds::empty(),
38 generics: LifetimeBounds::empty(),
43 combine_substructure: combine_substructure(box |a, b, c| {
44 default_substructure(a, b, c)
48 trait_def.expand(cx, mitem, item, push)
51 fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
52 let default_ident = vec!(
54 cx.ident_of("default"),
55 cx.ident_of("Default"),
56 cx.ident_of("default")
58 let default_call = |&: span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
60 return match *substr.fields {
61 StaticStruct(_, ref summary) => {
63 Unnamed(ref fields) => {
64 if fields.is_empty() {
65 cx.expr_ident(trait_span, substr.type_ident)
67 let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
68 cx.expr_call_ident(trait_span, substr.type_ident, exprs)
71 Named(ref fields) => {
72 let default_fields = fields.iter().map(|&(ident, span)| {
73 cx.field_imm(span, ident, default_call(span))
75 cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
80 cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs");
81 // let compilation continue
82 cx.expr_usize(trait_span, 0)
84 _ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`")