plugins - 如何从 ConstVal 中取出一个元组?

标签 plugins rust internals

对于当前的夜间事件,可以使用 rustc::middle::const_eval_partial(..)得到 Result<ConstVal, _> .然而,那个ConstValTuple { 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!()
}

fieldsVec<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/

相关文章:

c - VxWorks中任务阻塞时,栈中保存的任务上下文是什么?

javascript - Grafana,使用外部库开发插件

rust - 如何在不冒犯借用检查器的情况下进行计算状态转换?

git - Git checkout 的幕后发生了什么?

rust - 为什么在.map 中执行的闭包不会改变捕获的值?

closures - 有什么方法可以装箱和移动关闭吗?

perl - Perl 的词法范围的编译指示是如何实现的?

c++ - 将外部应用程序与我的应用程序集成

perl - 为什么我的 perl Catalyst redirect_and_detach 替换插件方法失败?

Eclipse StarTeam 插件?