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?
No, it cannot modify the item it is being run on.
Thanks. Thought that would be the case but wanted to confirm.
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.
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.
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.
Just ran into this myself.
It’s quite understandable that the attribute macro can’t change the struct definition, but boy would it have been handy for my use case.
Annotation-based plugins are stabilizing in 1.30 or 1.31(can’t remember which) that can do this kind of thing!