Reputation: 13
For the code that passes the Rust borrow checker, we can get its MIR via
rustc filename --emit=mir
But for the code that can not pass the Rust borrow checker the same option doesn't work. For example, we can use the demo code from this blog: 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()
}
How to get the MIR for this code block? As I know, the MIR is used for borrow checking. Lifetime inference and loan set collection are based on MIR, so even if the code can not pass the borrow checking, the MIR should exist during the compile time.
I've just tried the rustc filename --emit
, and it failed. Maybe I need some deep hack for the Rust compiler?
Upvotes: 1
Views: 535
Reputation: 71430
Use the -Zdump-mir=<function_name>
option:
cargo +nightly rustc -- -Zdump-mir=last_or_push
This generates a mir_dump
directory with files for each stage of the MIR.
Upvotes: 1