rust-analyzer/crates/ide/src/hover.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

404 lines
13 KiB
Rust
Raw Normal View History

2021-09-23 17:54:57 +00:00
mod render;
#[cfg(test)]
mod tests;
use std::iter;
use either::Either;
2021-09-23 17:54:57 +00:00
use hir::{HasSource, Semantics};
2020-08-13 14:39:16 +00:00
use ide_db::{
2021-09-23 17:54:57 +00:00
base_db::FileRange,
defs::{Definition, IdentClass, OperatorClass},
2022-03-06 18:01:30 +00:00
famous_defs::FamousDefs,
helpers::pick_best_token,
2021-11-18 11:34:33 +00:00
FxIndexSet, RootDatabase,
};
2020-08-13 14:39:16 +00:00
use itertools::Itertools;
2021-09-23 17:54:57 +00:00
use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxNode, SyntaxToken, T};
2019-01-08 19:33:36 +00:00
2019-05-30 17:46:43 +00:00
use crate::{
2021-09-23 17:54:57 +00:00
doc_links::token_as_doc_comment,
2020-07-08 20:37:35 +00:00
markup::Markup,
2021-01-10 11:24:01 +00:00
runnables::{runnable_fn, runnable_mod},
FileId, FilePosition, NavigationTarget, RangeInfo, Runnable, TryToNav,
2019-05-30 17:46:43 +00:00
};
2020-06-03 11:15:54 +00:00
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HoverConfig {
pub links_in_hover: bool,
pub documentation: Option<HoverDocFormat>,
2022-08-16 14:51:40 +00:00
pub keywords: bool,
}
impl HoverConfig {
fn markdown(&self) -> bool {
matches!(self.documentation, Some(HoverDocFormat::Markdown))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HoverDocFormat {
Markdown,
PlainText,
2020-06-03 11:15:54 +00:00
}
#[derive(Debug, Clone)]
pub enum HoverAction {
2020-06-06 11:30:29 +00:00
Runnable(Runnable),
2021-01-04 13:24:37 +00:00
Implementation(FilePosition),
2021-06-04 13:49:43 +00:00
Reference(FilePosition),
GoToType(Vec<HoverGotoTypeData>),
}
2021-08-11 11:39:36 +00:00
impl HoverAction {
fn goto_type_from_targets(db: &RootDatabase, targets: Vec<hir::ModuleDef>) -> Self {
let targets = targets
.into_iter()
.filter_map(|it| {
Some(HoverGotoTypeData {
2021-09-23 17:54:57 +00:00
mod_path: render::path(
2021-08-11 11:39:36 +00:00
db,
it.module(db)?,
it.name(db).map(|name| name.to_string()),
),
nav: it.try_to_nav(db)?,
})
})
.collect();
HoverAction::GoToType(targets)
}
}
2021-11-18 11:34:33 +00:00
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct HoverGotoTypeData {
pub mod_path: String,
pub nav: NavigationTarget,
2020-06-03 11:15:54 +00:00
}
/// Contains the results when hovering over an item
#[derive(Debug, Default)]
pub struct HoverResult {
2020-07-08 20:37:35 +00:00
pub markup: Markup,
pub actions: Vec<HoverAction>,
}
2021-07-27 21:50:26 +00:00
// Feature: Hover
//
// Shows additional information, like the type of an expression or the documentation for a definition when "focusing" code.
// Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
//
// image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
pub(crate) fn hover(
db: &RootDatabase,
2021-08-02 15:10:36 +00:00
FileRange { file_id, range }: FileRange,
config: &HoverConfig,
) -> Option<RangeInfo<HoverResult>> {
2021-09-23 13:37:52 +00:00
let sema = &hir::Semantics::new(db);
2021-08-02 15:10:36 +00:00
let file = sema.parse(file_id).syntax().clone();
2021-07-27 21:50:26 +00:00
if !range.is_empty() {
2021-10-16 11:32:55 +00:00
return hover_ranged(&file, range, sema, config);
}
let offset = range.start();
2021-07-27 21:50:26 +00:00
2021-09-22 15:05:54 +00:00
let original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] | T![Self] => 4,
// index and prefix ops
T!['['] | T![']'] | T![?] | T![*] | T![-] | T![!] => 3,
kind if kind.is_keyword() => 2,
T!['('] | T![')'] => 2,
kind if kind.is_trivia() => 0,
_ => 1,
})?;
if let Some(doc_comment) = token_as_doc_comment(&original_token) {
2021-09-23 13:37:52 +00:00
cov_mark::hit!(no_highlight_on_comment_hover);
return doc_comment.get_definition_with_descend_at(sema, offset, |def, node, range| {
2021-09-23 13:37:52 +00:00
let res = hover_for_definition(sema, file_id, def, &node, config)?;
Some(RangeInfo::new(range, res))
2021-09-23 13:37:52 +00:00
});
}
let in_attr = matches!(original_token.parent().and_then(ast::TokenTree::cast), Some(tt) if tt.syntax().ancestors().any(|it| ast::Meta::can_cast(it.kind())));
2022-08-15 14:16:59 +00:00
// prefer descending the same token kind in attribute expansions, in normal macros text
// equivalency is more important
let descended = if in_attr {
[sema.descend_into_macros_with_kind_preference(original_token.clone())].into()
} else {
sema.descend_into_macros_with_same_text(original_token.clone())
};
2021-09-23 13:37:52 +00:00
// FIXME: Definition should include known lints and the like instead of having this special case here
let hovered_lint = descended.iter().find_map(|token| {
2022-06-10 14:30:09 +00:00
let attr = token.parent_ancestors().find_map(ast::Attr::cast)?;
2021-10-16 11:32:55 +00:00
render::try_for_lint(&attr, token)
});
if let Some(res) = hovered_lint {
2021-09-23 17:54:57 +00:00
return Some(RangeInfo::new(original_token.text_range(), res));
2021-09-23 13:37:52 +00:00
}
let result = descended
.iter()
.filter_map(|token| {
let node = token.parent()?;
let class = IdentClass::classify_token(sema, token)?;
if let IdentClass::Operator(OperatorClass::Await(_)) = class {
// It's better for us to fall back to the keyword hover here,
// rendering poll is very confusing
return None;
}
Some(class.definitions().into_iter().zip(iter::once(node).cycle()))
2021-09-23 13:37:52 +00:00
})
.flatten()
.unique_by(|&(def, _)| def)
.filter_map(|(def, node)| hover_for_definition(sema, file_id, def, &node, config))
2021-11-18 11:34:33 +00:00
.reduce(|mut acc: HoverResult, HoverResult { markup, actions }| {
2021-09-23 13:37:52 +00:00
acc.actions.extend(actions);
acc.markup = Markup::from(format!("{}\n---\n{}", acc.markup, markup));
acc
});
2021-11-18 11:34:33 +00:00
2021-09-23 13:37:52 +00:00
if result.is_none() {
// fallbacks, show keywords or types
2022-03-12 12:04:13 +00:00
let res = descended.iter().find_map(|token| render::keyword(sema, config, token));
if let Some(res) = res {
2021-09-23 17:54:57 +00:00
return Some(RangeInfo::new(original_token.text_range(), res));
}
let res = descended
.iter()
.find_map(|token| hover_type_fallback(sema, config, token, &original_token));
2022-04-06 23:29:31 +00:00
if let Some(_) = res {
2021-09-23 13:37:52 +00:00
return res;
}
}
2021-11-18 11:34:33 +00:00
result.map(|mut res: HoverResult| {
res.actions = dedupe_or_merge_hover_actions(res.actions);
RangeInfo::new(original_token.text_range(), res)
})
}
2021-08-11 11:39:36 +00:00
2021-09-23 17:54:57 +00:00
pub(crate) fn hover_for_definition(
2022-07-20 13:02:08 +00:00
sema: &Semantics<'_, RootDatabase>,
2021-09-23 17:54:57 +00:00
file_id: FileId,
definition: Definition,
node: &SyntaxNode,
config: &HoverConfig,
2021-09-23 17:54:57 +00:00
) -> Option<HoverResult> {
let famous_defs = match &definition {
Definition::BuiltinType(_) => Some(FamousDefs(sema, sema.scope(node)?.krate())),
2021-09-23 17:54:57 +00:00
_ => None,
2020-07-09 07:39:53 +00:00
};
render::definition(sema.db, definition, famous_defs.as_ref(), config).map(|markup| {
HoverResult {
markup: render::process_markup(sema.db, definition, &markup, config),
actions: show_implementations_action(sema.db, definition)
.into_iter()
.chain(show_fn_references_action(sema.db, definition))
.chain(runnable_action(sema, definition, file_id))
.chain(goto_type_action_for_def(sema.db, definition))
.collect(),
2021-09-23 17:54:57 +00:00
}
})
}
2021-08-11 11:39:36 +00:00
fn hover_ranged(
file: &SyntaxNode,
range: syntax::TextRange,
2022-07-20 13:02:08 +00:00
sema: &Semantics<'_, RootDatabase>,
2021-08-11 11:39:36 +00:00
config: &HoverConfig,
) -> Option<RangeInfo<HoverResult>> {
// FIXME: make this work in attributes
let expr_or_pat = file.covering_element(range).ancestors().find_map(|it| {
2021-08-11 11:39:36 +00:00
match_ast! {
match it {
ast::Expr(expr) => Some(Either::Left(expr)),
ast::Pat(pat) => Some(Either::Right(pat)),
_ => None,
}
}
})?;
let res = match &expr_or_pat {
2021-09-23 17:54:57 +00:00
Either::Left(ast::Expr::TryExpr(try_expr)) => render::try_expr(sema, config, try_expr),
Either::Left(ast::Expr::PrefixExpr(prefix_expr))
if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
{
2021-09-23 17:54:57 +00:00
render::deref_expr(sema, config, prefix_expr)
}
_ => None,
};
2021-09-23 17:54:57 +00:00
let res = res.or_else(|| render::type_info(sema, config, &expr_or_pat));
res.map(|it| {
let range = match expr_or_pat {
2021-08-11 11:39:36 +00:00
Either::Left(it) => it.syntax().text_range(),
Either::Right(it) => it.syntax().text_range(),
};
RangeInfo::new(range, it)
})
}
2021-09-23 17:54:57 +00:00
fn hover_type_fallback(
2022-07-20 13:02:08 +00:00
sema: &Semantics<'_, RootDatabase>,
2021-08-02 15:10:36 +00:00
config: &HoverConfig,
2021-09-23 17:54:57 +00:00
token: &SyntaxToken,
original_token: &SyntaxToken,
2021-09-23 17:54:57 +00:00
) -> Option<RangeInfo<HoverResult>> {
2022-08-04 12:28:34 +00:00
let node =
token.parent_ancestors().take_while(|it| !ast::Item::can_cast(it.kind())).find(|n| {
ast::Expr::can_cast(n.kind())
|| ast::Pat::can_cast(n.kind())
|| ast::Type::can_cast(n.kind())
})?;
2021-08-02 15:10:36 +00:00
2021-09-23 17:54:57 +00:00
let expr_or_pat = match_ast! {
match node {
ast::Expr(it) => Either::Left(it),
ast::Pat(it) => Either::Right(it),
// If this node is a MACRO_CALL, it means that `descend_into_macros_many` failed to resolve.
// (e.g expanding a builtin macro). So we give up here.
ast::MacroCall(_it) => return None,
_ => return None,
2021-06-04 15:03:18 +00:00
}
2021-06-04 16:35:19 +00:00
};
2021-10-16 11:32:55 +00:00
let res = render::type_info(sema, config, &expr_or_pat)?;
let range = sema
.original_range_opt(&node)
.map(|frange| frange.range)
.unwrap_or_else(|| original_token.text_range());
2021-09-23 17:54:57 +00:00
Some(RangeInfo::new(range, res))
2021-06-04 15:03:18 +00:00
}
2020-06-03 11:15:54 +00:00
fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
fn to_action(nav_target: NavigationTarget) -> HoverAction {
2021-01-04 13:24:37 +00:00
HoverAction::Implementation(FilePosition {
2020-07-17 10:42:48 +00:00
file_id: nav_target.file_id,
offset: nav_target.focus_or_full_range().start(),
2020-06-03 11:15:54 +00:00
})
}
let adt = match def {
Definition::Trait(it) => return it.try_to_nav(db).map(to_action),
Definition::Adt(it) => Some(it),
2021-03-29 15:46:33 +00:00
Definition::SelfType(it) => it.self_ty(db).as_adt(),
2020-06-03 11:15:54 +00:00
_ => None,
}?;
2021-01-09 15:59:00 +00:00
adt.try_to_nav(db).map(to_action)
2020-06-03 11:15:54 +00:00
}
2021-06-04 13:49:43 +00:00
fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
match def {
Definition::Function(it) => it.try_to_nav(db).map(|nav_target| {
HoverAction::Reference(FilePosition {
file_id: nav_target.file_id,
offset: nav_target.focus_or_full_range().start(),
2021-06-04 13:49:43 +00:00
})
}),
2021-06-04 13:49:43 +00:00
_ => None,
}
}
2020-06-06 11:30:29 +00:00
fn runnable_action(
2022-07-20 13:02:08 +00:00
sema: &hir::Semantics<'_, RootDatabase>,
2020-06-06 11:30:29 +00:00
def: Definition,
file_id: FileId,
) -> Option<HoverAction> {
match def {
Definition::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
Definition::Function(func) => {
let src = func.source(sema.db)?;
if src.file_id != file_id.into() {
cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
return None;
2020-06-06 11:30:29 +00:00
}
runnable_fn(sema, func).map(HoverAction::Runnable)
}
2020-06-06 11:30:29 +00:00
_ => None,
}
}
2021-08-11 11:39:36 +00:00
fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
let mut targets: Vec<hir::ModuleDef> = Vec::new();
let mut push_new_def = |item: hir::ModuleDef| {
2021-01-04 14:19:09 +00:00
if !targets.contains(&item) {
targets.push(item);
}
};
2020-06-11 17:17:32 +00:00
if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
2021-01-04 14:44:19 +00:00
it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
} else {
let ty = match def {
Definition::Local(it) => it.ty(db),
Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
Definition::Field(field) => field.ty(db),
Definition::Function(function) => function.ret_type(db),
2021-01-04 14:44:19 +00:00
_ => return None,
};
2021-08-11 11:39:36 +00:00
walk_and_push_ty(db, &ty, &mut push_new_def);
2021-01-04 14:44:19 +00:00
}
2021-01-04 14:19:09 +00:00
2021-08-11 11:39:36 +00:00
Some(HoverAction::goto_type_from_targets(db, targets))
}
2021-01-04 14:19:09 +00:00
2021-08-11 11:39:36 +00:00
fn walk_and_push_ty(
db: &RootDatabase,
ty: &hir::Type,
push_new_def: &mut dyn FnMut(hir::ModuleDef),
) {
ty.walk(db, |t| {
if let Some(adt) = t.as_adt() {
push_new_def(adt.into());
} else if let Some(trait_) = t.as_dyn_trait() {
push_new_def(trait_.into());
} else if let Some(traits) = t.as_impl_traits(db) {
traits.for_each(|it| push_new_def(it.into()));
2021-08-11 11:39:36 +00:00
} else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
push_new_def(trait_.into());
}
});
}
2021-11-18 11:34:33 +00:00
fn dedupe_or_merge_hover_actions(actions: Vec<HoverAction>) -> Vec<HoverAction> {
let mut deduped_actions = Vec::with_capacity(actions.len());
let mut go_to_type_targets = FxIndexSet::default();
let mut seen_implementation = false;
let mut seen_reference = false;
let mut seen_runnable = false;
for action in actions {
match action {
HoverAction::GoToType(targets) => {
go_to_type_targets.extend(targets);
}
HoverAction::Implementation(..) => {
if !seen_implementation {
seen_implementation = true;
deduped_actions.push(action);
}
}
HoverAction::Reference(..) => {
if !seen_reference {
seen_reference = true;
deduped_actions.push(action);
}
}
HoverAction::Runnable(..) => {
if !seen_runnable {
seen_runnable = true;
deduped_actions.push(action);
}
}
};
}
if !go_to_type_targets.is_empty() {
deduped_actions.push(HoverAction::GoToType(go_to_type_targets.into_iter().collect()));
}
deduped_actions
}