1 use crate::deriving::generic::ty::*;
2 use crate::deriving::generic::*;
3 use crate::deriving::path_std;
5 use rustc_ast::ast::{Expr, MetaItem};
7 use rustc_errors::struct_span_err;
8 use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt};
9 use rustc_span::symbol::{kw, sym};
12 pub fn expand_deriving_default(
17 push: &mut dyn FnMut(Annotatable),
19 let inline = cx.meta_word(span, sym::inline);
20 let attrs = vec![cx.attribute(inline)];
21 let trait_def = TraitDef {
23 attributes: Vec::new(),
24 path: path_std!(cx, default::Default),
25 additional_bounds: Vec::new(),
26 generics: LifetimeBounds::empty(),
28 supports_unions: false,
29 methods: vec![MethodDef {
31 generics: LifetimeBounds::empty(),
37 unify_fieldless_variants: false,
38 combine_substructure: combine_substructure(Box::new(|a, b, c| {
39 default_substructure(a, b, c)
42 associated_types: Vec::new(),
44 trait_def.expand(cx, mitem, item, push)
47 fn default_substructure(
50 substr: &Substructure<'_>,
52 // Note that `kw::Default` is "default" and `sym::Default` is "Default"!
53 let default_ident = cx.std_path(&[kw::Default, sym::Default, kw::Default]);
54 let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
56 return match *substr.fields {
57 StaticStruct(_, ref summary) => match *summary {
58 Unnamed(ref fields, is_tuple) => {
60 cx.expr_ident(trait_span, substr.type_ident)
62 let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
63 cx.expr_call_ident(trait_span, substr.type_ident, exprs)
66 Named(ref fields) => {
67 let default_fields = fields
69 .map(|&(ident, span)| cx.field_imm(span, ident, default_call(span)))
71 cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
76 cx.parse_sess.span_diagnostic,
79 "`Default` cannot be derived for enums, only structs"
82 // let compilation continue
83 DummyResult::raw_expr(trait_span, true)
85 _ => cx.span_bug(trait_span, "method in `derive(Default)`"),