Improve path to Clone::clone
call when deriving Clone
#3371
Description
In the meantime we could generate something like
<to_clone_type as #[lang = "clone"]>::clone(to_clone)
but this is extra work. It's not super difficult, so I'll mark it as a good-first-pr
Originally posted by @CohenArthur in #3343 (comment)
When derivine Clone, we have to perform "clone calls" to sub items. e.g. to clone a struct Foo { a: T, b: U }
we need to create the following Clone implementation:
impl<T: #[lang = "clone"], U: #[lang = "clone"]> #[lang = "clone"] for Foo {
fn clone(&self) -> Self {
Foo { a: Clone::clone(self.a), b: Clone::clone(self.b)
}
}
The issue is that just calling Clone::clone
is not valid, especially if the module structure is complex. So we can run into name collision issues with a user-defined Clone
trait, which is not good. Similarly, we don't want to call a.clone()
as that may collide with a user defined trait.
We can fix this by using the field's type and casting it as the known, official Clone
trait and calling that trait's method. To do this, we need to generate the following code:
impl<T: #[lang = "clone"], U: #[lang = "clone"]> #[lang = "clone"] for Foo {
fn clone(&self) -> Self {
Foo { a: <T as #[lang = "clone"]>::clone(self.a), b: <U as #[lang = "clone"]>::clone(self.b)
}
}
Note that I think we could also do something like #[lang = "clone"]::clone(self.a)
, but I think this requires yet another rework of lang items in the AST... and I'm not sure it's worth it