Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rust - Why do proc-macros have to be defined in proc-macro crate?

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 the proc-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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

  • A normal crate will be cross-compiled, generate WASM code and linked with the rest of the crates.
  • A proc-macro crate must be compiled natively, in this case to Linux code, linked with the current compiler runtime (stable, beta, nightly) and be loaded by the compiler itself when compiling the crates where it is actually used. It will not be linked to the rest of the crates (different architecture!).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...