使用递归声明宏创建枚举
Using recursive declarative macros to create enums
是否可以在 Rust 中编写一个声明性宏,它采用树状块结构并创建枚举的组合分类?我正在尝试确定这是否仅适用于程序宏,或者我是否可以使用 TT munchers。递归不是唯一的挑战,因为我还需要组合用于标记每个块的标识符,比如 Exposure
和 Mode
变成 ExposureMode
,我似乎找不到一种实现方式。
例如,给出如下语句:
enum_tree! {
Exposure {
Mode {
FullAuto,
Manual,
ShutterPriority,
IrisPriority,
GainPriority,
},
Iris {
Reset,
Up,
Down,
Direct(u8),
},
},
Focus {
In,
Out,
Stop,
}
}
会产生如下结果:
enum ExposureMode {
FullAuto,
Manual,
ShutterPriority,
IrisPriority,
GainPriority,
}
enum ExposureIris {
Reset,
Up,
Down,
Direct(u8),
}
enum Focus {
In,
Out,
Stop,
}
如果我没记错的话,tt-munchers 是 turing-complete,因此几乎等同于 proc 宏。就算他们不一般,这个问题用他们也是可以解决的。
他们唯一不能做的就是操纵原子……比如连接标识符。有 concat_ident!()
宏,但如其文档中所述:
Also, as a general rule, macros are only allowed in item, statement or expression position. That means while you may use this macro for referring to existing variables, functions or modules etc, you cannot define a new one with it.
所以在这种情况下不适用。但是,这并不意味着您不能使用 macro_rules,因为人们已经编写了带有可以连接标识符的 proc 宏的 crate。一个流行的例子是 paste.
但是,如果宏很复杂,您可能会发现它更容易理解并编写为 proc 宏。
另见 Is it possible to declare variables procedurally using Rust macros?。
是否可以在 Rust 中编写一个声明性宏,它采用树状块结构并创建枚举的组合分类?我正在尝试确定这是否仅适用于程序宏,或者我是否可以使用 TT munchers。递归不是唯一的挑战,因为我还需要组合用于标记每个块的标识符,比如 Exposure
和 Mode
变成 ExposureMode
,我似乎找不到一种实现方式。
例如,给出如下语句:
enum_tree! {
Exposure {
Mode {
FullAuto,
Manual,
ShutterPriority,
IrisPriority,
GainPriority,
},
Iris {
Reset,
Up,
Down,
Direct(u8),
},
},
Focus {
In,
Out,
Stop,
}
}
会产生如下结果:
enum ExposureMode {
FullAuto,
Manual,
ShutterPriority,
IrisPriority,
GainPriority,
}
enum ExposureIris {
Reset,
Up,
Down,
Direct(u8),
}
enum Focus {
In,
Out,
Stop,
}
如果我没记错的话,tt-munchers 是 turing-complete,因此几乎等同于 proc 宏。就算他们不一般,这个问题用他们也是可以解决的。
他们唯一不能做的就是操纵原子……比如连接标识符。有 concat_ident!()
宏,但如其文档中所述:
Also, as a general rule, macros are only allowed in item, statement or expression position. That means while you may use this macro for referring to existing variables, functions or modules etc, you cannot define a new one with it.
所以在这种情况下不适用。但是,这并不意味着您不能使用 macro_rules,因为人们已经编写了带有可以连接标识符的 proc 宏的 crate。一个流行的例子是 paste.
但是,如果宏很复杂,您可能会发现它更容易理解并编写为 proc 宏。
另见 Is it possible to declare variables procedurally using Rust macros?。