我正在尝试建立一个进行一些代码转换的宏,并且应该能够解析其自身的语法。这是我能想到的最简单的例子:
replace!(x, y, x * 100 + z) ~> y * 100 + z
Run Code Online (Sandbox Code Playgroud)
此宏应该能够用作为第三参数提供的表达式中的第二个标识符替换第一个标识符。宏应该对第三个参数的语言有所了解(在我的特定情况下,与示例相反,它不会在Rust中解析),并对其进行递归应用。
在Rust中构建此类宏的最有效方法是什么?我知道这种proc_macro方法和macro_rules!一种方法。但是我不确定是否macro_rules!足够强大来处理此问题,并且找不到如何使用来构建自己的转换的文档proc_macro。谁能指出我正确的方向?
我忘记指定参数的类型,错误消息如下:
error: expected one of `:` or `@`, found `)`
--> src/main.rs:2:12
|
2 | fn func(arg)
| ^ expected one of `:` or `@` here
Run Code Online (Sandbox Code Playgroud)
这就提出了一个问题:@符号可以做什么?我不记得阅读有关将@符号用于任何东西的信息。我也做了一些谷歌搜索,却找不到任何东西。怎么@办?
我在宏中调用宏,即
macro_rules! foo {
(yes) => {
true
};
() => {
false
};
}
macro_rules! baz {
() => {
[(); 0]
};
($args: tt) => {
$args
};
}
macro_rules! parse_rule {
($rule: tt, $args: tt, $newline: expr) => {
println!("The rule is {}, with args {:?}", $rule, $args);
if $newline {
println!()
}
};
}
macro_rules! bar {
($($rule: tt $([$($args: tt),*])? $($flag: ident)?);+) => {
$(parse_rule!($rule, baz!($([$($args),*])?), foo!($($flag)?)));+
}
}
fn main() {
bar!("hi" yes; "there" …Run Code Online (Sandbox Code Playgroud)