2022-08-15 06:51:45 -05:00
|
|
|
use hir::{DefWithBody, Semantics};
|
2020-12-28 12:29:58 -06:00
|
|
|
use ide_db::base_db::FilePosition;
|
|
|
|
use ide_db::RootDatabase;
|
2023-12-08 13:13:52 -06:00
|
|
|
use syntax::{algo::ancestors_at_offset, ast, AstNode};
|
2020-12-28 12:29:58 -06:00
|
|
|
|
2021-01-01 13:25:18 -06:00
|
|
|
// Feature: View Hir
|
2020-12-28 12:29:58 -06:00
|
|
|
//
|
|
|
|
// |===
|
|
|
|
// | Editor | Action Name
|
|
|
|
//
|
2022-08-01 06:47:09 -05:00
|
|
|
// | VS Code | **rust-analyzer: View Hir**
|
2020-12-28 12:29:58 -06:00
|
|
|
// |===
|
2021-03-30 18:08:10 -05:00
|
|
|
// image::https://user-images.githubusercontent.com/48062697/113065588-068bdb80-91b1-11eb-9a78-0b4ef1e972fb.gif[]
|
2020-12-28 12:29:58 -06:00
|
|
|
pub(crate) fn view_hir(db: &RootDatabase, position: FilePosition) -> String {
|
2021-02-16 09:55:34 -06:00
|
|
|
body_hir(db, position).unwrap_or_else(|| "Not inside a function body".to_string())
|
2020-12-28 12:29:58 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
fn body_hir(db: &RootDatabase, position: FilePosition) -> Option<String> {
|
|
|
|
let sema = Semantics::new(db);
|
|
|
|
let source_file = sema.parse(position.file_id);
|
|
|
|
|
2023-12-08 13:13:52 -06:00
|
|
|
let item = ancestors_at_offset(source_file.syntax(), position.offset)
|
|
|
|
.filter(|it| ast::MacroCall::can_cast(it.kind()))
|
|
|
|
.find_map(ast::Item::cast)?;
|
2022-08-15 06:51:45 -05:00
|
|
|
let def: DefWithBody = match item {
|
|
|
|
ast::Item::Fn(it) => sema.to_def(&it)?.into(),
|
|
|
|
ast::Item::Const(it) => sema.to_def(&it)?.into(),
|
|
|
|
ast::Item::Static(it) => sema.to_def(&it)?.into(),
|
|
|
|
_ => return None,
|
|
|
|
};
|
|
|
|
Some(def.debug_hir(db))
|
2021-01-01 13:25:18 -06:00
|
|
|
}
|