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};
9 use thin_vec::thin_vec;
11 pub fn expand_deriving_clone(
16 push: &mut dyn FnMut(Annotatable),
19 // The simple form is `fn clone(&self) -> Self { *self }`, possibly with
20 // some additional `AssertParamIsClone` assertions.
22 // We can use the simple form if either of the following are true.
23 // - The type derives Copy and there are no generic parameters. (If we
24 // used the simple form with generics, we'd have to bound the generics
25 // with Clone + Copy, and then there'd be no Clone impl at all if the
26 // user fills in something that is Clone but not Copy. After
27 // specialization we can remove this no-generics limitation.)
28 // - The item is a union. (Unions with generic parameters still can derive
29 // Clone because they require Copy for deriving, Clone alone is not
30 // enough. Whether Clone is implemented for fields is irrelevant so we
36 Annotatable::Item(ref annitem) => match annitem.kind {
37 ItemKind::Struct(_, Generics { ref params, .. })
38 | ItemKind::Enum(_, Generics { ref params, .. }) => {
39 let container_id = cx.current_expansion.id.expn_data().parent.expect_local();
40 let has_derive_copy = cx.resolver.has_derive_copy(container_id);
44 .any(|param| matches!(param.kind, ast::GenericParamKind::Type { .. }))
48 substructure = combine_substructure(Box::new(|c, s, sub| {
49 cs_clone_simple("Clone", c, s, sub, false)
55 combine_substructure(Box::new(|c, s, sub| cs_clone("Clone", c, s, sub)));
58 ItemKind::Union(..) => {
59 bounds = vec![Path(path_std!(marker::Copy))];
61 substructure = combine_substructure(Box::new(|c, s, sub| {
62 cs_clone_simple("Clone", c, s, sub, true)
65 _ => cx.span_bug(span, "`#[derive(Clone)]` on wrong item kind"),
68 _ => cx.span_bug(span, "`#[derive(Clone)]` on trait item or impl item"),
71 let inline = cx.meta_word(span, sym::inline);
72 let attrs = thin_vec![cx.attribute(inline)];
73 let trait_def = TraitDef {
75 path: path_std!(clone::Clone),
76 skip_path_as_bound: false,
77 additional_bounds: bounds,
78 supports_unions: true,
79 methods: vec![MethodDef {
81 generics: Bounds::empty(),
83 nonself_args: Vec::new(),
86 unify_fieldless_variants: false,
87 combine_substructure: substructure,
89 associated_types: Vec::new(),
93 trait_def.expand_ext(cx, mitem, item, push, is_simple)
100 substr: &Substructure<'_>,
103 let mut stmts = Vec::new();
104 let mut seen_type_names = FxHashSet::default();
105 let mut process_variant = |variant: &VariantData| {
106 for field in variant.fields() {
107 // This basic redundancy checking only prevents duplication of
108 // assertions like `AssertParamIsClone<Foo>` where the type is a
109 // simple name. That's enough to get a lot of cases, though.
110 if let Some(name) = field.ty.kind.is_simple_path() && !seen_type_names.insert(name) {
111 // Already produced an assertion for this type.
113 // let _: AssertParamIsClone<FieldTy>;
114 super::assert_ty_bounds(
119 &[sym::clone, sym::AssertParamIsClone],
126 // Just a single assertion for unions, that the union impls `Copy`.
127 // let _: AssertParamIsCopy<Self>;
128 let self_ty = cx.ty_path(cx.path_ident(trait_span, Ident::with_dummy_span(kw::SelfUpper)));
129 super::assert_ty_bounds(
134 &[sym::clone, sym::AssertParamIsCopy],
137 match *substr.fields {
138 StaticStruct(vdata, ..) => {
139 process_variant(vdata);
141 StaticEnum(enum_def, ..) => {
142 for variant in &enum_def.variants {
143 process_variant(&variant.data);
148 &format!("unexpected substructure in simple `derive({})`", name),
152 BlockOrExpr::new_mixed(stmts, Some(cx.expr_deref(trait_span, cx.expr_self(trait_span))))
157 cx: &mut ExtCtxt<'_>,
159 substr: &Substructure<'_>,
163 let fn_path = cx.std_path(&[sym::clone, sym::Clone, sym::clone]);
164 let subcall = |cx: &mut ExtCtxt<'_>, field: &FieldInfo| {
165 let args = vec![field.self_expr.clone()];
166 cx.expr_call_global(field.span, fn_path.clone(), args)
170 match *substr.fields {
171 Struct(vdata_, ref af) => {
172 ctor_path = cx.path(trait_span, vec![substr.type_ident]);
176 EnumMatching(.., variant, ref af) => {
177 ctor_path = cx.path(trait_span, vec![substr.type_ident, variant.ident]);
179 vdata = &variant.data;
181 EnumTag(..) => cx.span_bug(trait_span, &format!("enum tags in `derive({})`", name,)),
182 StaticEnum(..) | StaticStruct(..) => {
183 cx.span_bug(trait_span, &format!("associated function in `derive({})`", name))
187 let expr = match *vdata {
188 VariantData::Struct(..) => {
189 let fields = all_fields
192 let Some(ident) = field.name else {
195 &format!("unnamed field in normal struct in `derive({})`", name,),
198 let call = subcall(cx, field);
199 cx.field_imm(field.span, ident, call)
201 .collect::<Vec<_>>();
203 cx.expr_struct(trait_span, ctor_path, fields)
205 VariantData::Tuple(..) => {
206 let subcalls = all_fields.iter().map(|f| subcall(cx, f)).collect();
207 let path = cx.expr_path(ctor_path);
208 cx.expr_call(trait_span, path, subcalls)
210 VariantData::Unit(..) => cx.expr_path(ctor_path),
212 BlockOrExpr::new_expr(expr)