gpt4 book ai didi

macros - 为什么 Rust 找不到多语句宏中的变量?

转载 作者:行者123 更新时间:2023-11-29 07:54:35 28 4
gpt4 key购买 nike

我有一个在 unsafe block 中调用的宏,它具有以下模式:

( $mrb:expr, $sig:expr, $args:ident, $name:ident : $t:tt) => {
let $args = uninitialized::<*const MRValue>();
let count = uninitialized::<i32>();

mrb_get_args($mrb, $sig, args!($name, $t), &$args as *const *const MRValue,
&count as *const i32);
};

我用 --pretty expanded,hygiene 扩展了宏,这给了我:

let args /* 77#30 */ =
uninitialized /* 789#28
*/::<*const MRValue /* 793#28 */>();
let count /* 807#31 */ =
uninitialized /* 789#28 */::<i32 /* 68#28 */>();
mrb_get_args /* 805#28
*/(mrb /* 804#29 */, sig /* 797#29 */,
&v /* 76#33 */ as *const i32 /* 68#34 */,
&args /* 77#27 */ as
*const *const MRValue /* 793#28 */,
&count /* 807#28 */ as *const i32 /* 68#28 */);

args 似乎相同(77)并且计数也似乎相同(807),但我得到尽管如此,仍出现以下错误:

<mrusty macros>:24:20: 24:21 error: unresolved name `args`. Did you mean the macro `args!`? [E0425]
<mrusty macros>:24 mrb , sig , $ args , $ ( $ name : $ t ) , * ) ; conv ! (
^
<mrusty macros>:23:29: 24:48 note: in this expansion of args_rest! (defined in <mrusty macros>)
src/main.rs:12:47: 16:7 note: in this expansion of mrfn! (defined in <mrusty macros>)
<mrusty macros>:24:20: 24:21 help: run `rustc --explain E0425` to see a detailed explanation
<mrusty macros>:6:5: 6:10 error: unresolved name `count` [E0425]
<mrusty macros>:6 , & count as * const i32 ) ; } ; (
^~~~~
<mrusty macros>:23:29: 24:48 note: in this expansion of args_rest! (defined in <mrusty macros>)
src/main.rs:12:47: 16:7 note: in this expansion of mrfn! (defined in <mrusty macros>)
<mrusty macros>:6:5: 6:10 help: run `rustc --explain E0425` to see a detailed explanation

这看起来很可疑,而且它似乎是一个错误,但在我提交关于 Rust 的问题之前,我希望能有另一双眼睛检查一下。

最佳答案

试试这个:

( $mrb:expr, $sig:expr, $args:ident, $name:ident : $t:tt) => {{
let $args = uninitialized::<*const MRValue>();
let count = uninitialized::<i32>();

mrb_get_args($mrb, $sig, args!($name, $t), &$args as *const *const MRValue,
&count as *const i32);
}};

(注意宏展开的主体包裹在第二组大括号中)

我不记得你需要这个的确切原因,但基本思想是宏扩展 block 中的每个语句都用自己的卫生上下文扩展,因此 $args 在第一个line 与最后一行中的 $args 不同。但是,如果将所有语句放入一个 block 中,卫生上下文就会共享,并且 $args 的两个扩展现在都引用相同的标识符。所以,这可能不是一个错误;这就是 Rust 中宏扩展的工作原理。

关于macros - 为什么 Rust 找不到多语句宏中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36085618/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com