如何获取无法通过借用检查器的 rust 代码的 MIR?



对于通过Rust借用检查器的代码,我们可以通过

获取它的MIR
rustc filename --emit=mir

但是对于不能通过Rust借用检查器的代码,相同的选项不起作用。例如,我们可以使用这个博客中的演示代码:https://blog.rust-lang.org/2022/08/05/nll-by-default.html

fn last_or_push<'a>(vec: &'a mut Vec<String>) -> &'a String {
if let Some(s) = vec.last() { // borrows vec
// returning s here forces vec to be borrowed
// for the rest of the function, even though it
// shouldn't have to be
return s; 
}

// Because vec is borrowed, this call to vec.push gives
// an error!
vec.push("".to_string()); // ERROR
vec.last().unwrap()
}

如何获得这个代码块的MIR ?据我所知,MIR是用来检查借阅的。生命周期推断和借阅集合收集是基于MIR的,所以即使代码不能通过借阅检查,在编译时也应该存在MIR。

我刚刚尝试了rustc filename --emit,它失败了。也许我需要对Rust编译器进行一些深入的修改?

使用-Zdump-mir=<function_name>选项:

cargo +nightly rustc -- -Zdump-mir=last_or_push

生成一个mir_dump目录,其中包含MIR的每个阶段的文件。

最新更新