Skip to main content

rustc_builtin_macros/deriving/
clone.rs

1use rustc_ast::{self as ast, Generics, ItemKind, Safety, VariantData};
2use rustc_data_structures::fx::FxHashSet;
3use rustc_expand::base::ExtCtxt;
4use rustc_span::{DUMMY_SP, Ident, Span, sym};
5use thin_vec::{ThinVec, thin_vec};
6
7use crate::deriving::generic::*;
8use crate::deriving::path_std;
9
10pub(crate) fn expand_derive_clone(
11    cx: &ExtCtxt<'_>,
12    span: Span,
13    item: &ast::Item,
14    push: &mut dyn FnMut(Box<ast::Item>),
15    is_const: bool,
16) {
17    // The simple form is `fn clone(&self) -> Self { *self }`, possibly with
18    // some additional `AssertParamIsClone` assertions.
19    //
20    // We can use the simple form if either of the following are true.
21    // - The type derives Copy and there are no generic parameters. (If we
22    //   used the simple form with generics, we'd have to bound the generics
23    //   with Clone + Copy, and then there'd be no Clone impl at all if the
24    //   user fills in something that is Clone but not Copy. After
25    //   specialization we can remove this no-generics limitation.)
26    // - The item is a union. (Unions with generic parameters still can derive
27    //   Clone because they require Copy for deriving, Clone alone is not
28    //   enough. Whether Clone is implemented for fields is irrelevant so we
29    //   don't assert it.)
30    let bounds;
31    let body;
32    let is_simple;
33    match &item.kind {
34        ItemKind::Struct(_, Generics { params, .. }, _)
35        | ItemKind::Enum(_, Generics { params, .. }, _) => {
36            let container_id = cx.current_expansion.id.expn_data().parent.expect_local();
37            let has_derive_copy = cx.resolver.has_derive_copy(container_id);
38            bounds = ::smallvec::SmallVec::new()smallvec![];
39            if has_derive_copy
40                && !params
41                    .iter()
42                    .any(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    ast::GenericParamKind::Type { .. } => true,
    _ => false,
}matches!(param.kind, ast::GenericParamKind::Type { .. }))
43            {
44                is_simple = true;
45                body = MethodBody::Directly(clone_simple_body(cx, span, item, false));
46            } else {
47                is_simple = false;
48                body = MethodBody::SubstructureFunc {
49                    body_func: Box::new(|c, s, sub| {
50                        clone_body(c, s, sub, item.kind.ident().unwrap())
51                    }),
52                    strategy: FieldlessVariantsStrategy::Default,
53                    has_other_selflike_arg: false,
54                };
55            }
56        }
57        ItemKind::Union(..) => {
58            bounds = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(cx.std_path(span, { &[sym::marker, sym::Copy] }));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [cx.std_path(span, { &[sym::marker, sym::Copy] })])))
    }
}smallvec![path_std!(cx, span, marker::Copy)];
59            is_simple = true;
60            body = MethodBody::Directly(clone_simple_body(cx, span, item, true));
61        }
62        _ => cx.dcx().span_bug(span, "`derive(Clone)` on wrong item kind"),
63    }
64
65    // If the clone method is just copying the value, also mark the type as
66    // `TrivialClone` to allow some library optimizations.
67    if is_simple {
68        let trivial_def = TraitDef {
69            span,
70            path: cx.std_path(span, { &[sym::clone, sym::TrivialClone] })path_std!(cx, span, clone::TrivialClone),
71            needs_copy_as_bound_if_packed: true,
72            additional_bounds: bounds.clone(),
73            supports_unions: true,
74            methods: SmallVec::new(),
75            is_const,
76            safety: Safety::Unsafe(DUMMY_SP),
77            // `TrivialClone` is not part of an API guarantee, so it shouldn't
78            // appear in rustdoc output.
79            document: false,
80            ..
81        };
82
83        trivial_def.expand(cx, item, push);
84    }
85
86    let trait_def = TraitDef {
87        span,
88        path: cx.std_path(span, { &[sym::clone, sym::Clone] })path_std!(cx, span, clone::Clone),
89        needs_copy_as_bound_if_packed: true,
90        additional_bounds: bounds,
91        supports_unions: true,
92        methods: {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(MethodDef {
                name: sym::clone,
                generics: cx.empty_generics(span),
                args: {
                    let len = [()].len();
                    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                    vec.push(cx.param_self_ref(span));
                    vec
                },
                ret_ty: cx.ty_self(span),
                attributes: {
                    let len = [(), ()].len();
                    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                    vec.push(cx.generated_attr(span,
                            ast::GeneratedAttr::Inline));
                    vec.push(cx.generated_attr(span,
                            ast::GeneratedAttr::RustcTrivialFieldReads));
                    vec
                },
                body,
            });
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [MethodDef {
                                name: sym::clone,
                                generics: cx.empty_generics(span),
                                args: {
                                    let len = [()].len();
                                    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                                    vec.push(cx.param_self_ref(span));
                                    vec
                                },
                                ret_ty: cx.ty_self(span),
                                attributes: {
                                    let len = [(), ()].len();
                                    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                                    vec.push(cx.generated_attr(span,
                                            ast::GeneratedAttr::Inline));
                                    vec.push(cx.generated_attr(span,
                                            ast::GeneratedAttr::RustcTrivialFieldReads));
                                    vec
                                },
                                body,
                            }])))
    }
}smallvec![MethodDef {
93            name: sym::clone,
94            generics: cx.empty_generics(span),
95            args: thin_vec![cx.param_self_ref(span)],
96            ret_ty: cx.ty_self(span),
97            attributes: thin_vec![
98                cx.generated_attr(span, ast::GeneratedAttr::Inline),
99                cx.generated_attr(span, ast::GeneratedAttr::RustcTrivialFieldReads)
100            ],
101            body,
102        }],
103        is_const,
104        ..
105    };
106
107    trait_def.expand(cx, item, push);
108}
109
110fn clone_simple_body(
111    cx: &ExtCtxt<'_>,
112    trait_span: Span,
113    item: &ast::Item,
114    is_union: bool,
115) -> BlockOrExpr {
116    let mut stmts = ThinVec::new();
117    let mut seen_type_names = FxHashSet::default();
118    let mut process_variant = |variant: &VariantData| {
119        for field in variant.fields() {
120            // This basic redundancy checking only prevents duplication of
121            // assertions like `AssertParamIsClone<Foo>` where the type is a
122            // simple name. That's enough to get a lot of cases, though.
123            if let Some(name) = field.ty.kind.is_simple_path()
124                && !seen_type_names.insert(name)
125            {
126                // Already produced an assertion for this type.
127                // Anonymous structs or unions must be eliminated as they cannot be
128                // type parameters.
129            } else {
130                // let _: AssertParamIsClone<FieldTy>;
131                super::assert_ty_bounds(
132                    cx,
133                    &mut stmts,
134                    field.ty.clone(),
135                    field.span,
136                    &[sym::clone, sym::AssertParamIsClone],
137                );
138            }
139        }
140    };
141
142    if is_union {
143        // Just a single assertion for unions, that the union impls `Copy`.
144        // let _: AssertParamIsCopy<Self>;
145        let self_ty = cx.ty_self(DUMMY_SP);
146        super::assert_ty_bounds(
147            cx,
148            &mut stmts,
149            self_ty,
150            trait_span,
151            &[sym::clone, sym::AssertParamIsCopy],
152        );
153    } else {
154        match &item.kind {
155            ast::ItemKind::Struct(.., vdata) => {
156                process_variant(vdata);
157            }
158            ast::ItemKind::Enum(.., enum_def) => {
159                for variant in &enum_def.variants {
160                    process_variant(&variant.data);
161                }
162            }
163            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
164        }
165    }
166    BlockOrExpr::new_mixed(stmts, Some(cx.expr_deref(trait_span, cx.expr_self(trait_span))))
167}
168
169fn clone_body(
170    cx: &ExtCtxt<'_>,
171    trait_span: Span,
172    substr: Substructure<'_>,
173    type_ident: Ident,
174) -> BlockOrExpr {
175    let subcall = |field: FieldInfo<'_>| {
176        let args = {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(field.self_expr);
    vec
}thin_vec![field.self_expr];
177        cx.expr_call_global(
178            field.span,
179            cx.std_path(field.span, &[sym::clone, sym::Clone, sym::clone]),
180            args,
181        )
182    };
183
184    let ctor_path;
185    let all_fields;
186    let vdata;
187    // We need to use `type_ident` instead of `Self` here,
188    // see https://github.com/rust-lang/rust/issues/163800
189    match substr {
190        Struct(vdata_, af) => {
191            ctor_path = cx.path(trait_span, &[type_ident]);
192            all_fields = af;
193            vdata = vdata_;
194        }
195        EnumMatching(.., variant, af) => {
196            ctor_path = cx.path(trait_span, &[type_ident, variant.ident]);
197            all_fields = af;
198            vdata = &variant.data;
199        }
200        _ => cx.dcx().span_bug(trait_span, "unexpected substructure in `derive(Clone)`"),
201    }
202
203    let expr = match *vdata {
204        VariantData::Struct { .. } => {
205            let fields = all_fields
206                .into_iter()
207                .map(|field| cx.field_imm(field.span, field.def.ident.unwrap(), subcall(field)))
208                .collect::<ThinVec<_>>();
209
210            cx.expr_struct(trait_span, ctor_path, fields)
211        }
212        VariantData::Tuple(..) => {
213            let subcalls = all_fields.into_iter().map(subcall).collect();
214            let path = cx.expr_path(ctor_path);
215            cx.expr_call(trait_span, path, subcalls)
216        }
217        VariantData::Unit(..) => cx.expr_path(ctor_path),
218    };
219    BlockOrExpr::new_expr(expr)
220}