__rust_force_expr是什么意思?

7

我在查看 Rust 中 vec![] 宏的实现时,注意到它使用了__rust_force_expr! 宏。这是后者的实现:

/// Force AST node to an expression to improve diagnostics in pattern position.
#[doc(hidden)]
#[macro_export]
#[unstable(feature = "liballoc_internals", issue = "none", reason = "implementation detail")]
macro_rules! __rust_force_expr {
    ($e:expr) => {
        $e
    };
}

有人能更详细地解释它到底是做什么的吗?

1个回答

7

这并不影响宏的使用方式,它只是用于在宏被错误使用时改善错误消息的质量,向编译器表明宏的输出始终是一个表达式,而不是一个项或多个表达式。

此更改旨在改善在模式匹配中使用vec![](无效的操作,您无法对Vec进行结构匹配)时产生的特定错误:

let x: Option<Vec<i32>> = Some(vec![]);
match x {
    Some(my_vec![]) => println!("1"),
    _ => println!("2"),
};

导致/造成

error[E0164]: expected tuple struct or tuple variant, found associated function `Vec::new`
  --> src/main.rs:9:9
   |
9  |         Vec::new()
   |         ^^^^^^^^^^ `fn` calls are not allowed in patterns
...
15 |     Some(my_vec![]) => println!("1"),
   |          --------- in this macro invocation
   |
   = help: for more information, visit https://doc.rust-lang.org/book/ch18-00-patterns.html
   = note: this error originates in the macro `mvec` (in Nightly builds, run with -Z macro-backtrace for more info)

这是一个相当令人困惑的错误,特别是在使用vec![1,2,3]语法时。看起来调用者中没有任何函数调用,但是通过将vec!的主体用__rust_force_expr包装,我们可以得到更好的错误提示:

error: arbitrary expressions aren't allowed in patterns
  --> src/main.rs:15:10
   |
15 |     Some(vec![]) => println!("1"),
   |          ^^^^^^
   |
   = note: this error originates in the macro `vec` (in Nightly builds, run with -Z macro-backtrace for more info)

这样就更加清晰易懂了:vec![] 生成了一个表达式,其中没有任何宏后面的函数调用引用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接