1 use crate::deriving::path_std;
2 use crate::deriving::generic::*;
3 use crate::deriving::generic::ty::*;
5 use syntax::ast::{Expr, MetaItem};
6 use syntax::ext::base::{Annotatable, DummyResult, ExtCtxt};
8 use syntax::symbol::{kw, sym};
12 pub fn expand_deriving_default(cx: &mut ExtCtxt<'_>,
16 push: &mut dyn FnMut(Annotatable)) {
17 let inline = cx.meta_word(span, sym::inline);
18 let attrs = vec![cx.attribute(inline)];
19 let trait_def = TraitDef {
21 attributes: Vec::new(),
22 path: path_std!(cx, default::Default),
23 additional_bounds: Vec::new(),
24 generics: LifetimeBounds::empty(),
26 supports_unions: false,
27 methods: vec![MethodDef {
29 generics: LifetimeBounds::empty(),
35 unify_fieldless_variants: false,
36 combine_substructure: combine_substructure(Box::new(|a, b, c| {
37 default_substructure(a, b, c)
40 associated_types: Vec::new(),
42 trait_def.expand(cx, mitem, item, push)
45 fn default_substructure(cx: &mut ExtCtxt<'_>,
47 substr: &Substructure<'_>)
49 // Note that `kw::Default` is "default" and `sym::Default` is "Default"!
50 let default_ident = cx.std_path(&[kw::Default, sym::Default, kw::Default]);
51 let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
53 return match *substr.fields {
54 StaticStruct(_, ref summary) => {
56 Unnamed(ref fields, is_tuple) => {
58 cx.expr_ident(trait_span, substr.type_ident)
60 let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
61 cx.expr_call_ident(trait_span, substr.type_ident, exprs)
64 Named(ref fields) => {
65 let default_fields = fields.iter()
66 .map(|&(ident, span)| cx.field_imm(span, ident, default_call(span)))
68 cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
73 span_err!(cx, trait_span, E0665,
74 "`Default` cannot be derived for enums, only structs");
75 // let compilation continue
76 DummyResult::raw_expr(trait_span, true)
78 _ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`"),