mcarton/rust-derivative

Generated code doesn't use fully qualified syntax leading to unexpected behaviour of derived trait impls

Opened this issue · 1 comments

Describe the bug

For the Clone trait (I haven't tried other traits), derivative will impl Clone on a type even if one of its members doesn't and instead just has a function called clone() that matches the interface.

This also means if the members where to impl Clone and have a separate clone function, then the derivative impl would not call, Clone::clone but the Members::clone.

To Reproduce
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=e357412d7e9b32c3aef52fb4b4b8a7a4

use derivative; // 2.2.0

struct DoesNotImplClone {}
impl DoesNotImplClone {
    fn clone(&self) -> Self {
        Self {}
    }
}

// Works, but I would expect it to fail
#[derive(derivative::Derivative)]
#[derivative(Clone)]
struct Derivative {x: DoesNotImplClone}

// Fails as expected
//
// #[derive(Clone)]
// struct Derive {x: DoesNotImplClone}

fn main() {}

Expected behavior
I would expect the derived trait's impl to always use the struct/enum member's impls of that derived trait (and if they don't impl the trait fail to compile). And to importantly never call functions that just happen to have the same interface, as the trait.

Version (please complete the following information):
stable 1.69.0 (See Playground), derivative 2.2.0

I've also tried this locally:

rustup --version: rustup 1.25.2 (fae52a197 2023-02-01)
cargo --version: cargo 1.65.0-nightly (4fd148c47 2022-08-03)
rustc --version: rustc 1.65.0-nightly (d394408fb 2022-08-07)
  • Version of derivative: 2.2.0

This (using arg.clone() instead of UFCS core::Clone::clone(arg)) is also the cause of issues like #90

A workaround is to make the expansion use UFCS via clone_with. In OP's case this means struct Derivative { #[derivative(Clone(clone_with = "Clone::clone"))] x: DoesNotImplClone }