I was trying to create a derive macro for my trait, to simplify some stuff.
I've encountered some problems:
the
#[proc_macro_derive]
attribute is only usable with crates of theproc-macro
crate type
and, after the small fix proc-macro=true
:
proc-macro
crate types cannot export any items other than functions tagged with#[proc_macro_derive]
currently functions tagged with#[proc_macro_derive]
must currently reside in the root of the crate`
What is the reason for this behavior?
Procedural macros allow you to run code at compile time that operates over Rust syntax, both consuming and producing Rust syntax. You can sort of think of procedural macros as functions from an AST to another AST. Procedural macros must be defined in a crate with the crate type of proc-macro .
What are Rust macros? Rust has excellent support for macros. Macros enable you to write code that writes other code, which is known as metaprogramming. Macros provide functionality similar to functions but without the runtime cost. There is some compile-time cost, however, since macros are expanded during compile time.
Procedural macros are fundamentally different from normal dependencies in your code. A normal library is just linked into your code, but a procedural macro is actually a compiler plugin.
Consider the case of cross-compiling: you are working on a Linux machine, but building a WASM project.
And since the compilation flow is different, the crate type must also be different, that is why the proc_macro=true
is needed.
About this restriction:
proc-macro
crate types cannot export any items other than functions tagged with#[proc_macro_derive]
Well, since the proc-macro crate is loaded by the compiler, not linked to the rest of your crates, any non-proc-macro code you export from this crate would be useless.
Note that the error message is inexact, as you can also export functions tagget with #[proc_macro]
.
And about this other restriction:
functions tagged with
#[proc_macro_derive]
must currently reside in the root of the crate
Adding proc_macro
or proc_macro_derive
items in nested modules is not currently supported, and does not seem to be particularly useful, IMHO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With