Can custom derive consume a struct/enum?


#1

Sorry if a dumb question - can a proc macro consume the data it is working on? For example take a struct, consume it from the ast, add a new field to it, and then add the new modified struct back?


#2

No, it cannot modify the item it is being run on.


#3

Thanks. Thought that would be the case but wanted to confirm.


#4

Imagine if it were allowed – then only the first deriver could reliably change fields, because those changes could potentially break derivations that came before it.


#5

I see reliability in this case as a nicety but not a necessity. Just because you could combine derives in a way that would be hard to reason doesn’t mean that there is no use for such functionality. It wouldn’t break safety which is most key. This is not to say there are no valid practical or theoretical reasons not to have it.

I came across rust-adorn which consumes fn’s in the way python decorators do and made me think of this. Personally wanted to use it for a hacky way to add trait fields.


#6

The long term intent is to allow users to define arbitrary attributes, which would be able to modify the type. We just wanted specifically derive attributes to only define new items.