rust/crates/ide/src/hover.rs

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

425 lines
14 KiB
Rust
Raw Normal View History

2021-09-23 12:54:57 -05:00
mod render;
#[cfg(test)]
mod tests;
use std::iter;
use either::Either;
2021-09-23 12:54:57 -05:00
use hir::{HasSource, Semantics};
2020-08-13 09:39:16 -05:00
use ide_db::{
2021-09-23 12:54:57 -05:00
base_db::FileRange,
defs::{Definition, IdentClass, OperatorClass},
2022-03-06 12:01:30 -06:00
famous_defs::FamousDefs,
helpers::pick_best_token,
2021-11-18 05:34:33 -06:00
FxIndexSet, RootDatabase,
};
2020-08-13 09:39:16 -05:00
use itertools::Itertools;
2021-09-23 12:54:57 -05:00
use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxNode, SyntaxToken, T};
2019-01-08 13:33:36 -06:00
2019-05-30 12:46:43 -05:00
use crate::{
2021-09-23 12:54:57 -05:00
doc_links::token_as_doc_comment,
2020-07-08 15:37:35 -05:00
markup::Markup,
2021-01-10 05:24:01 -06:00
runnables::{runnable_fn, runnable_mod},
FileId, FilePosition, NavigationTarget, RangeInfo, Runnable, TryToNav,
2019-05-30 12:46:43 -05:00
};
2020-06-03 06:15:54 -05:00
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HoverConfig {
pub links_in_hover: bool,
pub documentation: Option<HoverDocFormat>,
2022-08-16 09:51:40 -05: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 06:15:54 -05:00
}
#[derive(Debug, Clone)]
pub enum HoverAction {
2020-06-06 06:30:29 -05:00
Runnable(Runnable),
2021-01-04 07:24:37 -06:00
Implementation(FilePosition),
2021-06-04 08:49:43 -05:00
Reference(FilePosition),
GoToType(Vec<HoverGotoTypeData>),
}
2021-08-11 06:39:36 -05: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 12:54:57 -05:00
mod_path: render::path(
2021-08-11 06:39:36 -05: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 05:34:33 -06:00
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct HoverGotoTypeData {
pub mod_path: String,
pub nav: NavigationTarget,
2020-06-03 06:15:54 -05:00
}
/// Contains the results when hovering over an item
#[derive(Debug, Default)]
pub struct HoverResult {
2020-07-08 15:37:35 -05:00
pub markup: Markup,
pub actions: Vec<HoverAction>,
}
2021-07-27 16:50:26 -05: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.
//
2022-11-25 00:33:49 -06:00
// image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
pub(crate) fn hover(
db: &RootDatabase,
2021-08-02 10:10:36 -05:00
FileRange { file_id, range }: FileRange,
config: &HoverConfig,
) -> Option<RangeInfo<HoverResult>> {
2021-09-23 08:37:52 -05:00
let sema = &hir::Semantics::new(db);
2021-08-02 10:10:36 -05:00
let file = sema.parse(file_id).syntax().clone();
2021-07-27 16:50:26 -05:00
if !range.is_empty() {
2021-10-16 06:32:55 -05:00
return hover_ranged(&file, range, sema, config);
}
let offset = range.start();
2021-07-27 16:50:26 -05:00
2021-09-22 10:05:54 -05: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 08:37:52 -05: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 08:37:52 -05:00
let res = hover_for_definition(sema, file_id, def, &node, config)?;
Some(RangeInfo::new(range, res))
2021-09-23 08:37:52 -05:00
});
}
let in_attr = original_token
.parent_ancestors()
.filter_map(ast::Item::cast)
.any(|item| sema.is_attr_macro_call(&item))
&& !matches!(
original_token.parent().and_then(ast::TokenTree::cast),
Some(tt) if tt.syntax().ancestors().any(|it| ast::Meta::can_cast(it.kind()))
);
2022-11-19 09:53:33 -06:00
2022-08-15 09:16:59 -05: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 08:37:52 -05:00
// try lint hover
2021-09-23 08:37:52 -05:00
let result = descended
.iter()
.find_map(|token| {
// FIXME: Definition should include known lints and the like instead of having this special case here
let attr = token.parent_ancestors().find_map(ast::Attr::cast)?;
render::try_for_lint(&attr, token)
2021-09-23 08:37:52 -05:00
})
// try item definitions
.or_else(|| {
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()))
})
.flatten()
.unique_by(|&(def, _)| def)
.filter_map(|(def, node)| hover_for_definition(sema, file_id, def, &node, config))
.reduce(|mut acc: HoverResult, HoverResult { markup, actions }| {
acc.actions.extend(actions);
acc.markup = Markup::from(format!("{}\n---\n{}", acc.markup, markup));
acc
})
})
// try keywords
2022-11-19 09:53:33 -06:00
.or_else(|| descended.iter().find_map(|token| render::keyword(sema, config, token)))
// try rest item hover
.or_else(|| {
descended.iter().find_map(|token| {
if token.kind() != DOT2 {
return None;
}
2021-11-18 05:34:33 -06:00
let rest_pat = token.syntax().parent().and_then(ast::RestPat::cast)?;
let record_pat_field_list = rest_pat.syntax().parent().and_then(ast::RecordPatFieldList::cast)?;
let record_pat =
record_pat_field_list.syntax().parent().and_then(ast::RecordPat::cast)?;
Some(render::struct_rest_pat(sema, config, &record_pat))
})
});
result
.map(|mut res: HoverResult| {
res.actions = dedupe_or_merge_hover_actions(res.actions);
RangeInfo::new(original_token.text_range(), res)
})
// fallback to type hover if there aren't any other suggestions
// this finds its own range instead of using the closest token's range
.or_else(|| {
descended.iter().find_map(|token| hover_type_fallback(sema, config, token, &token))
})
}
2021-08-11 06:39:36 -05:00
2021-09-23 12:54:57 -05:00
pub(crate) fn hover_for_definition(
2022-07-20 08:02:08 -05:00
sema: &Semantics<'_, RootDatabase>,
2021-09-23 12:54:57 -05:00
file_id: FileId,
definition: Definition,
node: &SyntaxNode,
config: &HoverConfig,
2021-09-23 12:54:57 -05:00
) -> Option<HoverResult> {
let famous_defs = match &definition {
Definition::BuiltinType(_) => Some(FamousDefs(sema, sema.scope(node)?.krate())),
2021-09-23 12:54:57 -05:00
_ => None,
2020-07-09 02:39:53 -05: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 12:54:57 -05:00
}
})
}
2021-08-11 06:39:36 -05:00
fn hover_ranged(
file: &SyntaxNode,
range: syntax::TextRange,
2022-07-20 08:02:08 -05:00
sema: &Semantics<'_, RootDatabase>,
2021-08-11 06:39:36 -05: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 06:39:36 -05: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 12:54:57 -05: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 12:54:57 -05:00
render::deref_expr(sema, config, prefix_expr)
}
_ => None,
};
2021-09-23 12:54:57 -05: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 06:39:36 -05:00
Either::Left(it) => it.syntax().text_range(),
Either::Right(it) => it.syntax().text_range(),
};
RangeInfo::new(range, it)
})
}
2021-09-23 12:54:57 -05:00
fn hover_type_fallback(
2022-07-20 08:02:08 -05:00
sema: &Semantics<'_, RootDatabase>,
2021-08-02 10:10:36 -05:00
config: &HoverConfig,
2021-09-23 12:54:57 -05:00
token: &SyntaxToken,
original_token: &SyntaxToken,
2021-09-23 12:54:57 -05:00
) -> Option<RangeInfo<HoverResult>> {
2022-08-04 07:28:34 -05: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 10:10:36 -05:00
2021-09-23 12:54:57 -05: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 10:03:18 -05:00
}
2021-06-04 11:35:19 -05: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 12:54:57 -05:00
Some(RangeInfo::new(range, res))
2021-06-04 10:03:18 -05:00
}
2020-06-03 06:15:54 -05:00
fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
fn to_action(nav_target: NavigationTarget) -> HoverAction {
2021-01-04 07:24:37 -06:00
HoverAction::Implementation(FilePosition {
2020-07-17 05:42:48 -05:00
file_id: nav_target.file_id,
offset: nav_target.focus_or_full_range().start(),
2020-06-03 06:15:54 -05: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 10:46:33 -05:00
Definition::SelfType(it) => it.self_ty(db).as_adt(),
2020-06-03 06:15:54 -05:00
_ => None,
}?;
2021-01-09 09:59:00 -06:00
adt.try_to_nav(db).map(to_action)
2020-06-03 06:15:54 -05:00
}
2021-06-04 08:49:43 -05: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 08:49:43 -05:00
})
}),
2021-06-04 08:49:43 -05:00
_ => None,
}
}
2020-06-06 06:30:29 -05:00
fn runnable_action(
2022-07-20 08:02:08 -05:00
sema: &hir::Semantics<'_, RootDatabase>,
2020-06-06 06:30:29 -05: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 06:30:29 -05:00
}
runnable_fn(sema, func).map(HoverAction::Runnable)
}
2020-06-06 06:30:29 -05:00
_ => None,
}
}
2021-08-11 06:39:36 -05: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 08:19:09 -06:00
if !targets.contains(&item) {
targets.push(item);
}
};
2020-06-11 12:17:32 -05:00
if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
2021-01-04 08:44:19 -06: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 08:44:19 -06:00
_ => return None,
};
2021-08-11 06:39:36 -05:00
walk_and_push_ty(db, &ty, &mut push_new_def);
2021-01-04 08:44:19 -06:00
}
2021-01-04 08:19:09 -06:00
2021-08-11 06:39:36 -05:00
Some(HoverAction::goto_type_from_targets(db, targets))
}
2021-01-04 08:19:09 -06:00
2021-08-11 06:39:36 -05: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 06:39:36 -05:00
} else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
push_new_def(trait_.into());
}
});
}
2021-11-18 05:34:33 -06: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
}