9 use hir::{HasSource, Semantics};
13 helpers::{pick_best_token, FamousDefs},
16 use itertools::Itertools;
17 use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxNode, SyntaxToken, T};
21 doc_links::token_as_doc_comment,
23 runnables::{runnable_fn, runnable_mod},
24 FileId, FilePosition, NavigationTarget, RangeInfo, Runnable,
27 #[derive(Clone, Debug, PartialEq, Eq)]
28 pub struct HoverConfig {
29 pub links_in_hover: bool,
30 pub documentation: Option<HoverDocFormat>,
34 fn markdown(&self) -> bool {
35 matches!(self.documentation, Some(HoverDocFormat::Markdown))
39 #[derive(Clone, Debug, PartialEq, Eq)]
40 pub enum HoverDocFormat {
45 #[derive(Debug, Clone)]
46 pub enum HoverAction {
48 Implementation(FilePosition),
49 Reference(FilePosition),
50 GoToType(Vec<HoverGotoTypeData>),
54 fn goto_type_from_targets(db: &RootDatabase, targets: Vec<hir::ModuleDef>) -> Self {
58 Some(HoverGotoTypeData {
59 mod_path: render::path(
62 it.name(db).map(|name| name.to_string()),
64 nav: it.try_to_nav(db)?,
68 HoverAction::GoToType(targets)
72 #[derive(Debug, Clone, Eq, PartialEq)]
73 pub struct HoverGotoTypeData {
75 pub nav: NavigationTarget,
78 /// Contains the results when hovering over an item
79 #[derive(Debug, Default)]
80 pub struct HoverResult {
82 pub actions: Vec<HoverAction>,
87 // Shows additional information, like the type of an expression or the documentation for a definition when "focusing" code.
88 // Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
90 // image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
93 FileRange { file_id, range }: FileRange,
95 ) -> Option<RangeInfo<HoverResult>> {
96 let sema = &hir::Semantics::new(db);
97 let file = sema.parse(file_id).syntax().clone();
99 if !range.is_empty() {
100 return hover_ranged(&file, range, sema, config);
102 let offset = range.start();
104 let original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
105 IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] => 3,
106 T!['('] | T![')'] => 2,
107 kind if kind.is_trivia() => 0,
111 if let Some(doc_comment) = token_as_doc_comment(&original_token) {
112 cov_mark::hit!(no_highlight_on_comment_hover);
113 return doc_comment.get_definition_with_descend_at(sema, offset, |def, node, range| {
114 let res = hover_for_definition(sema, file_id, def, &node, config)?;
115 Some(RangeInfo::new(range, res))
119 let descended = sema.descend_into_macros(original_token.clone());
121 // FIXME: Definition should include known lints and the like instead of having this special case here
122 if let Some(res) = descended.iter().find_map(|token| {
123 let attr = token.ancestors().find_map(ast::Attr::cast)?;
124 render::try_for_lint(&attr, token)
126 return Some(RangeInfo::new(original_token.text_range(), res));
129 let result = descended
131 .filter_map(|token| {
132 let node = token.parent()?;
133 let defs = Definition::from_token(sema, token);
134 Some(defs.into_iter().zip(iter::once(node).cycle()))
137 .unique_by(|&(def, _)| def)
138 .filter_map(|(def, node)| hover_for_definition(sema, file_id, def, &node, config))
139 .reduce(|mut acc, HoverResult { markup, actions }| {
140 acc.actions.extend(actions);
141 acc.markup = Markup::from(format!("{}\n---\n{}", acc.markup, markup));
144 if result.is_none() {
145 // fallbacks, show keywords or types
146 if let Some(res) = render::keyword(sema, config, &original_token) {
147 return Some(RangeInfo::new(original_token.text_range(), res));
149 if let res @ Some(_) =
150 descended.iter().find_map(|token| hover_type_fallback(sema, config, token))
155 result.map(|res| RangeInfo::new(original_token.text_range(), res))
158 pub(crate) fn hover_for_definition(
159 sema: &Semantics<RootDatabase>,
161 definition: Definition,
163 config: &HoverConfig,
164 ) -> Option<HoverResult> {
165 let famous_defs = match &definition {
166 Definition::ModuleDef(hir::ModuleDef::BuiltinType(_)) => {
167 Some(FamousDefs(sema, sema.scope(node).krate()))
171 if let Some(markup) = render::definition(sema.db, definition, famous_defs.as_ref(), config) {
172 let mut res = HoverResult::default();
173 res.markup = render::process_markup(sema.db, definition, &markup, config);
174 if let Some(action) = show_implementations_action(sema.db, definition) {
175 res.actions.push(action);
178 if let Some(action) = show_fn_references_action(sema.db, definition) {
179 res.actions.push(action);
182 if let Some(action) = runnable_action(sema, definition, file_id) {
183 res.actions.push(action);
186 if let Some(action) = goto_type_action_for_def(sema.db, definition) {
187 res.actions.push(action);
196 range: syntax::TextRange,
197 sema: &Semantics<RootDatabase>,
198 config: &HoverConfig,
199 ) -> Option<RangeInfo<HoverResult>> {
200 let expr_or_pat = file.covering_element(range).ancestors().find_map(|it| {
203 ast::Expr(expr) => Some(Either::Left(expr)),
204 ast::Pat(pat) => Some(Either::Right(pat)),
209 let res = match &expr_or_pat {
210 Either::Left(ast::Expr::TryExpr(try_expr)) => render::try_expr(sema, config, try_expr),
211 Either::Left(ast::Expr::PrefixExpr(prefix_expr))
212 if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
214 render::deref_expr(sema, config, prefix_expr)
218 let res = res.or_else(|| render::type_info(sema, config, &expr_or_pat));
220 let range = match expr_or_pat {
221 Either::Left(it) => it.syntax().text_range(),
222 Either::Right(it) => it.syntax().text_range(),
224 RangeInfo::new(range, it)
228 fn hover_type_fallback(
229 sema: &Semantics<RootDatabase>,
230 config: &HoverConfig,
232 ) -> Option<RangeInfo<HoverResult>> {
235 .take_while(|it| !ast::Item::can_cast(it.kind()))
236 .find(|n| ast::Expr::can_cast(n.kind()) || ast::Pat::can_cast(n.kind()))?;
238 let expr_or_pat = match_ast! {
240 ast::Expr(it) => Either::Left(it),
241 ast::Pat(it) => Either::Right(it),
242 // If this node is a MACRO_CALL, it means that `descend_into_macros_many` failed to resolve.
243 // (e.g expanding a builtin macro). So we give up here.
244 ast::MacroCall(_it) => return None,
249 let res = render::type_info(sema, config, &expr_or_pat)?;
250 let range = sema.original_range(&node).range;
251 Some(RangeInfo::new(range, res))
254 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
255 fn to_action(nav_target: NavigationTarget) -> HoverAction {
256 HoverAction::Implementation(FilePosition {
257 file_id: nav_target.file_id,
258 offset: nav_target.focus_or_full_range().start(),
262 let adt = match def {
263 Definition::ModuleDef(hir::ModuleDef::Trait(it)) => {
264 return it.try_to_nav(db).map(to_action)
266 Definition::ModuleDef(hir::ModuleDef::Adt(it)) => Some(it),
267 Definition::SelfType(it) => it.self_ty(db).as_adt(),
270 adt.try_to_nav(db).map(to_action)
273 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
275 Definition::ModuleDef(hir::ModuleDef::Function(it)) => {
276 it.try_to_nav(db).map(|nav_target| {
277 HoverAction::Reference(FilePosition {
278 file_id: nav_target.file_id,
279 offset: nav_target.focus_or_full_range().start(),
288 sema: &hir::Semantics<RootDatabase>,
291 ) -> Option<HoverAction> {
293 Definition::ModuleDef(it) => match it {
294 hir::ModuleDef::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
295 hir::ModuleDef::Function(func) => {
296 let src = func.source(sema.db)?;
297 if src.file_id != file_id.into() {
298 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
299 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
303 runnable_fn(sema, func).map(HoverAction::Runnable)
311 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
312 let mut targets: Vec<hir::ModuleDef> = Vec::new();
313 let mut push_new_def = |item: hir::ModuleDef| {
314 if !targets.contains(&item) {
319 if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
320 it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
323 Definition::Local(it) => it.ty(db),
324 Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
325 Definition::Field(field) => field.ty(db),
329 walk_and_push_ty(db, &ty, &mut push_new_def);
332 Some(HoverAction::goto_type_from_targets(db, targets))
338 push_new_def: &mut dyn FnMut(hir::ModuleDef),
341 if let Some(adt) = t.as_adt() {
342 push_new_def(adt.into());
343 } else if let Some(trait_) = t.as_dyn_trait() {
344 push_new_def(trait_.into());
345 } else if let Some(traits) = t.as_impl_traits(db) {
346 traits.into_iter().for_each(|it| push_new_def(it.into()));
347 } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
348 push_new_def(trait_.into());