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 deriving::path_std;
12 use deriving::generic::*;
13 use deriving::generic::ty::*;
15 use syntax::ast::{Expr, MetaItem};
16 use syntax::ext::base::{Annotatable, ExtCtxt};
17 use syntax::ext::build::AstBuilder;
19 use syntax::symbol::Symbol;
22 pub fn expand_deriving_default(cx: &mut ExtCtxt,
26 push: &mut dyn FnMut(Annotatable)) {
27 let inline = cx.meta_word(span, Symbol::intern("inline"));
28 let attrs = vec![cx.attribute(span, inline)];
29 let trait_def = TraitDef {
31 attributes: Vec::new(),
32 path: path_std!(cx, default::Default),
33 additional_bounds: Vec::new(),
34 generics: LifetimeBounds::empty(),
36 supports_unions: false,
37 methods: vec![MethodDef {
39 generics: LifetimeBounds::empty(),
45 unify_fieldless_variants: false,
46 combine_substructure: combine_substructure(Box::new(|a, b, c| {
47 default_substructure(a, b, c)
50 associated_types: Vec::new(),
52 trait_def.expand(cx, mitem, item, push)
55 fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
56 let default_ident = cx.std_path(&["default", "Default", "default"]);
57 let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
59 return match *substr.fields {
60 StaticStruct(_, ref summary) => {
62 Unnamed(ref fields, is_tuple) => {
64 cx.expr_ident(trait_span, substr.type_ident)
66 let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
67 cx.expr_call_ident(trait_span, substr.type_ident, exprs)
70 Named(ref fields) => {
71 let default_fields = fields.iter()
72 .map(|&(ident, span)| cx.field_imm(span, ident, default_call(span)))
74 cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
79 span_err_if_not_stage0!(cx, trait_span, E0665,
80 "`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)`"),