Implementing a custom #[derive(Foo)] macro


Did a quick search but I haven't found anything about how I can implement the Foo macro over a custom struct.

Where could I find more info about creating a custom Foo for this struct?


I belive the #[derive(Foo)] attribute is just sugar for #[derive_Foo], so you would have to write a syntax extension that implements that attribute and use the register_attribute function on the registry. You might want to look into some tutorials on syntax extensions. I don't think there is a way of implementing attributes without a syntax extension.


Compiler Plugins has some information on writing compiler plugins, I think it has a start at least, though it doesn't have any documentation for specifically writing attributes (like #[derive_Foo]).

I would suggest looking at some existing projects which declare attributes like this, like That will probably have enough of an example to get you started writing one at least.

Since compiler plugins are unstable, writing these will need a nightly rust compiler and is subject to change in the future.

1 Like

You have to write a syntax extension.

Servo's #[jstraceable] is here, registered here, though if it was called derive_JSTraceable then it would be sugar for #[derive(JStraceable)]

There are other examples of deriving syntax extensions for the builtins here. General documentation here


Thank you guys, I made it work finally.

There are some caveats in creating syntax extesions but reading that bunch of links helped a lot!

I might create a blog post with a step by step guide.