8

I'm trying to create a proc-macro to derive and implement a trait for structs and I need that all fields within the struct implement Display.

How do I check that?

And furthermore how do I check if an attribute implements Iterator as well? (I want to handle if the item of the iterator implements display too).

I'm using syn and quote crates. And I managed to parse my struct and generate the implementation. But for types like Vec and Option I would like to check if they implement Iterator and handle it properly.

The syn::Field struct has the ty attribute which I believe should be a starting point, but looking into the docs I couldn't guess any way to check if this type implements a certain trait.

BZKN
  • 1,499
  • 2
  • 10
  • 25
Augusto
  • 1,234
  • 1
  • 16
  • 35
  • 1
    I don't think that is currently possible. AFAIK, `syn` gives you the _syntax_ of the source code, not its detailed _semantics_. – rodrigo Jan 27 '22 at 16:35
  • @rodrigo how does serde makes sure every field implements serialize when you derive it? – Augusto Jan 27 '22 at 17:26
  • 4
    It doesn't, serde generates code that *assumes* all the fields implement `Serialize`. It will trigger a compiler error if that's not the case. – kmdreko Jan 27 '22 at 17:40
  • When you `#[derive(Debug)]` on a generic struct `S`, how does Rust know to only derive the implementation when `T: Debug`? – BallpointBen Jan 27 '22 at 18:39
  • 2
    @BallpointBen Looking at the expanded code clarifies that: it generates bounds like `impl Debug for S`. – Chayim Friedman Jan 28 '22 at 01:02

1 Answers1

6

Add trait bounds and/or static assertions to the generated code. Macros run before type information is available since they can affect type information.

Solomon Ucko
  • 5,724
  • 3
  • 24
  • 45