ide/
view_mir.rs

1use hir::{DefWithBody, Semantics};
2use ide_db::{FilePosition, RootDatabase};
3use syntax::{AstNode, algo::ancestors_at_offset, ast};
4
5// Feature: View Mir
6//
7// | Editor  | Action Name |
8// |---------|-------------|
9// | VS Code | **rust-analyzer: View Mir**
10pub(crate) fn view_mir(db: &RootDatabase, position: FilePosition) -> String {
11    body_mir(db, position).unwrap_or_else(|| "Not inside a function body".to_owned())
12}
13
14fn body_mir(db: &RootDatabase, position: FilePosition) -> Option<String> {
15    let sema = Semantics::new(db);
16    let source_file = sema.parse_guess_edition(position.file_id);
17
18    let item = ancestors_at_offset(source_file.syntax(), position.offset)
19        .filter(|it| !ast::MacroCall::can_cast(it.kind()))
20        .find_map(ast::Item::cast)?;
21    let def: DefWithBody = match item {
22        ast::Item::Fn(it) => sema.to_def(&it)?.into(),
23        ast::Item::Const(it) => sema.to_def(&it)?.into(),
24        ast::Item::Static(it) => sema.to_def(&it)?.into(),
25        _ => return None,
26    };
27    Some(def.debug_mir(db))
28}