Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve path to Clone::clone call when deriving Clone #3371

Open
CohenArthur opened this issue Jan 20, 2025 · 0 comments
Open

Improve path to Clone::clone call when deriving Clone #3371

CohenArthur opened this issue Jan 20, 2025 · 0 comments

Comments

@CohenArthur
Copy link
Member

CohenArthur commented Jan 20, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant