Rust-GCC / Rust-GCC/gccrs

Improve path to `Clone::clone` call when deriving `Clone`

Open
#3,371 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

good-first-pr
Dominant language
C++
Stars
2.9k
Forks
230
Avg merge
19h 55m
Merged PRs (30d)
67

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 https://github.com/Rust-GCC/gccrs/pull/3343#discussion_r1922252076

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the derive-Clone implementation and the lang-item handling in gccrs; the issue does not name specific files or tests. Trace how clone calls are generated, then verify that derived implementations resolve the official Clone trait without collisions with user-defined traits.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.