对于当前的夜间事件,可以使用 rustc::middle::const_eval_partial(..)
得到 Result<ConstVal, _>
.然而,那个ConstVal
是 Tuple { node: NodeId }
对于元组值。我怎样才能得到这个元组的内容?
示例代码(此处是用作编译器插件的最小 lint):
use rustc::lint::*;
use syntax::ptr::P;
use rustc_front::hir::*;
use rustc::middle::const_eval::ConstVal::Tuple;
use rustc::middle::const_eval::eval_const_expr_partial;
use rustc::middle::const_eval::EvalHint::ExprTypeChecked;
declare_lint! { pub TEST_LINT, Warn, "Just a test, ignore this" }
#[derive(Copy,Clone)]
pub struct TestLint;
impl LintPass for TestLint {
fn get_lints(&self) -> LintArray {
lint_array!TEST_LINT)
}
}
impl LateLintPass for BitMask {
fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
let res = eval_const_expr_partial(cx.tcx, expr, ExprTypeChecked, None);
if let Ok(Tuple(node_id))) = res {
// ... how to get the parts of the tuple?
}
}
}
最佳答案
如果您查看 ExprTupField
的常量评估代码表达式(索引到元组),你可以看到如何提取特定字段:
if let hir::ExprTup(ref fields) = tcx.map.expect_expr(tup_id).node {
if index.node < fields.len() {
return eval_const_expr_partial(tcx, &fields[index.node], base_hint, fn_args)
} else {
signal!(e, TupleIndexOutOfBounds);
}
} else {
unreachable!()
}
fields
是 Vec<P<Expr>>
.所以你可以遍历 Vec
并调用eval_const_expr_partial
在上面获得 ConstVal
元组字段。
请注意,如果元组是在 const fn
中创建的,您将会遇到麻烦。 : https://github.com/rust-lang/rust/issues/29928
关于plugins - 如何从 ConstVal 中取出一个元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33960186/