rustc_builtin_macros/deriving/
clone.rs
1use rustc_ast::{self as ast, Generics, ItemKind, MetaItem, VariantData};
2use rustc_data_structures::fx::FxHashSet;
3use rustc_expand::base::{Annotatable, ExtCtxt};
4use rustc_span::{Ident, Span, kw, sym};
5use thin_vec::{ThinVec, thin_vec};
6
7use crate::deriving::generic::ty::*;
8use crate::deriving::generic::*;
9use crate::deriving::path_std;
10
11pub(crate) fn expand_deriving_clone(
12 cx: &ExtCtxt<'_>,
13 span: Span,
14 mitem: &MetaItem,
15 item: &Annotatable,
16 push: &mut dyn FnMut(Annotatable),
17 is_const: bool,
18) {
19 let bounds;
33 let substructure;
34 let is_simple;
35 match item {
36 Annotatable::Item(annitem) => match &annitem.kind {
37 ItemKind::Struct(_, Generics { params, .. })
38 | ItemKind::Enum(_, Generics { 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);
41 if has_derive_copy
42 && !params
43 .iter()
44 .any(|param| matches!(param.kind, ast::GenericParamKind::Type { .. }))
45 {
46 bounds = vec![];
47 is_simple = true;
48 substructure = combine_substructure(Box::new(|c, s, sub| {
49 cs_clone_simple("Clone", c, s, sub, false)
50 }));
51 } else {
52 bounds = vec![];
53 is_simple = false;
54 substructure =
55 combine_substructure(Box::new(|c, s, sub| cs_clone("Clone", c, s, sub)));
56 }
57 }
58 ItemKind::Union(..) => {
59 bounds = vec![Path(path_std!(marker::Copy))];
60 is_simple = true;
61 substructure = combine_substructure(Box::new(|c, s, sub| {
62 cs_clone_simple("Clone", c, s, sub, true)
63 }));
64 }
65 _ => cx.dcx().span_bug(span, "`#[derive(Clone)]` on wrong item kind"),
66 },
67
68 _ => cx.dcx().span_bug(span, "`#[derive(Clone)]` on trait item or impl item"),
69 }
70
71 let trait_def = TraitDef {
72 span,
73 path: path_std!(clone::Clone),
74 skip_path_as_bound: false,
75 needs_copy_as_bound_if_packed: true,
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: thin_vec![cx.attr_word(sym::inline, span)],
85 fieldless_variants_strategy: FieldlessVariantsStrategy::Default,
86 combine_substructure: substructure,
87 }],
88 associated_types: Vec::new(),
89 is_const,
90 };
91
92 trait_def.expand_ext(cx, mitem, item, push, is_simple)
93}
94
95fn cs_clone_simple(
96 name: &str,
97 cx: &ExtCtxt<'_>,
98 trait_span: Span,
99 substr: &Substructure<'_>,
100 is_union: bool,
101) -> BlockOrExpr {
102 let mut stmts = ThinVec::new();
103 let mut seen_type_names = FxHashSet::default();
104 let mut process_variant = |variant: &VariantData| {
105 for field in variant.fields() {
106 if let Some(name) = field.ty.kind.is_simple_path()
110 && !seen_type_names.insert(name)
111 {
112 } else {
116 super::assert_ty_bounds(
118 cx,
119 &mut stmts,
120 field.ty.clone(),
121 field.span,
122 &[sym::clone, sym::AssertParamIsClone],
123 );
124 }
125 }
126 };
127
128 if is_union {
129 let self_ty = cx.ty_path(cx.path_ident(trait_span, Ident::with_dummy_span(kw::SelfUpper)));
132 super::assert_ty_bounds(
133 cx,
134 &mut stmts,
135 self_ty,
136 trait_span,
137 &[sym::clone, sym::AssertParamIsCopy],
138 );
139 } else {
140 match *substr.fields {
141 StaticStruct(vdata, ..) => {
142 process_variant(vdata);
143 }
144 StaticEnum(enum_def, ..) => {
145 for variant in &enum_def.variants {
146 process_variant(&variant.data);
147 }
148 }
149 _ => cx.dcx().span_bug(
150 trait_span,
151 format!("unexpected substructure in simple `derive({name})`"),
152 ),
153 }
154 }
155 BlockOrExpr::new_mixed(stmts, Some(cx.expr_deref(trait_span, cx.expr_self(trait_span))))
156}
157
158fn cs_clone(
159 name: &str,
160 cx: &ExtCtxt<'_>,
161 trait_span: Span,
162 substr: &Substructure<'_>,
163) -> BlockOrExpr {
164 let ctor_path;
165 let all_fields;
166 let fn_path = cx.std_path(&[sym::clone, sym::Clone, sym::clone]);
167 let subcall = |cx: &ExtCtxt<'_>, field: &FieldInfo| {
168 let args = thin_vec![field.self_expr.clone()];
169 cx.expr_call_global(field.span, fn_path.clone(), args)
170 };
171
172 let vdata;
173 match substr.fields {
174 Struct(vdata_, af) => {
175 ctor_path = cx.path(trait_span, vec![substr.type_ident]);
176 all_fields = af;
177 vdata = *vdata_;
178 }
179 EnumMatching(.., variant, af) => {
180 ctor_path = cx.path(trait_span, vec![substr.type_ident, variant.ident]);
181 all_fields = af;
182 vdata = &variant.data;
183 }
184 EnumDiscr(..) | AllFieldlessEnum(..) => {
185 cx.dcx().span_bug(trait_span, format!("enum discriminants in `derive({name})`",))
186 }
187 StaticEnum(..) | StaticStruct(..) => {
188 cx.dcx().span_bug(trait_span, format!("associated function in `derive({name})`"))
189 }
190 }
191
192 let expr = match *vdata {
193 VariantData::Struct { .. } => {
194 let fields = all_fields
195 .iter()
196 .map(|field| {
197 let Some(ident) = field.name else {
198 cx.dcx().span_bug(
199 trait_span,
200 format!("unnamed field in normal struct in `derive({name})`",),
201 );
202 };
203 let call = subcall(cx, field);
204 cx.field_imm(field.span, ident, call)
205 })
206 .collect::<ThinVec<_>>();
207
208 cx.expr_struct(trait_span, ctor_path, fields)
209 }
210 VariantData::Tuple(..) => {
211 let subcalls = all_fields.iter().map(|f| subcall(cx, f)).collect();
212 let path = cx.expr_path(ctor_path);
213 cx.expr_call(trait_span, path, subcalls)
214 }
215 VariantData::Unit(..) => cx.expr_path(ctor_path),
216 };
217 BlockOrExpr::new_expr(expr)
218}