near / borsh-rs

Rust implementation of Binary Object Representation Serializer for Hashing
https://borsh.io/
Apache License 2.0
287 stars 62 forks source link

derive BoshSerialize fails if the type already uses `W` generic name #260

Closed Fuuzetsu closed 4 months ago

Fuuzetsu commented 7 months ago

The below fails to compile

#[derive(borsh::BorshSerialize)]
pub struct Foo<W> {
  inner: W
}

This is because the BorshSerialize deriver always tries to use W for the generic type of the borsh::io::Write and we end up with a conflict.

dj8yfo commented 7 months ago

NOTE: serde has similar issue, though it uses a hidden type parameter __S in the example, which behaves the same, but is less likely to be used outside of derived code context:

    use serde::Serialize;
    #[derive(Debug, Serialize)]
    struct Generic<K, __S>
    {
        x: HashMap<K, __S>,
        y: String,
    }
error[E0403]: the name `__S` is already used for a generic parameter in this item's generic parameters
 --> src/serialize.rs:8:21
  |
8 |     #[derive(Debug, Serialize)]
  |                     ^^^^^^^^^ already used
9 |     struct Generic<K, __S>
  |                       --- first use of `__S`
  |
  = note: this error originates in the derive macro `Serialize` (in Nightly builds, run with -Z macro-backtrace formore info)

error[E0053]: method `serialize` has an incompatible type for trait
 --> src/serialize.rs:8:21
  |
8 |     #[derive(Debug, Serialize)]
  |                     ^^^^^^^^^
  |                     |
  |                     expected type parameter `__S`, found a different type parameter `__S`
  |                     help: change the parameter type to match the trait: `__S`
9 |     struct Generic<K, __S>
  |                       --- found type parameter
  |
  = note: expected signature `fn(&serialize::_struct::Generic<K, __S>, __S) -> Result<<__S as Serializer>::Ok, <__Sas Serializer>::Error>`
             found signature `fn(&serialize::_struct::Generic<K, __S>, __S) -> Result<_, _>`
  = note: a type parameter was expected, but a different one was found; you might be missing a type parameter or trait bound
  = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters
  = note: this error originates in the derive macro `Serialize` (in Nightly builds, run with -Z macro-backtrace formore info)
Fuuzetsu commented 7 months ago

Right. As far as I understand, the macros are not hygenic w.r.t. generic type parameters (though I have no idea what the reasoning is) so the usual hacks are to use names that are unlikely to be taken by user.

frol commented 7 months ago

@dj8yfo Can we rename W to __S to reduce chances of naming collision?

Fuuzetsu commented 7 months ago

BorshDeserialize has the same issue with R FWIW so that probably needs renaming too.