bincode icon indicating copy to clipboard operation
bincode copied to clipboard

Derive macros break with where clauses

Open SabrinaJewson opened this issue 2 years ago • 3 comments

Test case:

#[derive(bincode::Encode)]
struct Test<T>
where
    T: Clone,
{
    a: T,
}

Output:

error: expected one of `{`, lifetime, or type, found `,`
 --> src/main.rs:3:10
  |
3 | #[derive(bincode::Encode)]
  |          ^^^^^^^^^^^^^^^ expected one of `{`, lifetime, or type
  |
  = note: this error originates in the derive macro `bincode::Encode` (in Nightly builds, run with -Z macro-backtrace for more info)

error: proc-macro derive produced unparseable tokens
 --> src/main.rs:3:10
  |
3 | #[derive(bincode::Encode)]
  |          ^^^^^^^^^^^^^^^

SabrinaJewson avatar Jul 22 '22 13:07 SabrinaJewson

There is an attribute you can use called bounds, I only just noticed we've not documented this.

There is an example in tests/issues/issue_431.rs that uses borrow_decode_bounds. There are these 4 attributes:

  • bounds, used by all 3 derives
  • decode_bounds, used by #[derive(Decode)]
  • borrow_decode_bounds, used by #[derive(BorrowDecode)]
  • encode_bounds, used by #[derive(Encode)]

You can check target/test_Encode.rs to see what bounds would be needed.

This is assuming either virtue or bincode-derive doesn't do something weird

VictorKoenders avatar Jul 23 '22 09:07 VictorKoenders

Thanks — the following does compile:

#[derive(bincode::Encode)]
#[bincode(encode_bounds = "T: bincode::Encode + Clone")]
struct Test<T>
where
    T: Clone,
{
    a: T,
}

I still think it would be nice for bincode to just automatically support where bounds, but if it must be unsupported could the error message be improved?

SabrinaJewson avatar Jul 23 '22 11:07 SabrinaJewson

It appears it does attempt to support automatic bounds.

purpleposeidon avatar Aug 15 '22 04:08 purpleposeidon

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Oct 17 '22 06:10 stale[bot]

Bincode is still generating syntactically invalid code in this situation. That's a bug independent of whether encode_bounds exists.

dtolnay avatar Dec 03 '22 16:12 dtolnay