1 use crate::deriving::generic::ty::*;
2 use crate::deriving::generic::*;
4 use rustc_ast::ast::{Expr, MetaItem};
6 use rustc_errors::struct_span_err;
7 use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt};
8 use rustc_span::symbol::{kw, sym};
11 pub fn expand_deriving_default(
16 push: &mut dyn FnMut(Annotatable),
18 let inline = cx.meta_word(span, sym::inline);
19 let attrs = vec![cx.attribute(inline)];
20 let trait_def = TraitDef {
22 attributes: Vec::new(),
23 path: Path::new(vec![kw::Default, sym::Default]),
24 additional_bounds: Vec::new(),
25 generics: Bounds::empty(),
27 supports_unions: false,
28 methods: vec![MethodDef {
30 generics: Bounds::empty(),
36 unify_fieldless_variants: false,
37 combine_substructure: combine_substructure(Box::new(|a, b, c| {
38 default_substructure(a, b, c)
41 associated_types: Vec::new(),
43 trait_def.expand(cx, mitem, item, push)
46 fn default_substructure(
49 substr: &Substructure<'_>,
51 // Note that `kw::Default` is "default" and `sym::Default` is "Default"!
52 let default_ident = cx.std_path(&[kw::Default, sym::Default, kw::Default]);
53 let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
55 match *substr.fields {
56 StaticStruct(_, ref summary) => match *summary {
57 Unnamed(ref fields, is_tuple) => {
59 cx.expr_ident(trait_span, substr.type_ident)
61 let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
62 cx.expr_call_ident(trait_span, substr.type_ident, exprs)
65 Named(ref fields) => {
66 let default_fields = fields
68 .map(|&(ident, span)| cx.field_imm(span, ident, default_call(span)))
70 cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
75 cx.parse_sess.span_diagnostic,
78 "`Default` cannot be derived for enums, only structs"
81 // let compilation continue
82 DummyResult::raw_expr(trait_span, true)
84 _ => cx.span_bug(trait_span, "method in `derive(Default)`"),