]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/deriving/clone.rs
Remove TraitDef::generics.
[rust.git] / compiler / rustc_builtin_macros / src / deriving / clone.rs
1 use crate::deriving::generic::ty::*;
2 use crate::deriving::generic::*;
3 use crate::deriving::path_std;
4 use rustc_ast::{self as ast, Generics, ItemKind, MetaItem, VariantData};
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_expand::base::{Annotatable, ExtCtxt};
7 use rustc_span::symbol::{kw, sym, Ident};
8 use rustc_span::Span;
9 use thin_vec::thin_vec;
10
11 pub fn expand_deriving_clone(
12     cx: &mut ExtCtxt<'_>,
13     span: Span,
14     mitem: &MetaItem,
15     item: &Annotatable,
16     push: &mut dyn FnMut(Annotatable),
17 ) {
18     // The simple form is `fn clone(&self) -> Self { *self }`, possibly with
19     // some additional `AssertParamIsClone` assertions.
20     //
21     // We can use the simple form if either of the following are true.
22     // - The type derives Copy and there are no generic parameters.  (If we
23     //   used the simple form with generics, we'd have to bound the generics
24     //   with Clone + Copy, and then there'd be no Clone impl at all if the
25     //   user fills in something that is Clone but not Copy. After
26     //   specialization we can remove this no-generics limitation.)
27     // - The item is a union. (Unions with generic parameters still can derive
28     //   Clone because they require Copy for deriving, Clone alone is not
29     //   enough. Whether Clone is implemented for fields is irrelevant so we
30     //   don't assert it.)
31     let bounds;
32     let substructure;
33     let is_simple;
34     match *item {
35         Annotatable::Item(ref annitem) => match annitem.kind {
36             ItemKind::Struct(_, Generics { ref params, .. })
37             | ItemKind::Enum(_, Generics { ref params, .. }) => {
38                 let container_id = cx.current_expansion.id.expn_data().parent.expect_local();
39                 let has_derive_copy = cx.resolver.has_derive_copy(container_id);
40                 if has_derive_copy
41                     && !params
42                         .iter()
43                         .any(|param| matches!(param.kind, ast::GenericParamKind::Type { .. }))
44                 {
45                     bounds = vec![];
46                     is_simple = true;
47                     substructure = combine_substructure(Box::new(|c, s, sub| {
48                         cs_clone_simple("Clone", c, s, sub, false)
49                     }));
50                 } else {
51                     bounds = vec![];
52                     is_simple = false;
53                     substructure =
54                         combine_substructure(Box::new(|c, s, sub| cs_clone("Clone", c, s, sub)));
55                 }
56             }
57             ItemKind::Union(..) => {
58                 bounds = vec![Path(path_std!(marker::Copy))];
59                 is_simple = true;
60                 substructure = combine_substructure(Box::new(|c, s, sub| {
61                     cs_clone_simple("Clone", c, s, sub, true)
62                 }));
63             }
64             _ => cx.span_bug(span, "`#[derive(Clone)]` on wrong item kind"),
65         },
66
67         _ => cx.span_bug(span, "`#[derive(Clone)]` on trait item or impl item"),
68     }
69
70     let inline = cx.meta_word(span, sym::inline);
71     let attrs = thin_vec![cx.attribute(inline)];
72     let trait_def = TraitDef {
73         span,
74         path: path_std!(clone::Clone),
75         skip_path_as_bound: false,
76         additional_bounds: bounds,
77         supports_unions: true,
78         methods: vec![MethodDef {
79             name: sym::clone,
80             generics: Bounds::empty(),
81             explicit_self: true,
82             nonself_args: Vec::new(),
83             ret_ty: Self_,
84             attributes: attrs,
85             unify_fieldless_variants: false,
86             combine_substructure: substructure,
87         }],
88         associated_types: Vec::new(),
89     };
90
91     trait_def.expand_ext(cx, mitem, item, push, is_simple)
92 }
93
94 fn cs_clone_simple(
95     name: &str,
96     cx: &mut ExtCtxt<'_>,
97     trait_span: Span,
98     substr: &Substructure<'_>,
99     is_union: bool,
100 ) -> BlockOrExpr {
101     let mut stmts = Vec::new();
102     let mut seen_type_names = FxHashSet::default();
103     let mut process_variant = |variant: &VariantData| {
104         for field in variant.fields() {
105             // This basic redundancy checking only prevents duplication of
106             // assertions like `AssertParamIsClone<Foo>` where the type is a
107             // simple name. That's enough to get a lot of cases, though.
108             if let Some(name) = field.ty.kind.is_simple_path() && !seen_type_names.insert(name) {
109                 // Already produced an assertion for this type.
110             } else {
111                 // let _: AssertParamIsClone<FieldTy>;
112                 super::assert_ty_bounds(
113                     cx,
114                     &mut stmts,
115                     field.ty.clone(),
116                     field.span,
117                     &[sym::clone, sym::AssertParamIsClone],
118                 );
119             }
120         }
121     };
122
123     if is_union {
124         // Just a single assertion for unions, that the union impls `Copy`.
125         // let _: AssertParamIsCopy<Self>;
126         let self_ty = cx.ty_path(cx.path_ident(trait_span, Ident::with_dummy_span(kw::SelfUpper)));
127         super::assert_ty_bounds(
128             cx,
129             &mut stmts,
130             self_ty,
131             trait_span,
132             &[sym::clone, sym::AssertParamIsCopy],
133         );
134     } else {
135         match *substr.fields {
136             StaticStruct(vdata, ..) => {
137                 process_variant(vdata);
138             }
139             StaticEnum(enum_def, ..) => {
140                 for variant in &enum_def.variants {
141                     process_variant(&variant.data);
142                 }
143             }
144             _ => cx.span_bug(
145                 trait_span,
146                 &format!("unexpected substructure in simple `derive({})`", name),
147             ),
148         }
149     }
150     BlockOrExpr::new_mixed(stmts, Some(cx.expr_deref(trait_span, cx.expr_self(trait_span))))
151 }
152
153 fn cs_clone(
154     name: &str,
155     cx: &mut ExtCtxt<'_>,
156     trait_span: Span,
157     substr: &Substructure<'_>,
158 ) -> BlockOrExpr {
159     let ctor_path;
160     let all_fields;
161     let fn_path = cx.std_path(&[sym::clone, sym::Clone, sym::clone]);
162     let subcall = |cx: &mut ExtCtxt<'_>, field: &FieldInfo| {
163         let args = vec![field.self_expr.clone()];
164         cx.expr_call_global(field.span, fn_path.clone(), args)
165     };
166
167     let vdata;
168     match *substr.fields {
169         Struct(vdata_, ref af) => {
170             ctor_path = cx.path(trait_span, vec![substr.type_ident]);
171             all_fields = af;
172             vdata = vdata_;
173         }
174         EnumMatching(.., variant, ref af) => {
175             ctor_path = cx.path(trait_span, vec![substr.type_ident, variant.ident]);
176             all_fields = af;
177             vdata = &variant.data;
178         }
179         EnumTag(..) => cx.span_bug(trait_span, &format!("enum tags in `derive({})`", name,)),
180         StaticEnum(..) | StaticStruct(..) => {
181             cx.span_bug(trait_span, &format!("associated function in `derive({})`", name))
182         }
183     }
184
185     let expr = match *vdata {
186         VariantData::Struct(..) => {
187             let fields = all_fields
188                 .iter()
189                 .map(|field| {
190                     let Some(ident) = field.name else {
191                         cx.span_bug(
192                             trait_span,
193                             &format!("unnamed field in normal struct in `derive({})`", name,),
194                         );
195                     };
196                     let call = subcall(cx, field);
197                     cx.field_imm(field.span, ident, call)
198                 })
199                 .collect::<Vec<_>>();
200
201             cx.expr_struct(trait_span, ctor_path, fields)
202         }
203         VariantData::Tuple(..) => {
204             let subcalls = all_fields.iter().map(|f| subcall(cx, f)).collect();
205             let path = cx.expr_path(ctor_path);
206             cx.expr_call(trait_span, path, subcalls)
207         }
208         VariantData::Unit(..) => cx.expr_path(ctor_path),
209     };
210     BlockOrExpr::new_expr(expr)
211 }