我想创建一个使用新的命名空间属性语法的自定义派生宏:example::attr
。我已经能够使用类型中的属性(例如,在struct字段或枚举变体上),但在应用于类型本身时则不行。
SRC / main.rs
use repro_derive::Example;
#[derive(Example)]
#[example::attr] // Does not work
struct Demo {
#[example::attr] // Works
field: i32,
}
fn main() {}
除了声明example::attr
是有效属性之外,过程宏本身什么都不做。
REPRO-派生/ SRC / lib.rs
extern crate proc_macro;
use proc_macro::TokenStream;
#[proc_macro_derive(Example, attributes(example::attr))]
pub fn example_derive(_input: TokenStream) -> TokenStream {
TokenStream::new()
}
汇总收益率:
error[E0433]: failed to resolve: use of undeclared type or module `example`
--> src/main.rs:4:3
|
4 | #[example::attr]
| ^^^^^^^ use of undeclared type or module `example`
切换到属性的非命名空间形式(example_attr
)工作正常。
我正在使用Rust 1.32.0。项目布局是
$ tree
.
├── Cargo.lock
├── Cargo.toml
├── repro-derive
│ ├── Cargo.toml
│ └── src
│ └── lib.rs
└── src
└── main.rs
Cargo.toml
$ cat Cargo.toml
[package]
name = "repro"
version = "0.1.0"
authors = ["Author"]
edition = "2018"
[dependencies]
repro-derive = { path = "repro-derive" }
REPRO-派生/ Cargo.toml
[package]
name = "repro-derive"
version = "0.1.0"
authors = ["Author"]
edition = "2018"
[lib]
proc-macro = true
[dependencies]
在proc_macro_derive
属性中声明的名称空间完全被忽略,这是一个known bug。由于这个错误,可以编译以下代码,但不应该编译。
#[derive(Example)]
#[attr] // Works (but shouldn't)
struct Demo {
#[lolwut::attr] // Works (but shouldn't)
field: i32,
}
在修复错误之前,您应该继续使用非命名空间的表单(example_attr
)。
另外,根据这个错误报告,从Rust 1.33.0开始,没有办法通过proc-macros实现OP想要的,以及如何允许#[example::attr]
工作仍在设计中。