]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/hover.rs
Merge #10809
[rust.git] / crates / ide / src / hover.rs
1 mod render;
2
3 #[cfg(test)]
4 mod tests;
5
6 use std::iter;
7
8 use either::Either;
9 use hir::{HasSource, Semantics};
10 use ide_db::{
11     base_db::FileRange,
12     defs::Definition,
13     helpers::{pick_best_token, FamousDefs},
14     FxIndexSet, RootDatabase,
15 };
16 use itertools::Itertools;
17 use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxNode, SyntaxToken, T};
18
19 use crate::{
20     doc_links::token_as_doc_comment,
21     markup::Markup,
22     runnables::{runnable_fn, runnable_mod},
23     FileId, FilePosition, NavigationTarget, RangeInfo, Runnable, TryToNav,
24 };
25
26 #[derive(Clone, Debug, PartialEq, Eq)]
27 pub struct HoverConfig {
28     pub links_in_hover: bool,
29     pub documentation: Option<HoverDocFormat>,
30 }
31
32 impl HoverConfig {
33     fn markdown(&self) -> bool {
34         matches!(self.documentation, Some(HoverDocFormat::Markdown))
35     }
36 }
37
38 #[derive(Clone, Debug, PartialEq, Eq)]
39 pub enum HoverDocFormat {
40     Markdown,
41     PlainText,
42 }
43
44 #[derive(Debug, Clone)]
45 pub enum HoverAction {
46     Runnable(Runnable),
47     Implementation(FilePosition),
48     Reference(FilePosition),
49     GoToType(Vec<HoverGotoTypeData>),
50 }
51
52 impl HoverAction {
53     fn goto_type_from_targets(db: &RootDatabase, targets: Vec<hir::ModuleDef>) -> Self {
54         let targets = targets
55             .into_iter()
56             .filter_map(|it| {
57                 Some(HoverGotoTypeData {
58                     mod_path: render::path(
59                         db,
60                         it.module(db)?,
61                         it.name(db).map(|name| name.to_string()),
62                     ),
63                     nav: it.try_to_nav(db)?,
64                 })
65             })
66             .collect();
67         HoverAction::GoToType(targets)
68     }
69 }
70
71 #[derive(Debug, Clone, Eq, PartialEq, Hash)]
72 pub struct HoverGotoTypeData {
73     pub mod_path: String,
74     pub nav: NavigationTarget,
75 }
76
77 /// Contains the results when hovering over an item
78 #[derive(Debug, Default)]
79 pub struct HoverResult {
80     pub markup: Markup,
81     pub actions: Vec<HoverAction>,
82 }
83
84 // Feature: Hover
85 //
86 // Shows additional information, like the type of an expression or the documentation for a definition when "focusing" code.
87 // Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.
88 //
89 // image::https://user-images.githubusercontent.com/48062697/113020658-b5f98b80-917a-11eb-9f88-3dbc27320c95.gif[]
90 pub(crate) fn hover(
91     db: &RootDatabase,
92     FileRange { file_id, range }: FileRange,
93     config: &HoverConfig,
94 ) -> Option<RangeInfo<HoverResult>> {
95     let sema = &hir::Semantics::new(db);
96     let file = sema.parse(file_id).syntax().clone();
97
98     if !range.is_empty() {
99         return hover_ranged(&file, range, sema, config);
100     }
101     let offset = range.start();
102
103     let original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
104         IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] => 3,
105         T!['('] | T![')'] => 2,
106         kind if kind.is_trivia() => 0,
107         _ => 1,
108     })?;
109
110     if let Some(doc_comment) = token_as_doc_comment(&original_token) {
111         cov_mark::hit!(no_highlight_on_comment_hover);
112         return doc_comment.get_definition_with_descend_at(sema, offset, |def, node, range| {
113             let res = hover_for_definition(sema, file_id, def, &node, config)?;
114             Some(RangeInfo::new(range, res))
115         });
116     }
117
118     let descended = sema.descend_into_macros(original_token.clone());
119
120     // FIXME: Definition should include known lints and the like instead of having this special case here
121     if let Some(res) = descended.iter().find_map(|token| {
122         let attr = token.ancestors().find_map(ast::Attr::cast)?;
123         render::try_for_lint(&attr, token)
124     }) {
125         return Some(RangeInfo::new(original_token.text_range(), res));
126     }
127
128     let result = descended
129         .iter()
130         .filter_map(|token| {
131             let node = token.parent()?;
132             let defs = Definition::from_token(sema, token);
133             Some(defs.into_iter().zip(iter::once(node).cycle()))
134         })
135         .flatten()
136         .unique_by(|&(def, _)| def)
137         .filter_map(|(def, node)| hover_for_definition(sema, file_id, def, &node, config))
138         .reduce(|mut acc: HoverResult, HoverResult { markup, actions }| {
139             acc.actions.extend(actions);
140             acc.markup = Markup::from(format!("{}\n---\n{}", acc.markup, markup));
141             acc
142         });
143
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));
148         }
149         if let res @ Some(_) =
150             descended.iter().find_map(|token| hover_type_fallback(sema, config, token))
151         {
152             return res;
153         }
154     }
155     result.map(|mut res: HoverResult| {
156         res.actions = dedupe_or_merge_hover_actions(res.actions);
157         RangeInfo::new(original_token.text_range(), res)
158     })
159 }
160
161 pub(crate) fn hover_for_definition(
162     sema: &Semantics<RootDatabase>,
163     file_id: FileId,
164     definition: Definition,
165     node: &SyntaxNode,
166     config: &HoverConfig,
167 ) -> Option<HoverResult> {
168     let famous_defs = match &definition {
169         Definition::BuiltinType(_) => Some(FamousDefs(sema, sema.scope(node).krate())),
170         _ => None,
171     };
172     if let Some(markup) = render::definition(sema.db, definition, famous_defs.as_ref(), config) {
173         let mut res = HoverResult::default();
174         res.markup = render::process_markup(sema.db, definition, &markup, config);
175         if let Some(action) = show_implementations_action(sema.db, definition) {
176             res.actions.push(action);
177         }
178
179         if let Some(action) = show_fn_references_action(sema.db, definition) {
180             res.actions.push(action);
181         }
182
183         if let Some(action) = runnable_action(sema, definition, file_id) {
184             res.actions.push(action);
185         }
186
187         if let Some(action) = goto_type_action_for_def(sema.db, definition) {
188             res.actions.push(action);
189         }
190         return Some(res);
191     }
192     None
193 }
194
195 fn hover_ranged(
196     file: &SyntaxNode,
197     range: syntax::TextRange,
198     sema: &Semantics<RootDatabase>,
199     config: &HoverConfig,
200 ) -> Option<RangeInfo<HoverResult>> {
201     let expr_or_pat = file.covering_element(range).ancestors().find_map(|it| {
202         match_ast! {
203             match it {
204                 ast::Expr(expr) => Some(Either::Left(expr)),
205                 ast::Pat(pat) => Some(Either::Right(pat)),
206                 _ => None,
207             }
208         }
209     })?;
210     let res = match &expr_or_pat {
211         Either::Left(ast::Expr::TryExpr(try_expr)) => render::try_expr(sema, config, try_expr),
212         Either::Left(ast::Expr::PrefixExpr(prefix_expr))
213             if prefix_expr.op_kind() == Some(ast::UnaryOp::Deref) =>
214         {
215             render::deref_expr(sema, config, prefix_expr)
216         }
217         _ => None,
218     };
219     let res = res.or_else(|| render::type_info(sema, config, &expr_or_pat));
220     res.map(|it| {
221         let range = match expr_or_pat {
222             Either::Left(it) => it.syntax().text_range(),
223             Either::Right(it) => it.syntax().text_range(),
224         };
225         RangeInfo::new(range, it)
226     })
227 }
228
229 fn hover_type_fallback(
230     sema: &Semantics<RootDatabase>,
231     config: &HoverConfig,
232     token: &SyntaxToken,
233 ) -> Option<RangeInfo<HoverResult>> {
234     let node = token
235         .ancestors()
236         .take_while(|it| !ast::Item::can_cast(it.kind()))
237         .find(|n| ast::Expr::can_cast(n.kind()) || ast::Pat::can_cast(n.kind()))?;
238
239     let expr_or_pat = match_ast! {
240         match node {
241             ast::Expr(it) => Either::Left(it),
242             ast::Pat(it) => Either::Right(it),
243             // If this node is a MACRO_CALL, it means that `descend_into_macros_many` failed to resolve.
244             // (e.g expanding a builtin macro). So we give up here.
245             ast::MacroCall(_it) => return None,
246             _ => return None,
247         }
248     };
249
250     let res = render::type_info(sema, config, &expr_or_pat)?;
251     let range = sema.original_range(&node).range;
252     Some(RangeInfo::new(range, res))
253 }
254
255 fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
256     fn to_action(nav_target: NavigationTarget) -> HoverAction {
257         HoverAction::Implementation(FilePosition {
258             file_id: nav_target.file_id,
259             offset: nav_target.focus_or_full_range().start(),
260         })
261     }
262
263     let adt = match def {
264         Definition::Trait(it) => return it.try_to_nav(db).map(to_action),
265         Definition::Adt(it) => Some(it),
266         Definition::SelfType(it) => it.self_ty(db).as_adt(),
267         _ => None,
268     }?;
269     adt.try_to_nav(db).map(to_action)
270 }
271
272 fn show_fn_references_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
273     match def {
274         Definition::Function(it) => it.try_to_nav(db).map(|nav_target| {
275             HoverAction::Reference(FilePosition {
276                 file_id: nav_target.file_id,
277                 offset: nav_target.focus_or_full_range().start(),
278             })
279         }),
280         _ => None,
281     }
282 }
283
284 fn runnable_action(
285     sema: &hir::Semantics<RootDatabase>,
286     def: Definition,
287     file_id: FileId,
288 ) -> Option<HoverAction> {
289     match def {
290         Definition::Module(it) => runnable_mod(sema, it).map(HoverAction::Runnable),
291         Definition::Function(func) => {
292             let src = func.source(sema.db)?;
293             if src.file_id != file_id.into() {
294                 cov_mark::hit!(hover_macro_generated_struct_fn_doc_comment);
295                 cov_mark::hit!(hover_macro_generated_struct_fn_doc_attr);
296                 return None;
297             }
298
299             runnable_fn(sema, func).map(HoverAction::Runnable)
300         }
301         _ => None,
302     }
303 }
304
305 fn goto_type_action_for_def(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
306     let mut targets: Vec<hir::ModuleDef> = Vec::new();
307     let mut push_new_def = |item: hir::ModuleDef| {
308         if !targets.contains(&item) {
309             targets.push(item);
310         }
311     };
312
313     if let Definition::GenericParam(hir::GenericParam::TypeParam(it)) = def {
314         it.trait_bounds(db).into_iter().for_each(|it| push_new_def(it.into()));
315     } else {
316         let ty = match def {
317             Definition::Local(it) => it.ty(db),
318             Definition::GenericParam(hir::GenericParam::ConstParam(it)) => it.ty(db),
319             Definition::Field(field) => field.ty(db),
320             Definition::Function(function) => function.ret_type(db),
321             _ => return None,
322         };
323
324         walk_and_push_ty(db, &ty, &mut push_new_def);
325     }
326
327     Some(HoverAction::goto_type_from_targets(db, targets))
328 }
329
330 fn walk_and_push_ty(
331     db: &RootDatabase,
332     ty: &hir::Type,
333     push_new_def: &mut dyn FnMut(hir::ModuleDef),
334 ) {
335     ty.walk(db, |t| {
336         if let Some(adt) = t.as_adt() {
337             push_new_def(adt.into());
338         } else if let Some(trait_) = t.as_dyn_trait() {
339             push_new_def(trait_.into());
340         } else if let Some(traits) = t.as_impl_traits(db) {
341             traits.into_iter().for_each(|it| push_new_def(it.into()));
342         } else if let Some(trait_) = t.as_associated_type_parent_trait(db) {
343             push_new_def(trait_.into());
344         }
345     });
346 }
347
348 fn dedupe_or_merge_hover_actions(actions: Vec<HoverAction>) -> Vec<HoverAction> {
349     let mut deduped_actions = Vec::with_capacity(actions.len());
350     let mut go_to_type_targets = FxIndexSet::default();
351
352     let mut seen_implementation = false;
353     let mut seen_reference = false;
354     let mut seen_runnable = false;
355     for action in actions {
356         match action {
357             HoverAction::GoToType(targets) => {
358                 go_to_type_targets.extend(targets);
359             }
360             HoverAction::Implementation(..) => {
361                 if !seen_implementation {
362                     seen_implementation = true;
363                     deduped_actions.push(action);
364                 }
365             }
366             HoverAction::Reference(..) => {
367                 if !seen_reference {
368                     seen_reference = true;
369                     deduped_actions.push(action);
370                 }
371             }
372             HoverAction::Runnable(..) => {
373                 if !seen_runnable {
374                     seen_runnable = true;
375                     deduped_actions.push(action);
376                 }
377             }
378         };
379     }
380
381     if !go_to_type_targets.is_empty() {
382         deduped_actions.push(HoverAction::GoToType(go_to_type_targets.into_iter().collect()));
383     }
384
385     deduped_actions
386 }